@guren/core 1.13.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/index.d.ts +168 -441
- package/dist/index.js +150 -401
- package/dist/internal/deploy-build.d.ts +101 -287
- package/dist/internal/deploy-build.js +127 -357
- package/package.json +4 -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;
|
|
@@ -669,56 +553,41 @@ function ulid(now = Date.now()) {
|
|
|
669
553
|
//#region src/attachments/engine.ts
|
|
670
554
|
/**
|
|
671
555
|
* The single storage key prefix every attachment object lives under:
|
|
672
|
-
* `attachments/<id>/<name>`
|
|
673
|
-
*
|
|
674
|
-
*
|
|
675
|
-
*
|
|
676
|
-
* Exported, and re-exported from `@guren/core`, because the layout is not
|
|
677
|
-
* private to this file. `guren check`'s attachments rules judge, from
|
|
678
|
-
* another package, whether uploaded bytes land somewhere the app serves
|
|
679
|
-
* statically — and the ones that reach the objects themselves have to name
|
|
680
|
-
* `<disk root>/attachments` to do it. A restated copy of the prefix over
|
|
681
|
-
* there does not fail loudly when this layout moves (a shard level, a
|
|
682
|
-
* rename): it stops matching, answers "not reachable", and reports an
|
|
683
|
-
* exposed app as safe. A build-failing security rule failing *open*, with
|
|
684
|
-
* nothing going red anywhere. Import this instead of restating it.
|
|
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.
|
|
685
560
|
*/
|
|
686
561
|
const ATTACHMENT_OBJECT_PREFIX = "attachments";
|
|
687
562
|
const DEFAULT_DELIVERY_ROUTE_NAME = "attachments.show";
|
|
688
563
|
/**
|
|
689
|
-
* The inner (presigned) TTL behind a redirect. Fixed
|
|
690
|
-
*
|
|
691
|
-
*
|
|
692
|
-
* outer lifetime silently exceed a driver's presign ceiling (R2 rejects
|
|
693
|
-
* 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).
|
|
694
567
|
*/
|
|
695
568
|
const INNER_PRESIGN_TTL_MS = 3e5;
|
|
696
569
|
const DEFAULT_MAX_PIXELS = 52e6;
|
|
697
570
|
/**
|
|
698
|
-
*
|
|
699
|
-
* the
|
|
700
|
-
*
|
|
701
|
-
* 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).
|
|
702
574
|
*/
|
|
703
575
|
const SNIFF_WINDOW_BYTES = 262144;
|
|
704
576
|
const DEFAULT_MAX_IMAGE_BYTES = 5e7;
|
|
705
577
|
const DEFAULT_URL_EXPIRES_IN = 3e5;
|
|
706
578
|
/**
|
|
707
579
|
* How recently minted a storage prefix may be before `--objects` refuses to
|
|
708
|
-
* touch it. attach() writes the object *before* the row, so a prefix
|
|
709
|
-
*
|
|
710
|
-
* so its age is readable; anything younger than this window is skipped and
|
|
711
|
-
* 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.
|
|
712
582
|
*/
|
|
713
583
|
const PRUNE_OBJECTS_GRACE_MS = 36e5;
|
|
714
584
|
/** Existence lookups are chunked to stay inside every dialect's bind-parameter limits. */
|
|
715
585
|
const PRUNE_LOOKUP_CHUNK = 500;
|
|
716
586
|
/**
|
|
717
|
-
* The spellings
|
|
718
|
-
*
|
|
719
|
-
*
|
|
720
|
-
*
|
|
721
|
-
* "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".
|
|
722
591
|
*/
|
|
723
592
|
function idSpellings(value) {
|
|
724
593
|
const raw = String(value).toLowerCase();
|
|
@@ -777,7 +646,7 @@ var AttachmentEngine = class {
|
|
|
777
646
|
this.urlExpiresIn = options.urlExpiresIn ?? DEFAULT_URL_EXPIRES_IN;
|
|
778
647
|
this.queue = options.queue;
|
|
779
648
|
}
|
|
780
|
-
/** Wired by `configureAttachments()
|
|
649
|
+
/** Wired by `configureAttachments()`, so this module never imports the job. */
|
|
781
650
|
setJobDispatcher(dispatch) {
|
|
782
651
|
this.dispatchJob = dispatch;
|
|
783
652
|
}
|
|
@@ -894,10 +763,9 @@ var AttachmentEngine = class {
|
|
|
894
763
|
return spec;
|
|
895
764
|
}
|
|
896
765
|
/**
|
|
897
|
-
* The three-gate image pipeline (RFC 0013 §6):
|
|
898
|
-
*
|
|
899
|
-
*
|
|
900
|
-
* 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.
|
|
901
769
|
*/
|
|
902
770
|
async inspectImage(spec, collection, source, defer = false) {
|
|
903
771
|
const opaque = {
|
|
@@ -976,10 +844,9 @@ var AttachmentEngine = class {
|
|
|
976
844
|
};
|
|
977
845
|
}
|
|
978
846
|
/**
|
|
979
|
-
* Seed one entry per *declared* variant
|
|
980
|
-
*
|
|
981
|
-
*
|
|
982
|
-
* 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.
|
|
983
850
|
*/
|
|
984
851
|
async buildVariants(spec, id, disk, inspection) {
|
|
985
852
|
const declared = Object.entries(spec.variants ?? {});
|
|
@@ -1018,11 +885,9 @@ var AttachmentEngine = class {
|
|
|
1018
885
|
return variants;
|
|
1019
886
|
}
|
|
1020
887
|
/**
|
|
1021
|
-
* Worker-side completion of a deferred attach
|
|
1022
|
-
*
|
|
1023
|
-
*
|
|
1024
|
-
* and settle every `pending` status record. Safe against races — a row or
|
|
1025
|
-
* 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.
|
|
1026
891
|
*/
|
|
1027
892
|
async generateVariants(payload) {
|
|
1028
893
|
const raw = await this.model.where({ id: payload.attachmentId }).first();
|
|
@@ -1095,11 +960,9 @@ var AttachmentEngine = class {
|
|
|
1095
960
|
await this.settleDeferred({ id: attachmentId }, "failed");
|
|
1096
961
|
}
|
|
1097
962
|
/**
|
|
1098
|
-
* Flip every `pending` variant to a terminal status
|
|
1099
|
-
*
|
|
1100
|
-
*
|
|
1101
|
-
* stale copy whose `pending` entries would otherwise clobber the variants
|
|
1102
|
-
* 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`.
|
|
1103
966
|
*/
|
|
1104
967
|
async settleDeferred(row, status, options = {}) {
|
|
1105
968
|
const fresh = await this.model.where({ id: row.id }).first();
|
|
@@ -1125,9 +988,8 @@ var AttachmentEngine = class {
|
|
|
1125
988
|
await this.model.forceUpdate({ id: row.id }, updates);
|
|
1126
989
|
}
|
|
1127
990
|
/**
|
|
1128
|
-
*
|
|
1129
|
-
*
|
|
1130
|
-
* 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.
|
|
1131
993
|
*/
|
|
1132
994
|
ensureQueueDispatchable() {
|
|
1133
995
|
if (!this.dispatchJob) throw new Error("Attachments queue dispatch is not wired. Call configureAttachments() before attaching.");
|
|
@@ -1144,9 +1006,8 @@ var AttachmentEngine = class {
|
|
|
1144
1006
|
await this.dispatchJob(payload);
|
|
1145
1007
|
}
|
|
1146
1008
|
/**
|
|
1147
|
-
* The single indexed query behind `withAttachments()`.
|
|
1148
|
-
*
|
|
1149
|
-
* 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.
|
|
1150
1011
|
*/
|
|
1151
1012
|
async rowsForPage(model, records, names) {
|
|
1152
1013
|
const ids = records.map((record) => String(record.id));
|
|
@@ -1167,9 +1028,9 @@ var AttachmentEngine = class {
|
|
|
1167
1028
|
return await this.model.where(where);
|
|
1168
1029
|
}
|
|
1169
1030
|
/**
|
|
1170
|
-
* Objects first, rows after (RFC 0013 §8): a crash between the two leaves
|
|
1171
|
-
*
|
|
1172
|
-
*
|
|
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.
|
|
1173
1034
|
*/
|
|
1174
1035
|
async purgeRows(rows) {
|
|
1175
1036
|
for (const row of rows) await this.storage().disk(String(row.disk)).deleteDirectory(`${ATTACHMENT_OBJECT_PREFIX}/${String(row.id)}`);
|
|
@@ -1177,12 +1038,9 @@ var AttachmentEngine = class {
|
|
|
1177
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();
|
|
1178
1039
|
}
|
|
1179
1040
|
/**
|
|
1180
|
-
* The sweeper behind `attachments:prune` (RFC 0013 §8): no DB cascade
|
|
1181
|
-
*
|
|
1182
|
-
*
|
|
1183
|
-
* type resolved through `Model.morphMap` and the record queried and found
|
|
1184
|
-
* missing. Anything unverifiable (type not in the morph map, a failing
|
|
1185
|
-
* 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.
|
|
1186
1044
|
*/
|
|
1187
1045
|
async pruneOrphans(options = {}) {
|
|
1188
1046
|
const rows = await this.model.withoutGlobalScopes();
|
|
@@ -1310,23 +1168,19 @@ var AttachmentEngine = class {
|
|
|
1310
1168
|
return this.deliveryKeys;
|
|
1311
1169
|
}
|
|
1312
1170
|
/**
|
|
1313
|
-
* The one URL policy (RFC 0015 §7): public disks stay on `disk.url()
|
|
1314
|
-
*
|
|
1315
|
-
*
|
|
1316
|
-
* 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()`.
|
|
1317
1174
|
*/
|
|
1318
|
-
/** Whether URLs for this row are minted through the delivery route. */
|
|
1319
1175
|
usesDeliveryRoute(row) {
|
|
1320
1176
|
return this.visibilityOf(row.disk) === "private" && this.delivery !== null && this.routeEnabledFor(row.disk);
|
|
1321
1177
|
}
|
|
1322
1178
|
/**
|
|
1323
|
-
* The one variant-resolution rule (RFC 0013 §7 / RFC 0015 §1), shared by
|
|
1324
|
-
*
|
|
1325
|
-
*
|
|
1326
|
-
*
|
|
1327
|
-
*
|
|
1328
|
-
* `failed`, `unavailable`, or an entry missing entirely on a row
|
|
1329
|
-
* 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.
|
|
1330
1184
|
*/
|
|
1331
1185
|
resolveVariantTarget(row, variant) {
|
|
1332
1186
|
const entry = variant ? row.variants?.[variant] : void 0;
|
|
@@ -1351,11 +1205,9 @@ var AttachmentEngine = class {
|
|
|
1351
1205
|
return disk.url(path);
|
|
1352
1206
|
}
|
|
1353
1207
|
/**
|
|
1354
|
-
* Path-relative
|
|
1355
|
-
*
|
|
1356
|
-
*
|
|
1357
|
-
* resolved at *serve* time, so the same URL starts serving the variant
|
|
1358
|
-
* 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.
|
|
1359
1211
|
*/
|
|
1360
1212
|
signDeliveryUrl(row, options) {
|
|
1361
1213
|
const params = new URLSearchParams();
|
|
@@ -1366,17 +1218,11 @@ var AttachmentEngine = class {
|
|
|
1366
1218
|
return signUrl(`${path}${query}`, this.deliveryKeyring(), { expiresIn: options.expiresIn ?? this.urlExpiresIn });
|
|
1367
1219
|
}
|
|
1368
1220
|
/**
|
|
1369
|
-
* Serve one delivery-route request (RFC 0015 §1)
|
|
1370
|
-
*
|
|
1371
|
-
*
|
|
1372
|
-
*
|
|
1373
|
-
*
|
|
1374
|
-
* Takes the raw web `Request`: every semantic parameter (id, variant,
|
|
1375
|
-
* disposition, expires) is re-read from the *same* `URL`/`URLSearchParams`
|
|
1376
|
-
* parse the signature verification canonicalizes with. A route
|
|
1377
|
-
* framework's own query decoder disagrees with `URLSearchParams` on
|
|
1378
|
-
* malformed percent-encoding, and a parser mismatch there is a signed-URL
|
|
1379
|
-
* 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.
|
|
1380
1226
|
*/
|
|
1381
1227
|
async handleDeliveryRequest(request) {
|
|
1382
1228
|
const notFound = () => new Response("Not Found", {
|
|
@@ -1492,10 +1338,9 @@ function setActiveAttachmentEngine(engine) {
|
|
|
1492
1338
|
activeEngine = engine;
|
|
1493
1339
|
}
|
|
1494
1340
|
/**
|
|
1495
|
-
* The delivery route's prefix and name:
|
|
1496
|
-
*
|
|
1497
|
-
*
|
|
1498
|
-
* 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.
|
|
1499
1344
|
*/
|
|
1500
1345
|
function resolveDeliveryRoute() {
|
|
1501
1346
|
return activeEngine?.deliveryRoute ?? {
|
|
@@ -1525,8 +1370,8 @@ async function normalizeSource(source, nameOverride) {
|
|
|
1525
1370
|
throw new TypeError("attach() accepts bytes only (File, Blob, or Uint8Array). Filesystem path strings are not supported.");
|
|
1526
1371
|
}
|
|
1527
1372
|
/**
|
|
1528
|
-
* Filenames become part of the object key, so they must not steer it: no
|
|
1529
|
-
*
|
|
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.
|
|
1530
1375
|
*/
|
|
1531
1376
|
function sanitizeFilename(name) {
|
|
1532
1377
|
const base = name.split(/[/\\]/).pop() ?? "";
|
|
@@ -1579,10 +1424,9 @@ function normalizeDeliveryPrefix(prefix) {
|
|
|
1579
1424
|
return trimmed;
|
|
1580
1425
|
}
|
|
1581
1426
|
/**
|
|
1582
|
-
* Content types allowed to render inline (RFC 0015 §4). Everything else
|
|
1583
|
-
*
|
|
1584
|
-
* `
|
|
1585
|
-
* 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.
|
|
1586
1430
|
*/
|
|
1587
1431
|
const INLINE_CONTENT_TYPES = /* @__PURE__ */ new Set([
|
|
1588
1432
|
"image/png",
|
|
@@ -1612,10 +1456,9 @@ function ifNoneMatchSatisfied(header, etag) {
|
|
|
1612
1456
|
return trimmed.split(",").some((candidate) => strip(candidate.trim()) === target);
|
|
1613
1457
|
}
|
|
1614
1458
|
/**
|
|
1615
|
-
* Replace lone surrogates so `encodeURIComponent` cannot throw on a stored
|
|
1616
|
-
*
|
|
1617
|
-
*
|
|
1618
|
-
* 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.
|
|
1619
1462
|
*/
|
|
1620
1463
|
function wellFormed(value) {
|
|
1621
1464
|
const candidate = value;
|
|
@@ -1632,13 +1475,10 @@ function encodeRfc5987(value) {
|
|
|
1632
1475
|
return encodeURIComponent(value).replace(/[!'()*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
1633
1476
|
}
|
|
1634
1477
|
/**
|
|
1635
|
-
* A validator over the *resolved object*, not the request: `id + variant`
|
|
1636
|
-
*
|
|
1637
|
-
*
|
|
1638
|
-
*
|
|
1639
|
-
* cases; `updatedAt` covers the one they miss — a same-key rewrite with
|
|
1640
|
-
* different bytes of the same length (queued variant regeneration), which
|
|
1641
|
-
* 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.
|
|
1642
1482
|
*/
|
|
1643
1483
|
function deliveryEtag(path, size, updatedAt) {
|
|
1644
1484
|
return `"${createHash("sha256").update(`${path}:${size ?? ""}:${updatedAt.getTime()}`).digest("base64url").slice(0, 20)}"`;
|
|
@@ -1646,30 +1486,11 @@ function deliveryEtag(path, size, updatedAt) {
|
|
|
1646
1486
|
//#endregion
|
|
1647
1487
|
//#region src/attachments/Attachable.ts
|
|
1648
1488
|
/**
|
|
1649
|
-
* Mixin
|
|
1650
|
-
*
|
|
1651
|
-
* statically
|
|
1652
|
-
* rely on for the model's other surfaces), and its collection names, kinds,
|
|
1653
|
-
* and variant names are inferred as compile-time facts.
|
|
1654
|
-
*
|
|
1655
|
-
* Composes with other mixins the way `SoftDeletes` does.
|
|
1656
|
-
*
|
|
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.
|
|
1657
1492
|
* @example
|
|
1658
|
-
*
|
|
1659
|
-
*
|
|
1660
|
-
* export class Post extends Attachable(defineModel(posts), {
|
|
1661
|
-
* cover: hasOneAttached({
|
|
1662
|
-
* image: 'require',
|
|
1663
|
-
* variants: { thumb: { width: 320 }, og: { width: 1200 } },
|
|
1664
|
-
* }),
|
|
1665
|
-
* images: hasManyAttached({ image: 'require' }),
|
|
1666
|
-
* draftPdf: hasOneAttached(),
|
|
1667
|
-
* }) {}
|
|
1668
|
-
*
|
|
1669
|
-
* // Later, anywhere:
|
|
1670
|
-
* await Post.attach(post.id, 'cover', await this.file('cover'))
|
|
1671
|
-
* const [withCover] = await Post.withAttachments([post], ['cover'])
|
|
1672
|
-
* const url = await Post.attachmentUrl(post, 'cover', { variant: 'thumb' })
|
|
1493
|
+
* class Post extends Attachable(defineModel(posts), { cover: hasOneAttached({ image: 'require' }), images: hasManyAttached() }) {}
|
|
1673
1494
|
*/
|
|
1674
1495
|
function Attachable(Base, declaration) {
|
|
1675
1496
|
const AttachableModel = class extends Base {};
|
|
@@ -1697,30 +1518,19 @@ function Attachable(Base, declaration) {
|
|
|
1697
1518
|
//#endregion
|
|
1698
1519
|
//#region src/attachments/generate-variants-job.ts
|
|
1699
1520
|
/**
|
|
1700
|
-
* Queue job behind `attach(..., { queued: true })` (RFC 0013 Part 2):
|
|
1701
|
-
*
|
|
1702
|
-
* opted in, and generates the declared variants, flipping their `pending`
|
|
1703
|
-
* 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.
|
|
1704
1523
|
*
|
|
1705
|
-
*
|
|
1706
|
-
*
|
|
1707
|
-
* work happens — point it at a runtime with an image processor (Bun with
|
|
1708
|
-
* `Bun.Image`, or a custom `configureAttachments({ processor })`), or every
|
|
1709
|
-
* 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`.
|
|
1710
1526
|
*/
|
|
1711
1527
|
var GenerateVariantsJob = class extends Job {
|
|
1712
|
-
/**
|
|
1713
|
-
* Pinned wire name: queued messages must survive bundler identifier
|
|
1714
|
-
* mangling and any future rename of this class.
|
|
1715
|
-
*/
|
|
1528
|
+
/** Pinned: queued messages must survive identifier mangling and renames. */
|
|
1716
1529
|
static jobName = "GenerateVariantsJob";
|
|
1717
1530
|
async handle(payload) {
|
|
1718
1531
|
await resolveAttachmentEngine("GenerateVariantsJob").generateVariants(payload);
|
|
1719
1532
|
}
|
|
1720
|
-
/**
|
|
1721
|
-
* After the last retry, stop `pending` variants from looking in-flight
|
|
1722
|
-
* forever — their URLs already fall back to the original either way.
|
|
1723
|
-
*/
|
|
1533
|
+
/** After the last retry, stop `pending` variants looking in-flight forever. */
|
|
1724
1534
|
async failed(payload, _error) {
|
|
1725
1535
|
try {
|
|
1726
1536
|
await resolveAttachmentEngine("GenerateVariantsJob").markDeferredFailed(payload.attachmentId);
|
|
@@ -1730,23 +1540,11 @@ var GenerateVariantsJob = class extends Job {
|
|
|
1730
1540
|
//#endregion
|
|
1731
1541
|
//#region src/attachments/configure.ts
|
|
1732
1542
|
/**
|
|
1733
|
-
* Wire the attachments layer, once per app
|
|
1734
|
-
*
|
|
1735
|
-
*
|
|
1736
|
-
* lazily and throw a clear error when it was never called.
|
|
1737
|
-
*
|
|
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.
|
|
1738
1546
|
* @example
|
|
1739
|
-
*
|
|
1740
|
-
* // config/attachments.ts
|
|
1741
|
-
* import { configureAttachments } from '@guren/core'
|
|
1742
|
-
* import { attachments } from '@/db/schema'
|
|
1743
|
-
*
|
|
1744
|
-
* export const { Attachment } = configureAttachments({
|
|
1745
|
-
* table: attachments,
|
|
1746
|
-
* storage: () => container.make('storage'),
|
|
1747
|
-
* disk: 'media',
|
|
1748
|
-
* })
|
|
1749
|
-
* ```
|
|
1547
|
+
* export const { Attachment } = configureAttachments({ table: attachments, storage: () => container.make('storage'), disk: 'media' })
|
|
1750
1548
|
*/
|
|
1751
1549
|
function configureAttachments(options) {
|
|
1752
1550
|
const engine = new AttachmentEngine(options);
|
|
@@ -1758,16 +1556,11 @@ function configureAttachments(options) {
|
|
|
1758
1556
|
//#endregion
|
|
1759
1557
|
//#region src/attachments/delivery.ts
|
|
1760
1558
|
/**
|
|
1761
|
-
* The signed attachment delivery route's controller (RFC 0015 §1).
|
|
1762
|
-
*
|
|
1763
|
-
*
|
|
1764
|
-
*
|
|
1765
|
-
*
|
|
1766
|
-
* Raw on purpose, too: every semantic parameter must be re-read from the
|
|
1767
|
-
* same `URLSearchParams` parse the signature canonicalizes with. Hono's
|
|
1768
|
-
* query decoder disagrees with `URLSearchParams` on malformed
|
|
1769
|
-
* percent-encoding, and a parser mismatch there is a signed-URL rewrite
|
|
1770
|
-
* 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.
|
|
1771
1564
|
*/
|
|
1772
1565
|
var AttachmentDeliveryController = class extends Controller {
|
|
1773
1566
|
async show() {
|
|
@@ -1775,26 +1568,11 @@ var AttachmentDeliveryController = class extends Controller {
|
|
|
1775
1568
|
}
|
|
1776
1569
|
};
|
|
1777
1570
|
/**
|
|
1778
|
-
* Mount the signed delivery route (RFC 0015 §6)
|
|
1779
|
-
* route registrar:
|
|
1780
|
-
*
|
|
1781
|
-
* ```ts
|
|
1782
|
-
* // routes/web.ts
|
|
1783
|
-
* import { registerAttachmentRoutes } from '@guren/core'
|
|
1784
|
-
*
|
|
1785
|
-
* export function registerWebRoutes(router: Router): void {
|
|
1786
|
-
* registerAttachmentRoutes(router)
|
|
1787
|
-
* // …app routes…
|
|
1788
|
-
* }
|
|
1789
|
-
* ```
|
|
1571
|
+
* Mount the signed delivery route (RFC 0015 §6) from the app's route registrar.
|
|
1790
1572
|
*
|
|
1791
|
-
*
|
|
1792
|
-
*
|
|
1793
|
-
*
|
|
1794
|
-
* booted, so a config-dependent throw here would break every inspection
|
|
1795
|
-
* tool. The controller resolves the engine per request instead; at runtime
|
|
1796
|
-
* providers register before routes mount, so the configured prefix and
|
|
1797
|
-
* 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.
|
|
1798
1576
|
*/
|
|
1799
1577
|
function registerAttachmentRoutes(router) {
|
|
1800
1578
|
const { prefix, routeName } = resolveDeliveryRoute();
|
|
@@ -1803,25 +1581,11 @@ function registerAttachmentRoutes(router) {
|
|
|
1803
1581
|
//#endregion
|
|
1804
1582
|
//#region src/attachments/prune-command.ts
|
|
1805
1583
|
/**
|
|
1806
|
-
* Console sweeper for the attachments layer (RFC 0013 §8)
|
|
1807
|
-
* `attachableType`/`attachableId` pair
|
|
1808
|
-
*
|
|
1809
|
-
*
|
|
1810
|
-
*
|
|
1811
|
-
* prefixes left behind by crashed or raced jobs.
|
|
1812
|
-
*
|
|
1813
|
-
* Register it in the app's console kernel:
|
|
1814
|
-
*
|
|
1815
|
-
* ```ts
|
|
1816
|
-
* // src/console.ts
|
|
1817
|
-
* import { AttachmentsPruneCommand } from '@guren/core'
|
|
1818
|
-
* kernel.register(AttachmentsPruneCommand)
|
|
1819
|
-
* ```
|
|
1820
|
-
*
|
|
1821
|
-
* Orphan rows are detected by resolving each `attachableType` through
|
|
1822
|
-
* `Model.morphMap` and querying for the records — set
|
|
1823
|
-
* `Model.morphMap = { Post, User, ... }` for every model that declares
|
|
1824
|
-
* 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.
|
|
1825
1589
|
*/
|
|
1826
1590
|
var AttachmentsPruneCommand = class extends Command {
|
|
1827
1591
|
static signature = "attachments:prune {--objects : Also delete attachments/ storage prefixes that no row references} {--dry-run : Report what would be removed without deleting}";
|
|
@@ -1868,28 +1632,13 @@ function buildSpec(kind, options) {
|
|
|
1868
1632
|
}
|
|
1869
1633
|
/**
|
|
1870
1634
|
* Declare a single-attachment collection (`attach` replaces the previous
|
|
1871
|
-
* attachment, purging its row and objects).
|
|
1872
|
-
*
|
|
1873
|
-
* @example
|
|
1874
|
-
* export class Post extends Attachable(defineModel(posts), {
|
|
1875
|
-
* cover: hasOneAttached({
|
|
1876
|
-
* image: 'require',
|
|
1877
|
-
* variants: { thumb: { width: 320 }, og: { width: 1200 } },
|
|
1878
|
-
* }),
|
|
1879
|
-
* draftPdf: hasOneAttached(), // opaque bytes; width/height/placeholder null
|
|
1880
|
-
* }) {}
|
|
1635
|
+
* attachment, purging its row and objects). Called with no options the bytes
|
|
1636
|
+
* stay opaque: width/height/placeholder are null.
|
|
1881
1637
|
*/
|
|
1882
1638
|
function hasOneAttached(options = {}) {
|
|
1883
1639
|
return buildSpec("one", options);
|
|
1884
1640
|
}
|
|
1885
|
-
/**
|
|
1886
|
-
* Declare a multi-attachment collection (`attach` appends).
|
|
1887
|
-
*
|
|
1888
|
-
* @example
|
|
1889
|
-
* export class Post extends Attachable(defineModel(posts), {
|
|
1890
|
-
* images: hasManyAttached({ image: 'require' }),
|
|
1891
|
-
* }) {}
|
|
1892
|
-
*/
|
|
1641
|
+
/** Declare a multi-attachment collection (`attach` appends). */
|
|
1893
1642
|
function hasManyAttached(options = {}) {
|
|
1894
1643
|
return buildSpec("many", options);
|
|
1895
1644
|
}
|