cursedbelt-server 4.48.1 → 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.
@@ -31,6 +31,7 @@
31
31
  * should not stall uploading the rest of the in progress uploads"* — and it generalizes: a
32
32
  * dropzone with one unreadable file in it must still drain the other 4,000.
33
33
  */
34
+ import type { IngestReporter, ReportResult } from "./report.js";
34
35
  /** A file the sweep found, with everything a handler needs to decide about it. */
35
36
  export interface DroppedFile {
36
37
  /** Absolute path on disk. */
@@ -149,8 +150,20 @@ export declare function isStable(file: DroppedFile, stabilityMs?: number): Promi
149
150
  * files that must survive.
150
151
  */
151
152
  export declare function pruneEmptyDirs(root: string, dir?: string): Promise<number>;
152
- /** What the app supplies: what to do with one file. */
153
- export type DropHandler = (file: DroppedFile) => Promise<DropOutcome>;
153
+ /**
154
+ * What the app supplies: what to do with one file. `uploading(key)` names the binary-server key its
155
+ * bytes stage under, once the handler knows it — station's Uploads page shows that transfer's own
156
+ * progress on the file's row.
157
+ */
158
+ export type DropHandler = (file: DroppedFile, ctx: {
159
+ uploading(key: string): void;
160
+ }) => Promise<DropOutcome>;
161
+ /**
162
+ * A sweep's outcome in the words station's Uploads page reads (`report.ts`) — `null` for `held`, which
163
+ * is a standing state rather than an event: the file stays where it is and every sweep meets it
164
+ * again, so it is shown as left alone (`skipped`) instead of journaled every five minutes.
165
+ */
166
+ export declare function reportResultOf(outcome: DropOutcome): ReportResult | null;
154
167
  /**
155
168
  * Walk a dropzone, hand every file to `handle`, and leave nothing behind that was dealt with.
156
169
  *
@@ -161,6 +174,12 @@ export type DropHandler = (file: DroppedFile) => Promise<DropOutcome>;
161
174
  export declare function sweepDropzone(root: string, handle: DropHandler, opts?: ScanOptions & {
162
175
  dryRun?: boolean;
163
176
  onProgress?: (done: number, total: number) => void;
177
+ /**
178
+ * Write what the sweep is doing for station's Uploads page (`createIngestReporter`). The dropzone
179
+ * is ONE account, id `""`: each top-level folder is a source, loose files one more. Never on a
180
+ * dry run, which files nothing. Every hook is guarded — a reporter fault never costs a file.
181
+ */
182
+ report?: IngestReporter;
164
183
  }): Promise<SweepReport>;
165
184
  /** A one-line summary — every consumer prints one, and they should read alike. */
166
185
  export declare const describeSweep: (report: SweepReport) => string;
@@ -185,6 +185,27 @@ export async function pruneEmptyDirs(root, dir = root) {
185
185
  return removed; // not empty — the right outcome, and not an error
186
186
  }
187
187
  }
188
+ /**
189
+ * A sweep's outcome in the words station's Uploads page reads (`report.ts`) — `null` for `held`, which
190
+ * is a standing state rather than an event: the file stays where it is and every sweep meets it
191
+ * again, so it is shown as left alone (`skipped`) instead of journaled every five minutes.
192
+ */
193
+ export function reportResultOf(outcome) {
194
+ const detail = outcome.detail ? { detail: outcome.detail } : {};
195
+ switch (outcome.kind) {
196
+ case "stored":
197
+ return { outcome: "added", ...detail };
198
+ case "duplicate":
199
+ return { outcome: "duplicate", ...detail };
200
+ // Refused by the app's own rule (a format it does not take) — not filed, and not a failure.
201
+ case "discard":
202
+ return { outcome: "blocked", detail: outcome.detail ?? "not something this app files" };
203
+ case "held":
204
+ return null;
205
+ case "failed":
206
+ return { outcome: "failed", detail: outcome.detail };
207
+ }
208
+ }
188
209
  /**
189
210
  * Walk a dropzone, hand every file to `handle`, and leave nothing behind that was dealt with.
190
211
  *
@@ -193,6 +214,19 @@ export async function pruneEmptyDirs(root, dir = root) {
193
214
  * silently. A handler says what happened; this decides what that means for the file on disk.
194
215
  */
195
216
  export async function sweepDropzone(root, handle, opts = {}) {
217
+ const reporter = opts.dryRun ? undefined : opts.report;
218
+ try {
219
+ const report = await sweep(root, handle, opts, reporter);
220
+ reporter?.finish();
221
+ return report;
222
+ }
223
+ catch (error) {
224
+ reporter?.finish(error instanceof Error ? error.message : String(error));
225
+ throw error;
226
+ }
227
+ }
228
+ async function sweep(root, handle, opts, reporter) {
229
+ const as = (file) => ({ accountId: "", path: file.path, relativePath: file.relativePath, size: file.size });
196
230
  const report = {
197
231
  scanned: 0,
198
232
  stored: 0,
@@ -205,17 +239,23 @@ export async function sweepDropzone(root, handle, opts = {}) {
205
239
  emptyDirsRemoved: 0,
206
240
  remaining: 0,
207
241
  };
242
+ reporter?.walking();
208
243
  const files = await scanDropzone(root, opts);
244
+ reporter?.found(files.map(as));
209
245
  for (const [index, file] of files.entries()) {
210
246
  report.scanned++;
211
247
  opts.onProgress?.(index + 1, files.length);
212
248
  if (!(await isStable(file, opts.stabilityMs))) {
213
249
  report.unstable.push(file.relativePath);
250
+ reporter?.progress.waiting(as(file), "copying");
214
251
  continue;
215
252
  }
216
253
  let outcome;
254
+ reporter?.progress.uploading(as(file), "");
217
255
  try {
218
- outcome = opts.dryRun ? { kind: "held", detail: "dry run" } : await handle(file);
256
+ outcome = opts.dryRun
257
+ ? { kind: "held", detail: "dry run" }
258
+ : await handle(file, { uploading: (key) => reporter?.progress.uploading(as(file), key) });
219
259
  }
220
260
  catch (error) {
221
261
  // Rule 3: a handler that throws costs one file, never the sweep.
@@ -224,6 +264,11 @@ export async function sweepDropzone(root, handle, opts = {}) {
224
264
  detail: error instanceof Error ? error.message : String(error),
225
265
  };
226
266
  }
267
+ const result = reportResultOf(outcome);
268
+ if (result)
269
+ reporter?.result(as(file), result);
270
+ else
271
+ reporter?.progress.waiting(as(file), "skipped");
227
272
  switch (outcome.kind) {
228
273
  case "stored":
229
274
  case "duplicate":
@@ -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.48.1",
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",
@@ -336,6 +336,14 @@ describe('pulling D1 down — paged SELECTs, table by table, never an export', (
336
336
  expect(slept).toEqual([WAITS[0] as number]);
337
337
  });
338
338
 
339
+ test("🔴 wrangler crashing on `setTypeOfService EINVAL` is a dropped connection, waited out (vault, 2026-10-23)", async () => {
340
+ const source = live("INSERT INTO items VALUES ('i1', 'a');");
341
+ const said = 'error: could not list D1\'s tables: …\nerror: setTypeOfService EINVAL\n errno: -22,\n syscall: "setTypeOfService",\n code: "EINVAL"';
342
+ const slept: number[] = [];
343
+ await pullWaiting(scratch(), blipping(source, (sql) => sql.includes('sqlite_master'), 1, said).run, slept);
344
+ expect(slept).toEqual([WAITS[0] as number]);
345
+ });
346
+
339
347
  test('a wire that stays down still REFUSES, with its own words, after every wait', async () => {
340
348
  const source = live("INSERT INTO items VALUES ('i1', 'a');");
341
349
  const slept: number[] = [];
@@ -244,12 +244,15 @@ export const TRANSIENT_WAITS_MS: readonly number[] = [5_000, 20_000, 60_000];
244
244
 
245
245
  /**
246
246
  * A failure of the WIRE between this Mac and Cloudflare, not an answer from D1 — which asking
247
- * again a little later fixes. Only these are waited out — a refusal D1 actually made (a page too
247
+ * again a little later fixes. `setTypeOfService EINVAL` is one in disguise: undici sets the socket's
248
+ * TOS before every request, and macOS answers `setsockopt` on a connection the peer already reset
249
+ * with EINVAL — so under Bun a dropped connection crashes wrangler with it instead of ECONNRESET
250
+ * (vault's and auth's nightly pulls, 2026-10-23, both under the background clamp's starved handshakes). Only these are waited out — a refusal D1 actually made (a page too
248
251
  * large, bad SQL, auth) is never retried here, so a page refused for its size still halves at
249
252
  * once instead of sleeping ~1.5 minutes per halving.
250
253
  */
251
254
  export const isTransient = (message: string): boolean =>
252
- /fetch failed|ECONNRESET|ECONNREFUSED|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|socket hang up|network connection was lost/i.test(
255
+ /fetch failed|ECONNRESET|ECONNREFUSED|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|socket hang up|network connection was lost|setTypeOfService EINVAL/i.test(
253
256
  message,
254
257
  );
255
258
 
@@ -28,3 +28,11 @@ export {
28
28
  type DuplicateVerdict,
29
29
  type DuplicateQuestion,
30
30
  } from "./duplicates.js";
31
+ export {
32
+ createIngestReporter,
33
+ FILES_JOURNAL,
34
+ type FileOutcome,
35
+ type IngestReporter,
36
+ type ReportFile,
37
+ type SourceDrive,
38
+ } from "./report.js";