@guren/core 1.2.0 → 1.4.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,6 +1,6 @@
1
- import { ApiTokenStore, ApiToken } from '@guren/server';
1
+ import { ApiTokenStore, ApiToken, SessionStore, SessionData, OAuthStateStore, OAuthStatePayload } from '@guren/server';
2
2
  export * from '@guren/server';
3
- export { AccessorDefinitions, AccessorFn, BelongsToManyRecord, BelongsToManyRelationResult, BelongsToRecord, BelongsToRelationResult, BelongsToRequiredRecord, CastType, DrizzleAdapter, FindManyOptions, GroupCondition, HasManyRecord, HasManyRelationResult, HasManyThroughRecord, HasManyThroughRelationResult, HasOneRecord, HasOneRelationResult, HookCallback, HookName, InferModelInsert, InferModelRecord, MassAssignmentException, Model, ModelHooks, ModelNotFoundException, ModelObserver, ModelObserverConstructor, ModelPaginationMeta, MorphManyRecord, MorphManyRelationResult, MorphToRecord, MorphToRelationResult, MutatorDefinitions, MutatorFn, MySqlDatabase, MySqlDatabaseOptions, ORMAdapter, ORMAdapterAdvanced, OrderByClause, OrderByInput, OrderDefinition, OrderDirection, PaginateOptions, PaginatedResult, PlainObject, PostgresDatabase, PostgresDatabaseOptions, QueryBuilder, QueryBuilderOptions, ScopeFunction, SeederContext, SeederHandler, SimpleCondition, SoftDeletes, SoftDeletesStatic, SqliteDatabase, SqliteDatabaseOptions, TransactionHandle, TransactionModelScope, WhereClause, WhereCondition, WhereOperator, WithRelations, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, runSeeders } from '@guren/orm';
3
+ export { AccessorDefinitions, AccessorFn, AwsDataApiDatabase, AwsDataApiDatabaseOptions, BelongsToManyRecord, BelongsToManyRelationResult, BelongsToRecord, BelongsToRelationResult, BelongsToRequiredRecord, CastType, D1DatabaseHandle, D1DatabaseOptions, DrizzleAdapter, FindManyOptions, GroupCondition, HasManyRecord, HasManyRelationResult, HasManyThroughRecord, HasManyThroughRelationResult, HasOneRecord, HasOneRelationResult, HookCallback, HookName, InferModelInsert, InferModelRecord, MassAssignmentException, Model, ModelHooks, ModelNotFoundException, ModelObserver, ModelObserverConstructor, ModelPaginationMeta, MorphManyRecord, MorphManyRelationResult, MorphToRecord, MorphToRelationResult, MutatorDefinitions, MutatorFn, MySqlDatabase, MySqlDatabaseOptions, ORMAdapter, ORMAdapterAdvanced, OrderByClause, OrderByInput, OrderDefinition, OrderDirection, PaginateOptions, PaginatedResult, PlainObject, PostgresDatabase, PostgresDatabaseOptions, QueryBuilder, QueryBuilderOptions, ScopeFunction, SeederContext, SeederHandler, SimpleCondition, SoftDeletes, SoftDeletesStatic, SqliteDatabase, SqliteDatabaseOptions, TransactionHandle, TransactionModelScope, WhereClause, WhereCondition, WhereOperator, WithRelations, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, runSeeders } from '@guren/orm';
4
4
 
5
5
  /**
6
6
  * Options for DatabaseApiTokenStore.
@@ -59,4 +59,153 @@ declare class DatabaseApiTokenStore implements ApiTokenStore {
59
59
  private deserialize;
60
60
  }
61
61
 
62
- export { DatabaseApiTokenStore, type DatabaseApiTokenStoreOptions };
62
+ /**
63
+ * Options for DatabaseSessionStore.
64
+ */
65
+ interface DatabaseSessionStoreOptions {
66
+ /**
67
+ * How the `data` column stores the serialized session.
68
+ *
69
+ * - `'json'` (default) passes the object straight through — use with a
70
+ * JSON-capable column (pg `jsonb`/`json`, sqlite `text(..., { mode: 'json' })`).
71
+ * - `'text'` serializes to a JSON string for plain text columns.
72
+ *
73
+ * Reads always accept both representations.
74
+ * @default 'json'
75
+ */
76
+ dataMode?: 'json' | 'text';
77
+ }
78
+ /**
79
+ * Database-backed session store built on the Guren ORM — works on any
80
+ * configured connection (SQLite, Postgres, MySQL, or Cloudflare D1), which
81
+ * makes it the serverless default: no Redis required on Lambda, Vercel, or
82
+ * Workers, and reads are strongly consistent (login → redirect → read works).
83
+ *
84
+ * Pass the Drizzle table for your `sessions` schema. Column property names
85
+ * must match `id` (text primary key), `data`, and `expiresAt`:
86
+ *
87
+ * ```ts
88
+ * export const sessions = sqliteTable('sessions', {
89
+ * id: text('id').primaryKey(),
90
+ * data: text('data', { mode: 'json' }).$type<Record<string, unknown>>().notNull(),
91
+ * expiresAt: integer('expires_at', { mode: 'timestamp_ms' }).notNull(),
92
+ * })
93
+ * ```
94
+ *
95
+ * Session values must be JSON-serializable: Dates come back as ISO strings,
96
+ * `undefined` properties are dropped, and `bigint` values fail to serialize —
97
+ * unlike `MemorySessionStore`, which keeps live references. Store primitives
98
+ * and plain objects/arrays in sessions.
99
+ *
100
+ * @example
101
+ * ```ts
102
+ * import { DatabaseSessionStore } from '@guren/core'
103
+ * import { sessions } from '@/db/schema'
104
+ *
105
+ * app.use(createSessionMiddleware({ store: new DatabaseSessionStore(sessions) }))
106
+ * ```
107
+ */
108
+ declare class DatabaseSessionStore implements SessionStore {
109
+ private readonly model;
110
+ private readonly dataMode;
111
+ constructor(table: unknown, options?: DatabaseSessionStoreOptions);
112
+ read(id: string): Promise<SessionData | undefined>;
113
+ write(id: string, data: SessionData, ttlSeconds: number): Promise<void>;
114
+ destroy(id: string): Promise<void>;
115
+ /**
116
+ * Refresh an existing session's TTL with a single conditional UPDATE — no
117
+ * data rewrite, no existence check. Missing rows and rows that have
118
+ * already expired (but not yet been swept) are left untouched, never
119
+ * resurrected — matching the `SessionStore.touch` contract and the memory
120
+ * store's behavior.
121
+ */
122
+ touch(id: string, ttlSeconds: number): Promise<void>;
123
+ /**
124
+ * Delete sessions whose expiration time has passed. Expired rows are
125
+ * already treated as missing (and removed) by `read`; call this from a
126
+ * scheduled job to keep the table small.
127
+ */
128
+ deleteExpired(now?: Date): Promise<void>;
129
+ private deserialize;
130
+ private expiryDate;
131
+ }
132
+
133
+ /**
134
+ * Database-backed OAuth state store built on the Guren ORM.
135
+ *
136
+ * The default `MemoryOAuthStateStore` keeps state in per-isolate memory,
137
+ * which breaks on serverless: the OAuth authorize redirect and the callback
138
+ * that follows it can land on different instances, so an in-memory map
139
+ * never sees the state that was just written. Backing the store with the
140
+ * database makes state visible to whichever instance handles the callback.
141
+ *
142
+ * Pass the Drizzle table for your `oauth_states` schema. Column property
143
+ * names must match `stateHash` (text primary key), `provider`,
144
+ * `redirectTo`, and `expiresAt`:
145
+ *
146
+ * ```ts
147
+ * export const oauthStates = sqliteTable('oauth_states', {
148
+ * stateHash: text('state_hash').primaryKey(),
149
+ * provider: text('provider').notNull(),
150
+ * redirectTo: text('redirect_to'),
151
+ * expiresAt: integer('expires_at', { mode: 'timestamp_ms' }).notNull(),
152
+ * })
153
+ * ```
154
+ *
155
+ * @example
156
+ * ```ts
157
+ * import { createOAuthManager, DatabaseOAuthStateStore } from '@guren/core'
158
+ * import { oauthStates } from '@/db/schema'
159
+ *
160
+ * export const oauth = createOAuthManager({
161
+ * stateStore: new DatabaseOAuthStateStore(oauthStates),
162
+ * })
163
+ * ```
164
+ */
165
+ declare class DatabaseOAuthStateStore implements OAuthStateStore {
166
+ private readonly model;
167
+ constructor(table: unknown);
168
+ store(stateHash: string, payload: OAuthStatePayload): Promise<void>;
169
+ find(stateHash: string): Promise<OAuthStatePayload | null>;
170
+ /**
171
+ * Fetch the row for `stateHash`, clearing it out and returning null if
172
+ * expired. Shared by `find` and `consume`, which otherwise diverge only
173
+ * in what they do with a live row.
174
+ */
175
+ private fetchLive;
176
+ delete(stateHash: string): Promise<void>;
177
+ /**
178
+ * Atomically fetch and delete a state, guaranteeing exactly one concurrent
179
+ * caller for the same hash receives the payload.
180
+ *
181
+ * This guarantee depends on the configured ORM adapter's `delete()`
182
+ * reporting whether a row actually matched — either the deleted row
183
+ * (RETURNING) or an affected-row count. `DrizzleAdapter`, the framework's
184
+ * default and only shipped adapter, always does this: RETURNING drivers
185
+ * (Postgres, SQLite, D1) resolve to the deleted row or `undefined` only
186
+ * when zero rows matched; MySQL resolves to a result carrying
187
+ * `affectedRows` (verified by inspection, not a dedicated test).
188
+ *
189
+ * The `ORMAdapter.delete` contract also permits a bare `void` return.
190
+ * A custom adapter (via `Model.useAdapter()`) that returns `void`
191
+ * unconditionally — on both a successful delete and a no-op — gives
192
+ * `consume()` no way to tell which caller won: the value is identical for
193
+ * both, so no post-hoc check can attribute the deletion. Rather than
194
+ * silently rejecting every real login for such adapters,
195
+ * `deleteRemovedRow` treats an unrecognized non-null result as removed —
196
+ * this reopens the pre-consume find-then-delete race window (multiple
197
+ * concurrent callers can pass) for adapters that can't report a match,
198
+ * but does not break login. It is fail-closed (returns null / rejects)
199
+ * only for `null`/`undefined`, DrizzleAdapter's definitive "no rows
200
+ * matched" signal.
201
+ */
202
+ consume(stateHash: string): Promise<OAuthStatePayload | null>;
203
+ /**
204
+ * Delete OAuth states whose expiration time has passed. Expired states
205
+ * are already rejected by `find`; call this from a scheduled job to keep
206
+ * the table small.
207
+ */
208
+ deleteExpired(now?: Date): Promise<void>;
209
+ }
210
+
211
+ export { DatabaseApiTokenStore, type DatabaseApiTokenStoreOptions, DatabaseOAuthStateStore, DatabaseSessionStore, type DatabaseSessionStoreOptions };
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // src/index.ts
2
2
  export * from "@guren/server";
3
3
  import {
4
- Model as Model2,
4
+ Model as Model4,
5
5
  defineModel,
6
6
  ModelNotFoundException,
7
7
  MassAssignmentException,
@@ -11,12 +11,44 @@ import {
11
11
  createPostgresDatabase,
12
12
  createMySqlDatabase,
13
13
  createSqliteDatabase,
14
+ createD1Database,
15
+ createAwsDataApiDatabase,
14
16
  runSeeders,
15
17
  defineSeeder
16
18
  } from "@guren/orm";
17
19
 
18
20
  // src/api-token-store.ts
19
21
  import { Model } from "@guren/orm";
22
+
23
+ // src/store-utils.ts
24
+ function toDate(value) {
25
+ if (value == null) return null;
26
+ if (value instanceof Date) return value;
27
+ if (typeof value === "number") return new Date(value);
28
+ if (typeof value === "string") {
29
+ const date = new Date(/^\d+$/.test(value) ? Number(value) : value);
30
+ return Number.isNaN(date.getTime()) ? null : date;
31
+ }
32
+ return null;
33
+ }
34
+ function isExpired(value, now = Date.now()) {
35
+ const date = toDate(value);
36
+ if (date === null) return true;
37
+ const time = date.getTime();
38
+ return Number.isNaN(time) || time <= now;
39
+ }
40
+ function decodeJsonColumn(value, fallback) {
41
+ if (typeof value === "string") {
42
+ try {
43
+ return JSON.parse(value);
44
+ } catch {
45
+ return fallback;
46
+ }
47
+ }
48
+ return value ?? fallback;
49
+ }
50
+
51
+ // src/api-token-store.ts
20
52
  var DatabaseApiTokenStore = class {
21
53
  model;
22
54
  abilitiesMode;
@@ -67,27 +99,204 @@ var DatabaseApiTokenStore = class {
67
99
  name: String(record.name),
68
100
  hashedToken: String(record.hashedToken),
69
101
  userId: typeof record.userId === "bigint" ? record.userId.toString() : record.userId,
70
- abilities: typeof abilities === "string" ? JSON.parse(abilities) : abilities,
102
+ // Corrupt text degrades to no abilities (deny-by-default) instead of
103
+ // throwing on every verification of the affected token.
104
+ abilities: decodeJsonColumn(abilities, []),
71
105
  lastUsedAt: toDate(record.lastUsedAt),
72
106
  expiresAt: toDate(record.expiresAt),
73
107
  createdAt: toDate(record.createdAt) ?? /* @__PURE__ */ new Date(0)
74
108
  };
75
109
  }
76
110
  };
77
- function toDate(value) {
78
- if (value == null) return null;
79
- if (value instanceof Date) return value;
80
- if (typeof value === "string" || typeof value === "number") return new Date(value);
81
- return null;
111
+
112
+ // src/session-store.ts
113
+ import { Model as Model2 } from "@guren/orm";
114
+ var DatabaseSessionStore = class {
115
+ model;
116
+ dataMode;
117
+ constructor(table, options = {}) {
118
+ this.dataMode = options.dataMode ?? "json";
119
+ this.model = class SessionModel extends Model2 {
120
+ static table = table;
121
+ };
122
+ }
123
+ async read(id) {
124
+ const record = await this.model.where({ id }).first();
125
+ if (!record) {
126
+ return void 0;
127
+ }
128
+ if (isExpired(record.expiresAt)) {
129
+ await this.model.where({ id, expiresAt: record.expiresAt }).delete();
130
+ return void 0;
131
+ }
132
+ return this.deserialize(record);
133
+ }
134
+ async write(id, data, ttlSeconds) {
135
+ const payload = {
136
+ data: this.dataMode === "text" ? JSON.stringify(data) : data,
137
+ expiresAt: this.expiryDate(ttlSeconds)
138
+ };
139
+ const existing = await this.model.where({ id }).first();
140
+ if (existing) {
141
+ await this.model.forceUpdate({ id }, payload);
142
+ return;
143
+ }
144
+ try {
145
+ await this.model.forceCreate({ id, ...payload });
146
+ } catch (error) {
147
+ const nowExists = await this.model.where({ id }).first();
148
+ if (!nowExists) {
149
+ throw error;
150
+ }
151
+ await this.model.forceUpdate({ id }, payload);
152
+ }
153
+ }
154
+ async destroy(id) {
155
+ await this.model.where({ id }).delete();
156
+ }
157
+ /**
158
+ * Refresh an existing session's TTL with a single conditional UPDATE — no
159
+ * data rewrite, no existence check. Missing rows and rows that have
160
+ * already expired (but not yet been swept) are left untouched, never
161
+ * resurrected — matching the `SessionStore.touch` contract and the memory
162
+ * store's behavior.
163
+ */
164
+ async touch(id, ttlSeconds) {
165
+ await this.model.where({ id }).where("expiresAt", ">", /* @__PURE__ */ new Date()).forceUpdate({ expiresAt: this.expiryDate(ttlSeconds) });
166
+ }
167
+ /**
168
+ * Delete sessions whose expiration time has passed. Expired rows are
169
+ * already treated as missing (and removed) by `read`; call this from a
170
+ * scheduled job to keep the table small.
171
+ */
172
+ async deleteExpired(now = /* @__PURE__ */ new Date()) {
173
+ await this.model.where("expiresAt", "<=", now).delete();
174
+ }
175
+ deserialize(record) {
176
+ return decodeJsonColumn(record.data, {});
177
+ }
178
+ expiryDate(ttlSeconds) {
179
+ return new Date(Date.now() + ttlSeconds * 1e3);
180
+ }
181
+ };
182
+
183
+ // src/oauth-state-store.ts
184
+ import { Model as Model3 } from "@guren/orm";
185
+ var DatabaseOAuthStateStore = class {
186
+ model;
187
+ constructor(table) {
188
+ this.model = class OAuthStateModel extends Model3 {
189
+ static table = table;
190
+ };
191
+ }
192
+ async store(stateHash, payload) {
193
+ await this.model.forceCreate({
194
+ stateHash,
195
+ provider: payload.provider,
196
+ redirectTo: payload.redirectTo ?? null,
197
+ expiresAt: payload.expiresAt
198
+ });
199
+ }
200
+ async find(stateHash) {
201
+ const record = await this.fetchLive(stateHash);
202
+ return record ? mapRecordToPayload(record) : null;
203
+ }
204
+ /**
205
+ * Fetch the row for `stateHash`, clearing it out and returning null if
206
+ * expired. Shared by `find` and `consume`, which otherwise diverge only
207
+ * in what they do with a live row.
208
+ */
209
+ async fetchLive(stateHash) {
210
+ const record = await this.model.where({ stateHash }).first();
211
+ if (!record) {
212
+ return null;
213
+ }
214
+ if (isExpired(record.expiresAt)) {
215
+ await this.model.where({ stateHash, expiresAt: record.expiresAt }).delete();
216
+ return null;
217
+ }
218
+ return record;
219
+ }
220
+ async delete(stateHash) {
221
+ await this.model.where({ stateHash }).delete();
222
+ }
223
+ /**
224
+ * Atomically fetch and delete a state, guaranteeing exactly one concurrent
225
+ * caller for the same hash receives the payload.
226
+ *
227
+ * This guarantee depends on the configured ORM adapter's `delete()`
228
+ * reporting whether a row actually matched — either the deleted row
229
+ * (RETURNING) or an affected-row count. `DrizzleAdapter`, the framework's
230
+ * default and only shipped adapter, always does this: RETURNING drivers
231
+ * (Postgres, SQLite, D1) resolve to the deleted row or `undefined` only
232
+ * when zero rows matched; MySQL resolves to a result carrying
233
+ * `affectedRows` (verified by inspection, not a dedicated test).
234
+ *
235
+ * The `ORMAdapter.delete` contract also permits a bare `void` return.
236
+ * A custom adapter (via `Model.useAdapter()`) that returns `void`
237
+ * unconditionally — on both a successful delete and a no-op — gives
238
+ * `consume()` no way to tell which caller won: the value is identical for
239
+ * both, so no post-hoc check can attribute the deletion. Rather than
240
+ * silently rejecting every real login for such adapters,
241
+ * `deleteRemovedRow` treats an unrecognized non-null result as removed —
242
+ * this reopens the pre-consume find-then-delete race window (multiple
243
+ * concurrent callers can pass) for adapters that can't report a match,
244
+ * but does not break login. It is fail-closed (returns null / rejects)
245
+ * only for `null`/`undefined`, DrizzleAdapter's definitive "no rows
246
+ * matched" signal.
247
+ */
248
+ async consume(stateHash) {
249
+ const record = await this.fetchLive(stateHash);
250
+ if (!record) {
251
+ return null;
252
+ }
253
+ const result = await this.model.where({ stateHash, expiresAt: record.expiresAt }).delete();
254
+ return deleteRemovedRow(result) ? mapRecordToPayload(record) : null;
255
+ }
256
+ /**
257
+ * Delete OAuth states whose expiration time has passed. Expired states
258
+ * are already rejected by `find`; call this from a scheduled job to keep
259
+ * the table small.
260
+ */
261
+ async deleteExpired(now = /* @__PURE__ */ new Date()) {
262
+ await this.model.where("expiresAt", "<=", now).delete();
263
+ }
264
+ };
265
+ function mapRecordToPayload(record) {
266
+ return {
267
+ provider: String(record.provider),
268
+ redirectTo: record.redirectTo == null ? void 0 : String(record.redirectTo),
269
+ // fetchLive's isExpired check guarantees this parses.
270
+ expiresAt: toDate(record.expiresAt)
271
+ };
272
+ }
273
+ function deleteRemovedRow(result) {
274
+ if (result == null) return false;
275
+ if (typeof result === "number") return result > 0;
276
+ if (Array.isArray(result)) {
277
+ return result.length > 0 && deleteRemovedRow(result[0]);
278
+ }
279
+ if (typeof result === "object") {
280
+ const record = result;
281
+ for (const key of ["affectedRows", "rowsAffected", "rowCount", "changes"]) {
282
+ if (typeof record[key] === "number") return record[key] > 0;
283
+ }
284
+ return true;
285
+ }
286
+ return Boolean(result);
82
287
  }
83
288
  export {
84
289
  DatabaseApiTokenStore,
290
+ DatabaseOAuthStateStore,
291
+ DatabaseSessionStore,
85
292
  DrizzleAdapter,
86
293
  MassAssignmentException,
87
- Model2 as Model,
294
+ Model4 as Model,
88
295
  ModelNotFoundException,
89
296
  QueryBuilder,
90
297
  SoftDeletes,
298
+ createAwsDataApiDatabase,
299
+ createD1Database,
91
300
  createMySqlDatabase,
92
301
  createPostgresDatabase,
93
302
  createSqliteDatabase,
@@ -0,0 +1,189 @@
1
+ type PathLike = string | URL;
2
+ type ManifestEntry = {
3
+ file?: string;
4
+ css?: string[];
5
+ };
6
+ type Manifest = Record<string, ManifestEntry>;
7
+ declare function resolvePathLike(value: PathLike): string;
8
+ /**
9
+ * Read the first manifest that parses, tolerating both Vite layouts
10
+ * (`.vite/manifest.json` and the flat `manifest.json` older configs emit), and
11
+ * report which path it was. A malformed file is skipped rather than fatal —
12
+ * the caller decides what a missing manifest means for its platform. The path
13
+ * is part of the result because a caller publishing the manifest location to
14
+ * the runtime has to name the file that was actually parsed: testing which one
15
+ * *exists* picks the malformed one that was just skipped.
16
+ */
17
+ declare function readManifest(...paths: string[]): {
18
+ manifest: Manifest;
19
+ path: string;
20
+ } | undefined;
21
+ /**
22
+ * Throw unless `out` is safe to delete: it must be neither the app root nor a
23
+ * directory containing it.
24
+ *
25
+ * Both paths are resolved through their symlinks first, because the delete
26
+ * that follows does too. Comparing lexically accepts `outputDir` values that
27
+ * reach the app root the long way — on macOS `/tmp` is itself a symlink to
28
+ * `/private/tmp`, so this is not a contrived case.
29
+ *
30
+ * Containment is then decided with `relative` rather than a string prefix
31
+ * because `out + sep` is `//` at the filesystem root, which no absolute path
32
+ * is prefixed by — a prefix test lets `outputDir: '/'` through. The escape
33
+ * test is `'..'` exactly or a `'../'` prefix, not `startsWith('..')`: a
34
+ * directory legitimately named `..-source` inside `out` yields the relative
35
+ * path `..-source`, which the looser test would read as an escape.
36
+ *
37
+ * Exported separately from `resetOutputDir` so a caller can validate the
38
+ * option early and delete later, but the delete itself should always go
39
+ * through `resetOutputDir`.
40
+ *
41
+ * @param label Platform name for the error message, e.g. `'Lambda build'`.
42
+ */
43
+ declare function assertOutputDirOutsideRoot(out: string, root: string, label: string): void;
44
+ /**
45
+ * Delete the output directory so the build starts from a clean slate, after
46
+ * checking it is safe to delete.
47
+ *
48
+ * The check and the delete are one call on purpose: they were separate
49
+ * statements in each plugin, and a plugin that had only the delete has already
50
+ * shipped.
51
+ *
52
+ * @param label Platform name for the error message, e.g. `'Lambda build'`.
53
+ */
54
+ declare function resetOutputDir(out: string, root: string, label: string): void;
55
+ /**
56
+ * Relative specifier for importing `target` from a module written into
57
+ * `fromDir`, in POSIX form so the emitted source is platform-agnostic.
58
+ *
59
+ * @param label Platform name for the error message, e.g. `'Lambda build'`.
60
+ */
61
+ declare function importSpecifier(fromDir: string, target: string, label: string): string;
62
+ interface ClientAssetEnv {
63
+ entry?: string;
64
+ styles?: string;
65
+ }
66
+ /**
67
+ * Locate the built client entry and its CSS in the Vite client manifest, as
68
+ * the `/assets/`-prefixed URLs the Inertia head expects.
69
+ *
70
+ * Takes the public directory rather than the app root so a caller passing a
71
+ * custom `publicDir` is honoured.
72
+ *
73
+ * @param label Platform name for the warning message, e.g. `'Lambda build'`.
74
+ */
75
+ declare function resolveClientAssetEnv(publicDir: string, clientEntryKey: string, label: string): ClientAssetEnv;
76
+ /**
77
+ * Absolute path of the built SSR entry chunk, or undefined when the app has no
78
+ * SSR build. Verifying that the chunk actually exports a renderer is left to
79
+ * the caller: the platforms disagree on whether importing it during a build is
80
+ * acceptable.
81
+ *
82
+ * @param label Platform name for the error messages, e.g. `'Lambda build'`.
83
+ */
84
+ declare function resolveSsrEntryFile(ssrDir: string, ssrEntryKey: string, label: string): string | undefined;
85
+ /**
86
+ * Runtime locations of a staged SSR bundle, for platforms that copy `ssrDir`
87
+ * under the function root and hand the layout to the server through
88
+ * environment variables. `prefix` is where the caller stages the directory —
89
+ * it cannot be derived here because staging happens later in the caller's own
90
+ * flow.
91
+ *
92
+ * The manifest path is derived from the file that parsed rather than the
93
+ * first one that exists: both Vite layouts occur in the wild, and a malformed
94
+ * `.vite/manifest.json` alongside a valid flat one would otherwise publish the
95
+ * path to the file that was skipped. It is optional only for the mid-build
96
+ * race where the manifest vanishes between `resolveSsrEntryFile` and this
97
+ * call — callers already hold a chunk path that manifest produced.
98
+ */
99
+ declare function ssrRuntimePaths(ssrDir: string, ssrFile: string, prefix: string): {
100
+ entry: string;
101
+ manifest?: string;
102
+ };
103
+ /**
104
+ * Copy `public/` into a platform's static-asset staging directory.
105
+ *
106
+ * Two pieces of Guren-specific knowledge, not platform policy, which is why
107
+ * this is shared: the dev-mode `index.html` shell must never ship (it would
108
+ * shadow the app's root route on any host that serves static files first), and
109
+ * built assets self-reference the Vite plugin's derived base `/public/assets/`
110
+ * while HTML references use `/assets/` — so on a host without rewrites the
111
+ * built-assets directory has to appear under both prefixes.
112
+ */
113
+ declare function stageStaticAssets(publicDir: string, assetsOut: string): void;
114
+ /** What a dev-only module is needed for, so a plugin can word its own message. */
115
+ type DevOnlyModuleKind = 'sqlite' | 'vite' | 'mcp';
116
+ interface DevOnlyModule {
117
+ readonly specifier: string;
118
+ readonly kind: DevOnlyModuleKind;
119
+ /**
120
+ * Names the importing code destructures. A stub must declare every one of
121
+ * them: an empty module fails the bundle with "no matching export" rather
122
+ * than at runtime. Empty means the module is only ever read through
123
+ * namespace property access, so an empty module suffices.
124
+ */
125
+ readonly exportNames: readonly string[];
126
+ }
127
+ /**
128
+ * Modules that cannot run off Bun but sit in the graph of any app importing
129
+ * `@guren/core`, reached only through dev-time branches. Core aggregates
130
+ * `@guren/server` and `@guren/orm`, where these imports actually live, so it
131
+ * is the one package that sees the whole set — which is why the list lives
132
+ * here rather than in each plugin, where two copies had already drifted apart.
133
+ *
134
+ * Bundlers follow these imports even when they are dynamic, so without stubs
135
+ * the build either fails to resolve them or ships megabytes of dev tooling.
136
+ *
137
+ * - `sqlite` — the local sqlite ORM factory, opposite the platform's own
138
+ * database branch in `config/database.ts`.
139
+ * - `vite` — the dev asset server `Application` starts when serving locally.
140
+ * - `mcp` — the opt-in MCP endpoint's lazy imports, which drag the CLI
141
+ * generators (and Babel) plus the MCP SDK in behind them.
142
+ *
143
+ * `as const` so a consumer can key an exhaustive table on the specifiers and
144
+ * have a new entry here surface as a compile error there.
145
+ */
146
+ declare const DEV_ONLY_MODULES: readonly [{
147
+ readonly specifier: "bun:sqlite";
148
+ readonly kind: "sqlite";
149
+ readonly exportNames: readonly ["Database"];
150
+ }, {
151
+ readonly specifier: "vite";
152
+ readonly kind: "vite";
153
+ readonly exportNames: readonly ["createServer"];
154
+ }, {
155
+ readonly specifier: "@guren/cli";
156
+ readonly kind: "mcp";
157
+ readonly exportNames: readonly [];
158
+ }, {
159
+ readonly specifier: "@modelcontextprotocol/sdk/server/mcp.js";
160
+ readonly kind: "mcp";
161
+ readonly exportNames: readonly ["McpServer", "ResourceTemplate"];
162
+ }, {
163
+ readonly specifier: "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
164
+ readonly kind: "mcp";
165
+ readonly exportNames: readonly ["WebStandardStreamableHTTPServerTransport"];
166
+ }];
167
+ type DevOnlySpecifier = (typeof DEV_ONLY_MODULES)[number]['specifier'];
168
+ /**
169
+ * Source for a stub replacing one dev-only module. Shared because what it
170
+ * encodes is a bundler constraint, not a platform choice: every name the
171
+ * importer destructures must be present or the bundle fails with "no matching
172
+ * export", and each is emitted as a throwing *function* because the stubbed
173
+ * names mix constructors (`new Database()`) with plain calls
174
+ * (`createServer()`) — a class invoked without `new` reports "Class
175
+ * constructor cannot be invoked without 'new'" instead of the real reason.
176
+ *
177
+ * @param message Platform-specific explanation, including the replacement API.
178
+ */
179
+ declare function renderDevOnlyStub(module: DevOnlyModule, message: string): string;
180
+ /**
181
+ * The MCP SDK is only ever reached through subpaths, and a bundler alias on a
182
+ * package name does not cover them — which is why `DEV_ONLY_MODULES` lists
183
+ * each one. A platform whose aliasing supports prefixes should also route
184
+ * unlisted subpaths under this prefix to a stub, so a new subpath added
185
+ * upstream cannot pull the real SDK into a deployed bundle.
186
+ */
187
+ declare const MCP_SDK_SUBPATH_PREFIX = "@modelcontextprotocol/sdk/";
188
+
189
+ export { type ClientAssetEnv, DEV_ONLY_MODULES, type DevOnlyModule, type DevOnlyModuleKind, type DevOnlySpecifier, MCP_SDK_SUBPATH_PREFIX, type Manifest, type ManifestEntry, type PathLike, assertOutputDirOutsideRoot, importSpecifier, readManifest, renderDevOnlyStub, resetOutputDir, resolveClientAssetEnv, resolvePathLike, resolveSsrEntryFile, ssrRuntimePaths, stageStaticAssets };
@@ -0,0 +1,155 @@
1
+ // src/internal/deploy-build.ts
2
+ import { cpSync, existsSync, mkdirSync, readFileSync, realpathSync, rmSync } from "fs";
3
+ import { basename, dirname, isAbsolute, relative, resolve, sep } from "path";
4
+ import { fileURLToPath } from "url";
5
+ function resolvePathLike(value) {
6
+ return value instanceof URL ? fileURLToPath(value) : resolve(String(value));
7
+ }
8
+ function readManifest(...paths) {
9
+ for (const path of paths) {
10
+ if (!existsSync(path)) {
11
+ continue;
12
+ }
13
+ try {
14
+ return { manifest: JSON.parse(readFileSync(path, "utf8")), path };
15
+ } catch {
16
+ continue;
17
+ }
18
+ }
19
+ return void 0;
20
+ }
21
+ function manifestPaths(dir) {
22
+ return [resolve(dir, ".vite/manifest.json"), resolve(dir, "manifest.json")];
23
+ }
24
+ function realpathOfNearestExisting(path) {
25
+ try {
26
+ return realpathSync(path);
27
+ } catch (error) {
28
+ if (error.code !== "ENOENT") {
29
+ throw error;
30
+ }
31
+ }
32
+ const parent = dirname(path);
33
+ if (parent === path) {
34
+ return path;
35
+ }
36
+ return resolve(realpathOfNearestExisting(parent), basename(path));
37
+ }
38
+ function assertOutputDirOutsideRoot(out, root, label) {
39
+ const outToRoot = relative(realpathOfNearestExisting(out), realpathOfNearestExisting(root));
40
+ const rootIsInsideOut = outToRoot !== ".." && !outToRoot.startsWith(`..${sep}`) && !isAbsolute(outToRoot);
41
+ if (outToRoot === "" || rootIsInsideOut) {
42
+ throw new Error(
43
+ `${label}: outputDir (${out}) must be a directory outside or below the app root, never the root itself or a parent of it \u2014 it is deleted on every build.`
44
+ );
45
+ }
46
+ }
47
+ function resetOutputDir(out, root, label) {
48
+ assertOutputDirOutsideRoot(out, root, label);
49
+ if (existsSync(out)) {
50
+ rmSync(out, { recursive: true, force: true });
51
+ }
52
+ }
53
+ function importSpecifier(fromDir, target, label) {
54
+ const rel = relative(fromDir, target);
55
+ if (isAbsolute(rel)) {
56
+ throw new Error(
57
+ `${label}: ${target} cannot be imported relative to ${fromDir} (different drive or root?). Keep the app, SSR output, and outputDir on the same volume.`
58
+ );
59
+ }
60
+ const specifier = rel.split(sep).join("/");
61
+ return specifier.startsWith(".") ? specifier : `./${specifier}`;
62
+ }
63
+ function resolveClientAssetEnv(publicDir, clientEntryKey, label) {
64
+ const manifest = readManifest(...manifestPaths(resolve(publicDir, "assets")))?.manifest;
65
+ const entry = manifest?.[clientEntryKey];
66
+ if (!entry?.file) {
67
+ console.warn(
68
+ `${label}: no client manifest entry for "${clientEntryKey}"; GUREN_INERTIA_ENTRY will not be set.`
69
+ );
70
+ return {};
71
+ }
72
+ return {
73
+ entry: `/assets/${entry.file}`,
74
+ styles: entry.css?.length ? entry.css.map((file) => `/assets/${file}`).join(",") : void 0
75
+ };
76
+ }
77
+ function resolveSsrEntryFile(ssrDir, ssrEntryKey, label) {
78
+ const manifest = readManifest(...manifestPaths(ssrDir))?.manifest;
79
+ const entryFile = manifest?.[ssrEntryKey]?.file;
80
+ if (!entryFile) {
81
+ return void 0;
82
+ }
83
+ const file = resolve(ssrDir, entryFile);
84
+ if (!file.startsWith(ssrDir + sep)) {
85
+ throw new Error(`${label}: SSR manifest entry "${entryFile}" escapes the SSR output directory ${ssrDir}.`);
86
+ }
87
+ if (!existsSync(file)) {
88
+ throw new Error(`${label}: SSR manifest points at ${file}, but the file does not exist.`);
89
+ }
90
+ return file;
91
+ }
92
+ function ssrRuntimePaths(ssrDir, ssrFile, prefix) {
93
+ const under = (target) => `${prefix}/${relative(ssrDir, target).split(sep).join("/")}`;
94
+ const read = readManifest(...manifestPaths(ssrDir));
95
+ return {
96
+ entry: under(ssrFile),
97
+ manifest: read ? under(read.path) : void 0
98
+ };
99
+ }
100
+ function stageStaticAssets(publicDir, assetsOut) {
101
+ mkdirSync(assetsOut, { recursive: true });
102
+ if (!existsSync(publicDir)) {
103
+ return;
104
+ }
105
+ cpSync(publicDir, assetsOut, { recursive: true });
106
+ const shadowingIndex = resolve(assetsOut, "index.html");
107
+ if (existsSync(shadowingIndex)) {
108
+ rmSync(shadowingIndex);
109
+ }
110
+ const clientAssetsDir = resolve(publicDir, "assets");
111
+ if (existsSync(clientAssetsDir)) {
112
+ cpSync(clientAssetsDir, resolve(assetsOut, "public/assets"), { recursive: true });
113
+ }
114
+ }
115
+ var DEV_ONLY_MODULES = [
116
+ { specifier: "bun:sqlite", kind: "sqlite", exportNames: ["Database"] },
117
+ { specifier: "vite", kind: "vite", exportNames: ["createServer"] },
118
+ { specifier: "@guren/cli", kind: "mcp", exportNames: [] },
119
+ {
120
+ specifier: "@modelcontextprotocol/sdk/server/mcp.js",
121
+ kind: "mcp",
122
+ exportNames: ["McpServer", "ResourceTemplate"]
123
+ },
124
+ {
125
+ specifier: "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js",
126
+ kind: "mcp",
127
+ exportNames: ["WebStandardStreamableHTTPServerTransport"]
128
+ }
129
+ ];
130
+ function renderDevOnlyStub(module, message) {
131
+ if (module.exportNames.length === 0) {
132
+ return `// ${message}
133
+ export {}
134
+ `;
135
+ }
136
+ const throwing = module.exportNames.map((name) => `export function ${name}() { throw new Error(${JSON.stringify(message)}) }`).join("\n");
137
+ return `${throwing}
138
+ export default { ${module.exportNames.join(", ")} }
139
+ `;
140
+ }
141
+ var MCP_SDK_SUBPATH_PREFIX = "@modelcontextprotocol/sdk/";
142
+ export {
143
+ DEV_ONLY_MODULES,
144
+ MCP_SDK_SUBPATH_PREFIX,
145
+ assertOutputDirOutsideRoot,
146
+ importSpecifier,
147
+ readManifest,
148
+ renderDevOnlyStub,
149
+ resetOutputDir,
150
+ resolveClientAssetEnv,
151
+ resolvePathLike,
152
+ resolveSsrEntryFile,
153
+ ssrRuntimePaths,
154
+ stageStaticAssets
155
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/core",
3
- "version": "1.2.0",
3
+ "version": "1.4.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -40,6 +40,10 @@
40
40
  "./redis": {
41
41
  "types": "./dist/redis.d.ts",
42
42
  "default": "./dist/redis.js"
43
+ },
44
+ "./internal/deploy-build": {
45
+ "types": "./dist/internal/deploy-build.d.ts",
46
+ "default": "./dist/internal/deploy-build.js"
43
47
  }
44
48
  },
45
49
  "bin": {
@@ -52,9 +56,9 @@
52
56
  "typecheck": "tsc --noEmit"
53
57
  },
54
58
  "dependencies": {
55
- "@guren/cli": "^1.4.0",
56
- "@guren/orm": "^1.1.0",
57
- "@guren/server": "^1.3.0"
59
+ "@guren/cli": "^1.6.0",
60
+ "@guren/orm": "^1.3.0",
61
+ "@guren/server": "^1.5.0"
58
62
  },
59
63
  "devDependencies": {
60
64
  "@types/node": "^20.14.10",