@guren/core 1.20.1 → 1.22.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,5 +1,5 @@
1
- import { ApiToken, ApiTokenStore, AppEnv, Command, ConfigDefinition, Container, Controller, Job, OAuthStatePayload, OAuthStateStore, QueueManager, Router, SessionConfig, SessionData, SessionManager, SessionStore, StorageManager } from "@guren/server";
2
- import { AccessorDefinitions, AccessorFn, AggregateFunction, AvgValue, AwsDataApiDatabase, AwsDataApiDatabaseOptions, AwsDataApiSeederContext, BelongsToManyRecord, BelongsToManyRelationResult, BelongsToRecord, BelongsToRelationResult, BelongsToRequiredRecord, CastType, ConnectionContext, ConnectionContext as ConnectionContext$1, D1DatabaseHandle, D1DatabaseOptions, DrizzleAdapter, DrizzleSelectQuery, 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, SumValue, TransactionHandle, TransactionModelScope, WhereClause, WhereCondition, WhereGroupCallback, WhereOperator, WithRelations, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, runSeeders } from "@guren/orm";
1
+ import { ApiToken, ApiTokenStore, AppEnv, AttachmentsDescription, Command, ConfigDefinition, Container, Controller, Job, OAuthStatePayload, OAuthStateStore, QueueManager, Router, SessionConfig, SessionData, SessionManager, SessionStore, StorageManager } from "@guren/server";
2
+ import { AccessorDefinitions, AccessorFn, AggregateFunction, AvgValue, AwsDataApiDatabase, AwsDataApiDatabaseOptions, AwsDataApiSeederContext, BelongsToManyRecord, BelongsToManyRelationResult, BelongsToRecord, BelongsToRelationResult, BelongsToRequiredRecord, CastType, ConnectionContext, ConnectionContext as ConnectionContext$1, D1DatabaseHandle, D1DatabaseOptions, DrizzleAdapter, DrizzleSelectQuery, 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, ModelSetOptions, 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, SumValue, 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
5
5
  interface DatabaseApiTokenStoreOptions {
@@ -13,13 +13,15 @@ interface DatabaseApiTokenStoreOptions {
13
13
  abilitiesMode?: 'json' | 'text';
14
14
  }
15
15
  /**
16
- * Database-backed API token store built on the Guren ORM. Pass the Drizzle
17
- * table for your `api_tokens` schema; column property names must match the
18
- * {@link ApiToken} fields. Configure the ORM before use.
16
+ * Database-backed API token store built on the Guren ORM. Pass the Drizzle table
17
+ * for your `api_tokens` schema; column property names must match the {@link ApiToken}
18
+ * fields, and each timestamp is written as its column declares (timestamp mode,
19
+ * text as ISO, integer as epoch ms). Configure the ORM before use.
19
20
  * @example `new DatabaseApiTokenStore(apiTokens)`
20
21
  */
21
22
  declare class DatabaseApiTokenStore implements ApiTokenStore {
22
23
  private readonly model;
24
+ private readonly table;
23
25
  private readonly abilitiesMode;
24
26
  constructor(table: unknown, options?: DatabaseApiTokenStoreOptions);
25
27
  store(token: ApiToken): Promise<void>;
@@ -33,6 +35,7 @@ declare class DatabaseApiTokenStore implements ApiTokenStore {
33
35
  * them; this only keeps the table small.
34
36
  */
35
37
  deleteExpired(now?: Date): Promise<void>;
38
+ private timestamp;
36
39
  private deserialize;
37
40
  }
38
41
  //#endregion
@@ -51,11 +54,12 @@ interface DatabaseSessionStoreOptions {
51
54
  * Database-backed session store built on the Guren ORM, the serverless default
52
55
  * (no Redis on Lambda, Vercel, or Workers; reads are strongly consistent). Column
53
56
  * property names of the `sessions` table must be `id` (text primary key), `data`,
54
- * and `expiresAt`. Values must be JSON-serializable, unlike `MemorySessionStore`:
55
- * Dates return as ISO strings, `undefined` properties drop, `bigint` throws.
57
+ * and `expiresAt`, written as its column declares (timestamp mode, text or integer).
58
+ * Values must be JSON-serializable, unlike `MemorySessionStore`: Dates return as ISO strings, `undefined` drops, `bigint` throws.
56
59
  */
57
60
  declare class DatabaseSessionStore implements SessionStore {
58
61
  private readonly model;
62
+ private readonly table;
59
63
  private readonly dataMode;
60
64
  constructor(table: unknown, options?: DatabaseSessionStoreOptions);
61
65
  read(id: string): Promise<SessionData | undefined>;
@@ -74,6 +78,7 @@ declare class DatabaseSessionStore implements SessionStore {
74
78
  deleteExpired(now?: Date): Promise<void>;
75
79
  private deserialize;
76
80
  private expiryDate;
81
+ private expiresAt;
77
82
  }
78
83
  //#endregion
79
84
  //#region src/session-manager.d.ts
@@ -159,13 +164,14 @@ declare function defineDatabaseConfig(database: ConfigurableDatabase, options?:
159
164
  //#region src/oauth-state-store.d.ts
160
165
  /**
161
166
  * Database-backed OAuth state store built on the Guren ORM, for serverless, where
162
- * authorize and callback can land on different instances. Column property names
163
- * of the `oauth_states` table must be `stateHash` (text primary key), `provider`,
164
- * `redirectTo`, `expiresAt`, and `binding` (else `authorize({ bindTo })` states come back unbound).
167
+ * authorize and callback can land on different instances. Column property names of
168
+ * the `oauth_states` table must be `stateHash` (text primary key), `provider`, `redirectTo`,
169
+ * `expiresAt` (written as its column declares) and `binding` (else `authorize({ bindTo })` states come back unbound).
165
170
  * @example `new DatabaseOAuthStateStore(oauthStates)`
166
171
  */
167
172
  declare class DatabaseOAuthStateStore implements OAuthStateStore {
168
173
  private readonly model;
174
+ private readonly table;
169
175
  constructor(table: unknown);
170
176
  store(stateHash: string, payload: OAuthStatePayload): Promise<void>;
171
177
  find(stateHash: string): Promise<OAuthStatePayload | null>;
@@ -399,6 +405,8 @@ declare module '@guren/server' {
399
405
  }
400
406
  }
401
407
  interface ConfigureAttachmentsOptions {
408
+ /** Shared exclusion for hasOne writes across processes; run callback while holding the key's lock. */
409
+ withCollectionLock?: <T>(key: string, callback: () => Promise<T>) => Promise<T>;
402
410
  /**
403
411
  * The app's Drizzle `attachments` table. Column property names must match the
404
412
  * documented contract: `id`, `attachableType`, `attachableId`, `collection`,
@@ -554,6 +562,8 @@ type QueueDispatcher = Pick<QueueManager, 'driver' | 'dispatch'>;
554
562
  type JobDispatcher = (payload: GenerateVariantsPayload, queue: QueueDispatcher | undefined) => Promise<unknown>;
555
563
  declare class AttachmentEngine {
556
564
  readonly model: typeof Model$1;
565
+ private readonly collectionLocks;
566
+ private readonly sharedCollectionLock;
557
567
  private readonly storageFactory;
558
568
  private container?;
559
569
  private readonly defaultDisk;
@@ -566,6 +576,7 @@ declare class AttachmentEngine {
566
576
  private readonly urlExpiresIn;
567
577
  private readonly queue?;
568
578
  private dispatchJob;
579
+ private readonly table;
569
580
  constructor(options: ConfigureAttachmentsOptions);
570
581
  /**
571
582
  * Bind this engine on `container` as `attachments` *and* resolve its storage
@@ -576,7 +587,9 @@ declare class AttachmentEngine {
576
587
  /** Wired by `configureAttachments()`, so this module never imports the job. */
577
588
  setJobDispatcher(dispatch: JobDispatcher): void;
578
589
  private storage;
590
+ private withCollectionWrite;
579
591
  attach(model: typeof Model$1, declaration: AttachmentsDeclaration, recordId: string | number, collection: string, source: AttachmentSource, options?: AttachOptions): Promise<AttachmentRecord>;
592
+ private attachUnlocked;
580
593
  detach(model: typeof Model$1, declaration: AttachmentsDeclaration, recordId: string | number, collection: string, attachmentId?: string): Promise<void>;
581
594
  withAttachments(model: typeof Model$1, declaration: AttachmentsDeclaration, records: readonly PlainObject$1[], names: readonly string[]): Promise<PlainObject$1[]>;
582
595
  attachmentUrl(model: typeof Model$1, declaration: AttachmentsDeclaration, recordOrId: PlainObject$1 | string | number, collection: string, options?: AttachmentUrlOptions & {
@@ -647,6 +660,11 @@ declare class AttachmentEngine {
647
660
  prefix: string;
648
661
  routeName: string;
649
662
  } | null;
663
+ /**
664
+ * The configuration as RFC 0026's manifest reports it, touching no disk. The
665
+ * manifest adds `delivery.mounted`, which only the route registry knows.
666
+ */
667
+ describe(): AttachmentsDescription;
650
668
  private deliveryKeyring;
651
669
  /**
652
670
  * The one URL policy (RFC 0015 §7): public disks stay on `disk.url()`; private
@@ -680,6 +698,13 @@ declare class AttachmentEngine {
680
698
  private toData;
681
699
  private toRecord;
682
700
  }
701
+ /**
702
+ * The engine an `Attachable` static would use, described (RFC 0026 §1): the
703
+ * default application's registered binding, else the one `configureAttachments()`
704
+ * built last. A deferred provider is not activated to find out, so an engine it
705
+ * binds at its first resolution is not the one described.
706
+ */
707
+ declare function describeActiveAttachmentEngine(): AttachmentsDescription;
683
708
  //#endregion
684
709
  //#region src/attachments/Attachable.d.ts
685
710
  /** A record id accepted by the attachment statics (int and uuid/text PKs). */
@@ -841,4 +866,4 @@ declare class GenerateVariantsJob extends Job<GenerateVariantsPayload> {
841
866
  failed(payload: GenerateVariantsPayload, _error: Error): Promise<void>;
842
867
  }
843
868
  //#endregion
844
- export { ATTACHMENT_OBJECT_PREFIX, type AccessorDefinitions, type AccessorFn, type AggregateFunction, type AttachOptions, Attachable, type AttachableRecordId, type AttachableStatic, type AttachedCollectionOptions, type AttachmentCollectionSpec, type AttachmentData, AttachmentDeliveryController, type AttachmentEngine, type AttachmentRecord, type AttachmentSource, type AttachmentUrlOptions, type AttachmentVariantRecord, type AttachmentsDeclaration, AttachmentsPruneCommand, type AvgValue, type AwsDataApiDatabase, type AwsDataApiDatabaseOptions, type AwsDataApiSeederContext, type BelongsToManyRecord, type BelongsToManyRelationResult, type BelongsToRecord, type BelongsToRelationResult, type BelongsToRequiredRecord, type CastType, type ConfigureAttachmentsOptions, type ConfiguredAttachments, type ConnectionContext, type D1DatabaseHandle, type D1DatabaseOptions, DEFAULT_DELIVERY_ROUTE_NAME, DatabaseApiTokenStore, type DatabaseApiTokenStoreOptions, DatabaseOAuthStateStore, type DatabaseSessionDriverOptions, DatabaseSessionStore, type DatabaseSessionStoreOptions, type DeliveryOptions, type DeliveryServeMode, type DiskDeliveryConfig, DrizzleAdapter, type DrizzleSelectQuery, 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, OAuthStatesPruneCommand, 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, SessionsPruneCommand, type SimpleCondition, SoftDeletes, type SoftDeletesStatic, type SqliteDatabase, type SqliteDatabaseOptions, type SqliteSeederContext, type SumValue, type TransactionHandle, type TransactionModelScope, type VariantSpec, type WhereClause, type WhereCondition, type WhereGroupCallback, type WhereOperator, type WithRelations, configureAttachments, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSessionManager, createSqliteDatabase, defineDatabaseConfig, defineModel, defineSeeder, defineSessionConfig, hasManyAttached, hasOneAttached, registerAttachmentRoutes, registerDatabaseSessionDriver, runSeeders };
869
+ export { ATTACHMENT_OBJECT_PREFIX, type AccessorDefinitions, type AccessorFn, type AggregateFunction, type AttachOptions, Attachable, type AttachableRecordId, type AttachableStatic, type AttachedCollectionOptions, type AttachmentCollectionSpec, type AttachmentData, AttachmentDeliveryController, type AttachmentEngine, type AttachmentRecord, type AttachmentSource, type AttachmentUrlOptions, type AttachmentVariantRecord, type AttachmentsDeclaration, AttachmentsPruneCommand, type AvgValue, type AwsDataApiDatabase, type AwsDataApiDatabaseOptions, type AwsDataApiSeederContext, type BelongsToManyRecord, type BelongsToManyRelationResult, type BelongsToRecord, type BelongsToRelationResult, type BelongsToRequiredRecord, type CastType, type ConfigureAttachmentsOptions, type ConfiguredAttachments, type ConnectionContext, type D1DatabaseHandle, type D1DatabaseOptions, DEFAULT_DELIVERY_ROUTE_NAME, DatabaseApiTokenStore, type DatabaseApiTokenStoreOptions, DatabaseOAuthStateStore, type DatabaseSessionDriverOptions, DatabaseSessionStore, type DatabaseSessionStoreOptions, type DeliveryOptions, type DeliveryServeMode, type DiskDeliveryConfig, DrizzleAdapter, type DrizzleSelectQuery, 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 ModelSetOptions, type MorphManyRecord, type MorphManyRelationResult, type MorphToRecord, type MorphToRelationResult, type MutatorDefinitions, type MutatorFn, type MySqlDatabase, type MySqlDatabaseOptions, type MySqlSeederContext, OAuthStatesPruneCommand, 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, SessionsPruneCommand, type SimpleCondition, SoftDeletes, type SoftDeletesStatic, type SqliteDatabase, type SqliteDatabaseOptions, type SqliteSeederContext, type SumValue, type TransactionHandle, type TransactionModelScope, type VariantSpec, type WhereClause, type WhereCondition, type WhereGroupCallback, type WhereOperator, type WithRelations, configureAttachments, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSessionManager, createSqliteDatabase, defineDatabaseConfig, defineModel, defineSeeder, defineSessionConfig, describeActiveAttachmentEngine, hasManyAttached, hasOneAttached, registerAttachmentRoutes, registerDatabaseSessionDriver, runSeeders };
package/dist/index.js CHANGED
@@ -17,18 +17,42 @@ function decodeJsonColumn(value, fallback) {
17
17
  }
18
18
  return value ?? fallback;
19
19
  }
20
+ /** `timestamp with time zone`, `timestamp(3)`, `datetime`, `date`, `time`: every driver binds a Date to these itself. */
21
+ const TEMPORAL_SQL_TYPE = /^(?:timestamp|datetime|date|time)\b/i;
22
+ /**
23
+ * A Date as the column declares it: temporal columns take the Date (drizzle and
24
+ * the pg/mysql drivers encode it), text takes the ISO string the SQLite scaffold's
25
+ * `$defaultFn` writes, integer takes epoch ms (`timestamp_ms`, what `toDate` reads).
26
+ * bun:sqlite cannot bind a Date, and a where clause binding one matches no row.
27
+ * `dataType` is split the way the ORM's `columnKind()` splits it (1.x: `number int53`).
28
+ */
29
+ function toColumnValue(table, field, value) {
30
+ if (!(value instanceof Date)) return value;
31
+ const column = table?.[field];
32
+ if (!column || typeof column !== "object") return value;
33
+ const sqlType = typeof column.getSQLType === "function" ? column.getSQLType() : "";
34
+ if (TEMPORAL_SQL_TYPE.test(sqlType)) return value;
35
+ const kind = typeof column.dataType === "string" ? column.dataType.split(" ")[0] : "";
36
+ if (kind === "string") return value.toISOString();
37
+ if (kind === "number") return value.getTime();
38
+ if (kind === "bigint") return BigInt(value.getTime());
39
+ return value;
40
+ }
20
41
  //#endregion
21
42
  //#region src/api-token-store.ts
22
43
  /**
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.
44
+ * Database-backed API token store built on the Guren ORM. Pass the Drizzle table
45
+ * for your `api_tokens` schema; column property names must match the {@link ApiToken}
46
+ * fields, and each timestamp is written as its column declares (timestamp mode,
47
+ * text as ISO, integer as epoch ms). Configure the ORM before use.
26
48
  * @example `new DatabaseApiTokenStore(apiTokens)`
27
49
  */
28
50
  var DatabaseApiTokenStore = class {
29
51
  model;
52
+ table;
30
53
  abilitiesMode;
31
54
  constructor(table, options = {}) {
55
+ this.table = table;
32
56
  this.abilitiesMode = options.abilitiesMode ?? "json";
33
57
  this.model = class ApiTokenModel extends Model$1 {
34
58
  static table = table;
@@ -37,7 +61,10 @@ var DatabaseApiTokenStore = class {
37
61
  async store(token) {
38
62
  await this.model.forceCreate({
39
63
  ...token,
40
- abilities: this.abilitiesMode === "text" ? JSON.stringify(token.abilities) : token.abilities
64
+ abilities: this.abilitiesMode === "text" ? JSON.stringify(token.abilities) : token.abilities,
65
+ lastUsedAt: this.timestamp("lastUsedAt", token.lastUsedAt),
66
+ expiresAt: this.timestamp("expiresAt", token.expiresAt),
67
+ createdAt: this.timestamp("createdAt", token.createdAt)
41
68
  });
42
69
  }
43
70
  async findByHashedToken(hashedToken) {
@@ -54,14 +81,17 @@ var DatabaseApiTokenStore = class {
54
81
  await this.model.where({ userId }).delete();
55
82
  }
56
83
  async updateLastUsed(id, timestamp) {
57
- await this.model.forceUpdate({ id }, { lastUsedAt: timestamp });
84
+ await this.model.forceUpdate({ id }, { lastUsedAt: this.timestamp("lastUsedAt", timestamp) });
58
85
  }
59
86
  /**
60
87
  * Delete tokens whose expiration has passed. `verifyApiToken` already rejects
61
88
  * them; this only keeps the table small.
62
89
  */
63
90
  async deleteExpired(now = /* @__PURE__ */ new Date()) {
64
- await this.model.where("expiresAt", "<", now).delete();
91
+ await this.model.where("expiresAt", "<", this.timestamp("expiresAt", now)).delete();
92
+ }
93
+ timestamp(field, value) {
94
+ return toColumnValue(this.table, field, value);
65
95
  }
66
96
  deserialize(record) {
67
97
  const abilities = decodeJsonColumn(record.abilities, []);
@@ -83,13 +113,15 @@ var DatabaseApiTokenStore = class {
83
113
  * Database-backed session store built on the Guren ORM, the serverless default
84
114
  * (no Redis on Lambda, Vercel, or Workers; reads are strongly consistent). Column
85
115
  * 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.
116
+ * and `expiresAt`, written as its column declares (timestamp mode, text or integer).
117
+ * Values must be JSON-serializable, unlike `MemorySessionStore`: Dates return as ISO strings, `undefined` drops, `bigint` throws.
88
118
  */
89
119
  var DatabaseSessionStore = class {
90
120
  model;
121
+ table;
91
122
  dataMode;
92
123
  constructor(table, options = {}) {
124
+ this.table = table;
93
125
  this.dataMode = options.dataMode ?? "json";
94
126
  this.model = class SessionModel extends Model$1 {
95
127
  static table = table;
@@ -135,20 +167,23 @@ var DatabaseSessionStore = class {
135
167
  * `SessionStore.touch` contract.
136
168
  */
137
169
  async touch(id, ttlSeconds) {
138
- await this.model.where({ id }).where("expiresAt", ">", /* @__PURE__ */ new Date()).forceUpdate({ expiresAt: this.expiryDate(ttlSeconds) });
170
+ await this.model.where({ id }).where("expiresAt", ">", this.expiresAt(/* @__PURE__ */ new Date())).forceUpdate({ expiresAt: this.expiryDate(ttlSeconds) });
139
171
  }
140
172
  /**
141
173
  * Delete sessions whose expiration has passed. `read` already treats them as
142
174
  * missing; this only keeps the table small.
143
175
  */
144
176
  async deleteExpired(now = /* @__PURE__ */ new Date()) {
145
- await this.model.where("expiresAt", "<=", now).delete();
177
+ await this.model.where("expiresAt", "<=", this.expiresAt(now)).delete();
146
178
  }
147
179
  deserialize(record) {
148
180
  return decodeJsonColumn(record.data, {});
149
181
  }
150
182
  expiryDate(ttlSeconds) {
151
- return new Date(Date.now() + ttlSeconds * 1e3);
183
+ return this.expiresAt(new Date(Date.now() + ttlSeconds * 1e3));
184
+ }
185
+ expiresAt(value) {
186
+ return toColumnValue(this.table, "expiresAt", value);
152
187
  }
153
188
  };
154
189
  //#endregion
@@ -229,14 +264,16 @@ function defineDatabaseConfig(database, options = {}) {
229
264
  //#region src/oauth-state-store.ts
230
265
  /**
231
266
  * Database-backed OAuth state store built on the Guren ORM, for serverless, where
232
- * authorize and callback can land on different instances. Column property names
233
- * of the `oauth_states` table must be `stateHash` (text primary key), `provider`,
234
- * `redirectTo`, `expiresAt`, and `binding` (else `authorize({ bindTo })` states come back unbound).
267
+ * authorize and callback can land on different instances. Column property names of
268
+ * the `oauth_states` table must be `stateHash` (text primary key), `provider`, `redirectTo`,
269
+ * `expiresAt` (written as its column declares) and `binding` (else `authorize({ bindTo })` states come back unbound).
235
270
  * @example `new DatabaseOAuthStateStore(oauthStates)`
236
271
  */
237
272
  var DatabaseOAuthStateStore = class {
238
273
  model;
274
+ table;
239
275
  constructor(table) {
276
+ this.table = table;
240
277
  this.model = class OAuthStateModel extends Model$1 {
241
278
  static table = table;
242
279
  };
@@ -246,7 +283,7 @@ var DatabaseOAuthStateStore = class {
246
283
  stateHash,
247
284
  provider: payload.provider,
248
285
  redirectTo: payload.redirectTo ?? null,
249
- expiresAt: payload.expiresAt,
286
+ expiresAt: toColumnValue(this.table, "expiresAt", payload.expiresAt),
250
287
  binding: payload.binding ?? null
251
288
  });
252
289
  }
@@ -290,7 +327,7 @@ var DatabaseOAuthStateStore = class {
290
327
  * only keeps the table small.
291
328
  */
292
329
  async deleteExpired(now = /* @__PURE__ */ new Date()) {
293
- await this.model.where("expiresAt", "<=", now).delete();
330
+ await this.model.where("expiresAt", "<=", toColumnValue(this.table, "expiresAt", now)).delete();
294
331
  }
295
332
  };
296
333
  /** Build the public payload from a live (non-expired) row. */
@@ -730,8 +767,11 @@ function unavailableContainer() {
730
767
  has: unavailable
731
768
  };
732
769
  }
770
+ const collectionWrites = /* @__PURE__ */ new WeakMap();
733
771
  var AttachmentEngine = class {
734
772
  model;
773
+ collectionLocks;
774
+ sharedCollectionLock;
735
775
  storageFactory;
736
776
  container;
737
777
  defaultDisk;
@@ -744,8 +784,14 @@ var AttachmentEngine = class {
744
784
  urlExpiresIn;
745
785
  queue;
746
786
  dispatchJob = null;
787
+ table;
747
788
  constructor(options) {
748
789
  const table = options.table;
790
+ this.table = table;
791
+ const locks = collectionWrites.get(table) ?? /* @__PURE__ */ new Map();
792
+ collectionWrites.set(table, locks);
793
+ this.collectionLocks = locks;
794
+ this.sharedCollectionLock = options.withCollectionLock ?? ((_key, callback) => callback());
749
795
  this.model = class AttachmentModel extends Model$1 {
750
796
  static table = table;
751
797
  };
@@ -779,8 +825,26 @@ var AttachmentEngine = class {
779
825
  storage() {
780
826
  return this.storageFactory(this.container ?? ambientContainer() ?? unavailableContainer());
781
827
  }
828
+ async withCollectionWrite(model, recordId, collection, callback) {
829
+ const key = JSON.stringify([
830
+ model.name,
831
+ String(recordId),
832
+ collection
833
+ ]);
834
+ const operation = (this.collectionLocks.get(key) ?? Promise.resolve()).catch(() => void 0).then(() => this.sharedCollectionLock(key, callback));
835
+ this.collectionLocks.set(key, operation);
836
+ try {
837
+ return await operation;
838
+ } finally {
839
+ if (this.collectionLocks.get(key) === operation) this.collectionLocks.delete(key);
840
+ }
841
+ }
782
842
  async attach(model, declaration, recordId, collection, source, options = {}) {
783
843
  const spec = this.specFor(model, declaration, collection);
844
+ const write = () => this.attachUnlocked(model, spec, recordId, collection, source, options);
845
+ return spec.kind === "one" ? this.withCollectionWrite(model, recordId, collection, write) : write();
846
+ }
847
+ async attachUnlocked(model, spec, recordId, collection, source, options) {
784
848
  const normalized = await normalizeSource(source, options.name);
785
849
  const queued = options.queued === true;
786
850
  if (queued) this.queueManager();
@@ -1293,6 +1357,20 @@ var AttachmentEngine = class {
1293
1357
  get deliveryRoute() {
1294
1358
  return this.delivery;
1295
1359
  }
1360
+ /**
1361
+ * The configuration as RFC 0026's manifest reports it, touching no disk. The
1362
+ * manifest adds `delivery.mounted`, which only the route registry knows.
1363
+ */
1364
+ describe() {
1365
+ const table = drizzleTableName(this.table);
1366
+ return {
1367
+ configured: true,
1368
+ ...table === void 0 ? {} : { table },
1369
+ disk: this.defaultDisk,
1370
+ disks: Object.fromEntries(Object.entries(this.diskDelivery).map(([name, disk]) => [name, { ...disk }])),
1371
+ ...this.delivery ? { delivery: { ...this.delivery } } : {}
1372
+ };
1373
+ }
1296
1374
  deliveryKeyring() {
1297
1375
  if (!this.deliveryKeys) this.deliveryKeys = deriveAppKeyring(getAppKeyringFromEnv(), "attachment-delivery");
1298
1376
  return this.deliveryKeys;
@@ -1483,6 +1561,23 @@ function resolveDeliveryRoute() {
1483
1561
  routeName: "attachments.show"
1484
1562
  };
1485
1563
  }
1564
+ /**
1565
+ * The engine an `Attachable` static would use, described (RFC 0026 §1): the
1566
+ * default application's registered binding, else the one `configureAttachments()`
1567
+ * built last. A deferred provider is not activated to find out, so an engine it
1568
+ * binds at its first resolution is not the one described.
1569
+ */
1570
+ function describeActiveAttachmentEngine() {
1571
+ const container = ambientContainer();
1572
+ const engine = (container?.has("attachments") ? container.make("attachments") : void 0) ?? activeEngine;
1573
+ return engine ? engine.describe() : { configured: false };
1574
+ }
1575
+ /** drizzle's `getTableName()` through its registry symbol; `session-manager.ts` in server reads it the same way. */
1576
+ function drizzleTableName(table) {
1577
+ if (!table || typeof table !== "object") return void 0;
1578
+ const name = table[Symbol.for("drizzle:Name")];
1579
+ return typeof name === "string" ? name : void 0;
1580
+ }
1486
1581
  function resolveAttachmentEngine(caller) {
1487
1582
  const engine = ambientBinding("attachments") ?? activeEngine;
1488
1583
  if (!engine) 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.`);
@@ -1786,4 +1881,4 @@ function hasManyAttached(options = {}) {
1786
1881
  return buildSpec("many", options);
1787
1882
  }
1788
1883
  //#endregion
1789
- export { ATTACHMENT_OBJECT_PREFIX, Attachable, AttachmentDeliveryController, AttachmentsPruneCommand, DEFAULT_DELIVERY_ROUTE_NAME, DatabaseApiTokenStore, DatabaseOAuthStateStore, DatabaseSessionStore, DrizzleAdapter, GenerateVariantsJob, MassAssignmentException, Model, ModelNotFoundException, OAuthStatesPruneCommand, QueryBuilder, SessionsPruneCommand, SoftDeletes, configureAttachments, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSessionManager, createSqliteDatabase, defineDatabaseConfig, defineModel, defineSeeder, defineSessionConfig, hasManyAttached, hasOneAttached, registerAttachmentRoutes, registerDatabaseSessionDriver, runSeeders };
1884
+ export { ATTACHMENT_OBJECT_PREFIX, Attachable, AttachmentDeliveryController, AttachmentsPruneCommand, DEFAULT_DELIVERY_ROUTE_NAME, DatabaseApiTokenStore, DatabaseOAuthStateStore, DatabaseSessionStore, DrizzleAdapter, GenerateVariantsJob, MassAssignmentException, Model, ModelNotFoundException, OAuthStatesPruneCommand, QueryBuilder, SessionsPruneCommand, SoftDeletes, configureAttachments, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSessionManager, createSqliteDatabase, defineDatabaseConfig, defineModel, defineSeeder, defineSessionConfig, describeActiveAttachmentEngine, hasManyAttached, hasOneAttached, registerAttachmentRoutes, registerDatabaseSessionDriver, runSeeders };
@@ -1,12 +1,6 @@
1
+ import { AGENTS_CONFIG_FILE } from "@guren/server/internal/app-conventions";
1
2
  //#region src/internal/deploy-build.d.ts
2
3
  type PathLike = string | URL;
3
- /**
4
- * The agent registry (RFC 0017 §3), at a path neither side may choose. Shared
5
- * rather than spelled twice: `guren check` reads it as source and a deploy build
6
- * reads it to generate the worker's Durable Object exports, so a second spelling
7
- * is a deploy exporting no agents while the check calls them registered.
8
- */
9
- declare const AGENTS_CONFIG_FILE = "config/agents.ts";
10
4
  type ManifestEntry = {
11
5
  file?: string;
12
6
  css?: string[];
@@ -221,10 +215,10 @@ interface SqlClientModule extends DevOnlyModule {
221
215
  }
222
216
  /**
223
217
  * Client libraries the Postgres, MySQL and Aurora Data API factories reach for.
224
- * Apart from `DEV_ONLY_MODULES` because their fate is per platform: unreachable on
225
- * Workers (D1 only), load-bearing on Lambda/Vercel, which stub only undeclared
226
- * dialects (`unusedSqlClients`). Stub the client *and* drizzle's entry importing it,
227
- * or a D1 app fails on `Could not resolve "postgres"`; export names mirror drizzle-orm's.
218
+ * Apart from `DEV_ONLY_MODULES`: unreachable on Workers (D1 only), load-bearing on
219
+ * Lambda/Vercel, which stub only undeclared dialects (`unusedSqlClients`). Stub the
220
+ * client *and* drizzle's entry importing it, or a D1 app fails to resolve `postgres`.
221
+ * `mysql2/promise` lists its whole public API, not just drizzle's `createPool` (#507).
228
222
  */
229
223
  declare const SQL_CLIENT_MODULES: readonly [{
230
224
  readonly specifier: 'postgres';
@@ -242,7 +236,7 @@ declare const SQL_CLIENT_MODULES: readonly [{
242
236
  readonly specifier: 'mysql2/promise';
243
237
  readonly kind: 'sql-driver';
244
238
  readonly dialect: 'mysql';
245
- readonly exportNames: readonly ["createPool"];
239
+ readonly exportNames: readonly ["createConnection", "createPool", "createPoolCluster", "escape", "escapeId", "format", "raw", "Connection", "PoolConnection", "PromisePool", "PromiseConnection", "PromisePoolConnection", "Types", "Charsets", "CharsetToEncoding", "setMaxParserCache", "clearParserCache", "TypedParameter"];
246
240
  readonly importedBy: 'packages/orm/src';
247
241
  }, {
248
242
  readonly specifier: '@aws-sdk/client-rds-data';
@@ -310,5 +304,60 @@ type DevOnlySpecifier = (typeof DEV_ONLY_MODULES)[number]['specifier'];
310
304
  * @param message Platform-specific explanation, including the replacement API.
311
305
  */
312
306
  declare function renderDevOnlyStub(module: Pick<DevOnlyModule, 'exportNames'>, message: string): string;
307
+ /**
308
+ * `Bun.build` minify options for a deploy bundle. Jobs, events, notifications and
309
+ * agents are stored under their class name, so identifiers stay unmangled, and
310
+ * `keepNames` restores the name syntax minification drops from a named class or
311
+ * function expression. It never replaces `identifiers: false`: on Bun 1.3.14 and
312
+ * 1.4.2 mangling wins. Neither restores a cross-module rename (`renamedNameKeyedClasses`).
313
+ */
314
+ declare const BUN_DEPLOY_MINIFY: {
315
+ readonly whitespace: true;
316
+ readonly syntax: true;
317
+ readonly identifiers: false;
318
+ readonly keepNames: true;
319
+ };
320
+ type NameKeyedKind = 'record' | 'model';
321
+ interface RenamedNameKeyedClass {
322
+ /** The name in source, which `bun run` reports. */
323
+ readonly name: string;
324
+ /** The name the bundle declares instead, and so the class's runtime `.name`. */
325
+ readonly bundledAs: string;
326
+ /** `record`: a job, event, notification or agent, which can pin its name. */
327
+ readonly kind: NameKeyedKind;
328
+ /** The app files declaring such a class called `name`. */
329
+ readonly files: readonly string[];
330
+ }
331
+ /**
332
+ * App models and unpinned records the bundle renamed to `<name><n>`, which happens when
333
+ * another module declares the same top-level name. A declaration counts only when the
334
+ * numbered class extends its base, so a renamed dependency class is not the app's. Read
335
+ * with regexes, since this module imports only builtins: a base built by an expression
336
+ * the patterns above do not match (a mixin they do not name) is missed, not guessed.
337
+ */
338
+ declare function renamedNameKeyedClasses(bundle: string, sources: ReadonlyArray<{
339
+ readonly file: string;
340
+ readonly text: string;
341
+ }>): RenamedNameKeyedClass[];
342
+ /** The part of a `Bun.build` result the reporter reads, structural so this module needs no bun-types. */
343
+ interface BundleResultLike {
344
+ readonly outputs: ReadonlyArray<{
345
+ readonly kind: string;
346
+ text(): Promise<string>;
347
+ }>;
348
+ readonly metafile?: {
349
+ readonly inputs: Readonly<Record<string, unknown>>;
350
+ };
351
+ }
352
+ /**
353
+ * Warns about each `renamedNameKeyedClasses` result of a `Bun.build` run with
354
+ * `metafile: true`, whose input paths (relative to the cwd) are the sources read.
355
+ * Module dependencies are skipped, and so is an input that will not read, such as a
356
+ * plugin namespace.
357
+ */
358
+ declare function reportRenamedNameKeyedClasses(result: BundleResultLike, options: {
359
+ root: string;
360
+ label: string;
361
+ }): Promise<void>;
313
362
  //#endregion
314
- export { AGENTS_CONFIG_FILE, CLIENT_ASSETS_URL_PREFIX, ClientAssetEnv, DATABASE_CONFIG_CANDIDATES, DATABASE_DIALECTS, DATABASE_FACTORIES, DEV_ONLY_MODULES, DOCUMENT_ASSET_EXTENSIONS, DOCUMENT_ASSET_HEADERS, DatabaseDialect, DatabaseDialectDetection, DevOnlyModule, DevOnlyModuleEntry, DevOnlyModuleKind, DevOnlySpecifier, MCP_PLUGIN_PACKAGE, MCP_SDK_SUBPATH_PREFIX, MCP_TRANSPORT_SPECIFIER, Manifest, ManifestEntry, PathLike, SQL_CLIENT_MODULES, SqlClientModule, SqlClientSpecifier, UnusedSqlClient, appUsesMcpPlugin, assertOutputDirOutsideRoot, bundledRuntimeEnv, clientManifestJson, detectDatabaseDialects, importSpecifier, parseDatabaseDialects, readManifest, removeShadowingIndex, renderDevOnlyStub, resetOutputDir, resolveClientAssetEnv, resolvePathLike, resolveSsrEntryFile, ssrRuntimePaths, stageStaticAssets, stubbableDevOnlyModules, translationCatalogJson, unusedSqlClients };
363
+ export { AGENTS_CONFIG_FILE, BUN_DEPLOY_MINIFY, BundleResultLike, CLIENT_ASSETS_URL_PREFIX, ClientAssetEnv, DATABASE_CONFIG_CANDIDATES, DATABASE_DIALECTS, DATABASE_FACTORIES, DEV_ONLY_MODULES, DOCUMENT_ASSET_EXTENSIONS, DOCUMENT_ASSET_HEADERS, DatabaseDialect, DatabaseDialectDetection, DevOnlyModule, DevOnlyModuleEntry, DevOnlyModuleKind, DevOnlySpecifier, MCP_PLUGIN_PACKAGE, MCP_SDK_SUBPATH_PREFIX, MCP_TRANSPORT_SPECIFIER, Manifest, ManifestEntry, PathLike, RenamedNameKeyedClass, SQL_CLIENT_MODULES, SqlClientModule, SqlClientSpecifier, UnusedSqlClient, appUsesMcpPlugin, assertOutputDirOutsideRoot, bundledRuntimeEnv, clientManifestJson, detectDatabaseDialects, importSpecifier, parseDatabaseDialects, readManifest, removeShadowingIndex, renamedNameKeyedClasses, renderDevOnlyStub, reportRenamedNameKeyedClasses, resetOutputDir, resolveClientAssetEnv, resolvePathLike, resolveSsrEntryFile, ssrRuntimePaths, stageStaticAssets, stubbableDevOnlyModules, translationCatalogJson, unusedSqlClients };
@@ -1,23 +1,17 @@
1
1
  import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync } from "node:fs";
2
2
  import { basename, dirname, extname, isAbsolute, relative, resolve, sep } from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
+ import { AGENTS_CONFIG_FILE } from "@guren/server/internal/app-conventions";
4
5
  //#region src/internal/deploy-build.ts
5
6
  /**
6
7
  * Build-time helpers shared by the deploy plugins (cloudflare, lambda, vercel).
7
8
  * Internal (`contributing/api-stability.md`): deep import only, never re-exported
8
- * from `@guren/core`. Imports only `node:` builtins so a plugin build never drags
9
+ * from `@guren/core`. Imports only builtins and shared constants so a plugin build never drags
9
10
  * the runtime in; `deploy-build.test.ts` asserts that of the built artifact.
10
11
  * Platform decisions (messages, stub delivery, whether a missing `build` script is
11
12
  * fatal, SSR renderer verification) stay per-plugin. A helper that *relates* two
12
13
  * paths canonicalizes both first; one that reads or writes a single path does not.
13
14
  */
14
- /**
15
- * The agent registry (RFC 0017 §3), at a path neither side may choose. Shared
16
- * rather than spelled twice: `guren check` reads it as source and a deploy build
17
- * reads it to generate the worker's Durable Object exports, so a second spelling
18
- * is a deploy exporting no agents while the check calls them registered.
19
- */
20
- const AGENTS_CONFIG_FILE = "config/agents.ts";
21
15
  function resolvePathLike(value) {
22
16
  return value instanceof URL ? fileURLToPath(value) : resolve(String(value));
23
17
  }
@@ -357,10 +351,10 @@ const DATABASE_FACTORIES = {
357
351
  };
358
352
  /**
359
353
  * Client libraries the Postgres, MySQL and Aurora Data API factories reach for.
360
- * Apart from `DEV_ONLY_MODULES` because their fate is per platform: unreachable on
361
- * Workers (D1 only), load-bearing on Lambda/Vercel, which stub only undeclared
362
- * dialects (`unusedSqlClients`). Stub the client *and* drizzle's entry importing it,
363
- * or a D1 app fails on `Could not resolve "postgres"`; export names mirror drizzle-orm's.
354
+ * Apart from `DEV_ONLY_MODULES`: unreachable on Workers (D1 only), load-bearing on
355
+ * Lambda/Vercel, which stub only undeclared dialects (`unusedSqlClients`). Stub the
356
+ * client *and* drizzle's entry importing it, or a D1 app fails to resolve `postgres`.
357
+ * `mysql2/promise` lists its whole public API, not just drizzle's `createPool` (#507).
364
358
  */
365
359
  const SQL_CLIENT_MODULES = [
366
360
  {
@@ -381,7 +375,26 @@ const SQL_CLIENT_MODULES = [
381
375
  specifier: "mysql2/promise",
382
376
  kind: "sql-driver",
383
377
  dialect: "mysql",
384
- exportNames: ["createPool"],
378
+ exportNames: [
379
+ "createConnection",
380
+ "createPool",
381
+ "createPoolCluster",
382
+ "escape",
383
+ "escapeId",
384
+ "format",
385
+ "raw",
386
+ "Connection",
387
+ "PoolConnection",
388
+ "PromisePool",
389
+ "PromiseConnection",
390
+ "PromisePoolConnection",
391
+ "Types",
392
+ "Charsets",
393
+ "CharsetToEncoding",
394
+ "setMaxParserCache",
395
+ "clearParserCache",
396
+ "TypedParameter"
397
+ ],
385
398
  importedBy: "packages/orm/src"
386
399
  },
387
400
  {
@@ -494,5 +507,152 @@ function renderDevOnlyStub(module, message) {
494
507
  const named = module.exportNames.length > 0 ? `, { ${module.exportNames.join(", ")} }` : "";
495
508
  return `// ${comment}\n${throwing}\n${`function unavailable() { ${error} }`}\nexport default Object.assign(unavailable${named})\n`;
496
509
  }
510
+ /**
511
+ * `Bun.build` minify options for a deploy bundle. Jobs, events, notifications and
512
+ * agents are stored under their class name, so identifiers stay unmangled, and
513
+ * `keepNames` restores the name syntax minification drops from a named class or
514
+ * function expression. It never replaces `identifiers: false`: on Bun 1.3.14 and
515
+ * 1.4.2 mangling wins. Neither restores a cross-module rename (`renamedNameKeyedClasses`).
516
+ */
517
+ const BUN_DEPLOY_MINIFY = {
518
+ whitespace: true,
519
+ syntax: true,
520
+ identifiers: false,
521
+ keepNames: true
522
+ };
523
+ /**
524
+ * Framework bases whose subclasses are stored under their class name. A record kind
525
+ * can pin that name; a model cannot: attachments and `morphMany` write `model.name`
526
+ * while `Model.morphMap` finds the model by its source name, so a rename splits them.
527
+ */
528
+ const NAME_KEYED_BASES = new Map([...[
529
+ "Job",
530
+ "Event",
531
+ "Notification",
532
+ "Agent"
533
+ ].map((base) => [base, "record"]), ...[
534
+ "Model",
535
+ "AuthenticatableModel",
536
+ "defineModel",
537
+ "Attachable",
538
+ "SoftDeletes"
539
+ ].map((base) => [base, "model"])]);
540
+ const NAME_PIN = /\bstatic\s+(?:override\s+)?(?:jobName|eventName|agentName)\b|\bget\s+type\s*\(/;
541
+ const HERITAGE = String.raw`\s+extends\s+(?:[A-Za-z_$][\w$]*\.)*([A-Za-z_$][\w$]*)`;
542
+ const SOURCE_CLASS = new RegExp(String.raw`^[ \t]*(?:export[ \t]+(?:default[ \t]+)?)?(?:abstract[ \t]+)?class[ \t]+([A-Za-z_$][\w$]*)(?:[ \t]*<[^{>\n]*>)?(?:${HERITAGE})?`, "gm");
543
+ const BUNDLED_CLASS = new RegExp(String.raw`(?:^|[^\w$.])class\s+([A-Za-z_$][\w$]*)(?:${HERITAGE})?`, "g");
544
+ const NAMED_IMPORTS = /import\s+(?:[A-Za-z_$][\w$]*\s*,\s*)?\{([^{}]*)\}\s*from\s*['"]([^'"]+)['"]/g;
545
+ const IMPORT_SPECIFIER = /^([A-Za-z_$][\w$]*)(?:\s+as\s+([A-Za-z_$][\w$]*))?$/;
546
+ /**
547
+ * App models and unpinned records the bundle renamed to `<name><n>`, which happens when
548
+ * another module declares the same top-level name. A declaration counts only when the
549
+ * numbered class extends its base, so a renamed dependency class is not the app's. Read
550
+ * with regexes, since this module imports only builtins: a base built by an expression
551
+ * the patterns above do not match (a mixin they do not name) is missed, not guessed.
552
+ */
553
+ function renamedNameKeyedClasses(bundle, sources) {
554
+ const declared = /* @__PURE__ */ new Map();
555
+ for (const { file, text } of sources) {
556
+ const imports = namedImports(text);
557
+ const pinned = NAME_PIN.test(text);
558
+ for (const [, name, local] of text.matchAll(SOURCE_CLASS)) {
559
+ const imported = local === void 0 ? void 0 : imports.get(local);
560
+ const entries = declared.get(name) ?? [];
561
+ entries.push({
562
+ file,
563
+ base: imported?.name ?? local,
564
+ fromFramework: imported?.fromFramework ?? false,
565
+ pinned
566
+ });
567
+ declared.set(name, entries);
568
+ }
569
+ }
570
+ const kindOf = (entry, seen = /* @__PURE__ */ new Set()) => {
571
+ if (entry.base === void 0) return void 0;
572
+ const own = entry.fromFramework ? void 0 : declared.get(entry.base);
573
+ if (own === void 0) return NAME_KEYED_BASES.get(entry.base);
574
+ if (seen.has(entry.base)) return void 0;
575
+ seen.add(entry.base);
576
+ for (const parent of own) {
577
+ const inherited = kindOf(parent, seen);
578
+ if (inherited !== void 0) return inherited;
579
+ }
580
+ };
581
+ const bundledBases = /* @__PURE__ */ new Map();
582
+ for (const [, bundledAs, base] of bundle.matchAll(BUNDLED_CLASS)) {
583
+ if (base === void 0) continue;
584
+ const bases = bundledBases.get(bundledAs) ?? /* @__PURE__ */ new Set();
585
+ bases.add(stem(base));
586
+ bundledBases.set(bundledAs, bases);
587
+ }
588
+ const renamed = [];
589
+ for (const [bundledAs, bases] of bundledBases) {
590
+ const name = withoutNumericSuffix(bundledAs);
591
+ if (name === void 0 || declared.has(bundledAs)) continue;
592
+ const files = /* @__PURE__ */ new Map();
593
+ for (const entry of declared.get(name) ?? []) {
594
+ if (entry.base === void 0 || !bases.has(stem(entry.base))) continue;
595
+ const kind = kindOf(entry);
596
+ if (kind === void 0 || kind === "record" && entry.pinned) continue;
597
+ files.set(kind, [...files.get(kind) ?? [], entry.file]);
598
+ }
599
+ for (const [kind, list] of files) renamed.push({
600
+ name,
601
+ bundledAs,
602
+ kind,
603
+ files: list.sort()
604
+ });
605
+ }
606
+ return renamed;
607
+ }
608
+ function withoutNumericSuffix(name) {
609
+ let end = name.length;
610
+ while (end > 0 && name.charCodeAt(end - 1) >= 48 && name.charCodeAt(end - 1) <= 57) end--;
611
+ return end > 0 && end < name.length ? name.slice(0, end) : void 0;
612
+ }
613
+ function stem(name) {
614
+ return withoutNumericSuffix(name) ?? name;
615
+ }
616
+ /** Local name → exported name, for a file's `import { A as B } from '…'` statements. */
617
+ function namedImports(text) {
618
+ const imports = /* @__PURE__ */ new Map();
619
+ for (const [, specifiers, from] of text.matchAll(NAMED_IMPORTS)) for (const specifier of specifiers.split(",")) {
620
+ const match = IMPORT_SPECIFIER.exec(specifier.trim());
621
+ if (match) imports.set(match[2] ?? match[1], {
622
+ name: match[1],
623
+ fromFramework: from.startsWith("@guren/")
624
+ });
625
+ }
626
+ return imports;
627
+ }
628
+ /**
629
+ * Warns about each `renamedNameKeyedClasses` result of a `Bun.build` run with
630
+ * `metafile: true`, whose input paths (relative to the cwd) are the sources read.
631
+ * Module dependencies are skipped, and so is an input that will not read, such as a
632
+ * plugin namespace.
633
+ */
634
+ async function reportRenamedNameKeyedClasses(result, options) {
635
+ const code = result.outputs.filter((output) => output.kind === "entry-point" || output.kind === "chunk");
636
+ const bundle = (await Promise.all(code.map((output) => output.text()))).join("\n");
637
+ const root = realpathOfNearestExisting(options.root);
638
+ const sources = [];
639
+ for (const input of Object.keys(result.metafile?.inputs ?? {})) {
640
+ if (/(?:^|[\\/])node_modules[\\/]/.test(input)) continue;
641
+ try {
642
+ const path = realpathSync(resolve(input));
643
+ sources.push({
644
+ file: relative(root, path),
645
+ text: readFileSync(path, "utf8")
646
+ });
647
+ } catch {
648
+ continue;
649
+ }
650
+ }
651
+ for (const { name, bundledAs, kind, files } of renamedNameKeyedClasses(bundle, sources)) {
652
+ const declares = `${files.join(", ")} ${files.length === 1 ? "declares" : "declare"}`;
653
+ const found = kind === "record" ? `${declares} a job, event, notification or agent named ${name}, which is stored under its class name: rename it, or pin \`static jobName\`, \`static eventName\`, \`get type()\` or \`static agentName\`.` : `${declares} a model named ${name}. Its attachments and polymorphic relations, if it has any, are stored as ${bundledAs} while \`Model.morphMap\` looks it up as ${name}: a model has no name to pin, so rename the class (rows already stored as ${bundledAs} need updating).`;
654
+ console.warn(`${options.label}: the bundle names a class ${name} as ${bundledAs}, because another module declares ${name} too and import order picks which one keeps it. ${found}`);
655
+ }
656
+ }
497
657
  //#endregion
498
- export { AGENTS_CONFIG_FILE, CLIENT_ASSETS_URL_PREFIX, DATABASE_CONFIG_CANDIDATES, DATABASE_DIALECTS, DATABASE_FACTORIES, DEV_ONLY_MODULES, DOCUMENT_ASSET_EXTENSIONS, DOCUMENT_ASSET_HEADERS, MCP_PLUGIN_PACKAGE, MCP_SDK_SUBPATH_PREFIX, MCP_TRANSPORT_SPECIFIER, SQL_CLIENT_MODULES, appUsesMcpPlugin, assertOutputDirOutsideRoot, bundledRuntimeEnv, clientManifestJson, detectDatabaseDialects, importSpecifier, parseDatabaseDialects, readManifest, removeShadowingIndex, renderDevOnlyStub, resetOutputDir, resolveClientAssetEnv, resolvePathLike, resolveSsrEntryFile, ssrRuntimePaths, stageStaticAssets, stubbableDevOnlyModules, translationCatalogJson, unusedSqlClients };
658
+ export { AGENTS_CONFIG_FILE, BUN_DEPLOY_MINIFY, CLIENT_ASSETS_URL_PREFIX, DATABASE_CONFIG_CANDIDATES, DATABASE_DIALECTS, DATABASE_FACTORIES, DEV_ONLY_MODULES, DOCUMENT_ASSET_EXTENSIONS, DOCUMENT_ASSET_HEADERS, MCP_PLUGIN_PACKAGE, MCP_SDK_SUBPATH_PREFIX, MCP_TRANSPORT_SPECIFIER, SQL_CLIENT_MODULES, appUsesMcpPlugin, assertOutputDirOutsideRoot, bundledRuntimeEnv, clientManifestJson, detectDatabaseDialects, importSpecifier, parseDatabaseDialects, readManifest, removeShadowingIndex, renamedNameKeyedClasses, renderDevOnlyStub, reportRenamedNameKeyedClasses, resetOutputDir, resolveClientAssetEnv, resolvePathLike, resolveSsrEntryFile, ssrRuntimePaths, stageStaticAssets, stubbableDevOnlyModules, translationCatalogJson, unusedSqlClients };
@@ -5,8 +5,8 @@
5
5
  * Its own entry, not part of `deploy-build`: that one imports node builtins
6
6
  * only (its test scans the built artifact), while the scan lives in
7
7
  * `@guren/cli`, reached here lazily so nothing loads until a build asks.
8
- * Warns, never throws: the scan reads constructions, not intent, and a wrong
9
- * guess must not block a deploy.
8
+ * The CLI reads the introspected app, and reports a verdict it cannot vouch for as unverified (RFC 0026 §5).
9
+ * Warns, never throws: a wrong guess must not block a deploy.
10
10
  */
11
11
  interface ReportDeployRuntimeHazardsOptions {
12
12
  /** App root the scan reads. */
@@ -15,9 +15,9 @@ interface ReportDeployRuntimeHazardsOptions {
15
15
  label: string;
16
16
  }
17
17
  /**
18
- * Print every non-passing verdict through `console.warn`, one line each, and
19
- * return the lines. A scan that cannot run prints one line saying so rather
20
- * than nothing: silence would read as a clean report.
18
+ * Print one `console.log` line naming the evidence, then every non-passing verdict
19
+ * through `console.warn`, one line each, and return those. A scan that cannot run
20
+ * prints one line saying so rather than nothing: silence would read as a clean report.
21
21
  */
22
22
  declare function reportDeployRuntimeHazards(options: ReportDeployRuntimeHazardsOptions): Promise<string[]>;
23
23
  //#endregion
@@ -3,9 +3,9 @@ function describeError(error) {
3
3
  return error instanceof Error ? error.message : String(error);
4
4
  }
5
5
  /**
6
- * Print every non-passing verdict through `console.warn`, one line each, and
7
- * return the lines. A scan that cannot run prints one line saying so rather
8
- * than nothing: silence would read as a clean report.
6
+ * Print one `console.log` line naming the evidence, then every non-passing verdict
7
+ * through `console.warn`, one line each, and return those. A scan that cannot run
8
+ * prints one line saying so rather than nothing: silence would read as a clean report.
9
9
  */
10
10
  async function reportDeployRuntimeHazards(options) {
11
11
  const { root, label } = options;
@@ -22,10 +22,28 @@ async function reportDeployRuntimeHazards(options) {
22
22
  } catch (error) {
23
23
  return skipped(label, `the scan failed (${describeError(error)})`);
24
24
  }
25
+ const evidence = describeEvidence(label, verdicts);
26
+ if (evidence) console.log(evidence);
25
27
  const lines = verdicts.filter((verdict) => verdict.status !== "pass").map((verdict) => `${label}: ${verdict.message}${verdict.fix ? ` ${verdict.fix}` : ""}`);
26
28
  for (const line of lines) console.warn(line);
27
29
  return lines;
28
30
  }
31
+ /** One line naming what each verdict was judged from, and why the source when the app could not be read. */
32
+ function describeEvidence(label, verdicts) {
33
+ const judged = [];
34
+ for (const { title, evidence } of verdicts) {
35
+ if (evidence === void 0) return void 0;
36
+ judged.push(`${title} from ${EVIDENCE_LABELS[evidence]}`);
37
+ }
38
+ if (judged.length === 0) return void 0;
39
+ const reasons = [...new Set(verdicts.flatMap((verdict) => verdict.evidenceReason ? [verdict.evidenceReason] : []))];
40
+ return `${label}: deploy-runtime checks judged ${judged.join(", ")}${reasons.length > 0 ? ` (${reasons.join("; ")})` : ""}.`;
41
+ }
42
+ const EVIDENCE_LABELS = {
43
+ manifest: "the introspected app",
44
+ static: "source",
45
+ none: "nothing verifiable"
46
+ };
29
47
  function skipped(label, reason) {
30
48
  const line = `${label}: deploy-runtime checks skipped — ${reason}. Run \`bunx guren doctor\` before deploying.`;
31
49
  console.warn(line);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/core",
3
- "version": "1.20.1",
3
+ "version": "1.22.0",
4
4
  "description": "Guren: the Bun-first fullstack TypeScript framework. Laravel-style MVC on Hono, Drizzle ORM and Inertia.js + React. Develop on Bun; deploy to Bun, AWS Lambda (Node.js), Vercel or Cloudflare Workers.",
5
5
  "keywords": [
6
6
  "guren",
@@ -104,9 +104,9 @@
104
104
  "typecheck": "tsc --noEmit"
105
105
  },
106
106
  "dependencies": {
107
- "@guren/cli": "^2.26.0",
108
- "@guren/orm": "^2.11.1",
109
- "@guren/server": "^2.25.1"
107
+ "@guren/cli": "^2.28.0",
108
+ "@guren/orm": "^2.13.0",
109
+ "@guren/server": "^2.27.0"
110
110
  },
111
111
  "devDependencies": {
112
112
  "@types/node": "^20.14.10",