cursedbelt-server 4.49.0 → 4.50.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -75,6 +75,7 @@
75
75
  * exists to fix. Each app keeps its own ONE DOOR (`maps.ts` in family, pinned by
76
76
  * a test that scans for Google hosts outside it) and both doors consume this.
77
77
  */
78
+ import type { D1LikeDatabase } from '../d1/types.js';
78
79
  /** Where the counter lives. A tiny KV, so an app can back it with whatever
79
80
  * durable store it already has — `apps/orch` uses its own settings store,
80
81
  * `apps/family` uses the `meta` table of the database it already opens. */
@@ -192,3 +193,22 @@ export interface MapsBudgetOptions<Api extends string> {
192
193
  now?: () => number;
193
194
  }
194
195
  export declare function createMapsBudget<Api extends string>(options: MapsBudgetOptions<Api>): MapsBudget<Api>;
196
+ /** What {@link createMetaTableBudget} hands back: the same check-and-count, awaited. */
197
+ export interface AsyncMapsBudget<Api extends string> {
198
+ consume(api: Api, calls?: number): Promise<BudgetVerdict>;
199
+ /** Every API in the ceilings, for a health surface — a roster read, so an API added to
200
+ * the ceilings cannot be missed by a surface that asks for each one by name. */
201
+ usage(): Promise<ReturnType<MapsBudget<Api>['usage']>[]>;
202
+ }
203
+ /**
204
+ * The ceiling over an app's own two-column `meta (key, value)` table on D1 or bun:sqlite —
205
+ * family's adapter, lifted when photos became the second app to need it (forge task 3700).
206
+ *
207
+ * 🔴 The package's store is SYNCHRONOUS by contract and D1 is not. So the counters are read
208
+ * into a snapshot before each decision (one query for every `maps-budget.*` row) and the
209
+ * ceiling decides over the snapshot. The write goes back as a DELTA (`value + n`), never the
210
+ * absolute number: two requests in two isolates each read 10 and each count one, and an
211
+ * absolute write would leave 11 where 12 is true. A spend ceiling that can lose increments
212
+ * under load is the one kind that cannot be trusted.
213
+ */
214
+ export declare function createMetaTableBudget<Api extends string>(db: Pick<D1LikeDatabase, 'prepare' | 'batch'>, options: Omit<MapsBudgetOptions<Api>, 'store'>): AsyncMapsBudget<Api>;
@@ -191,3 +191,60 @@ export function createMapsBudget(options) {
191
191
  },
192
192
  };
193
193
  }
194
+ /**
195
+ * The ceiling over an app's own two-column `meta (key, value)` table on D1 or bun:sqlite —
196
+ * family's adapter, lifted when photos became the second app to need it (forge task 3700).
197
+ *
198
+ * 🔴 The package's store is SYNCHRONOUS by contract and D1 is not. So the counters are read
199
+ * into a snapshot before each decision (one query for every `maps-budget.*` row) and the
200
+ * ceiling decides over the snapshot. The write goes back as a DELTA (`value + n`), never the
201
+ * absolute number: two requests in two isolates each read 10 and each count one, and an
202
+ * absolute write would leave 11 where 12 is true. A spend ceiling that can lose increments
203
+ * under load is the one kind that cannot be trusted.
204
+ */
205
+ export function createMetaTableBudget(db, options) {
206
+ const snapshot = new Map();
207
+ const loaded = new Map();
208
+ const sync = async () => {
209
+ snapshot.clear();
210
+ loaded.clear();
211
+ const rows = await db.prepare("SELECT key, value FROM meta WHERE key LIKE 'maps-budget.%'").all();
212
+ for (const row of rows.results) {
213
+ snapshot.set(row.key, row.value);
214
+ loaded.set(row.key, Number(row.value) || 0);
215
+ }
216
+ };
217
+ const flush = async () => {
218
+ const writes = [...snapshot]
219
+ .map(([key, value]) => ({ key, delta: (Number(value) || 0) - (loaded.get(key) ?? 0) }))
220
+ .filter((entry) => entry.delta !== 0);
221
+ if (writes.length === 0)
222
+ return;
223
+ await db.batch(writes.map(({ key, delta }) => db
224
+ .prepare(`INSERT INTO meta (key, value) VALUES (?1, CAST(?2 AS TEXT))
225
+ ON CONFLICT(key) DO UPDATE SET value = CAST(CAST(value AS INTEGER) + ?2 AS TEXT)`)
226
+ .bind(key, delta)));
227
+ };
228
+ const budget = createMapsBudget({
229
+ ...options,
230
+ store: {
231
+ read: (key) => snapshot.get(key) ?? null,
232
+ write: (key, value) => {
233
+ snapshot.set(key, value);
234
+ },
235
+ },
236
+ });
237
+ const apis = Object.keys(options.ceilings);
238
+ return {
239
+ consume: async (api, calls) => {
240
+ await sync();
241
+ const verdict = budget.consume(api, calls);
242
+ await flush();
243
+ return verdict;
244
+ },
245
+ usage: async () => {
246
+ await sync();
247
+ return apis.map((api) => budget.usage(api));
248
+ },
249
+ };
250
+ }
@@ -0,0 +1,103 @@
1
+ /**
2
+ * cursedbelt-server/maps-static — the shared half of an app's `/api/map` proxy: Google Static
3
+ * Maps imagery under a `cursedbelt/react/map-frame` overlay.
4
+ *
5
+ * Lifted from apps/family's `maps.ts` when photos became the second app to draw a map (forge
6
+ * task 3700). What is here is everything about a render that is not the network call: the
7
+ * request a query string may ask for (clamped, so the cache key space stays tiny), the URL with
8
+ * the fleet's map styling, the cache key, and an LRU for the bytes.
9
+ *
10
+ * 🔴 The FETCH is not here, on purpose. Each app keeps its own ONE DOOR to Google — the place
11
+ * its `cursedbelt-server/maps-budget` ceiling is consumed immediately before the request — so
12
+ * the ceiling and the call can never be separated. Build the URL here; spend it there.
13
+ *
14
+ * 🔴 The key NEVER reaches a browser: `GOOGLE_MAPS_API_KEY` is restricted by API and not by
15
+ * HTTP referrer, so the imagery is proxied and the frame's overlay is our own SVG.
16
+ */
17
+ /** The one Static Maps endpoint. An app's door checks a URL starts with it. */
18
+ export declare const STATIC_MAP_HOST = "https://maps.googleapis.com/maps/api/staticmap";
19
+ /** A lat/lng. Structural, so the server tier needs nothing from the React package. */
20
+ export interface StaticMapCenter {
21
+ lat: number;
22
+ lng: number;
23
+ }
24
+ export interface StaticMapRequest {
25
+ center: StaticMapCenter;
26
+ zoom: number;
27
+ width: number;
28
+ height: number;
29
+ /** `dark` renders the muted night styling the app's dark theme wants. */
30
+ theme: "light" | "dark";
31
+ /** 2 on a retina screen. Google caps this at 2. */
32
+ scale?: 1 | 2;
33
+ }
34
+ /**
35
+ * The map styling, as Google's `style=` parameters.
36
+ *
37
+ * Deliberately DESATURATED and label-light in both themes. The imagery here is a
38
+ * backdrop for our own pins and arcs; a full-color road map competes with them
39
+ * and turns a family's migration story into a picture of motorways. Points of
40
+ * interest and transit are off for the same reason — a 1889 birthplace does not
41
+ * need the nearest pharmacy marked.
42
+ *
43
+ * ── 🔴 The designer's direction, taken literally (2026-08-24) ───────────────
44
+ * *"The current basemap looks like a generic open-source canvas — switch to a
45
+ * premium vector style (a rich dark canvas, or a clean minimalist cream) that
46
+ * makes your data points pop."* Both, one per theme, because `MapFrame` already
47
+ * takes a theme and half of this app is read at night:
48
+ *
49
+ * · LIGHT is CREAM (`0xf7f3ea`), not the cool gray-green it was. Gray-green sat
50
+ * at almost exactly the chroma of the `.ft-viz` palette's teal and blue slots,
51
+ * so a pin over land was a saturated dot on a slightly-less-saturated field.
52
+ * A warm neutral is the complement of every cool hue in that palette at once,
53
+ * which is the whole reason a cream basemap is the classic choice.
54
+ * · DARK is a deeper, bluer canvas (`0x0a1120`) with more separation between
55
+ * land and water than the old pair had. The pins draw at full chroma, so what
56
+ * makes them pop is the backdrop's LIGHTNESS distance from them rather than
57
+ * any change to the marks.
58
+ * · ROAD GEOMETRY is now tinted to sit just off the landscape instead of being
59
+ * left at Google's default. Untinted roads are the single loudest thing in
60
+ * the old picture and they say nothing about a family — but turning them off
61
+ * entirely takes away the only cue that a place is a town rather than a field.
62
+ * · The road CASING (`geometry.stroke`) is off. It is a second line drawn beside
63
+ * every first one, at the width our own migration arcs are drawn at.
64
+ *
65
+ * 🔴 **A style change invalidates every cached render**, because `staticMapKey`
66
+ * includes the theme and the bytes are keyed on it — which is correct, and is why
67
+ * this is landed in ONE pass rather than iterated against the ceiling in this
68
+ * file. Steady state is unchanged: a town does not move, so each place re-renders
69
+ * once and then never again.
70
+ */
71
+ export declare function styleParams(theme: "light" | "dark"): string;
72
+ /** The cache key for a render. Everything that changes the bytes, and nothing
73
+ * else — so two viewers looking at the same place share one image. */
74
+ export declare const staticMapKey: (request: StaticMapRequest) => string;
75
+ /**
76
+ * A render's URL, key included — for the app's door to spend, never for a browser to see.
77
+ *
78
+ * Google caps a single render at 640×640 before `scale`; asking for more is a 400 rather than
79
+ * a bigger picture, so the size is clamped here.
80
+ */
81
+ export declare function staticMapUrl(request: StaticMapRequest, apiKey: string): string;
82
+ /**
83
+ * The render a `/api/map?lat=&lng=&z=&w=&h=&theme=` query asks for, or null when it names no
84
+ * place. The clamps are what keep the cache useful: a free-form size or zoom would make every
85
+ * page view a new billable render.
86
+ */
87
+ export declare function readStaticMapRequest(query: (name: string) => string | undefined): StaticMapRequest | null;
88
+ /**
89
+ * A tiny LRU for rendered map bytes — in process (or in one Worker isolate), never on disk or
90
+ * in a database: the bytes are a third party's disposable cache, so a restart costs a handful
91
+ * of re-renders, bounded by the app's ceiling, and a long browser cache header does the rest.
92
+ *
93
+ * Bounded by COUNT rather than by bytes because every entry is the same
94
+ * dimensions by construction (the viewport sizes are fixed by the layout), so
95
+ * counting images is counting megabytes with less arithmetic. 160 entries at a
96
+ * 640×360@2x PNG is roughly 12 MB — small enough to be invisible next to the
97
+ * process, large enough that a family's whole atlas stays resident.
98
+ */
99
+ export declare function createImageCache(max?: number): {
100
+ get(key: string): Uint8Array | null;
101
+ set(key: string, value: Uint8Array): void;
102
+ readonly size: number;
103
+ };
@@ -0,0 +1,171 @@
1
+ /**
2
+ * cursedbelt-server/maps-static — the shared half of an app's `/api/map` proxy: Google Static
3
+ * Maps imagery under a `cursedbelt/react/map-frame` overlay.
4
+ *
5
+ * Lifted from apps/family's `maps.ts` when photos became the second app to draw a map (forge
6
+ * task 3700). What is here is everything about a render that is not the network call: the
7
+ * request a query string may ask for (clamped, so the cache key space stays tiny), the URL with
8
+ * the fleet's map styling, the cache key, and an LRU for the bytes.
9
+ *
10
+ * 🔴 The FETCH is not here, on purpose. Each app keeps its own ONE DOOR to Google — the place
11
+ * its `cursedbelt-server/maps-budget` ceiling is consumed immediately before the request — so
12
+ * the ceiling and the call can never be separated. Build the URL here; spend it there.
13
+ *
14
+ * 🔴 The key NEVER reaches a browser: `GOOGLE_MAPS_API_KEY` is restricted by API and not by
15
+ * HTTP referrer, so the imagery is proxied and the frame's overlay is our own SVG.
16
+ */
17
+ /** The one Static Maps endpoint. An app's door checks a URL starts with it. */
18
+ export const STATIC_MAP_HOST = "https://maps.googleapis.com/maps/api/staticmap";
19
+ /**
20
+ * The map styling, as Google's `style=` parameters.
21
+ *
22
+ * Deliberately DESATURATED and label-light in both themes. The imagery here is a
23
+ * backdrop for our own pins and arcs; a full-color road map competes with them
24
+ * and turns a family's migration story into a picture of motorways. Points of
25
+ * interest and transit are off for the same reason — a 1889 birthplace does not
26
+ * need the nearest pharmacy marked.
27
+ *
28
+ * ── 🔴 The designer's direction, taken literally (2026-08-24) ───────────────
29
+ * *"The current basemap looks like a generic open-source canvas — switch to a
30
+ * premium vector style (a rich dark canvas, or a clean minimalist cream) that
31
+ * makes your data points pop."* Both, one per theme, because `MapFrame` already
32
+ * takes a theme and half of this app is read at night:
33
+ *
34
+ * · LIGHT is CREAM (`0xf7f3ea`), not the cool gray-green it was. Gray-green sat
35
+ * at almost exactly the chroma of the `.ft-viz` palette's teal and blue slots,
36
+ * so a pin over land was a saturated dot on a slightly-less-saturated field.
37
+ * A warm neutral is the complement of every cool hue in that palette at once,
38
+ * which is the whole reason a cream basemap is the classic choice.
39
+ * · DARK is a deeper, bluer canvas (`0x0a1120`) with more separation between
40
+ * land and water than the old pair had. The pins draw at full chroma, so what
41
+ * makes them pop is the backdrop's LIGHTNESS distance from them rather than
42
+ * any change to the marks.
43
+ * · ROAD GEOMETRY is now tinted to sit just off the landscape instead of being
44
+ * left at Google's default. Untinted roads are the single loudest thing in
45
+ * the old picture and they say nothing about a family — but turning them off
46
+ * entirely takes away the only cue that a place is a town rather than a field.
47
+ * · The road CASING (`geometry.stroke`) is off. It is a second line drawn beside
48
+ * every first one, at the width our own migration arcs are drawn at.
49
+ *
50
+ * 🔴 **A style change invalidates every cached render**, because `staticMapKey`
51
+ * includes the theme and the bytes are keyed on it — which is correct, and is why
52
+ * this is landed in ONE pass rather than iterated against the ceiling in this
53
+ * file. Steady state is unchanged: a town does not move, so each place re-renders
54
+ * once and then never again.
55
+ */
56
+ export function styleParams(theme) {
57
+ const common = [
58
+ "feature:poi|visibility:off",
59
+ "feature:transit|visibility:off",
60
+ "feature:road|element:labels|visibility:off",
61
+ // A casing is a second line beside every road, at the width our own arcs
62
+ // are drawn at — the exact competition this styling exists to remove.
63
+ "feature:road|element:geometry.stroke|visibility:off",
64
+ ];
65
+ const themed = theme === "dark"
66
+ ? [
67
+ "element:geometry|color:0x0a1120",
68
+ "element:labels.text.fill|color:0x94a6c4",
69
+ "element:labels.text.stroke|color:0x0a1120",
70
+ "feature:water|element:geometry|color:0x050a14",
71
+ "feature:administrative|element:geometry.stroke|color:0x33456a",
72
+ "feature:landscape|element:geometry|color:0x121c30",
73
+ "feature:road|element:geometry|color:0x1b2740",
74
+ ]
75
+ : [
76
+ "element:geometry|color:0xf7f3ea",
77
+ "element:labels.text.fill|color:0x6b6257",
78
+ "element:labels.text.stroke|color:0xfbf8f2",
79
+ "feature:water|element:geometry|color:0xdae3e4",
80
+ "feature:administrative|element:geometry.stroke|color:0xd8cfbc",
81
+ "feature:landscape|element:geometry|color:0xf2ece0",
82
+ "feature:road|element:geometry|color:0xeae2d4",
83
+ ];
84
+ return [...common, ...themed].map((style) => `&style=${encodeURIComponent(style)}`).join("");
85
+ }
86
+ /** The cache key for a render. Everything that changes the bytes, and nothing
87
+ * else — so two viewers looking at the same place share one image. */
88
+ export const staticMapKey = (request) => [
89
+ request.center.lat.toFixed(4),
90
+ request.center.lng.toFixed(4),
91
+ request.zoom,
92
+ request.width,
93
+ request.height,
94
+ request.theme,
95
+ request.scale ?? 2,
96
+ ].join(":");
97
+ /**
98
+ * A render's URL, key included — for the app's door to spend, never for a browser to see.
99
+ *
100
+ * Google caps a single render at 640×640 before `scale`; asking for more is a 400 rather than
101
+ * a bigger picture, so the size is clamped here.
102
+ */
103
+ export function staticMapUrl(request, apiKey) {
104
+ const scale = request.scale ?? 2;
105
+ const width = Math.min(640, Math.round(request.width));
106
+ const height = Math.min(640, Math.round(request.height));
107
+ return (`${STATIC_MAP_HOST}?center=${request.center.lat},${request.center.lng}` +
108
+ `&zoom=${request.zoom}&size=${width}x${height}&scale=${scale}&format=png` +
109
+ `&maptype=roadmap${styleParams(request.theme)}` +
110
+ `&key=${encodeURIComponent(apiKey)}`);
111
+ }
112
+ /**
113
+ * The render a `/api/map?lat=&lng=&z=&w=&h=&theme=` query asks for, or null when it names no
114
+ * place. The clamps are what keep the cache useful: a free-form size or zoom would make every
115
+ * page view a new billable render.
116
+ */
117
+ export function readStaticMapRequest(query) {
118
+ const lat = Number(query("lat"));
119
+ const lng = Number(query("lng"));
120
+ // `Number(undefined)` is NaN and `Number("")` is 0 — an absent coordinate must not become
121
+ // the Gulf of Guinea.
122
+ if (!query("lat") || !query("lng") || !Number.isFinite(lat) || !Number.isFinite(lng) || Math.abs(lat) > 90 || Math.abs(lng) > 180) {
123
+ return null;
124
+ }
125
+ return {
126
+ center: { lat, lng },
127
+ zoom: Math.min(16, Math.max(1, Math.round(Number(query("z")) || 4))),
128
+ width: Math.min(640, Math.max(120, Math.round(Number(query("w")) || 640))),
129
+ height: Math.min(640, Math.max(80, Math.round(Number(query("h")) || 360))),
130
+ theme: query("theme") === "dark" ? "dark" : "light",
131
+ };
132
+ }
133
+ /**
134
+ * A tiny LRU for rendered map bytes — in process (or in one Worker isolate), never on disk or
135
+ * in a database: the bytes are a third party's disposable cache, so a restart costs a handful
136
+ * of re-renders, bounded by the app's ceiling, and a long browser cache header does the rest.
137
+ *
138
+ * Bounded by COUNT rather than by bytes because every entry is the same
139
+ * dimensions by construction (the viewport sizes are fixed by the layout), so
140
+ * counting images is counting megabytes with less arithmetic. 160 entries at a
141
+ * 640×360@2x PNG is roughly 12 MB — small enough to be invisible next to the
142
+ * process, large enough that a family's whole atlas stays resident.
143
+ */
144
+ export function createImageCache(max = 160) {
145
+ const entries = new Map();
146
+ return {
147
+ get(key) {
148
+ const hit = entries.get(key);
149
+ if (!hit)
150
+ return null;
151
+ // Re-insert to mark it as recently used — Map preserves insertion order,
152
+ // which is the whole LRU here.
153
+ entries.delete(key);
154
+ entries.set(key, hit);
155
+ return hit;
156
+ },
157
+ set(key, value) {
158
+ entries.delete(key);
159
+ entries.set(key, value);
160
+ while (entries.size > max) {
161
+ const oldest = entries.keys().next().value;
162
+ if (oldest === undefined)
163
+ break;
164
+ entries.delete(oldest);
165
+ }
166
+ },
167
+ get size() {
168
+ return entries.size;
169
+ },
170
+ };
171
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cursedbelt-server",
3
- "version": "4.49.0",
3
+ "version": "4.50.0",
4
4
  "license": "ISC",
5
5
  "type": "module",
6
6
  "description": "The app-facing Bun/Hono server tier of the cursedbelt split — storage, sharing, activity, guard, sync. React-free; cursedbelt-core below it.",
@@ -210,6 +210,12 @@
210
210
  "source": "./src/server/maps-budget/mapsBudget.ts",
211
211
  "import": "./dist/server/maps-budget/mapsBudget.js"
212
212
  },
213
+ "./maps-static": {
214
+ "types": "./dist/server/maps-static/staticMap.d.ts",
215
+ "bun": "./src/server/maps-static/staticMap.ts",
216
+ "source": "./src/server/maps-static/staticMap.ts",
217
+ "import": "./dist/server/maps-static/staticMap.js"
218
+ },
213
219
  "./master-lock": {
214
220
  "types": "./dist/server/master-lock/index.d.ts",
215
221
  "bun": "./src/server/master-lock/index.ts",
@@ -76,6 +76,8 @@
76
76
  * a test that scans for Google hosts outside it) and both doors consume this.
77
77
  */
78
78
 
79
+ import type { D1LikeDatabase } from '../d1/types.js';
80
+
79
81
  /** Where the counter lives. A tiny KV, so an app can back it with whatever
80
82
  * durable store it already has — `apps/orch` uses its own settings store,
81
83
  * `apps/family` uses the `meta` table of the database it already opens. */
@@ -302,3 +304,77 @@ export function createMapsBudget<Api extends string>(
302
304
  },
303
305
  };
304
306
  }
307
+
308
+ /** What {@link createMetaTableBudget} hands back: the same check-and-count, awaited. */
309
+ export interface AsyncMapsBudget<Api extends string> {
310
+ consume(api: Api, calls?: number): Promise<BudgetVerdict>;
311
+ /** Every API in the ceilings, for a health surface — a roster read, so an API added to
312
+ * the ceilings cannot be missed by a surface that asks for each one by name. */
313
+ usage(): Promise<ReturnType<MapsBudget<Api>['usage']>[]>;
314
+ }
315
+
316
+ /**
317
+ * The ceiling over an app's own two-column `meta (key, value)` table on D1 or bun:sqlite —
318
+ * family's adapter, lifted when photos became the second app to need it (forge task 3700).
319
+ *
320
+ * 🔴 The package's store is SYNCHRONOUS by contract and D1 is not. So the counters are read
321
+ * into a snapshot before each decision (one query for every `maps-budget.*` row) and the
322
+ * ceiling decides over the snapshot. The write goes back as a DELTA (`value + n`), never the
323
+ * absolute number: two requests in two isolates each read 10 and each count one, and an
324
+ * absolute write would leave 11 where 12 is true. A spend ceiling that can lose increments
325
+ * under load is the one kind that cannot be trusted.
326
+ */
327
+ export function createMetaTableBudget<Api extends string>(
328
+ db: Pick<D1LikeDatabase, 'prepare' | 'batch'>,
329
+ options: Omit<MapsBudgetOptions<Api>, 'store'>,
330
+ ): AsyncMapsBudget<Api> {
331
+ const snapshot = new Map<string, string>();
332
+ const loaded = new Map<string, number>();
333
+ const sync = async (): Promise<void> => {
334
+ snapshot.clear();
335
+ loaded.clear();
336
+ const rows = await db.prepare("SELECT key, value FROM meta WHERE key LIKE 'maps-budget.%'").all<{ key: string; value: string }>();
337
+ for (const row of rows.results) {
338
+ snapshot.set(row.key, row.value);
339
+ loaded.set(row.key, Number(row.value) || 0);
340
+ }
341
+ };
342
+ const flush = async (): Promise<void> => {
343
+ const writes = [...snapshot]
344
+ .map(([key, value]) => ({ key, delta: (Number(value) || 0) - (loaded.get(key) ?? 0) }))
345
+ .filter((entry) => entry.delta !== 0);
346
+ if (writes.length === 0) return;
347
+ await db.batch(
348
+ writes.map(({ key, delta }) =>
349
+ db
350
+ .prepare(
351
+ `INSERT INTO meta (key, value) VALUES (?1, CAST(?2 AS TEXT))
352
+ ON CONFLICT(key) DO UPDATE SET value = CAST(CAST(value AS INTEGER) + ?2 AS TEXT)`,
353
+ )
354
+ .bind(key, delta),
355
+ ),
356
+ );
357
+ };
358
+ const budget = createMapsBudget<Api>({
359
+ ...options,
360
+ store: {
361
+ read: (key) => snapshot.get(key) ?? null,
362
+ write: (key, value) => {
363
+ snapshot.set(key, value);
364
+ },
365
+ },
366
+ });
367
+ const apis = Object.keys(options.ceilings) as Api[];
368
+ return {
369
+ consume: async (api, calls) => {
370
+ await sync();
371
+ const verdict = budget.consume(api, calls);
372
+ await flush();
373
+ return verdict;
374
+ },
375
+ usage: async () => {
376
+ await sync();
377
+ return apis.map((api) => budget.usage(api));
378
+ },
379
+ };
380
+ }
@@ -0,0 +1,34 @@
1
+ import { Database } from 'bun:sqlite';
2
+ import { describe, expect, it } from 'bun:test';
3
+ import { createLocalD1 } from '../d1/local.js';
4
+ import { createMetaTableBudget } from './mapsBudget.js';
5
+
6
+ const open = () => {
7
+ const sqlite = new Database(':memory:');
8
+ sqlite.run('CREATE TABLE meta ( key TEXT PRIMARY KEY, value TEXT NOT NULL )');
9
+ return { sqlite, db: createLocalD1(sqlite) };
10
+ };
11
+ const AT = Date.UTC(2026, 9, 15, 12);
12
+ const options = { ceilings: { staticmap: 20 }, refusal: () => ({ reason: 'over' }), now: () => AT };
13
+
14
+ describe('createMetaTableBudget — the ceiling over an app meta table', () => {
15
+ it('counts in the table, and a refusal counts nothing', async () => {
16
+ const { db } = open();
17
+ const budget = createMetaTableBudget<'staticmap'>(db, options);
18
+ for (let i = 0; i < 2; i++) expect((await budget.consume('staticmap')).allowed).toBe(true);
19
+ // The daily line is a tenth of the month's: 2 of 2 used, so the third is refused.
20
+ expect((await budget.consume('staticmap')).allowed).toBe(false);
21
+ const [usage] = await budget.usage();
22
+ expect(usage?.used).toBe(2);
23
+ expect(usage?.day.used).toBe(2);
24
+ });
25
+
26
+ it('🔴 writes a DELTA, so two isolates counting at once lose nothing', async () => {
27
+ const { db, sqlite } = open();
28
+ const one = createMetaTableBudget<'staticmap'>(db, options);
29
+ const two = createMetaTableBudget<'staticmap'>(db, options);
30
+ await Promise.all([one.consume('staticmap'), two.consume('staticmap')]);
31
+ const rows = sqlite.query("SELECT value FROM meta WHERE key LIKE 'maps-budget.staticmap.%'").all() as { value: string }[];
32
+ expect(rows.map((row) => Number(row.value))).toEqual([2, 2]);
33
+ });
34
+ });
@@ -0,0 +1,47 @@
1
+ import { describe, expect, it } from 'bun:test';
2
+ import { createImageCache, readStaticMapRequest, STATIC_MAP_HOST, staticMapKey, staticMapUrl } from './staticMap.js';
3
+
4
+ const query = (values: Record<string, string>) => (name: string) => values[name];
5
+
6
+ describe('readStaticMapRequest — what a /api/map query may ask for', () => {
7
+ it('an absent or empty coordinate is no request, never the Gulf of Guinea', () => {
8
+ expect(readStaticMapRequest(query({}))).toBeNull();
9
+ expect(readStaticMapRequest(query({ lat: '', lng: '' }))).toBeNull();
10
+ expect(readStaticMapRequest(query({ lat: '30' }))).toBeNull();
11
+ expect(readStaticMapRequest(query({ lat: '91', lng: '0' }))).toBeNull();
12
+ expect(readStaticMapRequest(query({ lat: '0', lng: '181' }))).toBeNull();
13
+ });
14
+
15
+ it('clamps zoom and size, so the cache key space stays small', () => {
16
+ const request = readStaticMapRequest(query({ lat: '30.2672', lng: '-97.7431', z: '40.4', w: '9999', h: '1', theme: 'dark' }));
17
+ expect(request).toEqual({ center: { lat: 30.2672, lng: -97.7431 }, zoom: 16, width: 640, height: 80, theme: 'dark' });
18
+ expect(readStaticMapRequest(query({ lat: '0', lng: '0', theme: 'neon' }))?.theme).toBe('light');
19
+ });
20
+ });
21
+
22
+ describe('staticMapUrl', () => {
23
+ it('names the host, the viewport, the styling and the key — and caps the size at 640', () => {
24
+ const url = staticMapUrl({ center: { lat: 1.5, lng: 2.5 }, zoom: 6, width: 900, height: 400, theme: 'light' }, 'k&y');
25
+ expect(url.startsWith(`${STATIC_MAP_HOST}?center=1.5,2.5&zoom=6&size=640x400&scale=2`)).toBe(true);
26
+ expect(url).toContain('&style=');
27
+ expect(url.endsWith('&key=k%26y')).toBe(true);
28
+ });
29
+
30
+ it('a theme is a different picture, so a different key', () => {
31
+ const at = { center: { lat: 1, lng: 2 }, zoom: 3, width: 640, height: 400 } as const;
32
+ expect(staticMapKey({ ...at, theme: 'light' })).not.toBe(staticMapKey({ ...at, theme: 'dark' }));
33
+ });
34
+ });
35
+
36
+ describe('createImageCache', () => {
37
+ it('evicts the least recently USED, not the oldest inserted', () => {
38
+ const cache = createImageCache(2);
39
+ cache.set('a', new Uint8Array([1]));
40
+ cache.set('b', new Uint8Array([2]));
41
+ cache.get('a');
42
+ cache.set('c', new Uint8Array([3]));
43
+ expect(cache.get('b')).toBeNull();
44
+ expect(cache.get('a')?.[0]).toBe(1);
45
+ expect(cache.size).toBe(2);
46
+ });
47
+ });
@@ -0,0 +1,197 @@
1
+ /**
2
+ * cursedbelt-server/maps-static — the shared half of an app's `/api/map` proxy: Google Static
3
+ * Maps imagery under a `cursedbelt/react/map-frame` overlay.
4
+ *
5
+ * Lifted from apps/family's `maps.ts` when photos became the second app to draw a map (forge
6
+ * task 3700). What is here is everything about a render that is not the network call: the
7
+ * request a query string may ask for (clamped, so the cache key space stays tiny), the URL with
8
+ * the fleet's map styling, the cache key, and an LRU for the bytes.
9
+ *
10
+ * 🔴 The FETCH is not here, on purpose. Each app keeps its own ONE DOOR to Google — the place
11
+ * its `cursedbelt-server/maps-budget` ceiling is consumed immediately before the request — so
12
+ * the ceiling and the call can never be separated. Build the URL here; spend it there.
13
+ *
14
+ * 🔴 The key NEVER reaches a browser: `GOOGLE_MAPS_API_KEY` is restricted by API and not by
15
+ * HTTP referrer, so the imagery is proxied and the frame's overlay is our own SVG.
16
+ */
17
+
18
+ /** The one Static Maps endpoint. An app's door checks a URL starts with it. */
19
+ export const STATIC_MAP_HOST = "https://maps.googleapis.com/maps/api/staticmap";
20
+
21
+ /** A lat/lng. Structural, so the server tier needs nothing from the React package. */
22
+ export interface StaticMapCenter {
23
+ lat: number;
24
+ lng: number;
25
+ }
26
+
27
+ export interface StaticMapRequest {
28
+ center: StaticMapCenter;
29
+ zoom: number;
30
+ width: number;
31
+ height: number;
32
+ /** `dark` renders the muted night styling the app's dark theme wants. */
33
+ theme: "light" | "dark";
34
+ /** 2 on a retina screen. Google caps this at 2. */
35
+ scale?: 1 | 2;
36
+ }
37
+
38
+ /**
39
+ * The map styling, as Google's `style=` parameters.
40
+ *
41
+ * Deliberately DESATURATED and label-light in both themes. The imagery here is a
42
+ * backdrop for our own pins and arcs; a full-color road map competes with them
43
+ * and turns a family's migration story into a picture of motorways. Points of
44
+ * interest and transit are off for the same reason — a 1889 birthplace does not
45
+ * need the nearest pharmacy marked.
46
+ *
47
+ * ── 🔴 The designer's direction, taken literally (2026-08-24) ───────────────
48
+ * *"The current basemap looks like a generic open-source canvas — switch to a
49
+ * premium vector style (a rich dark canvas, or a clean minimalist cream) that
50
+ * makes your data points pop."* Both, one per theme, because `MapFrame` already
51
+ * takes a theme and half of this app is read at night:
52
+ *
53
+ * · LIGHT is CREAM (`0xf7f3ea`), not the cool gray-green it was. Gray-green sat
54
+ * at almost exactly the chroma of the `.ft-viz` palette's teal and blue slots,
55
+ * so a pin over land was a saturated dot on a slightly-less-saturated field.
56
+ * A warm neutral is the complement of every cool hue in that palette at once,
57
+ * which is the whole reason a cream basemap is the classic choice.
58
+ * · DARK is a deeper, bluer canvas (`0x0a1120`) with more separation between
59
+ * land and water than the old pair had. The pins draw at full chroma, so what
60
+ * makes them pop is the backdrop's LIGHTNESS distance from them rather than
61
+ * any change to the marks.
62
+ * · ROAD GEOMETRY is now tinted to sit just off the landscape instead of being
63
+ * left at Google's default. Untinted roads are the single loudest thing in
64
+ * the old picture and they say nothing about a family — but turning them off
65
+ * entirely takes away the only cue that a place is a town rather than a field.
66
+ * · The road CASING (`geometry.stroke`) is off. It is a second line drawn beside
67
+ * every first one, at the width our own migration arcs are drawn at.
68
+ *
69
+ * 🔴 **A style change invalidates every cached render**, because `staticMapKey`
70
+ * includes the theme and the bytes are keyed on it — which is correct, and is why
71
+ * this is landed in ONE pass rather than iterated against the ceiling in this
72
+ * file. Steady state is unchanged: a town does not move, so each place re-renders
73
+ * once and then never again.
74
+ */
75
+ export function styleParams(theme: "light" | "dark"): string {
76
+ const common = [
77
+ "feature:poi|visibility:off",
78
+ "feature:transit|visibility:off",
79
+ "feature:road|element:labels|visibility:off",
80
+ // A casing is a second line beside every road, at the width our own arcs
81
+ // are drawn at — the exact competition this styling exists to remove.
82
+ "feature:road|element:geometry.stroke|visibility:off",
83
+ ];
84
+ const themed =
85
+ theme === "dark"
86
+ ? [
87
+ "element:geometry|color:0x0a1120",
88
+ "element:labels.text.fill|color:0x94a6c4",
89
+ "element:labels.text.stroke|color:0x0a1120",
90
+ "feature:water|element:geometry|color:0x050a14",
91
+ "feature:administrative|element:geometry.stroke|color:0x33456a",
92
+ "feature:landscape|element:geometry|color:0x121c30",
93
+ "feature:road|element:geometry|color:0x1b2740",
94
+ ]
95
+ : [
96
+ "element:geometry|color:0xf7f3ea",
97
+ "element:labels.text.fill|color:0x6b6257",
98
+ "element:labels.text.stroke|color:0xfbf8f2",
99
+ "feature:water|element:geometry|color:0xdae3e4",
100
+ "feature:administrative|element:geometry.stroke|color:0xd8cfbc",
101
+ "feature:landscape|element:geometry|color:0xf2ece0",
102
+ "feature:road|element:geometry|color:0xeae2d4",
103
+ ];
104
+ return [...common, ...themed].map((style) => `&style=${encodeURIComponent(style)}`).join("");
105
+ }
106
+
107
+ /** The cache key for a render. Everything that changes the bytes, and nothing
108
+ * else — so two viewers looking at the same place share one image. */
109
+ export const staticMapKey = (request: StaticMapRequest): string =>
110
+ [
111
+ request.center.lat.toFixed(4),
112
+ request.center.lng.toFixed(4),
113
+ request.zoom,
114
+ request.width,
115
+ request.height,
116
+ request.theme,
117
+ request.scale ?? 2,
118
+ ].join(":");
119
+
120
+ /**
121
+ * A render's URL, key included — for the app's door to spend, never for a browser to see.
122
+ *
123
+ * Google caps a single render at 640×640 before `scale`; asking for more is a 400 rather than
124
+ * a bigger picture, so the size is clamped here.
125
+ */
126
+ export function staticMapUrl(request: StaticMapRequest, apiKey: string): string {
127
+ const scale = request.scale ?? 2;
128
+ const width = Math.min(640, Math.round(request.width));
129
+ const height = Math.min(640, Math.round(request.height));
130
+ return (
131
+ `${STATIC_MAP_HOST}?center=${request.center.lat},${request.center.lng}` +
132
+ `&zoom=${request.zoom}&size=${width}x${height}&scale=${scale}&format=png` +
133
+ `&maptype=roadmap${styleParams(request.theme)}` +
134
+ `&key=${encodeURIComponent(apiKey)}`
135
+ );
136
+ }
137
+
138
+ /**
139
+ * The render a `/api/map?lat=&lng=&z=&w=&h=&theme=` query asks for, or null when it names no
140
+ * place. The clamps are what keep the cache useful: a free-form size or zoom would make every
141
+ * page view a new billable render.
142
+ */
143
+ export function readStaticMapRequest(query: (name: string) => string | undefined): StaticMapRequest | null {
144
+ const lat = Number(query("lat"));
145
+ const lng = Number(query("lng"));
146
+ // `Number(undefined)` is NaN and `Number("")` is 0 — an absent coordinate must not become
147
+ // the Gulf of Guinea.
148
+ if (!query("lat") || !query("lng") || !Number.isFinite(lat) || !Number.isFinite(lng) || Math.abs(lat) > 90 || Math.abs(lng) > 180) {
149
+ return null;
150
+ }
151
+ return {
152
+ center: { lat, lng },
153
+ zoom: Math.min(16, Math.max(1, Math.round(Number(query("z")) || 4))),
154
+ width: Math.min(640, Math.max(120, Math.round(Number(query("w")) || 640))),
155
+ height: Math.min(640, Math.max(80, Math.round(Number(query("h")) || 360))),
156
+ theme: query("theme") === "dark" ? "dark" : "light",
157
+ };
158
+ }
159
+
160
+ /**
161
+ * A tiny LRU for rendered map bytes — in process (or in one Worker isolate), never on disk or
162
+ * in a database: the bytes are a third party's disposable cache, so a restart costs a handful
163
+ * of re-renders, bounded by the app's ceiling, and a long browser cache header does the rest.
164
+ *
165
+ * Bounded by COUNT rather than by bytes because every entry is the same
166
+ * dimensions by construction (the viewport sizes are fixed by the layout), so
167
+ * counting images is counting megabytes with less arithmetic. 160 entries at a
168
+ * 640×360@2x PNG is roughly 12 MB — small enough to be invisible next to the
169
+ * process, large enough that a family's whole atlas stays resident.
170
+ */
171
+ export function createImageCache(max = 160) {
172
+ const entries = new Map<string, Uint8Array>();
173
+ return {
174
+ get(key: string): Uint8Array | null {
175
+ const hit = entries.get(key);
176
+ if (!hit) return null;
177
+ // Re-insert to mark it as recently used — Map preserves insertion order,
178
+ // which is the whole LRU here.
179
+ entries.delete(key);
180
+ entries.set(key, hit);
181
+ return hit;
182
+ },
183
+ set(key: string, value: Uint8Array): void {
184
+ entries.delete(key);
185
+ entries.set(key, value);
186
+ while (entries.size > max) {
187
+ const oldest = entries.keys().next().value;
188
+ if (oldest === undefined) break;
189
+ entries.delete(oldest);
190
+ }
191
+ },
192
+ get size(): number {
193
+ return entries.size;
194
+ },
195
+ };
196
+ }
197
+
@@ -11,13 +11,18 @@
11
11
  * app is told to use instead has itself grown the trap.
12
12
  *
13
13
  * The second half proves the first can fire: the same fixture with the directives stripped must
14
- * fail with TS2345 on exactly the two trap lines.
14
+ * fail with TS2345 on exactly the two trap lines. That copy is written OUTSIDE `src/`, under the
15
+ * package's `node_modules/.cache`: eight specs walk `src/` while this one runs beside them
16
+ * (`--parallel`), and one that listed the copy and then opened it after the `finally` had removed
17
+ * it failed the gate with ENOENT and refused a publish (the ship of 2026-10-25).
15
18
  */
16
19
  import { describe, expect, it } from 'bun:test';
17
- import { readFileSync, rmSync, writeFileSync } from 'node:fs';
20
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
21
+ import { relative } from 'node:path';
18
22
  import { fileURLToPath } from 'node:url';
19
23
 
20
24
  const DIR = fileURLToPath(new URL('./typetests/', import.meta.url));
25
+ const CACHE = fileURLToPath(new URL('../../node_modules/.cache/', import.meta.url));
21
26
  const TSC = fileURLToPath(new URL('../../node_modules/typescript/bin/tsc', import.meta.url));
22
27
 
23
28
  const tsc = async (project: string) => {
@@ -38,20 +43,29 @@ describe("Bun.serve's websocket overload", () => {
38
43
  }, 60_000);
39
44
 
40
45
  it('🔴 without the directives the SAME lines fail — so the check above can go red', async () => {
41
- const source = readFileSync(`${DIR}serveBunOverload.ts`, 'utf8').replace(/^\s*\/\/ @ts-expect-error.*$/gm, '');
42
- const file = `${DIR}serveBunOverload.stripped.ts`;
43
- const project = `${DIR}tsconfig.stripped.json`;
44
- writeFileSync(file, source);
45
- writeFileSync(project, JSON.stringify({ extends: './tsconfig.json', include: ['serveBunOverload.stripped.ts'] }));
46
+ mkdirSync(CACHE, { recursive: true });
47
+ const scratch = mkdtempSync(`${CACHE}serve-bun-overload-`);
48
+ // The fixture's one relative import, re-pointed from the scratch directory at the real seam.
49
+ const seam = relative(scratch, fileURLToPath(new URL('./app.js', import.meta.url)));
50
+ const source = readFileSync(`${DIR}serveBunOverload.ts`, 'utf8')
51
+ .replace(/^\s*\/\/ @ts-expect-error.*$/gm, '')
52
+ .replace("from '../app.js'", `from '${seam}'`);
53
+ expect(source).toContain(seam);
54
+ const project = `${scratch}/tsconfig.json`;
55
+ writeFileSync(`${scratch}/serveBunOverload.stripped.ts`, source);
56
+ writeFileSync(
57
+ project,
58
+ // `exclude: []` — the base excludes `node_modules`, which is where this copy sits.
59
+ JSON.stringify({ extends: `${DIR}tsconfig.json`, include: ['serveBunOverload.stripped.ts'], exclude: [] }),
60
+ );
46
61
  try {
47
62
  const run = await tsc(project);
48
63
  expect(run.code).not.toBe(0);
49
64
  const errors = run.out.split('\n').filter((line) => line.includes('error TS'));
50
- expect(errors).toHaveLength(2);
65
+ expect(errors, run.out).toHaveLength(2);
51
66
  for (const line of errors) expect(line).toContain('TS2345');
52
67
  } finally {
53
- rmSync(file, { force: true });
54
- rmSync(project, { force: true });
68
+ rmSync(scratch, { recursive: true, force: true });
55
69
  }
56
70
  }, 60_000);
57
71
  });
@@ -0,0 +1,146 @@
1
+ import { describe, expect, it } from 'bun:test';
2
+ import { readdirSync, readFileSync, statSync } from 'node:fs';
3
+ import { dirname, resolve } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+
6
+ /**
7
+ * 🔴 **A spec writes nothing into `src/` — its scratch goes under `node_modules/.cache` or a temp dir.**
8
+ *
9
+ * Measured 2026-10-25, the ship that was to publish cursedbelt-server 4.50.0: the publish gate went
10
+ * red and uploaded nothing, on
11
+ *
12
+ * ```
13
+ * ENOENT: no such file or directory, open '…/src/server/typetests/serveBunOverload.stripped.ts'
14
+ * at scan (src/nodeBuiltinsAreProbedByCalling.spec.ts:193:17)
15
+ * ```
16
+ *
17
+ * `serveBunOverload.spec.ts` wrote a stripped copy of its fixture beside the fixture, ran `tsc`,
18
+ * and removed it. `bun test --parallel` ran it beside one of the eight specs that walk `src/`,
19
+ * which listed the copy and opened it after it was gone. Neither spec was wrong alone; the tree
20
+ * they share was. So the rule is on the WRITER: `src/` is read-only to the suite.
21
+ *
22
+ * ## What it measures
23
+ *
24
+ * For every spec: each `const X = …new URL('<rel>', import.meta.url)…` (or `join(import.meta.dir,
25
+ * '<rel>')`) whose target lies inside `src/` makes `X` an in-src path, and so does any binding built
26
+ * from one. A write call (`writeFileSync`, `appendFileSync`, `mkdirSync`, `mkdtempSync`, `renameSync`,
27
+ * `Bun.write`) whose FIRST argument names such a binding, or spells such a URL itself, is a violation
28
+ * — a later argument is content, not a place, and `cpSync` is left out because its first argument
29
+ * is what it READS. A line carrying (or under) `specs-write-src:ignore` is excused, with its reason
30
+ * on the line. This spec skips itself: its fixtures below are the shape it hunts.
31
+ */
32
+
33
+ const SRC = fileURLToPath(new URL('./', import.meta.url));
34
+ const SELF = fileURLToPath(import.meta.url);
35
+ const IGNORE_MARKER = 'specs-write-src:ignore';
36
+ const WRITE = /\b(?:writeFileSync|appendFileSync|mkdirSync|mkdtempSync|renameSync|Bun\.write)\s*\(/g;
37
+ const URL_BINDING =
38
+ /(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=[^;\n]*?(?:new URL\(\s*['"`]([^'"`]*)['"`]\s*,\s*import\.meta\.url|import\.meta\.dir\s*,\s*['"`]([^'"`]*)['"`])/g;
39
+ const INLINE_URL = /new URL\(\s*['"`]([^'"`]*)['"`]\s*,\s*import\.meta\.url|import\.meta\.dir\s*,\s*['"`]([^'"`]*)['"`]/;
40
+
41
+ const ASSIGNMENT = /(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=([^\n]*)/g;
42
+
43
+ /** Does `text` name the identifier `name` (not merely a longer one that starts with it)? */
44
+ const mentions = (text: string, name: string): boolean =>
45
+ new RegExp(`(?:^|[^\\w$])${name.replaceAll('$', '\\$')}(?![\\w$])`).test(text);
46
+
47
+ /** The first argument of the call whose `(` ends at `from`: up to the first top-level `,` or `)`. */
48
+ const firstArgument = (text: string, from: number): string => {
49
+ let depth = 0;
50
+ for (let i = from; i < text.length; i++) {
51
+ const c = text[i];
52
+ if (c === '(' || c === '[' || c === '{') depth++;
53
+ else if ((c === ')' || c === ']' || c === '}') && depth-- === 0) return text.slice(from, i);
54
+ else if (c === ',' && depth === 0) return text.slice(from, i);
55
+ }
56
+ return text.slice(from);
57
+ };
58
+
59
+ const insideSrc = (specDir: string, rel: string): boolean => {
60
+ const target = resolve(specDir, rel);
61
+ return `${target}/`.startsWith(SRC);
62
+ };
63
+
64
+ /** Every violation in one spec's source. `file` is the spec's absolute path, for resolving its URLs. */
65
+ function writesIntoSrc(file: string, source: string): { line: number; text: string }[] {
66
+ const specDir = dirname(file);
67
+ const inSrc = new Set<string>();
68
+ for (const m of source.matchAll(URL_BINDING)) {
69
+ if (insideSrc(specDir, m[2] ?? m[3] ?? '')) inSrc.add(m[1]);
70
+ }
71
+ // A binding built from an in-src one is in src too (`const file = \`${DIR}x.ts\``), to a fixpoint.
72
+ const assigned = [...source.matchAll(ASSIGNMENT)];
73
+ for (let grew = true; grew; ) {
74
+ grew = false;
75
+ for (const [, name, rhs] of assigned) {
76
+ if (!inSrc.has(name) && [...inSrc].some((x) => mentions(rhs, x))) {
77
+ inSrc.add(name);
78
+ grew = true;
79
+ }
80
+ }
81
+ }
82
+ const lines = source.split('\n');
83
+ const found: { line: number; text: string }[] = [];
84
+ lines.forEach((text, index) => {
85
+ for (const m of text.matchAll(WRITE)) {
86
+ const arg = firstArgument(text, (m.index ?? 0) + m[0].length);
87
+ const named = [...inSrc].some((name) => mentions(arg, name));
88
+ const inline = INLINE_URL.exec(arg);
89
+ const spelled = inline !== null && insideSrc(specDir, inline[1] ?? inline[2] ?? '');
90
+ if (!named && !spelled) continue;
91
+ if (text.includes(IGNORE_MARKER) || (lines[index - 1] ?? '').includes(IGNORE_MARKER)) continue;
92
+ found.push({ line: index + 1, text: text.trim() });
93
+ }
94
+ });
95
+ return found;
96
+ }
97
+
98
+ function specFiles(dir: string, found: string[] = []): string[] {
99
+ for (const entry of readdirSync(dir)) {
100
+ const full = `${dir}${entry}`;
101
+ if (statSync(full).isDirectory()) specFiles(`${full}/`, found);
102
+ else if ((entry.endsWith('.spec.ts') || entry.endsWith('.spec.tsx')) && full !== SELF) found.push(full);
103
+ }
104
+ return found;
105
+ }
106
+
107
+ describe('specs write nothing into src/', () => {
108
+ it('has specs to read — otherwise the check below passes vacuously', () => {
109
+ expect(specFiles(SRC).length).toBeGreaterThan(100);
110
+ });
111
+
112
+ it('no spec writes into src/', () => {
113
+ const report = specFiles(SRC).flatMap((file) =>
114
+ writesIntoSrc(file, readFileSync(file, 'utf8')).map((v) => ` ${file.slice(SRC.length)}:${v.line} — ${v.text}`),
115
+ );
116
+ expect(
117
+ report.length === 0
118
+ ? ''
119
+ : `\n${report.join('\n')}\n\nWrite scratch under node_modules/.cache or a temp dir: other specs walk src/.\n`,
120
+ ).toBe('');
121
+ });
122
+
123
+ it('🔴 catches the shape that refused the 2026-10-25 publish — a derived binding and an inline URL both', () => {
124
+ const spec = `${SRC}server/serveBunOverload.spec.ts`;
125
+ const before = [
126
+ "const DIR = fileURLToPath(new URL('./typetests/', import.meta.url));",
127
+ // biome-ignore lint/suspicious/noTemplateCurlyInString: the fixture IS source text, placeholder and all
128
+ 'const file = `${DIR}serveBunOverload.stripped.ts`;',
129
+ 'writeFileSync(file, source);',
130
+ "Bun.write(fileURLToPath(new URL('./x.ts', import.meta.url)), '');",
131
+ ].join('\n');
132
+ expect(writesIntoSrc(spec, before).map((v) => v.line)).toEqual([3, 4]);
133
+ });
134
+
135
+ it('leaves a write outside src/ alone, and honors the marker', () => {
136
+ const spec = `${SRC}server/serveBunOverload.spec.ts`;
137
+ const after = [
138
+ "const CACHE = fileURLToPath(new URL('../../node_modules/.cache/', import.meta.url));",
139
+ "const DIR = fileURLToPath(new URL('./typetests/', import.meta.url));",
140
+ 'mkdirSync(CACHE, { recursive: true });',
141
+ 'const DIRECTORY = 1; writeFileSync(DIRECTORY_NAME, "");',
142
+ `writeFileSync(\`\${DIR}x\`, ''); // ${IGNORE_MARKER} a fixture no other spec walks`,
143
+ ].join('\n');
144
+ expect(writesIntoSrc(spec, after)).toEqual([]);
145
+ });
146
+ });