dsh-coding-subscription-oauth 0.6.3 → 0.6.5

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.
Files changed (127) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/CONTRIBUTING.md +13 -4
  3. package/INSTALL.md +7 -5
  4. package/README.de.md +6 -6
  5. package/README.es.md +6 -6
  6. package/README.fr.md +6 -6
  7. package/README.ja.md +6 -6
  8. package/README.ko.md +6 -6
  9. package/README.md +6 -6
  10. package/README.pt-BR.md +6 -6
  11. package/README.ru.md +6 -6
  12. package/README.zh-CN.md +6 -6
  13. package/docs/00-project-rules.md +4 -4
  14. package/docs/02-architecture.md +7 -3
  15. package/docs/02-architecture.zh-CN.md +7 -3
  16. package/lib/bin.js +1333 -569
  17. package/lib/bin.js.map +4 -4
  18. package/lib/client.js +1 -1
  19. package/lib/client.js.map +2 -2
  20. package/lib/gateway-protocol.d.ts +3 -46
  21. package/lib/gateway-protocol.d.ts.map +1 -1
  22. package/lib/gateway-routes.d.ts.map +1 -1
  23. package/lib/grok-errors.d.ts +2 -12
  24. package/lib/grok-errors.d.ts.map +1 -1
  25. package/lib/grok-imagine/client.d.ts +73 -0
  26. package/lib/grok-imagine/client.d.ts.map +1 -0
  27. package/lib/grok-imagine/index.d.ts +8 -0
  28. package/lib/grok-imagine/index.d.ts.map +1 -0
  29. package/lib/grok-imagine/net.d.ts +10 -0
  30. package/lib/grok-imagine/net.d.ts.map +1 -0
  31. package/lib/grok-imagine/parse.d.ts +20 -0
  32. package/lib/grok-imagine/parse.d.ts.map +1 -0
  33. package/lib/grok-imagine/types.d.ts +191 -0
  34. package/lib/grok-imagine/types.d.ts.map +1 -0
  35. package/lib/grok-imagine.d.ts +3 -263
  36. package/lib/grok-imagine.d.ts.map +1 -1
  37. package/lib/http-json.d.ts +2 -9
  38. package/lib/http-json.d.ts.map +1 -1
  39. package/lib/index.js +1395 -26178
  40. package/lib/index.js.map +4 -4
  41. package/lib/kimi-errors.d.ts +2 -12
  42. package/lib/kimi-errors.d.ts.map +1 -1
  43. package/lib/runtime/gateway-protocol.d.ts +47 -0
  44. package/lib/runtime/gateway-protocol.d.ts.map +1 -0
  45. package/lib/runtime/grok-errors.d.ts +13 -0
  46. package/lib/runtime/grok-errors.d.ts.map +1 -0
  47. package/lib/runtime/http-json.d.ts +10 -0
  48. package/lib/runtime/http-json.d.ts.map +1 -0
  49. package/lib/runtime/kimi-errors.d.ts +13 -0
  50. package/lib/runtime/kimi-errors.d.ts.map +1 -0
  51. package/package.json +12 -7
  52. package/scripts/release.mjs +1 -0
  53. package/src/adapter.ts +0 -348
  54. package/src/alias-adapter.ts +0 -147
  55. package/src/auth-routes.ts +0 -921
  56. package/src/auth.ts +0 -67
  57. package/src/bin.ts +0 -350
  58. package/src/capability-routes.ts +0 -279
  59. package/src/capability-runtime.ts +0 -314
  60. package/src/capability-settings.ts +0 -671
  61. package/src/capability-tools.ts +0 -685
  62. package/src/catalog.ts +0 -271
  63. package/src/client/GrokBuildSettings.tsx +0 -771
  64. package/src/client/api.ts +0 -88
  65. package/src/client/components/AboutTab.tsx +0 -30
  66. package/src/client/components/AccountsTab.tsx +0 -241
  67. package/src/client/components/Badge.tsx +0 -33
  68. package/src/client/components/CapabilitiesTab.tsx +0 -265
  69. package/src/client/components/CliPullPreview.tsx +0 -116
  70. package/src/client/components/CopyButton.tsx +0 -57
  71. package/src/client/components/GatewayTab.tsx +0 -469
  72. package/src/client/components/NoticeBanner.tsx +0 -46
  73. package/src/client/components/ProgressBar.tsx +0 -53
  74. package/src/client/components/ProviderCard.tsx +0 -606
  75. package/src/client/components/SettingsTabs.tsx +0 -75
  76. package/src/client/components/ToggleSwitch.tsx +0 -71
  77. package/src/client/constants.ts +0 -230
  78. package/src/client/display.ts +0 -61
  79. package/src/client/dshClientAdapter.ts +0 -127
  80. package/src/client/gatewaySnippets.ts +0 -37
  81. package/src/client/index.tsx +0 -156
  82. package/src/client/locales.ts +0 -540
  83. package/src/client/microStyles.ts +0 -52
  84. package/src/client/parsers.ts +0 -398
  85. package/src/client/styles.ts +0 -325
  86. package/src/client/types.ts +0 -199
  87. package/src/codex-http.ts +0 -447
  88. package/src/codex-images.ts +0 -503
  89. package/src/codex-model-capabilities.ts +0 -320
  90. package/src/codex-search.ts +0 -245
  91. package/src/codex-usage.ts +0 -263
  92. package/src/compatibility.ts +0 -55
  93. package/src/dsh-host-adapter.ts +0 -173
  94. package/src/gateway-anthropic-messages.ts +0 -84
  95. package/src/gateway-auth.ts +0 -102
  96. package/src/gateway-backend.ts +0 -274
  97. package/src/gateway-body.ts +0 -49
  98. package/src/gateway-config.ts +0 -76
  99. package/src/gateway-http.ts +0 -104
  100. package/src/gateway-openai-chat.ts +0 -124
  101. package/src/gateway-openai-responses.ts +0 -53
  102. package/src/gateway-parse.ts +0 -224
  103. package/src/gateway-protocol.ts +0 -52
  104. package/src/gateway-routes.ts +0 -158
  105. package/src/gateway.ts +0 -258
  106. package/src/grok-errors.ts +0 -24
  107. package/src/grok-imagine.ts +0 -1627
  108. package/src/grok-import.ts +0 -151
  109. package/src/http-json.ts +0 -82
  110. package/src/ids.ts +0 -59
  111. package/src/imagine-routes.ts +0 -463
  112. package/src/index.ts +0 -735
  113. package/src/invariant.ts +0 -17
  114. package/src/kimi-errors.ts +0 -26
  115. package/src/media-store.ts +0 -927
  116. package/src/oauth-import-routes.ts +0 -324
  117. package/src/oauth-providers.ts +0 -152
  118. package/src/oauth-session.ts +0 -183
  119. package/src/oauth-sources.ts +0 -1104
  120. package/src/oauth.ts +0 -620
  121. package/src/provider.ts +0 -128
  122. package/src/proxy.ts +0 -11
  123. package/src/redact.ts +0 -72
  124. package/src/session.ts +0 -218
  125. package/src/store.ts +0 -217
  126. package/src/web-origin.ts +0 -296
  127. package/src/web-routes.ts +0 -38
@@ -1,463 +0,0 @@
1
- /**
2
- * Same-origin GET routes for generated Imagine images and video artifacts.
3
- * The Host webServer only accepts exact paths, so this registrar keeps a
4
- * bounded table of opaque ids and registers one exact disposer per remembered
5
- * image ref or media artifact.
6
- * @module dsh-coding-subscription-oauth/imagine-routes
7
- */
8
-
9
- import type { IncomingMessage, ServerResponse } from "node:http";
10
- import type { ImageAttachmentRef } from "@deepseek-ai/dsh-attachment";
11
- import {
12
- DEFAULT_IMAGE_DOWNLOAD_MAX_BYTES,
13
- type ImagineImageAttachmentRef,
14
- type ImagineImageMediaType,
15
- imagineImageDownloadHeaders,
16
- imagineImagePath,
17
- isSafeImagineAttachmentId,
18
- parseImagineImagePath,
19
- } from "./grok-imagine.ts";
20
- import {
21
- createTrustedImagineAuthz,
22
- imagineMediaPath,
23
- isSafeMediaArtifactId,
24
- MEDIA_STORE_MAX_BYTES,
25
- type MediaArtifactMeta,
26
- type MediaDownloadView,
27
- MediaStoreError,
28
- type MediaStoreVideoType,
29
- mediaDownloadHeaders,
30
- parseImagineMediaPath,
31
- type TrustedImagineAuthz,
32
- } from "./media-store.ts";
33
- import { LOOPBACK_OWNER_REQUEST_POLICY, type OwnerRequestPolicy } from "./web-origin.ts";
34
-
35
- /** Hard ceiling for live exact download routes. Callers cannot raise this. */
36
- export const IMAGINE_ROUTE_MAX_ENTRIES = 64;
37
-
38
- /** Hard ceiling for remembered image routes. Callers cannot raise this. */
39
- export const IMAGINE_IMAGE_ROUTE_TTL_MS = 60 * 60 * 1000;
40
-
41
- const IMAGE_MEDIA_TYPES = new Set<string>(["image/png", "image/jpeg", "image/webp", "image/gif"]);
42
- const VIDEO_MEDIA_TYPES = new Set<string>(["video/mp4", "video/webm"]);
43
-
44
- /** Structural `ctx.webServer` + optional `ctx.effect` surface used by the registrar. */
45
- export interface ImagineRouteContext {
46
- readonly webServer: {
47
- register(route: {
48
- kind: "exact";
49
- path: string;
50
- handler: (req: IncomingMessage, res: ServerResponse) => void | Promise<void>;
51
- }): () => void;
52
- };
53
- effect?(setup: () => () => void | Promise<void>, label?: string): unknown;
54
- }
55
-
56
- /** Attachment seam used at GET time. Only metadata is retained in the registry. */
57
- export interface ImagineRouteAttachmentStore {
58
- readonly imageLimits?: { readonly maxImageBytes?: number };
59
- readImage(
60
- ref: ImagineImageAttachmentRef,
61
- signal?: AbortSignal,
62
- ): Promise<{ ref: ImagineImageAttachmentRef; data: Uint8Array }>;
63
- }
64
-
65
- /** Structural media download seam. Production adapts `MediaStore.openDownload`. */
66
- export interface ImagineMediaDownloadStore {
67
- readForDownload(artifactId: string, authz: TrustedImagineAuthz): Promise<MediaDownloadView>;
68
- }
69
-
70
- export interface ImagineRouteOptions {
71
- readonly attachments: ImagineRouteAttachmentStore;
72
- readonly media: ImagineMediaDownloadStore;
73
- readonly now?: () => number;
74
- /** Capped at {@link IMAGINE_ROUTE_MAX_ENTRIES}. */
75
- readonly maxEntries?: number;
76
- /** Capped at {@link IMAGINE_IMAGE_ROUTE_TTL_MS}. */
77
- readonly imageTtlMs?: number;
78
- readonly ownerRequestPolicy?: OwnerRequestPolicy;
79
- }
80
-
81
- export interface ImagineRouteRegistry {
82
- rememberImages(refs: readonly ImageAttachmentRef[] | readonly ImagineImageAttachmentRef[]): void;
83
- rememberArtifact(meta: MediaArtifactMeta): void;
84
- revokeImages(): void;
85
- revokeArtifacts(): void;
86
- dispose(): void;
87
- }
88
-
89
- interface ImageRouteEntry {
90
- readonly kind: "image";
91
- readonly id: string;
92
- readonly path: string;
93
- readonly routeToken: symbol;
94
- ref: ImagineImageAttachmentRef;
95
- expiresAt: number;
96
- readonly disposeRoute: () => void;
97
- }
98
-
99
- interface MediaRouteEntry {
100
- readonly kind: "media";
101
- readonly id: string;
102
- readonly path: string;
103
- readonly routeToken: symbol;
104
- meta: MediaArtifactMeta;
105
- expiresAt: number;
106
- readonly disposeRoute: () => void;
107
- }
108
-
109
- type RouteEntry = ImageRouteEntry | MediaRouteEntry;
110
-
111
- type RouteHandler = (req: IncomingMessage, res: ServerResponse) => void | Promise<void>;
112
-
113
- /** Register the bounded exact-path Imagine download registry. */
114
- export function registerImagineRoutes(ctx: ImagineRouteContext, options: ImagineRouteOptions): ImagineRouteRegistry {
115
- const now = options.now ?? Date.now;
116
- const maxEntries = clampPositive(options.maxEntries, IMAGINE_ROUTE_MAX_ENTRIES);
117
- const imageTtlMs = clampPositive(options.imageTtlMs, IMAGINE_IMAGE_ROUTE_TTL_MS);
118
- const ownerRequestPolicy = options.ownerRequestPolicy ?? LOOPBACK_OWNER_REQUEST_POLICY;
119
- const entries = new Map<string, RouteEntry>();
120
- let disposed = false;
121
-
122
- const wrapDisposer = (release: () => void): (() => void) => {
123
- let released = false;
124
- return () => {
125
- if (released) return;
126
- released = true;
127
- try {
128
- release();
129
- } catch {
130
- // One route disposer must not strand the rest of the table.
131
- }
132
- };
133
- };
134
-
135
- const evict = (key: string): void => {
136
- const entry = entries.get(key);
137
- if (entry === undefined) return;
138
- entries.delete(key);
139
- entry.disposeRoute();
140
- };
141
-
142
- const evictExpired = (at: number): void => {
143
- for (const [key, entry] of [...entries]) {
144
- if (entry.expiresAt <= at) evict(key);
145
- }
146
- };
147
-
148
- const evictOldest = (): void => {
149
- const oldest = entries.keys().next().value;
150
- if (oldest !== undefined) evict(oldest);
151
- };
152
-
153
- const lookupKey = (kind: RouteEntry["kind"], id: string): string => `${kind}:${id}`;
154
-
155
- const registerExact = (path: string, handler: RouteHandler): (() => void) =>
156
- wrapDisposer(
157
- ctx.webServer.register({
158
- kind: "exact",
159
- path,
160
- handler,
161
- }),
162
- );
163
-
164
- const isCurrent = (kind: RouteEntry["kind"], id: string, routeToken: symbol): boolean => {
165
- if (disposed) return false;
166
- const entry = entries.get(lookupKey(kind, id));
167
- return entry !== undefined && entry.kind === kind && entry.routeToken === routeToken && entry.expiresAt > now();
168
- };
169
-
170
- const handleGet = async (
171
- kind: RouteEntry["kind"],
172
- id: string,
173
- routeToken: symbol,
174
- req: IncomingMessage,
175
- res: ServerResponse,
176
- ): Promise<void> => {
177
- if ((req.method ?? "") !== "GET") {
178
- json(res, 405, { error: "method not allowed" });
179
- return;
180
- }
181
- if (!ownerRequestPolicy.authorize(req).authorized) {
182
- json(res, 403, { error: "forbidden" });
183
- return;
184
- }
185
- if (!isCurrent(kind, id, routeToken)) {
186
- const key = lookupKey(kind, id);
187
- const current = entries.get(key);
188
- if (current?.routeToken === routeToken && current.expiresAt <= now()) evict(key);
189
- json(res, 404, { error: "not found" });
190
- return;
191
- }
192
- const key = lookupKey(kind, id);
193
- const entry = entries.get(key);
194
- if (entry === undefined || entry.kind !== kind) {
195
- json(res, 404, { error: "not found" });
196
- return;
197
- }
198
- try {
199
- if (entry.kind === "image") {
200
- await serveImage(options.attachments, entry, req, res, () => isCurrent(kind, id, routeToken));
201
- } else {
202
- await serveMedia(options.media, entry, res, () => isCurrent(kind, id, routeToken));
203
- }
204
- } catch (error: unknown) {
205
- if (res.headersSent) return;
206
- if (!isCurrent(kind, id, routeToken)) {
207
- json(res, 404, { error: "not found" });
208
- return;
209
- }
210
- json(res, statusFor(error), { error: publicErrorMessage(error) });
211
- }
212
- };
213
-
214
- const rememberImage = (input: ImageAttachmentRef | ImagineImageAttachmentRef): void => {
215
- if (disposed) return;
216
- const at = now();
217
- evictExpired(at);
218
- const ref = cloneImageRef(input);
219
- if (ref === undefined) return;
220
- if (ref.bytes > maxImageBytes(options.attachments)) return;
221
- let path: string;
222
- try {
223
- path = imagineImagePath(ref.attachmentId);
224
- } catch {
225
- return;
226
- }
227
- if (parseImagineImagePath(path) !== ref.attachmentId) return;
228
- const key = lookupKey("image", ref.attachmentId);
229
- const existing = entries.get(key);
230
- if (existing?.kind === "image") {
231
- entries.delete(key);
232
- existing.ref = ref;
233
- existing.expiresAt = at + imageTtlMs;
234
- entries.set(key, existing);
235
- return;
236
- }
237
- while (entries.size >= maxEntries) evictOldest();
238
- const routeToken = Symbol(ref.attachmentId);
239
- const release = registerExact(path, (req, res) => handleGet("image", ref.attachmentId, routeToken, req, res));
240
- entries.set(key, {
241
- kind: "image",
242
- id: ref.attachmentId,
243
- path,
244
- routeToken,
245
- ref,
246
- expiresAt: at + imageTtlMs,
247
- disposeRoute: release,
248
- });
249
- };
250
-
251
- const rememberArtifact = (input: MediaArtifactMeta): void => {
252
- if (disposed) return;
253
- const at = now();
254
- evictExpired(at);
255
- const meta = cloneArtifactMeta(input);
256
- if (meta === undefined || meta.expiresAt <= at) return;
257
- let path: string;
258
- try {
259
- path = imagineMediaPath(meta.artifactId);
260
- } catch {
261
- return;
262
- }
263
- if (parseImagineMediaPath(path) !== meta.artifactId) return;
264
- const key = lookupKey("media", meta.artifactId);
265
- const existing = entries.get(key);
266
- if (existing?.kind === "media") {
267
- entries.delete(key);
268
- existing.meta = meta;
269
- existing.expiresAt = meta.expiresAt;
270
- entries.set(key, existing);
271
- return;
272
- }
273
- while (entries.size >= maxEntries) evictOldest();
274
- const routeToken = Symbol(meta.artifactId);
275
- const release = registerExact(path, (req, res) => handleGet("media", meta.artifactId, routeToken, req, res));
276
- entries.set(key, {
277
- kind: "media",
278
- id: meta.artifactId,
279
- path,
280
- routeToken,
281
- meta,
282
- expiresAt: meta.expiresAt,
283
- disposeRoute: release,
284
- });
285
- };
286
-
287
- const dispose = (): void => {
288
- if (disposed) return;
289
- disposed = true;
290
- for (const key of [...entries.keys()]) evict(key);
291
- };
292
-
293
- if (typeof ctx.effect === "function") {
294
- ctx.effect(() => dispose, "dsh-coding-subscription-oauth: imagine download routes");
295
- }
296
-
297
- return {
298
- rememberImages(refs) {
299
- for (const ref of refs) rememberImage(ref);
300
- },
301
- rememberArtifact,
302
- revokeImages() {
303
- for (const [key, entry] of [...entries]) {
304
- if (entry.kind === "image") evict(key);
305
- }
306
- },
307
- revokeArtifacts() {
308
- for (const [key, entry] of [...entries]) {
309
- if (entry.kind === "media") evict(key);
310
- }
311
- },
312
- dispose,
313
- };
314
- }
315
-
316
- async function serveImage(
317
- attachments: ImagineRouteAttachmentStore,
318
- entry: ImageRouteEntry,
319
- req: IncomingMessage,
320
- res: ServerResponse,
321
- alive: () => boolean,
322
- ): Promise<void> {
323
- const limit = maxImageBytes(attachments);
324
- if (entry.ref.bytes > limit) {
325
- json(res, 404, { error: "not found" });
326
- return;
327
- }
328
- const stored = await attachments.readImage(cloneImageRef(entry.ref) ?? entry.ref, requestSignal(req));
329
- if (res.headersSent) return;
330
- if (!alive()) {
331
- json(res, 404, { error: "not found" });
332
- return;
333
- }
334
- if (!sameImageIdentity(entry.ref, stored.ref) || stored.data.byteLength > limit) {
335
- json(res, 404, { error: "not found" });
336
- return;
337
- }
338
- const headers = imagineImageDownloadHeaders({
339
- ...stored.ref,
340
- bytes: stored.data.byteLength,
341
- });
342
- res.writeHead(200, {
343
- "Content-Type": headers["Content-Type"],
344
- "Content-Length": String(stored.data.byteLength),
345
- "Cache-Control": headers["Cache-Control"],
346
- "X-Content-Type-Options": headers["X-Content-Type-Options"],
347
- });
348
- res.end(Buffer.from(stored.data));
349
- }
350
-
351
- async function serveMedia(
352
- media: ImagineMediaDownloadStore,
353
- entry: MediaRouteEntry,
354
- res: ServerResponse,
355
- alive: () => boolean,
356
- ): Promise<void> {
357
- const authz = createTrustedImagineAuthz({ authorized: true });
358
- const view = await media.readForDownload(entry.id, authz);
359
- if (res.headersSent) return;
360
- if (!alive()) {
361
- json(res, 404, { error: "not found" });
362
- return;
363
- }
364
- if (
365
- view.meta.artifactId !== entry.id ||
366
- view.meta.mediaType !== entry.meta.mediaType ||
367
- view.meta.bytes !== view.body.byteLength ||
368
- view.body.byteLength > MEDIA_STORE_MAX_BYTES
369
- ) {
370
- json(res, 404, { error: "not found" });
371
- return;
372
- }
373
- const headers = mediaDownloadHeaders({ ...entry.meta, bytes: view.body.byteLength });
374
- res.writeHead(200, {
375
- "Content-Type": headers["Content-Type"],
376
- "Content-Length": headers["Content-Length"],
377
- "Content-Disposition": headers["Content-Disposition"],
378
- "Cache-Control": headers["Cache-Control"],
379
- "X-Content-Type-Options": headers["X-Content-Type-Options"],
380
- });
381
- res.end(Buffer.from(view.body));
382
- }
383
-
384
- function requestSignal(req: IncomingMessage): AbortSignal | undefined {
385
- const candidate = req as IncomingMessage & { signal?: unknown };
386
- return candidate.signal instanceof AbortSignal ? candidate.signal : undefined;
387
- }
388
-
389
- function maxImageBytes(attachments: ImagineRouteAttachmentStore): number {
390
- const configured = attachments.imageLimits?.maxImageBytes;
391
- if (typeof configured !== "number" || !Number.isFinite(configured) || configured <= 0) {
392
- return DEFAULT_IMAGE_DOWNLOAD_MAX_BYTES;
393
- }
394
- return Math.min(Math.floor(configured), DEFAULT_IMAGE_DOWNLOAD_MAX_BYTES);
395
- }
396
-
397
- function cloneImageRef(input: ImageAttachmentRef | ImagineImageAttachmentRef): ImagineImageAttachmentRef | undefined {
398
- if (typeof input.attachmentId !== "string" || !isSafeImagineAttachmentId(input.attachmentId)) return undefined;
399
- if (!IMAGE_MEDIA_TYPES.has(input.mediaType)) return undefined;
400
- if (!Number.isFinite(input.bytes) || input.bytes < 0) return undefined;
401
- if (!Number.isFinite(input.width) || !Number.isFinite(input.height)) return undefined;
402
- const cloned: ImagineImageAttachmentRef = {
403
- attachmentId: input.attachmentId,
404
- mediaType: input.mediaType as ImagineImageMediaType,
405
- bytes: Math.trunc(input.bytes),
406
- width: Math.trunc(input.width),
407
- height: Math.trunc(input.height),
408
- };
409
- if (typeof input.name === "string") cloned.name = input.name;
410
- return cloned;
411
- }
412
-
413
- function cloneArtifactMeta(input: MediaArtifactMeta): MediaArtifactMeta | undefined {
414
- if (typeof input.artifactId !== "string" || !isSafeMediaArtifactId(input.artifactId)) return undefined;
415
- if (!VIDEO_MEDIA_TYPES.has(input.mediaType)) return undefined;
416
- if (!Number.isFinite(input.bytes) || input.bytes <= 0) return undefined;
417
- if (!Number.isFinite(input.createdAt) || input.createdAt <= 0) return undefined;
418
- if (!Number.isFinite(input.expiresAt) || input.expiresAt <= input.createdAt) return undefined;
419
- const cloned: MediaArtifactMeta = {
420
- artifactId: input.artifactId,
421
- mediaType: input.mediaType as MediaStoreVideoType,
422
- bytes: Math.trunc(input.bytes),
423
- createdAt: input.createdAt,
424
- expiresAt: input.expiresAt,
425
- };
426
- if (typeof input.name === "string") cloned.name = input.name;
427
- return cloned;
428
- }
429
-
430
- function sameImageIdentity(expected: ImagineImageAttachmentRef, actual: ImagineImageAttachmentRef): boolean {
431
- return actual.attachmentId === expected.attachmentId && IMAGE_MEDIA_TYPES.has(actual.mediaType);
432
- }
433
-
434
- function statusFor(error: unknown): number {
435
- if (error instanceof MediaStoreError) {
436
- if (error.code === "NOT_FOUND" || error.code === "EXPIRED" || error.code === "INVALID_ID") return 404;
437
- if (error.code === "FORBIDDEN") return 403;
438
- }
439
- return 500;
440
- }
441
-
442
- function publicErrorMessage(error: unknown): string {
443
- if (error instanceof MediaStoreError) {
444
- if (error.code === "NOT_FOUND" || error.code === "EXPIRED" || error.code === "INVALID_ID") return "not found";
445
- if (error.code === "FORBIDDEN") return "forbidden";
446
- }
447
- return "download failed";
448
- }
449
-
450
- function clampPositive(value: number | undefined, ceiling: number): number {
451
- if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) return ceiling;
452
- return Math.min(Math.floor(value), ceiling);
453
- }
454
-
455
- function json(res: ServerResponse, status: number, value: unknown): void {
456
- if (res.headersSent) return;
457
- res.writeHead(status, {
458
- "content-type": "application/json; charset=utf-8",
459
- "cache-control": "no-store",
460
- "x-content-type-options": "nosniff",
461
- });
462
- res.end(JSON.stringify(value));
463
- }