heartwood every commit a ring

Fix datamaps strict-mode bugs preventing map render under Vite

2565493e by Isaac Bythewood · 27 days ago

Fix datamaps strict-mode bugs preventing map render under Vite

Two issues surfaced after the Bun + Vite migration:

- d3 v3 (bundled via datamaps) reads globals off `this` in its top-level
  IIFE (this.document, this.navigator, etc.). Under ESM/strict `this` is
  undefined. Bind the IIFE invocation with .call(globalThis).
- datamaps has a sloppy-mode bug where `hoverover = ...` is assigned without
  a matching declaration, previously creating an implicit global. Under
  strict mode that's a ReferenceError. Hoist `var hoverover` into the IIFE's
  top scope via the same transform plugin. Also switch to the non-minified
  datamaps.usa entry since the transform targets the readable source.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
modified properties/static_src/scripts/property_map.js
@@ -1,5 +1,5 @@import { scaleLinear } from "d3-scale";import Datamap from "datamaps/dist/datamaps.usa.min";import Datamap from "datamaps/dist/datamaps.usa";document.addEventListener("DOMContentLoaded", function () {  const datamapEl = document.getElementById("datamap");
modified vite.config.js
@@ -1,19 +1,28 @@import { resolve } from "path";import { defineConfig } from "vite";// datamaps pulls in d3 v3, whose IIFE reads `this.document` expecting the// global object. Under ESM/strict `this` is undefined, which crashes at load.const fixD3v3GlobalThis = {  name: "fix-d3-v3-global-this",// datamaps pulls in d3 v3, whose top-level IIFE reads globals off `this`// (this.document, this.navigator, etc.). Under ESM/strict `this` is undefined,// crashing at load. Bind the IIFE's `this` to globalThis so those reads work.//// Datamaps itself also has a sloppy-mode bug: `hoverover = ...` is written in// one function without ever being declared, relying on implicit global in// non-strict mode. Under ESM/strict that throws ReferenceError. Hoist a// declaration into the top-level IIFE so the bare assignment resolves.const fixDatamapsStrictMode = {  name: "fix-datamaps-strict-mode",  transform(code, id) {    if (id.includes("datamaps/node_modules/d3/d3.js")) {      return code.replace("this.document", "globalThis.document");      return code.replace(/\}\(\);\s*$/, "}.call(globalThis);\n");    }    if (id.match(/datamaps\/dist\/datamaps\.[^/]+\.js$/)) {      return code.replace("var svg;", "var svg, hoverover;");    }  },};export default defineConfig({  plugins: [fixD3v3GlobalThis],  plugins: [fixDatamapsStrictMode],  build: {    outDir: resolve(__dirname, "analytics/static"),    emptyOutDir: true,