@guren/core 1.9.0 → 1.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { ApiToken, ApiTokenStore, Command, Job, OAuthStatePayload, OAuthStateStore, SessionData, SessionStore, StorageManager } from "@guren/server";
1
+ import { ApiToken, ApiTokenStore, Command, Controller, Job, OAuthStatePayload, OAuthStateStore, Router, SessionData, SessionStore, StorageManager } from "@guren/server";
2
2
  import { AccessorDefinitions, AccessorFn, AwsDataApiDatabase, AwsDataApiDatabaseOptions, AwsDataApiSeederContext, BelongsToManyRecord, BelongsToManyRelationResult, BelongsToRecord, BelongsToRelationResult, BelongsToRequiredRecord, CastType, D1DatabaseHandle, D1DatabaseOptions, DrizzleAdapter, EagerLoadConstraint, FindManyOptions, GroupCondition, HasManyRecord, HasManyRelationResult, HasManyThroughRecord, HasManyThroughRelationResult, HasOneRecord, HasOneRelationResult, HookCallback, HookName, InferModelInsert, InferModelRecord, MassAssignmentException, MigrationRunSummary, MigrationStatusEntry, Model, Model as Model$1, ModelHooks, ModelNotFoundException, ModelObserver, ModelObserverConstructor, ModelPaginationMeta, ModelQueryOptions, MorphManyRecord, MorphManyRelationResult, MorphToRecord, MorphToRelationResult, MutatorDefinitions, MutatorFn, MySqlDatabase, MySqlDatabaseOptions, MySqlSeederContext, ORMAdapter, ORMAdapterAdvanced, OrderByClause, OrderByInput, OrderDefinition, OrderDirection, PaginateOptions, PaginatedResult, PlainObject, PlainObject as PlainObject$1, PostgresDatabase, PostgresDatabaseOptions, PostgresSeederContext, QueryBuilder, QueryBuilderOptions, ScopeFunction, SeederContext, SeederHandler, SeederRunSummary, SimpleCondition, SoftDeletes, SoftDeletesStatic, SqliteDatabase, SqliteDatabaseOptions, SqliteSeederContext, TransactionHandle, TransactionModelScope, WhereClause, WhereCondition, WhereGroupCallback, WhereOperator, WithRelations, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, runSeeders } from "@guren/orm";
3
3
  export * from "@guren/server";
4
4
  //#region src/api-token-store.d.ts
@@ -469,12 +469,22 @@ interface ConfigureAttachmentsOptions {
469
469
  /** Default disk name for new attachments. */
470
470
  disk: string;
471
471
  /**
472
- * Per-disk visibility: `'public'` disks serve via `disk.url()`, `'private'`
473
- * ones via `disk.temporaryUrl()`. Per disk, not per attachment, because at
474
- * least one driver (R2) has no per-object visibility. Undeclared disks
475
- * default to `'public'`.
472
+ * Per-disk visibility (and, with the object form, how a private disk's
473
+ * bytes are served — RFC 0015 §3). `'public'` disks serve via
474
+ * `disk.url()`; `'private'` ones serve through the signed delivery route
475
+ * when `delivery` is configured, else via `disk.temporaryUrl()`. Per
476
+ * disk, not per attachment, because at least one driver (R2) has no
477
+ * per-object visibility. Undeclared disks default to `'public'`.
476
478
  */
477
- disks?: Record<string, 'public' | 'private'>;
479
+ disks?: Record<string, DiskDeliveryConfig>;
480
+ /**
481
+ * Signed delivery route configuration (RFC 0015). Presence switches
482
+ * private-disk URLs from `disk.temporaryUrl()` to signed route URLs; the
483
+ * route itself is mounted by `registerAttachmentRoutes(router)` in the
484
+ * app's route registrar. Without this option nothing changes — v1
485
+ * behaviour and its documented limitations stand.
486
+ */
487
+ delivery?: DeliveryOptions;
478
488
  /**
479
489
  * Decode cap in pixels (decompression-bomb defense). Header-declared and
480
490
  * decoded dimensions above this are rejected before a pixel buffer is
@@ -528,6 +538,46 @@ interface GenerateVariantsPayload {
528
538
  heic?: HeicPolicy;
529
539
  variants?: Record<string, VariantSpec>;
530
540
  }
541
+ /**
542
+ * How a private disk's bytes are served behind the signed route
543
+ * (RFC 0015 §3):
544
+ * - `'auto'` (default): redirect when the driver positively declares
545
+ * `capabilities.presignedGet`, else proxy. Declared, never probed —
546
+ * `LocalDriver.temporaryUrl()` succeeds with a plain public URL, so a
547
+ * probe would misclassify exactly the disk that must not redirect.
548
+ * - `'redirect'` / `'proxy'`: force one behaviour.
549
+ * - `'direct'`: bypass the route entirely — v1's raw `temporaryUrl()`
550
+ * URLs, for disks that measured the extra hop and want it gone.
551
+ */
552
+ type DeliveryServeMode = 'auto' | 'redirect' | 'proxy' | 'direct';
553
+ type DiskDeliveryConfig = 'public' | 'private' | {
554
+ visibility: 'public' | 'private';
555
+ serve?: DeliveryServeMode;
556
+ };
557
+ /**
558
+ * Per-URL options for `attachmentUrl()`. `disposition` accepts only
559
+ * `'attachment'`: `inline` is already the default outcome for allowlisted
560
+ * types, and the route's allowlist can never be forced to inline — a
561
+ * signed `inline` value would change the URL while doing nothing.
562
+ */
563
+ interface AttachmentUrlOptions {
564
+ expiresIn?: number;
565
+ disposition?: 'attachment';
566
+ }
567
+ interface DeliveryOptions {
568
+ /**
569
+ * Route prefix the delivery URLs live under.
570
+ * @default '/attachments'
571
+ */
572
+ prefix?: string;
573
+ /**
574
+ * Named-route name `registerAttachmentRoutes` registers under.
575
+ * `Router.name()` silently overwrites duplicates, so the default is
576
+ * reserved for the framework.
577
+ * @default 'attachments.show'
578
+ */
579
+ routeName?: string;
580
+ }
531
581
  interface PruneOptions {
532
582
  /** Also delete `attachments/` storage prefixes that no row references. */
533
583
  objects?: boolean;
@@ -629,12 +679,15 @@ interface AttachableStatic<TBase extends typeof Model$1, TDecl extends Declarati
629
679
  id: string | number;
630
680
  }, K extends keyof TDecl & string>(records: readonly TRecord[], names: readonly K[]): Promise<Array<TRecord & AttachedProps<TDecl, K>>>;
631
681
  /**
632
- * URL for a collection's attachment: `disk.url()` on public disks,
633
- * `disk.temporaryUrl()` on private ones. A declared-but-not-ready variant
634
- * falls back to the original's URL; a variant name that was never
635
- * declared throws. Returns `null` when nothing is attached.
682
+ * URL for a collection's attachment: `disk.url()` on public disks; on
683
+ * private ones a signed delivery-route URL when `delivery` is configured
684
+ * (RFC 0015), else `disk.temporaryUrl()`. A declared-but-not-ready
685
+ * variant falls back to the original; a variant name that was never
686
+ * declared throws. `expiresIn` (ms) overrides the configured
687
+ * `urlExpiresIn` for this one URL. Returns `null` when nothing is
688
+ * attached.
636
689
  */
637
- attachmentUrl<K extends keyof TDecl & string>(record: PlainObject$1 | AttachableRecordId, collection: K, options?: {
690
+ attachmentUrl<K extends keyof TDecl & string>(record: PlainObject$1 | AttachableRecordId, collection: K, options?: AttachmentUrlOptions & {
638
691
  variant?: VariantNamesOf<TDecl[NoInfer<K>]>;
639
692
  }): Promise<string | null>;
640
693
  /**
@@ -705,6 +758,46 @@ interface ConfiguredAttachments {
705
758
  */
706
759
  declare function configureAttachments(options: ConfigureAttachmentsOptions): ConfiguredAttachments;
707
760
  //#endregion
761
+ //#region src/attachments/delivery.d.ts
762
+ /**
763
+ * The signed attachment delivery route's controller (RFC 0015 §1). Thin on
764
+ * purpose: it hands the raw `Request` to the engine, which owns
765
+ * verification, variant resolution, and the redirect/proxy split — so the
766
+ * serving contract is testable without HTTP.
767
+ *
768
+ * Raw on purpose, too: every semantic parameter must be re-read from the
769
+ * same `URLSearchParams` parse the signature canonicalizes with. Hono's
770
+ * query decoder disagrees with `URLSearchParams` on malformed
771
+ * percent-encoding, and a parser mismatch there is a signed-URL rewrite
772
+ * primitive.
773
+ */
774
+ declare class AttachmentDeliveryController extends Controller {
775
+ show(): Promise<Response>;
776
+ }
777
+ /**
778
+ * Mount the signed delivery route (RFC 0015 §6) — call it from the app's
779
+ * route registrar:
780
+ *
781
+ * ```ts
782
+ * // routes/web.ts
783
+ * import { registerAttachmentRoutes } from '@guren/core'
784
+ *
785
+ * export function registerWebRoutes(router: Router): void {
786
+ * registerAttachmentRoutes(router)
787
+ * // …app routes…
788
+ * }
789
+ * ```
790
+ *
791
+ * Registration never throws and does not require `configureAttachments()`
792
+ * to have run: route tooling (`routes:types`, `guren check`, audit,
793
+ * OpenAPI) invokes registrars against a bare `Router` with no providers
794
+ * booted, so a config-dependent throw here would break every inspection
795
+ * tool. The controller resolves the engine per request instead; at runtime
796
+ * providers register before routes mount, so the configured prefix and
797
+ * route name are picked up whenever they exist.
798
+ */
799
+ declare function registerAttachmentRoutes(router: Router): void;
800
+ //#endregion
708
801
  //#region src/attachments/prune-command.d.ts
709
802
  /**
710
803
  * Console sweeper for the attachments layer (RFC 0013 §8). The polymorphic
@@ -760,4 +853,4 @@ declare class GenerateVariantsJob extends Job<GenerateVariantsPayload> {
760
853
  failed(payload: GenerateVariantsPayload, _error: Error): Promise<void>;
761
854
  }
762
855
  //#endregion
763
- export { type AccessorDefinitions, type AccessorFn, type AttachOptions, Attachable, type AttachableRecordId, type AttachableStatic, type AttachedCollectionOptions, type AttachmentCollectionSpec, type AttachmentData, type AttachmentRecord, type AttachmentSource, type AttachmentVariantRecord, type AttachmentsDeclaration, AttachmentsPruneCommand, type AwsDataApiDatabase, type AwsDataApiDatabaseOptions, type AwsDataApiSeederContext, type BelongsToManyRecord, type BelongsToManyRelationResult, type BelongsToRecord, type BelongsToRelationResult, type BelongsToRequiredRecord, type CastType, type ConfigureAttachmentsOptions, type ConfiguredAttachments, type D1DatabaseHandle, type D1DatabaseOptions, DatabaseApiTokenStore, type DatabaseApiTokenStoreOptions, DatabaseOAuthStateStore, DatabaseSessionStore, type DatabaseSessionStoreOptions, DrizzleAdapter, type EagerLoadConstraint, type FindManyOptions, GenerateVariantsJob, type GenerateVariantsPayload, type GroupCondition, type HasManyRecord, type HasManyRelationResult, type HasManyThroughRecord, type HasManyThroughRelationResult, type HasOneRecord, type HasOneRelationResult, type HeicPolicy, type HookCallback, type HookName, type ImagePolicy, type ImageProcessor, type InferModelInsert, type InferModelRecord, MassAssignmentException, type MigrationRunSummary, type MigrationStatusEntry, Model, type ModelHooks, ModelNotFoundException, type ModelObserver, type ModelObserverConstructor, type ModelPaginationMeta, type ModelQueryOptions, type MorphManyRecord, type MorphManyRelationResult, type MorphToRecord, type MorphToRelationResult, type MutatorDefinitions, type MutatorFn, type MySqlDatabase, type MySqlDatabaseOptions, type MySqlSeederContext, type ORMAdapter, type ORMAdapterAdvanced, type OrderByClause, type OrderByInput, type OrderDefinition, type OrderDirection, type PaginateOptions, type PaginatedResult, type PlainObject, type PostgresDatabase, type PostgresDatabaseOptions, type PostgresSeederContext, type PruneOptions, type PruneReport, QueryBuilder, type QueryBuilderOptions, type ScopeFunction, type SeederContext, type SeederHandler, type SeederRunSummary, type SimpleCondition, SoftDeletes, type SoftDeletesStatic, type SqliteDatabase, type SqliteDatabaseOptions, type SqliteSeederContext, type TransactionHandle, type TransactionModelScope, type VariantSpec, type WhereClause, type WhereCondition, type WhereGroupCallback, type WhereOperator, type WithRelations, configureAttachments, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, hasManyAttached, hasOneAttached, runSeeders };
856
+ export { type AccessorDefinitions, type AccessorFn, type AttachOptions, Attachable, type AttachableRecordId, type AttachableStatic, type AttachedCollectionOptions, type AttachmentCollectionSpec, type AttachmentData, AttachmentDeliveryController, type AttachmentRecord, type AttachmentSource, type AttachmentUrlOptions, type AttachmentVariantRecord, type AttachmentsDeclaration, AttachmentsPruneCommand, type AwsDataApiDatabase, type AwsDataApiDatabaseOptions, type AwsDataApiSeederContext, type BelongsToManyRecord, type BelongsToManyRelationResult, type BelongsToRecord, type BelongsToRelationResult, type BelongsToRequiredRecord, type CastType, type ConfigureAttachmentsOptions, type ConfiguredAttachments, type D1DatabaseHandle, type D1DatabaseOptions, DatabaseApiTokenStore, type DatabaseApiTokenStoreOptions, DatabaseOAuthStateStore, DatabaseSessionStore, type DatabaseSessionStoreOptions, type DeliveryOptions, type DeliveryServeMode, type DiskDeliveryConfig, DrizzleAdapter, type EagerLoadConstraint, type FindManyOptions, GenerateVariantsJob, type GenerateVariantsPayload, type GroupCondition, type HasManyRecord, type HasManyRelationResult, type HasManyThroughRecord, type HasManyThroughRelationResult, type HasOneRecord, type HasOneRelationResult, type HeicPolicy, type HookCallback, type HookName, type ImagePolicy, type ImageProcessor, type InferModelInsert, type InferModelRecord, MassAssignmentException, type MigrationRunSummary, type MigrationStatusEntry, Model, type ModelHooks, ModelNotFoundException, type ModelObserver, type ModelObserverConstructor, type ModelPaginationMeta, type ModelQueryOptions, type MorphManyRecord, type MorphManyRelationResult, type MorphToRecord, type MorphToRelationResult, type MutatorDefinitions, type MutatorFn, type MySqlDatabase, type MySqlDatabaseOptions, type MySqlSeederContext, type ORMAdapter, type ORMAdapterAdvanced, type OrderByClause, type OrderByInput, type OrderDefinition, type OrderDirection, type PaginateOptions, type PaginatedResult, type PlainObject, type PostgresDatabase, type PostgresDatabaseOptions, type PostgresSeederContext, type PruneOptions, type PruneReport, QueryBuilder, type QueryBuilderOptions, type ScopeFunction, type SeederContext, type SeederHandler, type SeederRunSummary, type SimpleCondition, SoftDeletes, type SoftDeletesStatic, type SqliteDatabase, type SqliteDatabaseOptions, type SqliteSeederContext, type TransactionHandle, type TransactionModelScope, type VariantSpec, type WhereClause, type WhereCondition, type WhereGroupCallback, type WhereOperator, type WithRelations, configureAttachments, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, hasManyAttached, hasOneAttached, registerAttachmentRoutes, runSeeders };
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
- import { Command, HttpException, Job, ValidationException, getQueueDriver, registerJob, setQueueDriver } from "@guren/server";
1
+ import { Command, Controller, HttpException, Job, ValidationException, deriveAppKeyring, getAppKeyringFromEnv, getQueueDriver, registerJob, setQueueDriver, signUrl, verifySignedUrl } from "@guren/server";
2
2
  import { DrizzleAdapter, MassAssignmentException, Model, Model as Model$1, ModelNotFoundException, QueryBuilder, SoftDeletes, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, runSeeders } from "@guren/orm";
3
3
  import { isExpired, toDate, toOptionalExpiry } from "@guren/server/support/expiry";
4
+ import { createHash } from "node:crypto";
4
5
  export * from "@guren/server";
5
6
  //#region src/store-utils.ts
6
7
  /**
@@ -664,8 +665,14 @@ function ulid(now = Date.now()) {
664
665
  for (let i = 0; i < 16; i++) chars += ENCODING[lastRandom[i]];
665
666
  return chars;
666
667
  }
667
- //#endregion
668
- //#region src/attachments/engine.ts
668
+ /**
669
+ * The inner (presigned) TTL behind a redirect. Fixed rather than derived
670
+ * from `urlExpiresIn`: the inner credential is minted per request, so it
671
+ * never needs to outlive one fetch — and deriving it would let a raised
672
+ * outer lifetime silently exceed a driver's presign ceiling (R2 rejects
673
+ * anything over 7 days).
674
+ */
675
+ const INNER_PRESIGN_TTL_MS = 3e5;
669
676
  const DEFAULT_MAX_PIXELS = 52e6;
670
677
  /**
671
678
  * Header sniffing only ever needs the first bytes; capping the window keeps
@@ -722,7 +729,9 @@ var AttachmentEngine = class {
722
729
  model;
723
730
  storage;
724
731
  defaultDisk;
725
- diskVisibility;
732
+ diskDelivery;
733
+ delivery;
734
+ deliveryKeys = null;
726
735
  maxPixels;
727
736
  maxImageBytes;
728
737
  processor;
@@ -737,7 +746,11 @@ var AttachmentEngine = class {
737
746
  this.model.morphTo("attachable", "attachable");
738
747
  this.storage = options.storage;
739
748
  this.defaultDisk = options.disk;
740
- this.diskVisibility = options.disks ?? {};
749
+ this.diskDelivery = normalizeDiskDelivery(options.disks ?? {});
750
+ this.delivery = options.delivery ? {
751
+ prefix: normalizeDeliveryPrefix(options.delivery.prefix ?? "/attachments"),
752
+ routeName: options.delivery.routeName ?? "attachments.show"
753
+ } : null;
741
754
  this.maxPixels = options.maxPixels ?? DEFAULT_MAX_PIXELS;
742
755
  this.maxImageBytes = options.maxImageBytes ?? DEFAULT_MAX_IMAGE_BYTES;
743
756
  this.processor = options.processor !== void 0 ? options.processor : resolveDefaultImageProcessor(this.maxPixels);
@@ -845,11 +858,11 @@ var AttachmentEngine = class {
845
858
  const raw = spec.kind === "one" ? rows[rows.length - 1] : rows[0];
846
859
  if (!raw) return null;
847
860
  const row = this.toRecord(raw);
848
- if (variant !== void 0) {
849
- const entry = row.variants?.[variant];
850
- if (entry?.status === "ready" && entry.path) return this.urlFor(row.disk, entry.path);
851
- }
852
- return this.urlFor(row.disk, row.path);
861
+ return this.urlForRow(row, {
862
+ variant,
863
+ expiresIn: options.expiresIn,
864
+ disposition: options.disposition
865
+ });
853
866
  }
854
867
  async purgeAttachments(model, recordId) {
855
868
  const rows = await this.rowsFor(model, recordId, {});
@@ -1221,7 +1234,7 @@ var AttachmentEngine = class {
1221
1234
  const diskNames = /* @__PURE__ */ new Set([
1222
1235
  ...registered,
1223
1236
  this.defaultDisk,
1224
- ...Object.keys(this.diskVisibility),
1237
+ ...Object.keys(this.diskDelivery),
1225
1238
  ...rows.map((row) => String(row.disk))
1226
1239
  ]);
1227
1240
  for (const diskName of diskNames) {
@@ -1258,27 +1271,165 @@ var AttachmentEngine = class {
1258
1271
  }
1259
1272
  }
1260
1273
  visibilityOf(diskName) {
1261
- return this.diskVisibility[diskName] ?? "public";
1274
+ return this.diskDelivery[diskName]?.visibility ?? "public";
1262
1275
  }
1263
- async urlFor(diskName, path) {
1264
- const disk = this.storage().disk(diskName);
1265
- if (this.visibilityOf(diskName) === "private") return disk.temporaryUrl(path, new Date(Date.now() + this.urlExpiresIn));
1276
+ serveModeFor(diskName) {
1277
+ return this.diskDelivery[diskName]?.serve ?? "auto";
1278
+ }
1279
+ /** Whether URL minting for this disk goes through the delivery route (`serve: 'direct'` opts out). */
1280
+ routeEnabledFor(diskName) {
1281
+ return this.diskDelivery[diskName]?.route ?? true;
1282
+ }
1283
+ /** The normalized delivery route config, for `resolveDeliveryRoute()`. */
1284
+ get deliveryRoute() {
1285
+ return this.delivery;
1286
+ }
1287
+ deliveryKeyring() {
1288
+ if (!this.deliveryKeys) this.deliveryKeys = deriveAppKeyring(getAppKeyringFromEnv(), "attachment-delivery");
1289
+ return this.deliveryKeys;
1290
+ }
1291
+ /**
1292
+ * The one URL policy (RFC 0015 §7): public disks stay on `disk.url()`
1293
+ * untouched; private disks hand out signed route URLs when `delivery` is
1294
+ * configured (and the disk did not opt out with `serve: 'direct'`), else
1295
+ * the v1 `temporaryUrl()` behaviour with its documented limitations.
1296
+ */
1297
+ /** Whether URLs for this row are minted through the delivery route. */
1298
+ usesDeliveryRoute(row) {
1299
+ return this.visibilityOf(row.disk) === "private" && this.delivery !== null && this.routeEnabledFor(row.disk);
1300
+ }
1301
+ /**
1302
+ * The one variant-resolution rule (RFC 0013 §7 / RFC 0015 §1), shared by
1303
+ * URL minting, resource payloads, and the delivery route: a `ready`
1304
+ * entry resolves to the variant's key and format-derived MIME type
1305
+ * (variants are transcoded — serving them under the original's type with
1306
+ * `nosniff` would be self-sabotage); anything else — `pending`,
1307
+ * `failed`, `unavailable`, or an entry missing entirely on a row
1308
+ * attached before the variant was declared — falls back to the original.
1309
+ */
1310
+ resolveVariantTarget(row, variant) {
1311
+ const entry = variant ? row.variants?.[variant] : void 0;
1312
+ if (entry?.status === "ready" && entry.path) return {
1313
+ path: entry.path,
1314
+ contentType: entry.format && IMAGE_MIME[entry.format] || "application/octet-stream",
1315
+ size: entry.size ?? null,
1316
+ ready: true
1317
+ };
1318
+ return {
1319
+ path: row.path,
1320
+ contentType: row.contentType,
1321
+ size: row.size,
1322
+ ready: false
1323
+ };
1324
+ }
1325
+ async urlForRow(row, options) {
1326
+ if (this.usesDeliveryRoute(row)) return this.signDeliveryUrl(row, options);
1327
+ const { path } = this.resolveVariantTarget(row, options.variant);
1328
+ const disk = this.storage().disk(row.disk);
1329
+ if (this.visibilityOf(row.disk) === "private") return disk.temporaryUrl(path, new Date(Date.now() + (options.expiresIn ?? this.urlExpiresIn)));
1266
1330
  return disk.url(path);
1267
1331
  }
1332
+ /**
1333
+ * Path-relative on purpose: the `Host` header never participates in URL
1334
+ * construction (RFC 0015 T6); emails prefix the app's canonical URL
1335
+ * themselves. The variant rides as a signed query parameter and is
1336
+ * resolved at *serve* time, so the same URL starts serving the variant
1337
+ * once generation completes.
1338
+ */
1339
+ signDeliveryUrl(row, options) {
1340
+ const params = new URLSearchParams();
1341
+ if (options.variant) params.set("variant", options.variant);
1342
+ if (options.disposition) params.set("disposition", options.disposition);
1343
+ const query = params.size > 0 ? `?${params}` : "";
1344
+ const path = `${this.delivery.prefix}/${encodeURIComponent(row.id)}/${encodeURIComponent(wellFormed(row.name))}`;
1345
+ return signUrl(`${path}${query}`, this.deliveryKeyring(), { expiresIn: options.expiresIn ?? this.urlExpiresIn });
1346
+ }
1347
+ /**
1348
+ * Serve one delivery-route request (RFC 0015 §1): verify → load →
1349
+ * resolve → redirect or proxy. Everything before the row load is one
1350
+ * HMAC per keyring key, and every failure is the same 404 — invalid
1351
+ * signature, expired URL, and unknown id must be indistinguishable.
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.
1359
+ */
1360
+ async handleDeliveryRequest(request) {
1361
+ const notFound = () => new Response("Not Found", {
1362
+ status: 404,
1363
+ headers: { "X-Content-Type-Options": "nosniff" }
1364
+ });
1365
+ if (!this.delivery) return notFound();
1366
+ const url = new URL(request.url);
1367
+ const signedPart = `${url.pathname}${url.search}`;
1368
+ if (!verifySignedUrl(signedPart, this.deliveryKeyring(), { requireExpiration: true })) return notFound();
1369
+ let id;
1370
+ try {
1371
+ id = decodeURIComponent(url.pathname.slice(this.delivery.prefix.length + 1).split("/")[0] ?? "");
1372
+ } catch {
1373
+ return notFound();
1374
+ }
1375
+ const variant = url.searchParams.get("variant") ?? void 0;
1376
+ const forceAttachment = url.searchParams.get("disposition") === "attachment";
1377
+ const raw = await this.model.find(id);
1378
+ if (!raw) return notFound();
1379
+ const row = this.toRecord(raw);
1380
+ const target = this.resolveVariantTarget(row, variant);
1381
+ const remainingMs = Math.max(0, Number(url.searchParams.get("expires")) * 1e3 - Date.now());
1382
+ const disposition = contentDispositionFor(target.contentType, forceAttachment, wellFormed(row.name));
1383
+ const disk = this.storage().disk(row.disk);
1384
+ const mode = this.serveModeFor(row.disk);
1385
+ const canPresign = disk.capabilities?.presignedGet === true;
1386
+ if (mode === "redirect" && !canPresign) warnRedirectDowngradeOnce(row.disk);
1387
+ if (canPresign && mode !== "proxy") {
1388
+ const inner = new Date(Date.now() + Math.min(remainingMs, INNER_PRESIGN_TTL_MS));
1389
+ const location = await disk.temporaryUrl(target.path, inner, {
1390
+ responseContentDisposition: disposition,
1391
+ responseContentType: target.contentType
1392
+ });
1393
+ return new Response(null, {
1394
+ status: 302,
1395
+ headers: {
1396
+ Location: location,
1397
+ "Cache-Control": "no-store",
1398
+ "Referrer-Policy": "no-referrer"
1399
+ }
1400
+ });
1401
+ }
1402
+ const etag = deliveryEtag(target.path, target.size, row.updatedAt);
1403
+ const headers = {
1404
+ "Content-Type": target.contentType,
1405
+ "Content-Disposition": disposition,
1406
+ "X-Content-Type-Options": "nosniff",
1407
+ "Content-Security-Policy": "sandbox",
1408
+ "Referrer-Policy": "no-referrer",
1409
+ "Cache-Control": `private, max-age=${Math.floor(remainingMs / 1e3)}`,
1410
+ ETag: etag
1411
+ };
1412
+ if (ifNoneMatchSatisfied(request.headers.get("if-none-match"), etag)) return new Response(null, {
1413
+ status: 304,
1414
+ headers
1415
+ });
1416
+ if (target.size != null) headers["Content-Length"] = String(target.size);
1417
+ if (request.method === "HEAD") return await disk.exists(target.path) ? new Response(null, { headers }) : notFound();
1418
+ const body = disk.getStream ? await disk.getStream(target.path) : await disk.get(target.path);
1419
+ if (!body) return notFound();
1420
+ return new Response(body, { headers });
1421
+ }
1268
1422
  async toData(row, spec) {
1269
- const originalUrl = await this.urlFor(row.disk, row.path);
1423
+ const viaRoute = this.usesDeliveryRoute(row);
1424
+ const originalUrl = await this.urlForRow(row, {});
1270
1425
  const variants = {};
1271
1426
  for (const name of Object.keys(spec.variants ?? {})) {
1427
+ const target = this.resolveVariantTarget(row, name);
1272
1428
  const entry = row.variants?.[name];
1273
- if (entry?.status === "ready" && entry.path) variants[name] = {
1274
- url: await this.urlFor(row.disk, entry.path),
1275
- width: entry.width ?? null,
1276
- height: entry.height ?? null
1277
- };
1278
- else variants[name] = {
1279
- url: originalUrl,
1280
- width: null,
1281
- height: null
1429
+ variants[name] = {
1430
+ url: viaRoute || target.ready ? await this.urlForRow(row, { variant: name }) : originalUrl,
1431
+ width: target.ready ? entry?.width ?? null : null,
1432
+ height: target.ready ? entry?.height ?? null : null
1282
1433
  };
1283
1434
  }
1284
1435
  return {
@@ -1319,6 +1470,18 @@ let activeEngine = null;
1319
1470
  function setActiveAttachmentEngine(engine) {
1320
1471
  activeEngine = engine;
1321
1472
  }
1473
+ /**
1474
+ * The delivery route's prefix and name: the configured values when an
1475
+ * engine is active, the defaults otherwise (bootless route tooling invokes
1476
+ * registrars with no providers booted). The one place the defaults are
1477
+ * applied outside the engine constructor.
1478
+ */
1479
+ function resolveDeliveryRoute() {
1480
+ return activeEngine?.deliveryRoute ?? {
1481
+ prefix: "/attachments",
1482
+ routeName: "attachments.show"
1483
+ };
1484
+ }
1322
1485
  function resolveAttachmentEngine(caller) {
1323
1486
  if (!activeEngine) throw new Error(`${caller} requires attachments to be configured. Call configureAttachments({ table, storage, disk }) once at boot (e.g. in config/attachments.ts) before using the attachment statics.`);
1324
1487
  return activeEngine;
@@ -1345,7 +1508,8 @@ async function normalizeSource(source, nameOverride) {
1345
1508
  * path separators, no control characters, never empty or dot-only.
1346
1509
  */
1347
1510
  function sanitizeFilename(name) {
1348
- const cleaned = (name.split(/[/\\]/).pop() ?? "").replace(/[\u0000-\u001f\u007f]/g, "").trim().slice(0, 200);
1511
+ const base = name.split(/[/\\]/).pop() ?? "";
1512
+ const cleaned = Array.from(base.replace(/[\u0000-\u001f\u007f]/g, "").trim()).slice(0, 200).join("");
1349
1513
  if (cleaned === "" || /^\.+$/.test(cleaned)) return "file";
1350
1514
  return cleaned;
1351
1515
  }
@@ -1369,6 +1533,95 @@ function sortById(rows) {
1369
1533
  return 0;
1370
1534
  });
1371
1535
  }
1536
+ function normalizeDiskDelivery(disks) {
1537
+ const normalized = {};
1538
+ for (const [name, config] of Object.entries(disks)) if (typeof config === "string") normalized[name] = {
1539
+ visibility: config,
1540
+ route: true,
1541
+ serve: "auto"
1542
+ };
1543
+ else {
1544
+ const serve = config.serve ?? "auto";
1545
+ normalized[name] = {
1546
+ visibility: config.visibility,
1547
+ route: serve !== "direct",
1548
+ serve: serve === "direct" ? "auto" : serve
1549
+ };
1550
+ }
1551
+ return normalized;
1552
+ }
1553
+ function normalizeDeliveryPrefix(prefix) {
1554
+ let end = prefix.length;
1555
+ while (end > 0 && prefix.charCodeAt(end - 1) === 47) end--;
1556
+ const trimmed = prefix.slice(0, end);
1557
+ if (!trimmed.startsWith("/") || trimmed.startsWith("//") || /[?#\s]/.test(trimmed)) throw new Error(`configureAttachments: delivery.prefix must be a plain absolute path ('/attachments'-shaped), got '${prefix}'.`);
1558
+ return trimmed;
1559
+ }
1560
+ /**
1561
+ * Content types allowed to render inline (RFC 0015 §4). Everything else —
1562
+ * notably image/svg+xml and text/html — is forced to `attachment`: the
1563
+ * `disposition` parameter can force `attachment` for a listed type, but
1564
+ * nothing can force `inline` for an unlisted one.
1565
+ */
1566
+ const INLINE_CONTENT_TYPES = /* @__PURE__ */ new Set([
1567
+ "image/png",
1568
+ "image/jpeg",
1569
+ "image/gif",
1570
+ "image/webp",
1571
+ "image/avif",
1572
+ "application/pdf",
1573
+ "video/mp4",
1574
+ "audio/mpeg",
1575
+ "text/plain"
1576
+ ]);
1577
+ function contentDispositionFor(contentType, forceAttachment, filename) {
1578
+ return `${forceAttachment || !INLINE_CONTENT_TYPES.has(contentType) ? "attachment" : "inline"}; filename="${filename.replace(/[^\x20-\x7e]/g, "_").replace(/["\\]/g, "_")}"; filename*=UTF-8''${encodeRfc5987(filename)}`;
1579
+ }
1580
+ /**
1581
+ * `If-None-Match` per RFC 9110: a comma-separated list of entity tags (or
1582
+ * `*`), compared weakly — a `W/` prefix on either side does not break the
1583
+ * match.
1584
+ */
1585
+ function ifNoneMatchSatisfied(header, etag) {
1586
+ if (!header) return false;
1587
+ const trimmed = header.trim();
1588
+ if (trimmed === "*") return true;
1589
+ const strip = (value) => value.startsWith("W/") ? value.slice(2) : value;
1590
+ const target = strip(etag);
1591
+ return trimmed.split(",").some((candidate) => strip(candidate.trim()) === target);
1592
+ }
1593
+ /**
1594
+ * Replace lone surrogates so `encodeURIComponent` cannot throw on a stored
1595
+ * name whose truncation once split a pair. `String#toWellFormed` is
1596
+ * ES2024 (Bun, Node ≥ 20); older runtimes fall through — their names were
1597
+ * produced by the same truncation and are overwhelmingly well-formed.
1598
+ */
1599
+ function wellFormed(value) {
1600
+ const candidate = value;
1601
+ return typeof candidate.toWellFormed === "function" ? candidate.toWellFormed() : value;
1602
+ }
1603
+ const warnedRedirectDowngrades = /* @__PURE__ */ new Set();
1604
+ function warnRedirectDowngradeOnce(diskName) {
1605
+ if (warnedRedirectDowngrades.has(diskName)) return;
1606
+ warnedRedirectDowngrades.add(diskName);
1607
+ console.warn(`[guren] Attachments disk '${diskName}' is configured serve: 'redirect' but its driver does not declare capabilities.presignedGet — redirecting would hand out whatever temporaryUrl() returns, which on a local disk is the plain public URL. Serving via proxy instead; fix the disk's serve mode or use a presign-capable driver.`);
1608
+ }
1609
+ /** RFC 5987 attr-char escaping: encodeURIComponent leaves !'()* unescaped. */
1610
+ function encodeRfc5987(value) {
1611
+ return encodeURIComponent(value).replace(/[!'()*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);
1612
+ }
1613
+ /**
1614
+ * A validator over the *resolved object*, not the request: `id + variant`
1615
+ * is not a byte identity (a pending variant resolves to original bytes
1616
+ * today and variant bytes tomorrow; queued HEIC conversion rewrites the
1617
+ * path under the same row id). Resolved key + size move in both of those
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.
1621
+ */
1622
+ function deliveryEtag(path, size, updatedAt) {
1623
+ return `"${createHash("sha256").update(`${path}:${size ?? ""}:${updatedAt.getTime()}`).digest("base64url").slice(0, 20)}"`;
1624
+ }
1372
1625
  //#endregion
1373
1626
  //#region src/attachments/Attachable.ts
1374
1627
  /**
@@ -1482,6 +1735,51 @@ function configureAttachments(options) {
1482
1735
  return { Attachment: engine.model };
1483
1736
  }
1484
1737
  //#endregion
1738
+ //#region src/attachments/delivery.ts
1739
+ /**
1740
+ * The signed attachment delivery route's controller (RFC 0015 §1). Thin on
1741
+ * purpose: it hands the raw `Request` to the engine, which owns
1742
+ * verification, variant resolution, and the redirect/proxy split — so the
1743
+ * serving contract is testable without HTTP.
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.
1750
+ */
1751
+ var AttachmentDeliveryController = class extends Controller {
1752
+ async show() {
1753
+ return resolveAttachmentEngine("The attachments delivery route").handleDeliveryRequest(this.ctx.req.raw);
1754
+ }
1755
+ };
1756
+ /**
1757
+ * Mount the signed delivery route (RFC 0015 §6) — call it from the app's
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
+ * ```
1769
+ *
1770
+ * Registration never throws and does not require `configureAttachments()`
1771
+ * to have run: route tooling (`routes:types`, `guren check`, audit,
1772
+ * OpenAPI) invokes registrars against a bare `Router` with no providers
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.
1777
+ */
1778
+ function registerAttachmentRoutes(router) {
1779
+ const { prefix, routeName } = resolveDeliveryRoute();
1780
+ router.get(`${prefix}/:id/:filename`, [AttachmentDeliveryController, "show"]).name(routeName);
1781
+ }
1782
+ //#endregion
1485
1783
  //#region src/attachments/prune-command.ts
1486
1784
  /**
1487
1785
  * Console sweeper for the attachments layer (RFC 0013 §8). The polymorphic
@@ -1575,4 +1873,4 @@ function hasManyAttached(options = {}) {
1575
1873
  return buildSpec("many", options);
1576
1874
  }
1577
1875
  //#endregion
1578
- export { Attachable, AttachmentsPruneCommand, DatabaseApiTokenStore, DatabaseOAuthStateStore, DatabaseSessionStore, DrizzleAdapter, GenerateVariantsJob, MassAssignmentException, Model, ModelNotFoundException, QueryBuilder, SoftDeletes, configureAttachments, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, hasManyAttached, hasOneAttached, runSeeders };
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 };
@@ -77,6 +77,30 @@ interface ClientAssetEnv {
77
77
  * @param label Platform name for the warning message, e.g. `'Lambda build'`.
78
78
  */
79
79
  declare function resolveClientAssetEnv(publicDir: string, clientEntryKey: string, label: string): ClientAssetEnv;
80
+ /**
81
+ * The client build manifest as JSON text, for the deploy targets' runtime
82
+ * manifest injection (`GUREN_VITE_MANIFEST`): `viteAsset()` resolves
83
+ * content-page asset URLs from the client manifest at render time, and a
84
+ * bundled function or worker has no `public/assets/manifest.json` to read.
85
+ * How the payload reaches the runtime is per-plugin (a generated-entry
86
+ * assignment, a bundler `define`); *what* the payload is, is this.
87
+ *
88
+ * Separate from `resolveClientAssetEnv` because that helper answers only for
89
+ * the client *entry*: a content-page app can have a manifest of CSS build
90
+ * inputs and no `resources/js/app.tsx` at all, and its `viteAsset()` calls
91
+ * still need the whole manifest.
92
+ *
93
+ * The payload is trimmed to the fields the runtime rule reads — `file` and
94
+ * `css` per entry (`getManifestFile`/`getManifestCss` in @guren/server's
95
+ * vite-manifest.ts) — because it ships inside executable code: a large app's
96
+ * manifest is dominated by per-chunk `imports`/`dynamicImports` graph
97
+ * metadata nothing consumes, and Workers caps bundle size. Trimming also
98
+ * validates the shape at build time, so a parseable-but-not-a-manifest file
99
+ * (`null`, an array) is reported as "no manifest" here instead of being baked
100
+ * in to fail at first render. String and array entry forms pass through
101
+ * untrimmed — the runtime accepts them, and the two paths must not diverge.
102
+ */
103
+ declare function clientManifestJson(publicDir: string): string | undefined;
80
104
  /**
81
105
  * Absolute path of the built SSR entry chunk, or undefined when the app has no
82
106
  * SSR build. Verifying that the chunk actually exports a renderer is left to
@@ -332,4 +356,4 @@ declare function renderDevOnlyStub(module: DevOnlyModule, message: string): stri
332
356
  */
333
357
  declare const MCP_SDK_SUBPATH_PREFIX = "@modelcontextprotocol/sdk/";
334
358
  //#endregion
335
- export { ClientAssetEnv, DATABASE_CONFIG_CANDIDATES, DATABASE_DIALECTS, DATABASE_FACTORIES, DEV_ONLY_MODULES, DatabaseDialect, DatabaseDialectDetection, DevOnlyModule, DevOnlyModuleKind, DevOnlySpecifier, MCP_SDK_SUBPATH_PREFIX, Manifest, ManifestEntry, PathLike, SQL_CLIENT_MODULES, SqlClientModule, SqlClientSpecifier, UnusedSqlClient, assertOutputDirOutsideRoot, detectDatabaseDialects, importSpecifier, parseDatabaseDialects, readManifest, renderDevOnlyStub, resetOutputDir, resolveClientAssetEnv, resolvePathLike, resolveSsrEntryFile, ssrRuntimePaths, stageStaticAssets, unusedSqlClients };
359
+ export { ClientAssetEnv, DATABASE_CONFIG_CANDIDATES, DATABASE_DIALECTS, DATABASE_FACTORIES, DEV_ONLY_MODULES, DatabaseDialect, DatabaseDialectDetection, DevOnlyModule, DevOnlyModuleKind, DevOnlySpecifier, MCP_SDK_SUBPATH_PREFIX, Manifest, ManifestEntry, PathLike, SQL_CLIENT_MODULES, SqlClientModule, SqlClientSpecifier, UnusedSqlClient, assertOutputDirOutsideRoot, clientManifestJson, detectDatabaseDialects, importSpecifier, parseDatabaseDialects, readManifest, renderDevOnlyStub, resetOutputDir, resolveClientAssetEnv, resolvePathLike, resolveSsrEntryFile, ssrRuntimePaths, stageStaticAssets, unusedSqlClients };
@@ -59,11 +59,29 @@ function readManifest(...paths) {
59
59
  }
60
60
  }
61
61
  }
62
- /** The two layouts `readManifest` accepts, in preference order. */
62
+ /**
63
+ * The two layouts `readManifest` accepts, in preference order: `.vite/` first,
64
+ * because Vite >= 5 writes it there and a flat `manifest.json` beside it is
65
+ * most likely stale output of an older config. `@guren/server`'s runtime
66
+ * lookup (`clientManifestCandidates` in `http/vite-manifest.ts`) prefers the
67
+ * same layout — the orders must agree, or an app with both files resolves
68
+ * different asset versions locally than after a deploy; the server's
69
+ * `tests/http/vite-manifest.test.ts` pins the agreement (the rule cannot be
70
+ * shared as code, since this module imports nothing beyond node builtins).
71
+ */
63
72
  function manifestPaths(dir) {
64
73
  return [resolve(dir, ".vite/manifest.json"), resolve(dir, "manifest.json")];
65
74
  }
66
75
  /**
76
+ * The one statement of where an app's *client* manifest lives: under
77
+ * `<publicDir>/assets`, in either Vite layout. `resolveClientAssetEnv` and
78
+ * `clientManifestJson` both answer from this read — stating the composition
79
+ * twice is how the two would come to look in different places.
80
+ */
81
+ function readClientManifest(publicDir) {
82
+ return readManifest(...manifestPaths(resolve(publicDir, "assets")))?.manifest;
83
+ }
84
+ /**
67
85
  * Resolve symlinks in the parts of `path` that exist, keeping the trailing
68
86
  * components that do not. `realpathSync` throws on a path that is not there
69
87
  * yet, and an output directory usually is not on a first build.
@@ -155,7 +173,7 @@ function importSpecifier(fromDir, target, label) {
155
173
  * @param label Platform name for the warning message, e.g. `'Lambda build'`.
156
174
  */
157
175
  function resolveClientAssetEnv(publicDir, clientEntryKey, label) {
158
- const entry = (readManifest(...manifestPaths(resolve(publicDir, "assets")))?.manifest)?.[clientEntryKey];
176
+ const entry = readClientManifest(publicDir)?.[clientEntryKey];
159
177
  if (!entry?.file) {
160
178
  console.warn(`${label}: no client manifest entry for "${clientEntryKey}"; GUREN_INERTIA_ENTRY will not be set.`);
161
179
  return {};
@@ -166,6 +184,47 @@ function resolveClientAssetEnv(publicDir, clientEntryKey, label) {
166
184
  };
167
185
  }
168
186
  /**
187
+ * The client build manifest as JSON text, for the deploy targets' runtime
188
+ * manifest injection (`GUREN_VITE_MANIFEST`): `viteAsset()` resolves
189
+ * content-page asset URLs from the client manifest at render time, and a
190
+ * bundled function or worker has no `public/assets/manifest.json` to read.
191
+ * How the payload reaches the runtime is per-plugin (a generated-entry
192
+ * assignment, a bundler `define`); *what* the payload is, is this.
193
+ *
194
+ * Separate from `resolveClientAssetEnv` because that helper answers only for
195
+ * the client *entry*: a content-page app can have a manifest of CSS build
196
+ * inputs and no `resources/js/app.tsx` at all, and its `viteAsset()` calls
197
+ * still need the whole manifest.
198
+ *
199
+ * The payload is trimmed to the fields the runtime rule reads — `file` and
200
+ * `css` per entry (`getManifestFile`/`getManifestCss` in @guren/server's
201
+ * vite-manifest.ts) — because it ships inside executable code: a large app's
202
+ * manifest is dominated by per-chunk `imports`/`dynamicImports` graph
203
+ * metadata nothing consumes, and Workers caps bundle size. Trimming also
204
+ * validates the shape at build time, so a parseable-but-not-a-manifest file
205
+ * (`null`, an array) is reported as "no manifest" here instead of being baked
206
+ * in to fail at first render. String and array entry forms pass through
207
+ * untrimmed — the runtime accepts them, and the two paths must not diverge.
208
+ */
209
+ function clientManifestJson(publicDir) {
210
+ const manifest = readClientManifest(publicDir);
211
+ if (manifest === void 0) return;
212
+ if (typeof manifest !== "object" || manifest === null || Array.isArray(manifest)) return;
213
+ const trimmed = {};
214
+ for (const [key, entry] of Object.entries(manifest)) {
215
+ if (typeof entry === "string" || Array.isArray(entry)) {
216
+ trimmed[key] = entry;
217
+ continue;
218
+ }
219
+ if (typeof entry !== "object" || entry === null) continue;
220
+ const kept = {};
221
+ if (typeof entry.file === "string") kept.file = entry.file;
222
+ if (Array.isArray(entry.css) && entry.css.length > 0) kept.css = entry.css;
223
+ if (kept.file !== void 0 || kept.css !== void 0) trimmed[key] = kept;
224
+ }
225
+ return JSON.stringify(trimmed);
226
+ }
227
+ /**
169
228
  * Absolute path of the built SSR entry chunk, or undefined when the app has no
170
229
  * SSR build. Verifying that the chunk actually exports a renderer is left to
171
230
  * the caller: the platforms disagree on whether importing it during a build is
@@ -498,4 +557,4 @@ function renderDevOnlyStub(module, message) {
498
557
  */
499
558
  const MCP_SDK_SUBPATH_PREFIX = "@modelcontextprotocol/sdk/";
500
559
  //#endregion
501
- export { DATABASE_CONFIG_CANDIDATES, DATABASE_DIALECTS, DATABASE_FACTORIES, DEV_ONLY_MODULES, MCP_SDK_SUBPATH_PREFIX, SQL_CLIENT_MODULES, assertOutputDirOutsideRoot, detectDatabaseDialects, importSpecifier, parseDatabaseDialects, readManifest, renderDevOnlyStub, resetOutputDir, resolveClientAssetEnv, resolvePathLike, resolveSsrEntryFile, ssrRuntimePaths, stageStaticAssets, unusedSqlClients };
560
+ export { DATABASE_CONFIG_CANDIDATES, DATABASE_DIALECTS, DATABASE_FACTORIES, DEV_ONLY_MODULES, MCP_SDK_SUBPATH_PREFIX, SQL_CLIENT_MODULES, assertOutputDirOutsideRoot, clientManifestJson, detectDatabaseDialects, importSpecifier, parseDatabaseDialects, readManifest, renderDevOnlyStub, resetOutputDir, resolveClientAssetEnv, resolvePathLike, resolveSsrEntryFile, ssrRuntimePaths, stageStaticAssets, unusedSqlClients };
@@ -0,0 +1 @@
1
+ export * from "@guren/server/jsx-dev-runtime";
@@ -0,0 +1,2 @@
1
+ export * from "@guren/server/jsx-dev-runtime";
2
+ export {};
@@ -0,0 +1 @@
1
+ export * from "@guren/server/jsx-runtime";
@@ -0,0 +1,2 @@
1
+ export * from "@guren/server/jsx-runtime";
2
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/core",
3
- "version": "1.9.0",
3
+ "version": "1.11.0",
4
4
  "type": "module",
5
5
  "sideEffects": [
6
6
  "./src/bin.ts",
@@ -52,6 +52,14 @@
52
52
  "./internal/zod-compat": {
53
53
  "types": "./dist/internal/zod-compat.d.ts",
54
54
  "default": "./dist/internal/zod-compat.js"
55
+ },
56
+ "./jsx-runtime": {
57
+ "types": "./dist/jsx-runtime.d.ts",
58
+ "default": "./dist/jsx-runtime.js"
59
+ },
60
+ "./jsx-dev-runtime": {
61
+ "types": "./dist/jsx-dev-runtime.d.ts",
62
+ "default": "./dist/jsx-dev-runtime.js"
55
63
  }
56
64
  },
57
65
  "bin": {
@@ -64,9 +72,9 @@
64
72
  "typecheck": "tsc --noEmit"
65
73
  },
66
74
  "dependencies": {
67
- "@guren/cli": "^2.10.0",
75
+ "@guren/cli": "^2.12.0",
68
76
  "@guren/orm": "^2.6.1",
69
- "@guren/server": "^2.11.0"
77
+ "@guren/server": "^2.13.0"
70
78
  },
71
79
  "devDependencies": {
72
80
  "@types/node": "^20.14.10",