@guren/core 1.12.0 → 1.13.1
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/agent.d.ts +1 -0
- package/dist/agent.js +2 -0
- package/dist/index.d.ts +174 -429
- package/dist/index.js +165 -395
- package/dist/internal/deploy-build.d.ts +123 -196
- package/dist/internal/deploy-build.js +166 -279
- package/package.json +8 -4
package/dist/index.js
CHANGED
|
@@ -5,12 +5,9 @@ import { createHash } from "node:crypto";
|
|
|
5
5
|
export * from "@guren/server";
|
|
6
6
|
//#region src/store-utils.ts
|
|
7
7
|
/**
|
|
8
|
-
* Decode a JSON-capable column
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
* Stays here: it is a drizzle column concern, and the Redis stores decode
|
|
13
|
-
* their own JSON payloads through `redis-values.ts` instead.
|
|
8
|
+
* Decode a JSON-capable column holding either the native value (drizzle json
|
|
9
|
+
* mode) or a text-encoded string. Corrupt text falls back instead of throwing,
|
|
10
|
+
* so one bad row cannot break every read.
|
|
14
11
|
*/
|
|
15
12
|
function decodeJsonColumn(value, fallback) {
|
|
16
13
|
if (typeof value === "string") try {
|
|
@@ -23,26 +20,10 @@ function decodeJsonColumn(value, fallback) {
|
|
|
23
20
|
//#endregion
|
|
24
21
|
//#region src/api-token-store.ts
|
|
25
22
|
/**
|
|
26
|
-
* Database-backed API token store built on the Guren ORM.
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
* `hashedToken`, `userId`, `abilities`, `lastUsedAt`, `expiresAt`,
|
|
31
|
-
* `createdAt`). The ORM must be configured (the standard
|
|
32
|
-
* `DatabaseProvider` setup) before the store is used.
|
|
33
|
-
*
|
|
34
|
-
* @example
|
|
35
|
-
* ```ts
|
|
36
|
-
* import { DatabaseApiTokenStore, createApiToken } from '@guren/core'
|
|
37
|
-
* import { apiTokens } from '@/db/schema'
|
|
38
|
-
*
|
|
39
|
-
* const store = new DatabaseApiTokenStore(apiTokens)
|
|
40
|
-
*
|
|
41
|
-
* const { plainTextToken } = await createApiToken(store, {
|
|
42
|
-
* name: 'Mobile App Token',
|
|
43
|
-
* userId: user.id,
|
|
44
|
-
* })
|
|
45
|
-
* ```
|
|
23
|
+
* Database-backed API token store built on the Guren ORM. Pass the Drizzle
|
|
24
|
+
* table for your `api_tokens` schema; column property names must match the
|
|
25
|
+
* {@link ApiToken} fields. Configure the ORM before use.
|
|
26
|
+
* @example `new DatabaseApiTokenStore(apiTokens)`
|
|
46
27
|
*/
|
|
47
28
|
var DatabaseApiTokenStore = class {
|
|
48
29
|
model;
|
|
@@ -76,9 +57,8 @@ var DatabaseApiTokenStore = class {
|
|
|
76
57
|
await this.model.forceUpdate({ id }, { lastUsedAt: timestamp });
|
|
77
58
|
}
|
|
78
59
|
/**
|
|
79
|
-
* Delete tokens whose expiration
|
|
80
|
-
*
|
|
81
|
-
* job to keep the table small.
|
|
60
|
+
* Delete tokens whose expiration has passed. `verifyApiToken` already rejects
|
|
61
|
+
* them; this only keeps the table small.
|
|
82
62
|
*/
|
|
83
63
|
async deleteExpired(now = /* @__PURE__ */ new Date()) {
|
|
84
64
|
await this.model.where("expiresAt", "<", now).delete();
|
|
@@ -100,34 +80,11 @@ var DatabaseApiTokenStore = class {
|
|
|
100
80
|
//#endregion
|
|
101
81
|
//#region src/session-store.ts
|
|
102
82
|
/**
|
|
103
|
-
* Database-backed session store built on the Guren ORM
|
|
104
|
-
*
|
|
105
|
-
*
|
|
106
|
-
*
|
|
107
|
-
*
|
|
108
|
-
* Pass the Drizzle table for your `sessions` schema. Column property names
|
|
109
|
-
* must match `id` (text primary key), `data`, and `expiresAt`:
|
|
110
|
-
*
|
|
111
|
-
* ```ts
|
|
112
|
-
* export const sessions = sqliteTable('sessions', {
|
|
113
|
-
* id: text('id').primaryKey(),
|
|
114
|
-
* data: text('data', { mode: 'json' }).$type<Record<string, unknown>>().notNull(),
|
|
115
|
-
* expiresAt: integer('expires_at', { mode: 'timestamp_ms' }).notNull(),
|
|
116
|
-
* })
|
|
117
|
-
* ```
|
|
118
|
-
*
|
|
119
|
-
* Session values must be JSON-serializable: Dates come back as ISO strings,
|
|
120
|
-
* `undefined` properties are dropped, and `bigint` values fail to serialize —
|
|
121
|
-
* unlike `MemorySessionStore`, which keeps live references. Store primitives
|
|
122
|
-
* and plain objects/arrays in sessions.
|
|
123
|
-
*
|
|
124
|
-
* @example
|
|
125
|
-
* ```ts
|
|
126
|
-
* import { DatabaseSessionStore } from '@guren/core'
|
|
127
|
-
* import { sessions } from '@/db/schema'
|
|
128
|
-
*
|
|
129
|
-
* app.use(createSessionMiddleware({ store: new DatabaseSessionStore(sessions) }))
|
|
130
|
-
* ```
|
|
83
|
+
* Database-backed session store built on the Guren ORM, the serverless default
|
|
84
|
+
* (no Redis on Lambda, Vercel, or Workers; reads are strongly consistent). Column
|
|
85
|
+
* property names of the `sessions` table must be `id` (text primary key), `data`,
|
|
86
|
+
* and `expiresAt`. Values must be JSON-serializable, unlike `MemorySessionStore`:
|
|
87
|
+
* Dates return as ISO strings, `undefined` properties drop, `bigint` throws.
|
|
131
88
|
*/
|
|
132
89
|
var DatabaseSessionStore = class {
|
|
133
90
|
model;
|
|
@@ -173,19 +130,16 @@ var DatabaseSessionStore = class {
|
|
|
173
130
|
await this.model.where({ id }).delete();
|
|
174
131
|
}
|
|
175
132
|
/**
|
|
176
|
-
* Refresh an existing session's TTL with
|
|
177
|
-
*
|
|
178
|
-
*
|
|
179
|
-
* resurrected — matching the `SessionStore.touch` contract and the memory
|
|
180
|
-
* store's behavior.
|
|
133
|
+
* Refresh an existing session's TTL with one conditional UPDATE. Missing and
|
|
134
|
+
* already-expired rows are left untouched, never resurrected, per the
|
|
135
|
+
* `SessionStore.touch` contract.
|
|
181
136
|
*/
|
|
182
137
|
async touch(id, ttlSeconds) {
|
|
183
138
|
await this.model.where({ id }).where("expiresAt", ">", /* @__PURE__ */ new Date()).forceUpdate({ expiresAt: this.expiryDate(ttlSeconds) });
|
|
184
139
|
}
|
|
185
140
|
/**
|
|
186
|
-
* Delete sessions whose expiration
|
|
187
|
-
*
|
|
188
|
-
* scheduled job to keep the table small.
|
|
141
|
+
* Delete sessions whose expiration has passed. `read` already treats them as
|
|
142
|
+
* missing; this only keeps the table small.
|
|
189
143
|
*/
|
|
190
144
|
async deleteExpired(now = /* @__PURE__ */ new Date()) {
|
|
191
145
|
await this.model.where("expiresAt", "<=", now).delete();
|
|
@@ -200,41 +154,11 @@ var DatabaseSessionStore = class {
|
|
|
200
154
|
//#endregion
|
|
201
155
|
//#region src/oauth-state-store.ts
|
|
202
156
|
/**
|
|
203
|
-
* Database-backed OAuth state store built on the Guren ORM
|
|
204
|
-
*
|
|
205
|
-
*
|
|
206
|
-
*
|
|
207
|
-
*
|
|
208
|
-
* never sees the state that was just written. Backing the store with the
|
|
209
|
-
* database makes state visible to whichever instance handles the callback.
|
|
210
|
-
*
|
|
211
|
-
* Pass the Drizzle table for your `oauth_states` schema. Column property
|
|
212
|
-
* names must match `stateHash` (text primary key), `provider`,
|
|
213
|
-
* `redirectTo`, `expiresAt`, and `binding`:
|
|
214
|
-
*
|
|
215
|
-
* ```ts
|
|
216
|
-
* export const oauthStates = sqliteTable('oauth_states', {
|
|
217
|
-
* stateHash: text('state_hash').primaryKey(),
|
|
218
|
-
* provider: text('provider').notNull(),
|
|
219
|
-
* redirectTo: text('redirect_to'),
|
|
220
|
-
* expiresAt: integer('expires_at', { mode: 'timestamp_ms' }).notNull(),
|
|
221
|
-
* binding: text('binding'),
|
|
222
|
-
* })
|
|
223
|
-
* ```
|
|
224
|
-
*
|
|
225
|
-
* `binding` is required for `authorize({ bindTo })` to survive the round trip
|
|
226
|
-
* to the provider. Without the column the store cannot persist it, and every
|
|
227
|
-
* bound state comes back unbound.
|
|
228
|
-
*
|
|
229
|
-
* @example
|
|
230
|
-
* ```ts
|
|
231
|
-
* import { createOAuthManager, DatabaseOAuthStateStore } from '@guren/core'
|
|
232
|
-
* import { oauthStates } from '@/db/schema'
|
|
233
|
-
*
|
|
234
|
-
* export const oauth = createOAuthManager({
|
|
235
|
-
* stateStore: new DatabaseOAuthStateStore(oauthStates),
|
|
236
|
-
* })
|
|
237
|
-
* ```
|
|
157
|
+
* Database-backed OAuth state store built on the Guren ORM, for serverless, where
|
|
158
|
+
* authorize and callback can land on different instances. Column property names
|
|
159
|
+
* of the `oauth_states` table must be `stateHash` (text primary key), `provider`,
|
|
160
|
+
* `redirectTo`, `expiresAt`, and `binding` (else `authorize({ bindTo })` states come back unbound).
|
|
161
|
+
* @example `new DatabaseOAuthStateStore(oauthStates)`
|
|
238
162
|
*/
|
|
239
163
|
var DatabaseOAuthStateStore = class {
|
|
240
164
|
model;
|
|
@@ -256,11 +180,7 @@ var DatabaseOAuthStateStore = class {
|
|
|
256
180
|
const record = await this.fetchLive(stateHash);
|
|
257
181
|
return record ? mapRecordToPayload(record) : null;
|
|
258
182
|
}
|
|
259
|
-
/**
|
|
260
|
-
* Fetch the row for `stateHash`, clearing it out and returning null if
|
|
261
|
-
* expired. Shared by `find` and `consume`, which otherwise diverge only
|
|
262
|
-
* in what they do with a live row.
|
|
263
|
-
*/
|
|
183
|
+
/** Fetch the row for `stateHash`, clearing it and returning null if expired. */
|
|
264
184
|
async fetchLive(stateHash) {
|
|
265
185
|
const record = await this.model.where({ stateHash }).first();
|
|
266
186
|
if (!record) return null;
|
|
@@ -277,29 +197,11 @@ var DatabaseOAuthStateStore = class {
|
|
|
277
197
|
await this.model.where({ stateHash }).delete();
|
|
278
198
|
}
|
|
279
199
|
/**
|
|
280
|
-
* Atomically fetch and delete a state,
|
|
281
|
-
*
|
|
282
|
-
*
|
|
283
|
-
*
|
|
284
|
-
*
|
|
285
|
-
* (RETURNING) or an affected-row count. `DrizzleAdapter`, the framework's
|
|
286
|
-
* default and only shipped adapter, always does this: RETURNING drivers
|
|
287
|
-
* (Postgres, SQLite, D1) resolve to the deleted row or `undefined` only
|
|
288
|
-
* when zero rows matched; MySQL resolves to a result carrying
|
|
289
|
-
* `affectedRows` (verified by inspection, not a dedicated test).
|
|
290
|
-
*
|
|
291
|
-
* The `ORMAdapter.delete` contract also permits a bare `void` return.
|
|
292
|
-
* A custom adapter (via `Model.useAdapter()`) that returns `void`
|
|
293
|
-
* unconditionally — on both a successful delete and a no-op — gives
|
|
294
|
-
* `consume()` no way to tell which caller won: the value is identical for
|
|
295
|
-
* both, so no post-hoc check can attribute the deletion. Rather than
|
|
296
|
-
* silently rejecting every real login for such adapters,
|
|
297
|
-
* `deleteRemovedRow` treats an unrecognized non-null result as removed —
|
|
298
|
-
* this reopens the pre-consume find-then-delete race window (multiple
|
|
299
|
-
* concurrent callers can pass) for adapters that can't report a match,
|
|
300
|
-
* but does not break login. It is fail-closed (returns null / rejects)
|
|
301
|
-
* only for `null`/`undefined`, DrizzleAdapter's definitive "no rows
|
|
302
|
-
* matched" signal.
|
|
200
|
+
* Atomically fetch and delete a state, so exactly one concurrent caller for a
|
|
201
|
+
* hash receives the payload. Relies on `delete()` reporting a match
|
|
202
|
+
* (`DrizzleAdapter`: RETURNING row, or MySQL `affectedRows`). An adapter
|
|
203
|
+
* returning bare `void` reopens the find-then-delete race: `deleteRemovedRow`
|
|
204
|
+
* fails closed only on `null`/`undefined`, Drizzle's definitive "no rows matched".
|
|
303
205
|
*/
|
|
304
206
|
async consume(stateHash) {
|
|
305
207
|
const record = await this.fetchLive(stateHash);
|
|
@@ -310,18 +212,14 @@ var DatabaseOAuthStateStore = class {
|
|
|
310
212
|
}).delete()) ? mapRecordToPayload(record) : null;
|
|
311
213
|
}
|
|
312
214
|
/**
|
|
313
|
-
* Delete
|
|
314
|
-
*
|
|
315
|
-
* the table small.
|
|
215
|
+
* Delete states whose expiration has passed. `find` already rejects them; this
|
|
216
|
+
* only keeps the table small.
|
|
316
217
|
*/
|
|
317
218
|
async deleteExpired(now = /* @__PURE__ */ new Date()) {
|
|
318
219
|
await this.model.where("expiresAt", "<=", now).delete();
|
|
319
220
|
}
|
|
320
221
|
};
|
|
321
|
-
/**
|
|
322
|
-
* Build the public payload from a live (non-expired) row. Shared by `find`
|
|
323
|
-
* and `consume` so the column-to-payload mapping only lives in one place.
|
|
324
|
-
*/
|
|
222
|
+
/** Build the public payload from a live (non-expired) row. */
|
|
325
223
|
function mapRecordToPayload(record) {
|
|
326
224
|
return {
|
|
327
225
|
provider: String(record.provider),
|
|
@@ -331,11 +229,8 @@ function mapRecordToPayload(record) {
|
|
|
331
229
|
};
|
|
332
230
|
}
|
|
333
231
|
/**
|
|
334
|
-
* Interpret an adapter delete result as "this call removed the row"
|
|
335
|
-
*
|
|
336
|
-
* is exact for DrizzleAdapter, and best-effort (assume removed) for any
|
|
337
|
-
* other result shape, since a bare `void` return carries no information to
|
|
338
|
-
* confirm or refute a match.
|
|
232
|
+
* Interpret an adapter delete result as "this call removed the row": exact for
|
|
233
|
+
* DrizzleAdapter, assume-removed for any other shape (see `consume()`).
|
|
339
234
|
*/
|
|
340
235
|
function deleteRemovedRow(result) {
|
|
341
236
|
if (result == null) return false;
|
|
@@ -356,17 +251,11 @@ function deleteRemovedRow(result) {
|
|
|
356
251
|
//#endregion
|
|
357
252
|
//#region src/attachments/bun-image-processor.ts
|
|
358
253
|
/**
|
|
359
|
-
* The default {@link ImageProcessor}, backed by `Bun.Image`.
|
|
360
|
-
*
|
|
361
|
-
*
|
|
362
|
-
*
|
|
363
|
-
*
|
|
364
|
-
* as `unavailable`).
|
|
365
|
-
*
|
|
366
|
-
* Format support is decided by the OS codecs at call time: rejections carry
|
|
367
|
-
* `error.code === 'ERR_IMAGE_FORMAT_UNSUPPORTED'` and the pipeline branches
|
|
368
|
-
* on that code only — there is no hardcoded format×platform matrix, because
|
|
369
|
-
* measured counterexamples exist for every such table.
|
|
254
|
+
* The default {@link ImageProcessor}, backed by `Bun.Image`. Resolved by feature
|
|
255
|
+
* check, never by version: a Bun lane without the API gets no default processor
|
|
256
|
+
* and variants are recorded as `unavailable`. Format support is an OS-codec
|
|
257
|
+
* property at call time, so the pipeline branches only on `error.code ===
|
|
258
|
+
* 'ERR_IMAGE_FORMAT_UNSUPPORTED'`, never on a format×platform table.
|
|
370
259
|
*/
|
|
371
260
|
var BunImageProcessor = class {
|
|
372
261
|
Image;
|
|
@@ -423,9 +312,8 @@ var BunImageProcessor = class {
|
|
|
423
312
|
}
|
|
424
313
|
};
|
|
425
314
|
/**
|
|
426
|
-
*
|
|
427
|
-
*
|
|
428
|
-
* variants degrade to `unavailable`).
|
|
315
|
+
* `Bun.Image` when present, `null` otherwise (Node/Lambda/Workers — inject a
|
|
316
|
+
* custom processor or let variants degrade to `unavailable`).
|
|
429
317
|
*/
|
|
430
318
|
function resolveDefaultImageProcessor(maxPixels) {
|
|
431
319
|
if (typeof Bun === "undefined" || !("Image" in Bun)) return null;
|
|
@@ -608,21 +496,17 @@ function findIspe(bytes, start, end, depth) {
|
|
|
608
496
|
//#region src/attachments/ulid.ts
|
|
609
497
|
/**
|
|
610
498
|
* Dependency-free monotonic ULID generator (https://github.com/ulid/spec):
|
|
611
|
-
* 48-bit
|
|
499
|
+
* 48-bit ms timestamp + 80 bits of randomness, Crockford base32.
|
|
612
500
|
*
|
|
613
|
-
* Attachment ids
|
|
614
|
-
*
|
|
615
|
-
*
|
|
616
|
-
*
|
|
617
|
-
* in insertion order. They must also be unguessable before the row exists
|
|
618
|
-
* (the random half). `byte % 32` is bias-free here because 256 is a
|
|
619
|
-
* multiple of 32.
|
|
501
|
+
* Attachment ids are the sort key for `hasMany` collections, so they must sort
|
|
502
|
+
* even *within* one millisecond — the spec's monotonic mode increments the
|
|
503
|
+
* random half rather than redrawing it. `byte % 32` is bias-free because 256
|
|
504
|
+
* is a multiple of 32.
|
|
620
505
|
*/
|
|
621
506
|
const ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
|
622
507
|
/**
|
|
623
|
-
* The
|
|
624
|
-
*
|
|
625
|
-
* prune sweep uses it to leave recently-minted prefixes alone.
|
|
508
|
+
* The ms timestamp in a ULID's first 10 characters, or `null` for anything that
|
|
509
|
+
* is not a 26-character Crockford string.
|
|
626
510
|
*/
|
|
627
511
|
function ulidTime(id) {
|
|
628
512
|
if (!/^[0-9A-HJKMNP-TV-Z]{26}$/.test(id)) return null;
|
|
@@ -665,40 +549,45 @@ function ulid(now = Date.now()) {
|
|
|
665
549
|
for (let i = 0; i < 16; i++) chars += ENCODING[lastRandom[i]];
|
|
666
550
|
return chars;
|
|
667
551
|
}
|
|
552
|
+
//#endregion
|
|
553
|
+
//#region src/attachments/engine.ts
|
|
554
|
+
/**
|
|
555
|
+
* The single storage key prefix every attachment object lives under:
|
|
556
|
+
* `attachments/<id>/<name>` originals, `attachments/<id>/variants/…`
|
|
557
|
+
* derivatives, `attachments/` the prune sweep's listing. Exported because
|
|
558
|
+
* `guren check` names `<disk root>/attachments` from another package; a restated
|
|
559
|
+
* copy there would stop matching when this moves and report an exposed app safe.
|
|
560
|
+
*/
|
|
561
|
+
const ATTACHMENT_OBJECT_PREFIX = "attachments";
|
|
562
|
+
const DEFAULT_DELIVERY_ROUTE_NAME = "attachments.show";
|
|
668
563
|
/**
|
|
669
|
-
* The inner (presigned) TTL behind a redirect. Fixed
|
|
670
|
-
*
|
|
671
|
-
*
|
|
672
|
-
* outer lifetime silently exceed a driver's presign ceiling (R2 rejects
|
|
673
|
-
* anything over 7 days).
|
|
564
|
+
* The inner (presigned) TTL behind a redirect. Fixed, not derived from
|
|
565
|
+
* `urlExpiresIn`: it is minted per request and need not outlive one fetch, and
|
|
566
|
+
* deriving it could exceed a driver's presign ceiling (R2 rejects over 7 days).
|
|
674
567
|
*/
|
|
675
568
|
const INNER_PRESIGN_TTL_MS = 3e5;
|
|
676
569
|
const DEFAULT_MAX_PIXELS = 52e6;
|
|
677
570
|
/**
|
|
678
|
-
*
|
|
679
|
-
* the
|
|
680
|
-
*
|
|
681
|
-
* collections must not size-reject non-image files).
|
|
571
|
+
* Caps the JPEG marker walk at O(cap) rather than O(input) on attacker-sized
|
|
572
|
+
* bytes that reach the sniffer before the byte-cap gate applies (`image:
|
|
573
|
+
* 'allow'` collections must not size-reject non-image files).
|
|
682
574
|
*/
|
|
683
575
|
const SNIFF_WINDOW_BYTES = 262144;
|
|
684
576
|
const DEFAULT_MAX_IMAGE_BYTES = 5e7;
|
|
685
577
|
const DEFAULT_URL_EXPIRES_IN = 3e5;
|
|
686
578
|
/**
|
|
687
579
|
* How recently minted a storage prefix may be before `--objects` refuses to
|
|
688
|
-
* touch it. attach() writes the object *before* the row, so a prefix
|
|
689
|
-
*
|
|
690
|
-
* so its age is readable; anything younger than this window is skipped and
|
|
691
|
-
* picked up by the next sweep if it really was abandoned.
|
|
580
|
+
* touch it. attach() writes the object *before* the row, so a rowless prefix is
|
|
581
|
+
* either debris or an attach in flight; the ULID id makes its age readable.
|
|
692
582
|
*/
|
|
693
583
|
const PRUNE_OBJECTS_GRACE_MS = 36e5;
|
|
694
584
|
/** Existence lookups are chunked to stay inside every dialect's bind-parameter limits. */
|
|
695
585
|
const PRUNE_LOOKUP_CHUNK = 500;
|
|
696
586
|
/**
|
|
697
|
-
* The spellings
|
|
698
|
-
*
|
|
699
|
-
*
|
|
700
|
-
*
|
|
701
|
-
* "the record exists".
|
|
587
|
+
* The spellings an id may appear under on either side of the prune comparison:
|
|
588
|
+
* lowercased (UUID hex case is not identity) and, for numeric values, the
|
|
589
|
+
* canonical numeric form ('01' and 1 are one key). Used symmetrically so a
|
|
590
|
+
* representation mismatch errs toward "the record exists".
|
|
702
591
|
*/
|
|
703
592
|
function idSpellings(value) {
|
|
704
593
|
const raw = String(value).toLowerCase();
|
|
@@ -757,7 +646,7 @@ var AttachmentEngine = class {
|
|
|
757
646
|
this.urlExpiresIn = options.urlExpiresIn ?? DEFAULT_URL_EXPIRES_IN;
|
|
758
647
|
this.queue = options.queue;
|
|
759
648
|
}
|
|
760
|
-
/** Wired by `configureAttachments()
|
|
649
|
+
/** Wired by `configureAttachments()`, so this module never imports the job. */
|
|
761
650
|
setJobDispatcher(dispatch) {
|
|
762
651
|
this.dispatchJob = dispatch;
|
|
763
652
|
}
|
|
@@ -769,7 +658,7 @@ var AttachmentEngine = class {
|
|
|
769
658
|
const inspection = await this.inspectImage(spec, collection, normalized, queued);
|
|
770
659
|
const id = ulid();
|
|
771
660
|
const name = inspection.name;
|
|
772
|
-
const path =
|
|
661
|
+
const path = `${ATTACHMENT_OBJECT_PREFIX}/${id}/${name}`;
|
|
773
662
|
const diskName = options.disk ?? this.defaultDisk;
|
|
774
663
|
const disk = this.storage().disk(diskName);
|
|
775
664
|
const contentType = inspection.contentType ?? normalized.declaredContentType ?? "application/octet-stream";
|
|
@@ -874,10 +763,9 @@ var AttachmentEngine = class {
|
|
|
874
763
|
return spec;
|
|
875
764
|
}
|
|
876
765
|
/**
|
|
877
|
-
* The three-gate image pipeline (RFC 0013 §6):
|
|
878
|
-
*
|
|
879
|
-
*
|
|
880
|
-
* decode needs a processor.
|
|
766
|
+
* The three-gate image pipeline (RFC 0013 §6): encoded-byte cap, header
|
|
767
|
+
* dimensions, full decode. The first two plus the HEIC signature rejection are
|
|
768
|
+
* pure JS; only the full decode needs a processor.
|
|
881
769
|
*/
|
|
882
770
|
async inspectImage(spec, collection, source, defer = false) {
|
|
883
771
|
const opaque = {
|
|
@@ -956,10 +844,9 @@ var AttachmentEngine = class {
|
|
|
956
844
|
};
|
|
957
845
|
}
|
|
958
846
|
/**
|
|
959
|
-
* Seed one entry per *declared* variant
|
|
960
|
-
*
|
|
961
|
-
*
|
|
962
|
-
* declared" after a reload.
|
|
847
|
+
* Seed one entry per *declared* variant, generating inline where a processor
|
|
848
|
+
* exists. Recording declared names is what lets `attachmentUrl()` tell "not
|
|
849
|
+
* yet generated" from "never declared" after a reload.
|
|
963
850
|
*/
|
|
964
851
|
async buildVariants(spec, id, disk, inspection) {
|
|
965
852
|
const declared = Object.entries(spec.variants ?? {});
|
|
@@ -980,7 +867,8 @@ var AttachmentEngine = class {
|
|
|
980
867
|
}
|
|
981
868
|
try {
|
|
982
869
|
const result = await this.processor.process(inspection.bytes, variantSpec);
|
|
983
|
-
const
|
|
870
|
+
const extension = VARIANT_EXTENSION[result.format] ?? result.format;
|
|
871
|
+
const path = `${ATTACHMENT_OBJECT_PREFIX}/${id}/variants/${name}.${extension}`;
|
|
984
872
|
await disk.put(path, Buffer.from(result.bytes), { contentType: IMAGE_MIME[result.format] ?? "application/octet-stream" });
|
|
985
873
|
variants[name] = {
|
|
986
874
|
status: "ready",
|
|
@@ -997,11 +885,9 @@ var AttachmentEngine = class {
|
|
|
997
885
|
return variants;
|
|
998
886
|
}
|
|
999
887
|
/**
|
|
1000
|
-
* Worker-side completion of a deferred attach
|
|
1001
|
-
*
|
|
1002
|
-
*
|
|
1003
|
-
* and settle every `pending` status record. Safe against races — a row or
|
|
1004
|
-
* object purged while the job sat in the queue is simply nothing to do.
|
|
888
|
+
* Worker-side completion of a deferred attach: the skipped full decode, any
|
|
889
|
+
* opted-in HEIC conversion, the declared variants, and settling every
|
|
890
|
+
* `pending` record. A row or object purged meanwhile is nothing to do.
|
|
1005
891
|
*/
|
|
1006
892
|
async generateVariants(payload) {
|
|
1007
893
|
const raw = await this.model.where({ id: payload.attachmentId }).first();
|
|
@@ -1043,7 +929,7 @@ var AttachmentEngine = class {
|
|
|
1043
929
|
if (sniffed?.format === "heic" && payload.heic === "convert") {
|
|
1044
930
|
const converted = await this.processor.process(bytes, { format: "jpeg" });
|
|
1045
931
|
const name = replaceExtension(row.name, "jpg");
|
|
1046
|
-
const path =
|
|
932
|
+
const path = `${ATTACHMENT_OBJECT_PREFIX}/${row.id}/${name}`;
|
|
1047
933
|
await disk.put(path, Buffer.from(converted.bytes), { contentType: "image/jpeg" });
|
|
1048
934
|
if (path !== row.path) supersededPath = row.path;
|
|
1049
935
|
bytes = converted.bytes;
|
|
@@ -1061,7 +947,7 @@ var AttachmentEngine = class {
|
|
|
1061
947
|
if (variants) updates.variants = variants;
|
|
1062
948
|
updates.updatedAt = /* @__PURE__ */ new Date();
|
|
1063
949
|
if (!await this.model.where({ id: row.id }).first()) {
|
|
1064
|
-
await disk.deleteDirectory(
|
|
950
|
+
await disk.deleteDirectory(`${ATTACHMENT_OBJECT_PREFIX}/${row.id}`);
|
|
1065
951
|
return;
|
|
1066
952
|
}
|
|
1067
953
|
await this.model.forceUpdate({ id: row.id }, updates);
|
|
@@ -1074,11 +960,9 @@ var AttachmentEngine = class {
|
|
|
1074
960
|
await this.settleDeferred({ id: attachmentId }, "failed");
|
|
1075
961
|
}
|
|
1076
962
|
/**
|
|
1077
|
-
* Flip every `pending` variant to a terminal status
|
|
1078
|
-
*
|
|
1079
|
-
*
|
|
1080
|
-
* stale copy whose `pending` entries would otherwise clobber the variants
|
|
1081
|
-
* a completed run already marked `ready`.
|
|
963
|
+
* Flip every `pending` variant to a terminal status. Works on a *fresh* read
|
|
964
|
+
* of the row: under at-least-once delivery a duplicate execution holding a
|
|
965
|
+
* stale copy would clobber variants a completed run already marked `ready`.
|
|
1082
966
|
*/
|
|
1083
967
|
async settleDeferred(row, status, options = {}) {
|
|
1084
968
|
const fresh = await this.model.where({ id: row.id }).first();
|
|
@@ -1104,9 +988,8 @@ var AttachmentEngine = class {
|
|
|
1104
988
|
await this.model.forceUpdate({ id: row.id }, updates);
|
|
1105
989
|
}
|
|
1106
990
|
/**
|
|
1107
|
-
*
|
|
1108
|
-
*
|
|
1109
|
-
* whatever queue driver the app has already booted globally.
|
|
991
|
+
* The configured QueueManager's default driver, or with no `queue` option
|
|
992
|
+
* whatever driver the app has already booted globally.
|
|
1110
993
|
*/
|
|
1111
994
|
ensureQueueDispatchable() {
|
|
1112
995
|
if (!this.dispatchJob) throw new Error("Attachments queue dispatch is not wired. Call configureAttachments() before attaching.");
|
|
@@ -1123,9 +1006,8 @@ var AttachmentEngine = class {
|
|
|
1123
1006
|
await this.dispatchJob(payload);
|
|
1124
1007
|
}
|
|
1125
1008
|
/**
|
|
1126
|
-
* The single indexed query behind `withAttachments()`.
|
|
1127
|
-
*
|
|
1128
|
-
* adapter rather than matching nothing.
|
|
1009
|
+
* The single indexed query behind `withAttachments()`. Empty `records` or
|
|
1010
|
+
* `names` short-circuits: either would send an empty `IN ()` to the adapter.
|
|
1129
1011
|
*/
|
|
1130
1012
|
async rowsForPage(model, records, names) {
|
|
1131
1013
|
const ids = records.map((record) => String(record.id));
|
|
@@ -1146,22 +1028,19 @@ var AttachmentEngine = class {
|
|
|
1146
1028
|
return await this.model.where(where);
|
|
1147
1029
|
}
|
|
1148
1030
|
/**
|
|
1149
|
-
* Objects first, rows after (RFC 0013 §8): a crash between the two leaves
|
|
1150
|
-
*
|
|
1151
|
-
*
|
|
1031
|
+
* Objects first, rows after (RFC 0013 §8): a crash between the two leaves a
|
|
1032
|
+
* row pointing at nothing, which the next `url()` surfaces loudly. The reverse
|
|
1033
|
+
* leaves orphaned objects only a bucket audit finds.
|
|
1152
1034
|
*/
|
|
1153
1035
|
async purgeRows(rows) {
|
|
1154
|
-
for (const row of rows) await this.storage().disk(String(row.disk)).deleteDirectory(
|
|
1036
|
+
for (const row of rows) await this.storage().disk(String(row.disk)).deleteDirectory(`${ATTACHMENT_OBJECT_PREFIX}/${String(row.id)}`);
|
|
1155
1037
|
const ids = rows.map((row) => String(row.id));
|
|
1156
1038
|
for (let start = 0; start < ids.length; start += PRUNE_LOOKUP_CHUNK) await this.model.where({ id: ids.slice(start, start + PRUNE_LOOKUP_CHUNK) }).delete();
|
|
1157
1039
|
}
|
|
1158
1040
|
/**
|
|
1159
|
-
* The sweeper behind `attachments:prune` (RFC 0013 §8): no DB cascade
|
|
1160
|
-
*
|
|
1161
|
-
*
|
|
1162
|
-
* type resolved through `Model.morphMap` and the record queried and found
|
|
1163
|
-
* missing. Anything unverifiable (type not in the morph map, a failing
|
|
1164
|
-
* query, an unlistable disk) is reported and left alone.
|
|
1041
|
+
* The sweeper behind `attachments:prune` (RFC 0013 §8): no DB cascade exists
|
|
1042
|
+
* for a polymorphic pair. Rows are removed only on *positive* evidence the
|
|
1043
|
+
* record is gone; anything unverifiable is reported and left alone.
|
|
1165
1044
|
*/
|
|
1166
1045
|
async pruneOrphans(options = {}) {
|
|
1167
1046
|
const rows = await this.model.withoutGlobalScopes();
|
|
@@ -1242,7 +1121,7 @@ var AttachmentEngine = class {
|
|
|
1242
1121
|
let disk;
|
|
1243
1122
|
try {
|
|
1244
1123
|
disk = this.storage().disk(diskName);
|
|
1245
|
-
prefixes = await disk.directories(
|
|
1124
|
+
prefixes = await disk.directories(ATTACHMENT_OBJECT_PREFIX);
|
|
1246
1125
|
} catch (error) {
|
|
1247
1126
|
report.skippedDisks.push({
|
|
1248
1127
|
disk: diskName,
|
|
@@ -1289,23 +1168,19 @@ var AttachmentEngine = class {
|
|
|
1289
1168
|
return this.deliveryKeys;
|
|
1290
1169
|
}
|
|
1291
1170
|
/**
|
|
1292
|
-
* The one URL policy (RFC 0015 §7): public disks stay on `disk.url()
|
|
1293
|
-
*
|
|
1294
|
-
*
|
|
1295
|
-
* the v1 `temporaryUrl()` behaviour with its documented limitations.
|
|
1171
|
+
* The one URL policy (RFC 0015 §7): public disks stay on `disk.url()`; private
|
|
1172
|
+
* disks get signed route URLs when `delivery` is configured and the disk did
|
|
1173
|
+
* not opt out with `serve: 'direct'`, else v1's `temporaryUrl()`.
|
|
1296
1174
|
*/
|
|
1297
|
-
/** Whether URLs for this row are minted through the delivery route. */
|
|
1298
1175
|
usesDeliveryRoute(row) {
|
|
1299
1176
|
return this.visibilityOf(row.disk) === "private" && this.delivery !== null && this.routeEnabledFor(row.disk);
|
|
1300
1177
|
}
|
|
1301
1178
|
/**
|
|
1302
|
-
* The one variant-resolution rule (RFC 0013 §7 / RFC 0015 §1), shared by
|
|
1303
|
-
*
|
|
1304
|
-
*
|
|
1305
|
-
*
|
|
1306
|
-
*
|
|
1307
|
-
* `failed`, `unavailable`, or an entry missing entirely on a row
|
|
1308
|
-
* attached before the variant was declared — falls back to the original.
|
|
1179
|
+
* The one variant-resolution rule (RFC 0013 §7 / RFC 0015 §1), shared by URL
|
|
1180
|
+
* minting, resource payloads, and the delivery route. A `ready` entry resolves
|
|
1181
|
+
* to the variant's key and *format-derived* MIME type — variants are
|
|
1182
|
+
* transcoded, and serving them under the original's type with `nosniff` would
|
|
1183
|
+
* be self-sabotage. Anything else falls back to the original.
|
|
1309
1184
|
*/
|
|
1310
1185
|
resolveVariantTarget(row, variant) {
|
|
1311
1186
|
const entry = variant ? row.variants?.[variant] : void 0;
|
|
@@ -1330,11 +1205,9 @@ var AttachmentEngine = class {
|
|
|
1330
1205
|
return disk.url(path);
|
|
1331
1206
|
}
|
|
1332
1207
|
/**
|
|
1333
|
-
* Path-relative
|
|
1334
|
-
*
|
|
1335
|
-
*
|
|
1336
|
-
* resolved at *serve* time, so the same URL starts serving the variant
|
|
1337
|
-
* once generation completes.
|
|
1208
|
+
* Path-relative: the `Host` header never participates in URL construction (RFC
|
|
1209
|
+
* 0015 T6). The variant rides as a signed query parameter resolved at *serve*
|
|
1210
|
+
* time, so the same URL starts serving it once generation completes.
|
|
1338
1211
|
*/
|
|
1339
1212
|
signDeliveryUrl(row, options) {
|
|
1340
1213
|
const params = new URLSearchParams();
|
|
@@ -1345,17 +1218,11 @@ var AttachmentEngine = class {
|
|
|
1345
1218
|
return signUrl(`${path}${query}`, this.deliveryKeyring(), { expiresIn: options.expiresIn ?? this.urlExpiresIn });
|
|
1346
1219
|
}
|
|
1347
1220
|
/**
|
|
1348
|
-
* Serve one delivery-route request (RFC 0015 §1)
|
|
1349
|
-
*
|
|
1350
|
-
*
|
|
1351
|
-
*
|
|
1352
|
-
*
|
|
1353
|
-
* Takes the raw web `Request`: every semantic parameter (id, variant,
|
|
1354
|
-
* disposition, expires) is re-read from the *same* `URL`/`URLSearchParams`
|
|
1355
|
-
* parse the signature verification canonicalizes with. A route
|
|
1356
|
-
* framework's own query decoder disagrees with `URLSearchParams` on
|
|
1357
|
-
* malformed percent-encoding, and a parser mismatch there is a signed-URL
|
|
1358
|
-
* rewrite primitive.
|
|
1221
|
+
* Serve one delivery-route request (RFC 0015 §1). Every failure is the same
|
|
1222
|
+
* 404: invalid signature, expired URL, and unknown id stay indistinguishable.
|
|
1223
|
+
* Takes the raw `Request` so each parameter is re-read from the *same*
|
|
1224
|
+
* `URLSearchParams` parse the signature canonicalizes with; a route decoder
|
|
1225
|
+
* disagrees on malformed percent-encoding, a signed-URL rewrite primitive.
|
|
1359
1226
|
*/
|
|
1360
1227
|
async handleDeliveryRequest(request) {
|
|
1361
1228
|
const notFound = () => new Response("Not Found", {
|
|
@@ -1471,10 +1338,9 @@ function setActiveAttachmentEngine(engine) {
|
|
|
1471
1338
|
activeEngine = engine;
|
|
1472
1339
|
}
|
|
1473
1340
|
/**
|
|
1474
|
-
* The delivery route's prefix and name:
|
|
1475
|
-
*
|
|
1476
|
-
*
|
|
1477
|
-
* applied outside the engine constructor.
|
|
1341
|
+
* The delivery route's prefix and name: configured values when an engine is
|
|
1342
|
+
* active, defaults otherwise (bootless route tooling boots no providers). The
|
|
1343
|
+
* one place the defaults are applied outside the engine constructor.
|
|
1478
1344
|
*/
|
|
1479
1345
|
function resolveDeliveryRoute() {
|
|
1480
1346
|
return activeEngine?.deliveryRoute ?? {
|
|
@@ -1504,8 +1370,8 @@ async function normalizeSource(source, nameOverride) {
|
|
|
1504
1370
|
throw new TypeError("attach() accepts bytes only (File, Blob, or Uint8Array). Filesystem path strings are not supported.");
|
|
1505
1371
|
}
|
|
1506
1372
|
/**
|
|
1507
|
-
* Filenames become part of the object key, so they must not steer it: no
|
|
1508
|
-
*
|
|
1373
|
+
* Filenames become part of the object key, so they must not steer it: no path
|
|
1374
|
+
* separators, no control characters, never empty or dot-only.
|
|
1509
1375
|
*/
|
|
1510
1376
|
function sanitizeFilename(name) {
|
|
1511
1377
|
const base = name.split(/[/\\]/).pop() ?? "";
|
|
@@ -1558,10 +1424,9 @@ function normalizeDeliveryPrefix(prefix) {
|
|
|
1558
1424
|
return trimmed;
|
|
1559
1425
|
}
|
|
1560
1426
|
/**
|
|
1561
|
-
* Content types allowed to render inline (RFC 0015 §4). Everything else
|
|
1562
|
-
*
|
|
1563
|
-
* `
|
|
1564
|
-
* nothing can force `inline` for an unlisted one.
|
|
1427
|
+
* Content types allowed to render inline (RFC 0015 §4). Everything else, notably
|
|
1428
|
+
* image/svg+xml and text/html, is forced to `attachment`; nothing can force
|
|
1429
|
+
* `inline` for an unlisted type.
|
|
1565
1430
|
*/
|
|
1566
1431
|
const INLINE_CONTENT_TYPES = /* @__PURE__ */ new Set([
|
|
1567
1432
|
"image/png",
|
|
@@ -1591,10 +1456,9 @@ function ifNoneMatchSatisfied(header, etag) {
|
|
|
1591
1456
|
return trimmed.split(",").some((candidate) => strip(candidate.trim()) === target);
|
|
1592
1457
|
}
|
|
1593
1458
|
/**
|
|
1594
|
-
* Replace lone surrogates so `encodeURIComponent` cannot throw on a stored
|
|
1595
|
-
*
|
|
1596
|
-
*
|
|
1597
|
-
* produced by the same truncation and are overwhelmingly well-formed.
|
|
1459
|
+
* Replace lone surrogates so `encodeURIComponent` cannot throw on a stored name
|
|
1460
|
+
* whose truncation split a pair. `String#toWellFormed` is ES2024 (Bun, Node ≥
|
|
1461
|
+
* 20); older runtimes fall through.
|
|
1598
1462
|
*/
|
|
1599
1463
|
function wellFormed(value) {
|
|
1600
1464
|
const candidate = value;
|
|
@@ -1611,13 +1475,10 @@ function encodeRfc5987(value) {
|
|
|
1611
1475
|
return encodeURIComponent(value).replace(/[!'()*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
1612
1476
|
}
|
|
1613
1477
|
/**
|
|
1614
|
-
* A validator over the *resolved object*, not the request: `id + variant`
|
|
1615
|
-
*
|
|
1616
|
-
*
|
|
1617
|
-
*
|
|
1618
|
-
* cases; `updatedAt` covers the one they miss — a same-key rewrite with
|
|
1619
|
-
* different bytes of the same length (queued variant regeneration), which
|
|
1620
|
-
* always lands with a row update.
|
|
1478
|
+
* A validator over the *resolved object*, not the request: `id + variant` is no
|
|
1479
|
+
* byte identity, since a pending variant resolves to original bytes today and
|
|
1480
|
+
* variant bytes tomorrow. Resolved key + size cover that; `updatedAt` covers a
|
|
1481
|
+
* same-key rewrite with different bytes of the same length.
|
|
1621
1482
|
*/
|
|
1622
1483
|
function deliveryEtag(path, size, updatedAt) {
|
|
1623
1484
|
return `"${createHash("sha256").update(`${path}:${size ?? ""}:${updatedAt.getTime()}`).digest("base64url").slice(0, 20)}"`;
|
|
@@ -1625,30 +1486,11 @@ function deliveryEtag(path, size, updatedAt) {
|
|
|
1625
1486
|
//#endregion
|
|
1626
1487
|
//#region src/attachments/Attachable.ts
|
|
1627
1488
|
/**
|
|
1628
|
-
* Mixin
|
|
1629
|
-
*
|
|
1630
|
-
* statically
|
|
1631
|
-
* rely on for the model's other surfaces), and its collection names, kinds,
|
|
1632
|
-
* and variant names are inferred as compile-time facts.
|
|
1633
|
-
*
|
|
1634
|
-
* Composes with other mixins the way `SoftDeletes` does.
|
|
1635
|
-
*
|
|
1489
|
+
* Mixin declaring attachment collections on a model (RFC 0013). The declaration
|
|
1490
|
+
* sits in the heritage clause so `guren check` and `guren context` read it
|
|
1491
|
+
* statically while collection names, kinds, and variant names are inferred types.
|
|
1636
1492
|
* @example
|
|
1637
|
-
*
|
|
1638
|
-
*
|
|
1639
|
-
* export class Post extends Attachable(defineModel(posts), {
|
|
1640
|
-
* cover: hasOneAttached({
|
|
1641
|
-
* image: 'require',
|
|
1642
|
-
* variants: { thumb: { width: 320 }, og: { width: 1200 } },
|
|
1643
|
-
* }),
|
|
1644
|
-
* images: hasManyAttached({ image: 'require' }),
|
|
1645
|
-
* draftPdf: hasOneAttached(),
|
|
1646
|
-
* }) {}
|
|
1647
|
-
*
|
|
1648
|
-
* // Later, anywhere:
|
|
1649
|
-
* await Post.attach(post.id, 'cover', await this.file('cover'))
|
|
1650
|
-
* const [withCover] = await Post.withAttachments([post], ['cover'])
|
|
1651
|
-
* const url = await Post.attachmentUrl(post, 'cover', { variant: 'thumb' })
|
|
1493
|
+
* class Post extends Attachable(defineModel(posts), { cover: hasOneAttached({ image: 'require' }), images: hasManyAttached() }) {}
|
|
1652
1494
|
*/
|
|
1653
1495
|
function Attachable(Base, declaration) {
|
|
1654
1496
|
const AttachableModel = class extends Base {};
|
|
@@ -1676,30 +1518,19 @@ function Attachable(Base, declaration) {
|
|
|
1676
1518
|
//#endregion
|
|
1677
1519
|
//#region src/attachments/generate-variants-job.ts
|
|
1678
1520
|
/**
|
|
1679
|
-
* Queue job behind `attach(..., { queued: true })` (RFC 0013 Part 2):
|
|
1680
|
-
*
|
|
1681
|
-
* opted in, and generates the declared variants, flipping their `pending`
|
|
1682
|
-
* status records to `ready`/`failed`.
|
|
1521
|
+
* Queue job behind `attach(..., { queued: true })` (RFC 0013 Part 2): the
|
|
1522
|
+
* deferred full decode, opted-in HEIC conversion, and the declared variants.
|
|
1683
1523
|
*
|
|
1684
|
-
*
|
|
1685
|
-
*
|
|
1686
|
-
* work happens — point it at a runtime with an image processor (Bun with
|
|
1687
|
-
* `Bun.Image`, or a custom `configureAttachments({ processor })`), or every
|
|
1688
|
-
* variant settles as `unavailable`.
|
|
1524
|
+
* The worker is where the image work happens — point it at a runtime with an
|
|
1525
|
+
* image processor, or every variant settles as `unavailable`.
|
|
1689
1526
|
*/
|
|
1690
1527
|
var GenerateVariantsJob = class extends Job {
|
|
1691
|
-
/**
|
|
1692
|
-
* Pinned wire name: queued messages must survive bundler identifier
|
|
1693
|
-
* mangling and any future rename of this class.
|
|
1694
|
-
*/
|
|
1528
|
+
/** Pinned: queued messages must survive identifier mangling and renames. */
|
|
1695
1529
|
static jobName = "GenerateVariantsJob";
|
|
1696
1530
|
async handle(payload) {
|
|
1697
1531
|
await resolveAttachmentEngine("GenerateVariantsJob").generateVariants(payload);
|
|
1698
1532
|
}
|
|
1699
|
-
/**
|
|
1700
|
-
* After the last retry, stop `pending` variants from looking in-flight
|
|
1701
|
-
* forever — their URLs already fall back to the original either way.
|
|
1702
|
-
*/
|
|
1533
|
+
/** After the last retry, stop `pending` variants looking in-flight forever. */
|
|
1703
1534
|
async failed(payload, _error) {
|
|
1704
1535
|
try {
|
|
1705
1536
|
await resolveAttachmentEngine("GenerateVariantsJob").markDeferredFailed(payload.attachmentId);
|
|
@@ -1709,23 +1540,11 @@ var GenerateVariantsJob = class extends Job {
|
|
|
1709
1540
|
//#endregion
|
|
1710
1541
|
//#region src/attachments/configure.ts
|
|
1711
1542
|
/**
|
|
1712
|
-
* Wire the attachments layer, once per app
|
|
1713
|
-
*
|
|
1714
|
-
*
|
|
1715
|
-
* lazily and throw a clear error when it was never called.
|
|
1716
|
-
*
|
|
1543
|
+
* Wire the attachments layer, once per app: the app owns the table, the
|
|
1544
|
+
* framework returns the model. `Attachable` statics resolve this lazily and
|
|
1545
|
+
* throw a clear error when it was never called.
|
|
1717
1546
|
* @example
|
|
1718
|
-
*
|
|
1719
|
-
* // config/attachments.ts
|
|
1720
|
-
* import { configureAttachments } from '@guren/core'
|
|
1721
|
-
* import { attachments } from '@/db/schema'
|
|
1722
|
-
*
|
|
1723
|
-
* export const { Attachment } = configureAttachments({
|
|
1724
|
-
* table: attachments,
|
|
1725
|
-
* storage: () => container.make('storage'),
|
|
1726
|
-
* disk: 'media',
|
|
1727
|
-
* })
|
|
1728
|
-
* ```
|
|
1547
|
+
* export const { Attachment } = configureAttachments({ table: attachments, storage: () => container.make('storage'), disk: 'media' })
|
|
1729
1548
|
*/
|
|
1730
1549
|
function configureAttachments(options) {
|
|
1731
1550
|
const engine = new AttachmentEngine(options);
|
|
@@ -1737,16 +1556,11 @@ function configureAttachments(options) {
|
|
|
1737
1556
|
//#endregion
|
|
1738
1557
|
//#region src/attachments/delivery.ts
|
|
1739
1558
|
/**
|
|
1740
|
-
* The signed attachment delivery route's controller (RFC 0015 §1).
|
|
1741
|
-
*
|
|
1742
|
-
*
|
|
1743
|
-
*
|
|
1744
|
-
*
|
|
1745
|
-
* Raw on purpose, too: every semantic parameter must be re-read from the
|
|
1746
|
-
* same `URLSearchParams` parse the signature canonicalizes with. Hono's
|
|
1747
|
-
* query decoder disagrees with `URLSearchParams` on malformed
|
|
1748
|
-
* percent-encoding, and a parser mismatch there is a signed-URL rewrite
|
|
1749
|
-
* primitive.
|
|
1559
|
+
* The signed attachment delivery route's controller (RFC 0015 §1). It hands the
|
|
1560
|
+
* *raw* `Request` to the engine so every semantic parameter is re-read from the
|
|
1561
|
+
* same `URLSearchParams` parse the signature canonicalizes with: Hono's query
|
|
1562
|
+
* decoder disagrees with `URLSearchParams` on malformed percent-encoding, and
|
|
1563
|
+
* that mismatch is a signed-URL rewrite primitive.
|
|
1750
1564
|
*/
|
|
1751
1565
|
var AttachmentDeliveryController = class extends Controller {
|
|
1752
1566
|
async show() {
|
|
@@ -1754,26 +1568,11 @@ var AttachmentDeliveryController = class extends Controller {
|
|
|
1754
1568
|
}
|
|
1755
1569
|
};
|
|
1756
1570
|
/**
|
|
1757
|
-
* Mount the signed delivery route (RFC 0015 §6)
|
|
1758
|
-
* route registrar:
|
|
1759
|
-
*
|
|
1760
|
-
* ```ts
|
|
1761
|
-
* // routes/web.ts
|
|
1762
|
-
* import { registerAttachmentRoutes } from '@guren/core'
|
|
1763
|
-
*
|
|
1764
|
-
* export function registerWebRoutes(router: Router): void {
|
|
1765
|
-
* registerAttachmentRoutes(router)
|
|
1766
|
-
* // …app routes…
|
|
1767
|
-
* }
|
|
1768
|
-
* ```
|
|
1571
|
+
* Mount the signed delivery route (RFC 0015 §6) from the app's route registrar.
|
|
1769
1572
|
*
|
|
1770
|
-
*
|
|
1771
|
-
*
|
|
1772
|
-
*
|
|
1773
|
-
* booted, so a config-dependent throw here would break every inspection
|
|
1774
|
-
* tool. The controller resolves the engine per request instead; at runtime
|
|
1775
|
-
* providers register before routes mount, so the configured prefix and
|
|
1776
|
-
* route name are picked up whenever they exist.
|
|
1573
|
+
* Never throws and does not require `configureAttachments()` to have run: route
|
|
1574
|
+
* tooling invokes registrars against a bare `Router` with no providers booted.
|
|
1575
|
+
* The controller resolves the engine per request instead.
|
|
1777
1576
|
*/
|
|
1778
1577
|
function registerAttachmentRoutes(router) {
|
|
1779
1578
|
const { prefix, routeName } = resolveDeliveryRoute();
|
|
@@ -1782,25 +1581,11 @@ function registerAttachmentRoutes(router) {
|
|
|
1782
1581
|
//#endregion
|
|
1783
1582
|
//#region src/attachments/prune-command.ts
|
|
1784
1583
|
/**
|
|
1785
|
-
* Console sweeper for the attachments layer (RFC 0013 §8)
|
|
1786
|
-
* `attachableType`/`attachableId` pair
|
|
1787
|
-
*
|
|
1788
|
-
*
|
|
1789
|
-
*
|
|
1790
|
-
* prefixes left behind by crashed or raced jobs.
|
|
1791
|
-
*
|
|
1792
|
-
* Register it in the app's console kernel:
|
|
1793
|
-
*
|
|
1794
|
-
* ```ts
|
|
1795
|
-
* // src/console.ts
|
|
1796
|
-
* import { AttachmentsPruneCommand } from '@guren/core'
|
|
1797
|
-
* kernel.register(AttachmentsPruneCommand)
|
|
1798
|
-
* ```
|
|
1799
|
-
*
|
|
1800
|
-
* Orphan rows are detected by resolving each `attachableType` through
|
|
1801
|
-
* `Model.morphMap` and querying for the records — set
|
|
1802
|
-
* `Model.morphMap = { Post, User, ... }` for every model that declares
|
|
1803
|
-
* attachments, or their rows are reported as unverifiable and left alone.
|
|
1584
|
+
* Console sweeper for the attachments layer (RFC 0013 §8): the polymorphic
|
|
1585
|
+
* `attachableType`/`attachableId` pair carries no foreign key, so deletion is
|
|
1586
|
+
* explicit (`purgeAttachments()`) plus this sweep. Register it in the console
|
|
1587
|
+
* kernel. Orphans are found by resolving `attachableType` through `Model.morphMap`;
|
|
1588
|
+
* a model missing there has its rows reported as unverifiable and left alone.
|
|
1804
1589
|
*/
|
|
1805
1590
|
var AttachmentsPruneCommand = class extends Command {
|
|
1806
1591
|
static signature = "attachments:prune {--objects : Also delete attachments/ storage prefixes that no row references} {--dry-run : Report what would be removed without deleting}";
|
|
@@ -1847,30 +1632,15 @@ function buildSpec(kind, options) {
|
|
|
1847
1632
|
}
|
|
1848
1633
|
/**
|
|
1849
1634
|
* Declare a single-attachment collection (`attach` replaces the previous
|
|
1850
|
-
* attachment, purging its row and objects).
|
|
1851
|
-
*
|
|
1852
|
-
* @example
|
|
1853
|
-
* export class Post extends Attachable(defineModel(posts), {
|
|
1854
|
-
* cover: hasOneAttached({
|
|
1855
|
-
* image: 'require',
|
|
1856
|
-
* variants: { thumb: { width: 320 }, og: { width: 1200 } },
|
|
1857
|
-
* }),
|
|
1858
|
-
* draftPdf: hasOneAttached(), // opaque bytes; width/height/placeholder null
|
|
1859
|
-
* }) {}
|
|
1635
|
+
* attachment, purging its row and objects). Called with no options the bytes
|
|
1636
|
+
* stay opaque: width/height/placeholder are null.
|
|
1860
1637
|
*/
|
|
1861
1638
|
function hasOneAttached(options = {}) {
|
|
1862
1639
|
return buildSpec("one", options);
|
|
1863
1640
|
}
|
|
1864
|
-
/**
|
|
1865
|
-
* Declare a multi-attachment collection (`attach` appends).
|
|
1866
|
-
*
|
|
1867
|
-
* @example
|
|
1868
|
-
* export class Post extends Attachable(defineModel(posts), {
|
|
1869
|
-
* images: hasManyAttached({ image: 'require' }),
|
|
1870
|
-
* }) {}
|
|
1871
|
-
*/
|
|
1641
|
+
/** Declare a multi-attachment collection (`attach` appends). */
|
|
1872
1642
|
function hasManyAttached(options = {}) {
|
|
1873
1643
|
return buildSpec("many", options);
|
|
1874
1644
|
}
|
|
1875
1645
|
//#endregion
|
|
1876
|
-
export { Attachable, AttachmentDeliveryController, AttachmentsPruneCommand, DatabaseApiTokenStore, DatabaseOAuthStateStore, DatabaseSessionStore, DrizzleAdapter, GenerateVariantsJob, MassAssignmentException, Model, ModelNotFoundException, QueryBuilder, SoftDeletes, configureAttachments, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, hasManyAttached, hasOneAttached, registerAttachmentRoutes, runSeeders };
|
|
1646
|
+
export { ATTACHMENT_OBJECT_PREFIX, Attachable, AttachmentDeliveryController, AttachmentsPruneCommand, DEFAULT_DELIVERY_ROUTE_NAME, DatabaseApiTokenStore, DatabaseOAuthStateStore, DatabaseSessionStore, DrizzleAdapter, GenerateVariantsJob, MassAssignmentException, Model, ModelNotFoundException, QueryBuilder, SoftDeletes, configureAttachments, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, hasManyAttached, hasOneAttached, registerAttachmentRoutes, runSeeders };
|