cursedbelt-server 4.49.0 → 4.51.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.
- package/dist/server/dropzone/index.d.ts +5 -1
- package/dist/server/dropzone/index.js +5 -1
- package/dist/server/dropzone/links.d.ts +79 -0
- package/dist/server/dropzone/links.js +190 -0
- package/dist/server/dropzone/scan.d.ts +63 -3
- package/dist/server/dropzone/scan.js +105 -30
- package/dist/server/maps-budget/mapsBudget.d.ts +20 -0
- package/dist/server/maps-budget/mapsBudget.js +57 -0
- package/dist/server/maps-static/staticMap.d.ts +103 -0
- package/dist/server/maps-static/staticMap.js +171 -0
- package/package.json +7 -1
- package/src/server/dropzone/index.ts +21 -0
- package/src/server/dropzone/links.spec.ts +176 -0
- package/src/server/dropzone/links.ts +219 -0
- package/src/server/dropzone/scan.spec.ts +32 -1
- package/src/server/dropzone/scan.ts +142 -30
- package/src/server/maps-budget/mapsBudget.ts +76 -0
- package/src/server/maps-budget/metaTableBudget.spec.ts +34 -0
- package/src/server/maps-static/staticMap.spec.ts +47 -0
- package/src/server/maps-static/staticMap.ts +197 -0
- package/src/server/serveBunOverload.spec.ts +24 -10
- package/src/specsWriteNothingIntoSrc.spec.ts +146 -0
|
@@ -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
|
-
|
|
42
|
-
const
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
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(
|
|
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
|
+
});
|