@guren/server 0.1.1-alpha.4 → 0.2.0-alpha.6

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.js CHANGED
@@ -1,14 +1,81 @@
1
1
  import {
2
2
  gurenVitePlugin
3
- } from "./chunk-GDCUIM6V.js";
3
+ } from "./chunk-FK2XQSBF.js";
4
+
5
+ // src/support/error-polyfill.ts
6
+ var patched = false;
7
+ function ensureErrorStackTracePolyfill() {
8
+ if (patched) {
9
+ return;
10
+ }
11
+ const capture = Error.captureStackTrace;
12
+ if (typeof capture !== "function") {
13
+ ;
14
+ Error.captureStackTrace = (target) => copyStackFromNewError(target);
15
+ patched = true;
16
+ return;
17
+ }
18
+ ;
19
+ Error.captureStackTrace = (target, constructorOpt) => {
20
+ if (target instanceof Error) {
21
+ try {
22
+ return capture(target, constructorOpt);
23
+ } catch {
24
+ }
25
+ }
26
+ const placeholder = new Error();
27
+ capture(placeholder, constructorOpt);
28
+ copyStackFromError(target, placeholder);
29
+ return target;
30
+ };
31
+ patched = true;
32
+ }
33
+ function copyStackFromNewError(target) {
34
+ const placeholder = new Error();
35
+ copyStackFromError(target, placeholder);
36
+ }
37
+ function copyStackFromError(target, source) {
38
+ if (!target || typeof target !== "object") {
39
+ return;
40
+ }
41
+ if (source.stack) {
42
+ Object.defineProperty(target, "stack", {
43
+ configurable: true,
44
+ enumerable: false,
45
+ writable: true,
46
+ value: source.stack
47
+ });
48
+ }
49
+ if (source.name && !("name" in target)) {
50
+ Object.defineProperty(target, "name", {
51
+ configurable: true,
52
+ enumerable: false,
53
+ writable: true,
54
+ value: source.name
55
+ });
56
+ }
57
+ if (source.message && !("message" in target)) {
58
+ Object.defineProperty(target, "message", {
59
+ configurable: true,
60
+ enumerable: false,
61
+ writable: true,
62
+ value: source.message
63
+ });
64
+ }
65
+ }
4
66
 
5
67
  // src/http/Application.ts
6
68
  import { Hono } from "hono";
7
69
 
8
70
  // src/mvc/Route.ts
71
+ var ROUTE_REGISTRY_KEY = "__guren_route_registry__";
72
+ var ROUTE_PREFIX_STACK_KEY = "__guren_route_prefix_stack__";
73
+ var routeGlobal = globalThis;
74
+ routeGlobal[ROUTE_REGISTRY_KEY] ??= [];
75
+ routeGlobal[ROUTE_PREFIX_STACK_KEY] ??= [];
9
76
  var Route = class {
10
- static registry = [];
11
- static prefixStack = [];
77
+ static registry = routeGlobal[ROUTE_REGISTRY_KEY];
78
+ static prefixStack = routeGlobal[ROUTE_PREFIX_STACK_KEY];
12
79
  static add(method, path, handler, middlewares = []) {
13
80
  const fullPath = joinPaths(this.prefixStack, path);
14
81
  this.registry.push({ method, path: fullPath, handler, middlewares });
@@ -194,16 +261,19 @@ var PluginManager = class {
194
261
  };
195
262
 
196
263
  // src/mvc/inertia/InertiaEngine.ts
264
+ import { isAbsolute, resolve as resolvePath } from "path";
265
+ import { pathToFileURL } from "url";
266
+ ensureErrorStackTracePolyfill();
197
267
  var DEFAULT_TITLE = "Guren";
198
268
  var DEFAULT_IMPORT_MAP = {
199
269
  react: "https://esm.sh/react@19.0.0?dev",
200
270
  "react/jsx-runtime": "https://esm.sh/react@19.0.0/jsx-runtime?dev",
201
271
  "react/jsx-dev-runtime": "https://esm.sh/react@19.0.0/jsx-dev-runtime?dev",
202
272
  "react-dom/client": "https://esm.sh/react-dom@19.0.0/client?dev",
203
- "@inertiajs/react": "https://esm.sh/@inertiajs/react@2.2.15?dev&external=react,react-dom/client",
204
- "@guren/inertia-client": "/vendor/inertia-client.tsx"
273
+ "@guren/inertia-client": "/vendor/inertia-client.tsx",
274
+ "@inertiajs/react": "https://esm.sh/@inertiajs/react@2.2.15?dev&external=react,react-dom/client"
205
275
  };
206
- function inertia(component, props, options = {}) {
276
+ async function inertia(component, props, options = {}) {
207
277
  const page = {
208
278
  component,
209
279
  props,
@@ -219,33 +289,35 @@ function inertia(component, props, options = {}) {
219
289
  headers: {
220
290
  "Content-Type": "application/json; charset=utf-8",
221
291
  "X-Inertia": "true",
222
- "Vary": "Accept",
292
+ Vary: "Accept",
223
293
  ...options.version ? { "X-Inertia-Version": options.version } : {},
224
294
  ...options.headers
225
295
  }
226
296
  });
227
297
  }
228
- const html = renderDocument(page, options);
298
+ const html = await renderDocument(page, options);
229
299
  return new Response(html, {
230
300
  status: options.status ?? 200,
231
301
  headers: {
232
302
  "Content-Type": "text/html; charset=utf-8",
233
303
  "X-Inertia": "true",
234
- "Vary": "Accept",
304
+ Vary: "Accept",
235
305
  ...options.version ? { "X-Inertia-Version": options.version } : {},
236
306
  ...options.headers
237
307
  }
238
308
  });
239
309
  }
240
- function renderDocument(page, options) {
310
+ async function renderDocument(page, options) {
241
311
  const defaultEntry = process.env.GUREN_INERTIA_ENTRY ?? "/resources/js/app.tsx";
242
312
  const entry = options.entry ?? defaultEntry;
243
313
  const title = escapeHtml(options.title ?? DEFAULT_TITLE);
244
314
  const styles = options.styles ?? parseStylesEnv(process.env.GUREN_INERTIA_STYLES);
315
+ const envImportMap = parseImportMap(process.env.GUREN_INERTIA_IMPORT_MAP);
245
316
  const importMap = JSON.stringify(
246
317
  {
247
318
  imports: {
248
319
  ...DEFAULT_IMPORT_MAP,
320
+ ...envImportMap,
249
321
  ...options.importMap ?? {}
250
322
  }
251
323
  },
@@ -254,28 +326,147 @@ function renderDocument(page, options) {
254
326
  );
255
327
  const serializedPage = serializePage(page);
256
328
  const stylesheetLinks = renderStyles(styles);
329
+ const ssrResult = await tryRenderSsr(page, options);
330
+ const headElements = (ssrResult?.head ?? []).map(normalizeHeadElement);
331
+ const hasCustomTitle = headElements.some(
332
+ (element) => /<title\b[^>]*>/iu.test(element)
333
+ );
334
+ const headSegments = [
335
+ '<meta charset="utf-8" />',
336
+ '<meta name="viewport" content="width=device-width, initial-scale=1" />',
337
+ hasCustomTitle ? "" : `<title>${title}</title>`,
338
+ stylesheetLinks,
339
+ ...headElements,
340
+ `<script type="importmap">${importMap}</script>`,
341
+ `<script>window.__INERTIA_PAGE__ = ${serializedPage};</script>`
342
+ ].filter((segment) => segment && segment.length > 0);
343
+ const appMarkup = ssrResult?.body ?? `<div id="app" data-page="${escapeAttribute(serializedPage)}"></div>`;
257
344
  return `<!DOCTYPE html>
258
345
  <html lang="en">
259
346
  <head>
260
- <meta charset="utf-8" />
261
- <meta name="viewport" content="width=device-width, initial-scale=1" />
262
- <title>${title}</title>
263
- ${stylesheetLinks}
264
- <script type="importmap">${importMap}</script>
265
- <script>window.__INERTIA_PAGE__ = ${serializedPage};</script>
347
+ ${headSegments.join("\n ")}
266
348
  </head>
267
349
  <body>
268
- <div id="app" data-page="${escapeAttribute(serializedPage)}"></div>
350
+ ${appMarkup}
269
351
  <script type="module" src="${entry}"></script>
270
352
  </body>
271
353
  </html>`;
272
354
  }
355
+ async function tryRenderSsr(page, options) {
356
+ const ssrOptions = options.ssr;
357
+ if (ssrOptions?.enabled === false) {
358
+ return void 0;
359
+ }
360
+ const manifest = (ssrOptions?.manifest ?? process.env.GUREN_INERTIA_SSR_MANIFEST)?.trim() || void 0;
361
+ const renderer = ssrOptions?.render ?? await loadSsrRenderer(
362
+ ssrOptions?.entry ?? process.env.GUREN_INERTIA_SSR_ENTRY
363
+ );
364
+ if (!renderer) {
365
+ return void 0;
366
+ }
367
+ try {
368
+ const result = await renderer({
369
+ page,
370
+ request: options.request,
371
+ manifest
372
+ });
373
+ if (!result || typeof result.body !== "string") {
374
+ return void 0;
375
+ }
376
+ return {
377
+ body: result.body,
378
+ head: Array.isArray(result.head) ? result.head : []
379
+ };
380
+ } catch (error) {
381
+ console.error(
382
+ "Inertia SSR renderer failed; falling back to client rendering.",
383
+ error
384
+ );
385
+ return void 0;
386
+ }
387
+ }
388
+ async function loadSsrRenderer(entry) {
389
+ const specifier = entry?.trim();
390
+ if (!specifier) {
391
+ return void 0;
392
+ }
393
+ const normalized = normalizeSsrSpecifier(specifier);
394
+ try {
395
+ const module = await import(normalized);
396
+ const renderCandidate = extractSsrRenderer(module);
397
+ if (!renderCandidate) {
398
+ console.warn(
399
+ `Inertia SSR entry "${specifier}" does not export a renderer. Expected a default export or a named "render" function.`
400
+ );
401
+ return void 0;
402
+ }
403
+ return renderCandidate;
404
+ } catch (error) {
405
+ console.error(`Failed to import Inertia SSR entry "${specifier}".`, error);
406
+ return void 0;
407
+ }
408
+ }
409
+ function extractSsrRenderer(module) {
410
+ if (!module || typeof module !== "object") {
411
+ return void 0;
412
+ }
413
+ const candidate = typeof module.render === "function" ? module.render : typeof module.default === "function" ? module.default : void 0;
414
+ if (!candidate) {
415
+ return void 0;
416
+ }
417
+ return (context) => Promise.resolve(candidate(context));
418
+ }
419
+ function normalizeSsrSpecifier(specifier) {
420
+ if (specifier.startsWith("file://") || isUrlLike(specifier)) {
421
+ return specifier;
422
+ }
423
+ if (specifier.startsWith("./") || specifier.startsWith("../")) {
424
+ const absolute = resolvePath(process.cwd(), specifier);
425
+ return pathToFileURL(absolute).href;
426
+ }
427
+ if (isAbsolute(specifier)) {
428
+ return pathToFileURL(specifier).href;
429
+ }
430
+ return specifier;
431
+ }
432
+ function isUrlLike(specifier) {
433
+ return /^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(specifier);
434
+ }
273
435
  function renderStyles(styles) {
274
436
  if (!styles.length) {
275
437
  return "";
276
438
  }
277
439
  return styles.map((href) => `<link rel="stylesheet" href="${escapeAttribute(href)}" />`).join("\n ");
278
440
  }
441
+ function parseImportMap(value) {
442
+ if (!value) {
443
+ return {};
444
+ }
445
+ try {
446
+ const parsed = JSON.parse(value);
447
+ const result = {};
448
+ for (const [key, entry] of Object.entries(parsed)) {
449
+ if (typeof entry === "string" && entry.length > 0) {
450
+ result[key] = entry;
451
+ }
452
+ }
453
+ return result;
454
+ } catch (error) {
455
+ console.warn(
456
+ "Failed to parse GUREN_INERTIA_IMPORT_MAP. Expected JSON object.",
457
+ error
458
+ );
459
+ return {};
460
+ }
461
+ }
462
+ function normalizeHeadElement(element) {
463
+ const markup = typeof element === "string" ? element : String(element ?? "");
464
+ const pattern = /href="\/(?!public\/)([^"?]+\.(?:js|css))(\?[^"']*)?"/g;
465
+ return markup.replace(
466
+ pattern,
467
+ (_match, file, query = "") => `href="/public/assets/${file}${query}"`
468
+ );
469
+ }
279
470
  function serializePage(page) {
280
471
  return JSON.stringify(page).replace(/[<\u2028\u2029]/gu, (char) => {
281
472
  switch (char) {
@@ -987,210 +1178,2188 @@ var ModelUserProvider = class extends BaseUserProvider {
987
1178
  }
988
1179
  };
989
1180
 
990
- // src/http/Application.ts
991
- var Application = class {
992
- constructor(options = {}) {
993
- this.options = options;
994
- this.hono = new Hono();
995
- this.authManager = new AuthManager();
996
- this.plugins = new PluginManager(() => this.resolveContext());
997
- this.registerDefaultProviders();
998
- if (Array.isArray(this.options.providers)) {
999
- this.plugins.addMany(this.options.providers);
1181
+ // ../../node_modules/.bun/drizzle-orm@0.44.7+ef50eaea70fa4f8c/node_modules/drizzle-orm/entity.js
1182
+ var entityKind = Symbol.for("drizzle:entityKind");
1183
+ var hasOwnEntityKind = Symbol.for("drizzle:hasOwnEntityKind");
1184
+ function is(value, type) {
1185
+ if (!value || typeof value !== "object") {
1186
+ return false;
1187
+ }
1188
+ if (value instanceof type) {
1189
+ return true;
1190
+ }
1191
+ if (!Object.prototype.hasOwnProperty.call(type, entityKind)) {
1192
+ throw new Error(
1193
+ `Class "${type.name ?? "<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`
1194
+ );
1195
+ }
1196
+ let cls = Object.getPrototypeOf(value).constructor;
1197
+ if (cls) {
1198
+ while (cls) {
1199
+ if (entityKind in cls && cls[entityKind] === type[entityKind]) {
1200
+ return true;
1201
+ }
1202
+ cls = Object.getPrototypeOf(cls);
1000
1203
  }
1001
1204
  }
1002
- hono;
1003
- plugins;
1004
- context;
1005
- authManager;
1006
- get auth() {
1007
- return this.authManager;
1205
+ return false;
1206
+ }
1207
+
1208
+ // ../../node_modules/.bun/drizzle-orm@0.44.7+ef50eaea70fa4f8c/node_modules/drizzle-orm/column.js
1209
+ var Column = class {
1210
+ constructor(table, config) {
1211
+ this.table = table;
1212
+ this.config = config;
1213
+ this.name = config.name;
1214
+ this.keyAsName = config.keyAsName;
1215
+ this.notNull = config.notNull;
1216
+ this.default = config.default;
1217
+ this.defaultFn = config.defaultFn;
1218
+ this.onUpdateFn = config.onUpdateFn;
1219
+ this.hasDefault = config.hasDefault;
1220
+ this.primary = config.primaryKey;
1221
+ this.isUnique = config.isUnique;
1222
+ this.uniqueName = config.uniqueName;
1223
+ this.uniqueType = config.uniqueType;
1224
+ this.dataType = config.dataType;
1225
+ this.columnType = config.columnType;
1226
+ this.generated = config.generated;
1227
+ this.generatedIdentity = config.generatedIdentity;
1228
+ }
1229
+ static [entityKind] = "Column";
1230
+ name;
1231
+ keyAsName;
1232
+ primary;
1233
+ notNull;
1234
+ default;
1235
+ defaultFn;
1236
+ onUpdateFn;
1237
+ hasDefault;
1238
+ isUnique;
1239
+ uniqueName;
1240
+ uniqueType;
1241
+ dataType;
1242
+ columnType;
1243
+ enumValues = void 0;
1244
+ generated = void 0;
1245
+ generatedIdentity = void 0;
1246
+ config;
1247
+ mapFromDriverValue(value) {
1248
+ return value;
1249
+ }
1250
+ mapToDriverValue(value) {
1251
+ return value;
1252
+ }
1253
+ // ** @internal */
1254
+ shouldDisableInsert() {
1255
+ return this.config.generated !== void 0 && this.config.generated.type !== "byDefault";
1256
+ }
1257
+ };
1258
+
1259
+ // ../../node_modules/.bun/drizzle-orm@0.44.7+ef50eaea70fa4f8c/node_modules/drizzle-orm/column-builder.js
1260
+ var ColumnBuilder = class {
1261
+ static [entityKind] = "ColumnBuilder";
1262
+ config;
1263
+ constructor(name, dataType, columnType) {
1264
+ this.config = {
1265
+ name,
1266
+ keyAsName: name === "",
1267
+ notNull: false,
1268
+ default: void 0,
1269
+ hasDefault: false,
1270
+ primaryKey: false,
1271
+ isUnique: false,
1272
+ uniqueName: void 0,
1273
+ uniqueType: void 0,
1274
+ dataType,
1275
+ columnType,
1276
+ generated: void 0
1277
+ };
1008
1278
  }
1009
1279
  /**
1010
- * Mounts all routes that were defined through the Route DSL.
1280
+ * Changes the data type of the column. Commonly used with `json` columns. Also, useful for branded types.
1281
+ *
1282
+ * @example
1283
+ * ```ts
1284
+ * const users = pgTable('users', {
1285
+ * id: integer('id').$type<UserId>().primaryKey(),
1286
+ * details: json('details').$type<UserDetails>().notNull(),
1287
+ * });
1288
+ * ```
1011
1289
  */
1012
- mountRoutes() {
1013
- Route.mount(this.hono);
1290
+ $type() {
1291
+ return this;
1014
1292
  }
1015
1293
  /**
1016
- * Allows registering global middlewares directly on the underlying Hono app.
1294
+ * Adds a `not null` clause to the column definition.
1295
+ *
1296
+ * Affects the `select` model of the table - columns *without* `not null` will be nullable on select.
1017
1297
  */
1018
- use(path, ...middleware) {
1019
- this.hono.use(path, ...middleware);
1298
+ notNull() {
1299
+ this.config.notNull = true;
1300
+ return this;
1020
1301
  }
1021
1302
  /**
1022
- * Executes the optional boot callback and mounts the registered routes.
1303
+ * Adds a `default <value>` clause to the column definition.
1304
+ *
1305
+ * Affects the `insert` model of the table - columns *with* `default` are optional on insert.
1306
+ *
1307
+ * If you need to set a dynamic default value, use {@link $defaultFn} instead.
1023
1308
  */
1024
- async boot() {
1025
- await this.plugins.registerAll();
1026
- await this.options.boot?.(this.hono);
1027
- this.mountRoutes();
1028
- await this.plugins.bootAll();
1309
+ default(value) {
1310
+ this.config.default = value;
1311
+ this.config.hasDefault = true;
1312
+ return this;
1029
1313
  }
1030
1314
  /**
1031
- * Fetch handler to integrate with Bun.serve or any standard Fetch runtime.
1315
+ * Adds a dynamic default value to the column.
1316
+ * The function will be called when the row is inserted, and the returned value will be used as the column value.
1317
+ *
1318
+ * **Note:** This value does not affect the `drizzle-kit` behavior, it is only used at runtime in `drizzle-orm`.
1032
1319
  */
1033
- async fetch(request, env, executionCtx) {
1034
- return this.hono.fetch(request, env, executionCtx);
1320
+ $defaultFn(fn) {
1321
+ this.config.defaultFn = fn;
1322
+ this.config.hasDefault = true;
1323
+ return this;
1035
1324
  }
1036
1325
  /**
1037
- * Convenience helper to start a Bun server when available.
1326
+ * Alias for {@link $defaultFn}.
1038
1327
  */
1039
- listen(options = {}) {
1040
- if (!Bun) {
1041
- throw new Error("Bun runtime is required to call Application.listen");
1328
+ $default = this.$defaultFn;
1329
+ /**
1330
+ * Adds a dynamic update value to the column.
1331
+ * The function will be called when the row is updated, and the returned value will be used as the column value if none is provided.
1332
+ * If no `default` (or `$defaultFn`) value is provided, the function will be called when the row is inserted as well, and the returned value will be used as the column value.
1333
+ *
1334
+ * **Note:** This value does not affect the `drizzle-kit` behavior, it is only used at runtime in `drizzle-orm`.
1335
+ */
1336
+ $onUpdateFn(fn) {
1337
+ this.config.onUpdateFn = fn;
1338
+ this.config.hasDefault = true;
1339
+ return this;
1340
+ }
1341
+ /**
1342
+ * Alias for {@link $onUpdateFn}.
1343
+ */
1344
+ $onUpdate = this.$onUpdateFn;
1345
+ /**
1346
+ * Adds a `primary key` clause to the column definition. This implicitly makes the column `not null`.
1347
+ *
1348
+ * In SQLite, `integer primary key` implicitly makes the column auto-incrementing.
1349
+ */
1350
+ primaryKey() {
1351
+ this.config.primaryKey = true;
1352
+ this.config.notNull = true;
1353
+ return this;
1354
+ }
1355
+ /** @internal Sets the name of the column to the key within the table definition if a name was not given. */
1356
+ setName(name) {
1357
+ if (this.config.name !== "") return;
1358
+ this.config.name = name;
1359
+ }
1360
+ };
1361
+
1362
+ // ../../node_modules/.bun/drizzle-orm@0.44.7+ef50eaea70fa4f8c/node_modules/drizzle-orm/table.utils.js
1363
+ var TableName = Symbol.for("drizzle:Name");
1364
+
1365
+ // ../../node_modules/.bun/drizzle-orm@0.44.7+ef50eaea70fa4f8c/node_modules/drizzle-orm/pg-core/foreign-keys.js
1366
+ var ForeignKeyBuilder = class {
1367
+ static [entityKind] = "PgForeignKeyBuilder";
1368
+ /** @internal */
1369
+ reference;
1370
+ /** @internal */
1371
+ _onUpdate = "no action";
1372
+ /** @internal */
1373
+ _onDelete = "no action";
1374
+ constructor(config, actions) {
1375
+ this.reference = () => {
1376
+ const { name, columns, foreignColumns } = config();
1377
+ return { name, columns, foreignTable: foreignColumns[0].table, foreignColumns };
1378
+ };
1379
+ if (actions) {
1380
+ this._onUpdate = actions.onUpdate;
1381
+ this._onDelete = actions.onDelete;
1042
1382
  }
1043
- const { port = 3e3, hostname = "0.0.0.0" } = options;
1044
- Bun.serve({
1045
- port,
1046
- hostname,
1047
- fetch: (request) => this.fetch(request)
1048
- });
1049
1383
  }
1050
- register(provider) {
1051
- this.plugins.add(provider);
1384
+ onUpdate(action) {
1385
+ this._onUpdate = action === void 0 ? "no action" : action;
1052
1386
  return this;
1053
1387
  }
1054
- registerMany(providers) {
1055
- this.plugins.addMany(providers);
1388
+ onDelete(action) {
1389
+ this._onDelete = action === void 0 ? "no action" : action;
1056
1390
  return this;
1057
1391
  }
1058
- resolveContext() {
1059
- if (!this.context) {
1060
- this.context = new ApplicationContext(this, this.authManager);
1061
- }
1062
- return this.context;
1392
+ /** @internal */
1393
+ build(table) {
1394
+ return new ForeignKey(table, this);
1063
1395
  }
1064
- registerDefaultProviders() {
1065
- this.plugins.add(InertiaViewProvider);
1066
- this.plugins.add(AuthServiceProvider);
1396
+ };
1397
+ var ForeignKey = class {
1398
+ constructor(table, builder) {
1399
+ this.table = table;
1400
+ this.reference = builder.reference;
1401
+ this.onUpdate = builder._onUpdate;
1402
+ this.onDelete = builder._onDelete;
1403
+ }
1404
+ static [entityKind] = "PgForeignKey";
1405
+ reference;
1406
+ onUpdate;
1407
+ onDelete;
1408
+ getName() {
1409
+ const { name, columns, foreignColumns } = this.reference();
1410
+ const columnNames = columns.map((column) => column.name);
1411
+ const foreignColumnNames = foreignColumns.map((column) => column.name);
1412
+ const chunks = [
1413
+ this.table[TableName],
1414
+ ...columnNames,
1415
+ foreignColumns[0].table[TableName],
1416
+ ...foreignColumnNames
1417
+ ];
1418
+ return name ?? `${chunks.join("_")}_fk`;
1067
1419
  }
1068
1420
  };
1069
1421
 
1070
- // src/http/dev-assets.ts
1071
- import { serveStatic } from "hono/bun";
1072
- import { dirname, extname, resolve } from "path";
1073
- import { fileURLToPath } from "url";
1074
- import { createRequire } from "module";
1075
- var DEFAULT_PREFIX = "/resources/js";
1076
- var DEFAULT_VENDOR_PATH = "/vendor/inertia-client.tsx";
1077
- var DEFAULT_JSX_RUNTIME = "https://esm.sh/react@19.0.0/jsx-dev-runtime?dev";
1078
- var require2 = createRequire(import.meta.url);
1079
- var gurenInertiaClient = require2.resolve("@guren/inertia-client/app");
1080
- function registerDevAssets(app, options) {
1081
- if (typeof Bun === "undefined") {
1082
- throw new Error("Bun runtime is required for dev asset serving.");
1422
+ // ../../node_modules/.bun/drizzle-orm@0.44.7+ef50eaea70fa4f8c/node_modules/drizzle-orm/tracing-utils.js
1423
+ function iife(fn, ...args) {
1424
+ return fn(...args);
1425
+ }
1426
+
1427
+ // ../../node_modules/.bun/drizzle-orm@0.44.7+ef50eaea70fa4f8c/node_modules/drizzle-orm/pg-core/unique-constraint.js
1428
+ function uniqueKeyName(table, columns) {
1429
+ return `${table[TableName]}_${columns.join("_")}_unique`;
1430
+ }
1431
+ var UniqueConstraintBuilder = class {
1432
+ constructor(columns, name) {
1433
+ this.name = name;
1434
+ this.columns = columns;
1435
+ }
1436
+ static [entityKind] = "PgUniqueConstraintBuilder";
1437
+ /** @internal */
1438
+ columns;
1439
+ /** @internal */
1440
+ nullsNotDistinctConfig = false;
1441
+ nullsNotDistinct() {
1442
+ this.nullsNotDistinctConfig = true;
1443
+ return this;
1083
1444
  }
1084
- const moduleDir = options.importMeta ? dirname(fileURLToPath(options.importMeta.url)) : void 0;
1085
- const resourcesDir = options.resourcesDir ?? (moduleDir ? resolve(moduleDir, options.resourcesPath ?? "../resources") : void 0);
1086
- if (!resourcesDir) {
1087
- throw new Error("registerDevAssets requires either `resourcesDir` or `importMeta`.");
1445
+ /** @internal */
1446
+ build(table) {
1447
+ return new UniqueConstraint(table, this.columns, this.nullsNotDistinctConfig, this.name);
1088
1448
  }
1089
- const prefix = options.prefix ?? DEFAULT_PREFIX;
1090
- const inertiaClientPath = options.inertiaClientPath ?? DEFAULT_VENDOR_PATH;
1091
- const inertiaClientSource = options.inertiaClientSource ?? gurenInertiaClient;
1092
- const jsxRuntimeUrl = options.jsxRuntimeUrl ?? DEFAULT_JSX_RUNTIME;
1093
- const resourcesJsDir = resolve(resourcesDir, "js");
1094
- const reactImportPattern = /from\s+['"]react['"]/u;
1095
- const transpilerOptions = {
1096
- target: "browser",
1097
- jsx: "transform",
1098
- jsxFactory: "React.createElement",
1099
- jsxFragment: "React.Fragment",
1100
- define: {
1101
- "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV ?? "development")
1102
- }
1103
- };
1104
- const tsxTranspiler = new Bun.Transpiler({ loader: "tsx", ...transpilerOptions });
1105
- const tsTranspiler = new Bun.Transpiler({ loader: "ts", ...transpilerOptions });
1106
- app.hono.get(`${prefix}/*`, (ctx) => handleTranspileRequest(ctx, resourcesJsDir, prefix, reactImportPattern, tsxTranspiler, tsTranspiler, jsxRuntimeUrl));
1107
- if (options.inertiaClient !== false) {
1108
- app.hono.get(inertiaClientPath, () => transpileFile(inertiaClientSource, reactImportPattern, tsxTranspiler, tsTranspiler, jsxRuntimeUrl));
1449
+ };
1450
+ var UniqueOnConstraintBuilder = class {
1451
+ static [entityKind] = "PgUniqueOnConstraintBuilder";
1452
+ /** @internal */
1453
+ name;
1454
+ constructor(name) {
1455
+ this.name = name;
1109
1456
  }
1110
- const publicPathOption = options.publicPath === void 0 ? "../public" : options.publicPath;
1111
- const publicDir = options.publicDir ?? (moduleDir && publicPathOption ? resolve(moduleDir, publicPathOption) : void 0);
1112
- const shouldServePublic = publicDir && publicPathOption !== false;
1113
- if (shouldServePublic) {
1114
- const publicRoute = options.publicRoute ?? "/public/*";
1115
- const rewriteRequestPath = createStaticRewrite(publicRoute);
1116
- app.use(
1117
- publicRoute,
1118
- serveStatic({
1119
- root: publicDir,
1120
- rewriteRequestPath
1121
- })
1122
- );
1123
- if (options.favicon !== false) {
1124
- app.hono.get("/favicon.ico", () => new Response(null, { status: 204 }));
1125
- }
1457
+ on(...columns) {
1458
+ return new UniqueConstraintBuilder(columns, this.name);
1126
1459
  }
1127
- }
1128
- function createStaticRewrite(route) {
1129
- const wildcardIndex = route.indexOf("*");
1130
- const base = wildcardIndex >= 0 ? route.slice(0, wildcardIndex) : route;
1131
- const normalizedBase = base.endsWith("/") ? base.slice(0, -1) : base;
1132
- if (!normalizedBase) {
1133
- return (path) => path || "/";
1460
+ };
1461
+ var UniqueConstraint = class {
1462
+ constructor(table, columns, nullsNotDistinct, name) {
1463
+ this.table = table;
1464
+ this.columns = columns;
1465
+ this.name = name ?? uniqueKeyName(this.table, this.columns.map((column) => column.name));
1466
+ this.nullsNotDistinct = nullsNotDistinct;
1467
+ }
1468
+ static [entityKind] = "PgUniqueConstraint";
1469
+ columns;
1470
+ name;
1471
+ nullsNotDistinct = false;
1472
+ getName() {
1473
+ return this.name;
1134
1474
  }
1135
- return (path) => {
1136
- if (!path.startsWith(normalizedBase)) {
1137
- return path || "/";
1475
+ };
1476
+
1477
+ // ../../node_modules/.bun/drizzle-orm@0.44.7+ef50eaea70fa4f8c/node_modules/drizzle-orm/pg-core/utils/array.js
1478
+ function parsePgArrayValue(arrayString, startFrom, inQuotes) {
1479
+ for (let i = startFrom; i < arrayString.length; i++) {
1480
+ const char = arrayString[i];
1481
+ if (char === "\\") {
1482
+ i++;
1483
+ continue;
1138
1484
  }
1139
- const remainder = path.slice(normalizedBase.length);
1140
- if (!remainder) {
1141
- return "/";
1485
+ if (char === '"') {
1486
+ return [arrayString.slice(startFrom, i).replace(/\\/g, ""), i + 1];
1487
+ }
1488
+ if (inQuotes) {
1489
+ continue;
1490
+ }
1491
+ if (char === "," || char === "}") {
1492
+ return [arrayString.slice(startFrom, i).replace(/\\/g, ""), i];
1142
1493
  }
1143
- return remainder.startsWith("/") ? remainder : `/${remainder}`;
1144
- };
1145
- }
1146
- async function handleTranspileRequest(ctx, resourcesJsDir, prefix, reactImportPattern, tsxTranspiler, tsTranspiler, jsxRuntimeUrl) {
1147
- const relative = ctx.req.path.slice(prefix.length + 1);
1148
- const fsPath = resolve(resourcesJsDir, relative);
1149
- if (!fsPath.startsWith(resourcesJsDir)) {
1150
- return ctx.notFound();
1151
1494
  }
1152
- return transpileFile(fsPath, reactImportPattern, tsxTranspiler, tsTranspiler, jsxRuntimeUrl);
1495
+ return [arrayString.slice(startFrom).replace(/\\/g, ""), arrayString.length];
1153
1496
  }
1154
- async function transpileFile(fsPath, reactImportPattern, tsxTranspiler, tsTranspiler, jsxRuntimeUrl) {
1155
- const candidates = buildCandidatePaths(fsPath);
1156
- let filePath;
1157
- let file;
1158
- for (const candidate of candidates) {
1159
- const bunFile = Bun.file(candidate);
1160
- if (await bunFile.exists()) {
1161
- filePath = candidate;
1162
- file = bunFile;
1163
- break;
1497
+ function parsePgNestedArray(arrayString, startFrom = 0) {
1498
+ const result = [];
1499
+ let i = startFrom;
1500
+ let lastCharIsComma = false;
1501
+ while (i < arrayString.length) {
1502
+ const char = arrayString[i];
1503
+ if (char === ",") {
1504
+ if (lastCharIsComma || i === startFrom) {
1505
+ result.push("");
1506
+ }
1507
+ lastCharIsComma = true;
1508
+ i++;
1509
+ continue;
1510
+ }
1511
+ lastCharIsComma = false;
1512
+ if (char === "\\") {
1513
+ i += 2;
1514
+ continue;
1515
+ }
1516
+ if (char === '"') {
1517
+ const [value2, startFrom2] = parsePgArrayValue(arrayString, i + 1, true);
1518
+ result.push(value2);
1519
+ i = startFrom2;
1520
+ continue;
1521
+ }
1522
+ if (char === "}") {
1523
+ return [result, i + 1];
1524
+ }
1525
+ if (char === "{") {
1526
+ const [value2, startFrom2] = parsePgNestedArray(arrayString, i + 1);
1527
+ result.push(value2);
1528
+ i = startFrom2;
1529
+ continue;
1530
+ }
1531
+ const [value, newStartFrom] = parsePgArrayValue(arrayString, i, false);
1532
+ result.push(value);
1533
+ i = newStartFrom;
1534
+ }
1535
+ return [result, i];
1536
+ }
1537
+ function parsePgArray(arrayString) {
1538
+ const [result] = parsePgNestedArray(arrayString, 1);
1539
+ return result;
1540
+ }
1541
+ function makePgArray(array) {
1542
+ return `{${array.map((item) => {
1543
+ if (Array.isArray(item)) {
1544
+ return makePgArray(item);
1545
+ }
1546
+ if (typeof item === "string") {
1547
+ return `"${item.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
1164
1548
  }
1549
+ return `${item}`;
1550
+ }).join(",")}}`;
1551
+ }
1552
+
1553
+ // ../../node_modules/.bun/drizzle-orm@0.44.7+ef50eaea70fa4f8c/node_modules/drizzle-orm/pg-core/columns/common.js
1554
+ var PgColumnBuilder = class extends ColumnBuilder {
1555
+ foreignKeyConfigs = [];
1556
+ static [entityKind] = "PgColumnBuilder";
1557
+ array(size) {
1558
+ return new PgArrayBuilder(this.config.name, this, size);
1559
+ }
1560
+ references(ref, actions = {}) {
1561
+ this.foreignKeyConfigs.push({ ref, actions });
1562
+ return this;
1165
1563
  }
1166
- if (!file || !filePath) {
1167
- return new Response("Not Found", { status: 404 });
1564
+ unique(name, config) {
1565
+ this.config.isUnique = true;
1566
+ this.config.uniqueName = name;
1567
+ this.config.uniqueType = config?.nulls;
1568
+ return this;
1168
1569
  }
1169
- const ext = extname(filePath);
1170
- let source = await file.text();
1171
- if (ext === ".tsx" && !reactImportPattern.test(source)) {
1172
- source = "import React from 'react'\n" + source;
1570
+ generatedAlwaysAs(as) {
1571
+ this.config.generated = {
1572
+ as,
1573
+ type: "always",
1574
+ mode: "stored"
1575
+ };
1576
+ return this;
1173
1577
  }
1174
- if (ext === ".tsx" || ext === ".ts") {
1175
- const transpiled = ext === ".tsx" ? tsxTranspiler.transformSync(source, {
1176
- loader: "tsx",
1177
- sourceMap: isDev() ? "inline" : false,
1178
- filename: filePath
1179
- }) : tsTranspiler.transformSync(source, {
1180
- loader: "ts",
1181
- sourceMap: isDev() ? "inline" : false,
1182
- filename: filePath
1183
- });
1184
- const helpers = collectJsxHelpers(transpiled);
1185
- const runtimeShim = helpers.size ? createJsxRuntimeShim(helpers, jsxRuntimeUrl) : "";
1186
- return new Response(runtimeShim + transpiled, {
1187
- headers: {
1188
- "Content-Type": "application/javascript; charset=utf-8",
1189
- "Cache-Control": isDev() ? "no-cache" : "public, max-age=31536000"
1190
- }
1578
+ /** @internal */
1579
+ buildForeignKeys(column, table) {
1580
+ return this.foreignKeyConfigs.map(({ ref, actions }) => {
1581
+ return iife(
1582
+ (ref2, actions2) => {
1583
+ const builder = new ForeignKeyBuilder(() => {
1584
+ const foreignColumn = ref2();
1585
+ return { columns: [column], foreignColumns: [foreignColumn] };
1586
+ });
1587
+ if (actions2.onUpdate) {
1588
+ builder.onUpdate(actions2.onUpdate);
1589
+ }
1590
+ if (actions2.onDelete) {
1591
+ builder.onDelete(actions2.onDelete);
1592
+ }
1593
+ return builder.build(table);
1594
+ },
1595
+ ref,
1596
+ actions
1597
+ );
1191
1598
  });
1192
1599
  }
1193
- const body = await file.arrayBuffer();
1600
+ /** @internal */
1601
+ buildExtraConfigColumn(table) {
1602
+ return new ExtraConfigColumn(table, this.config);
1603
+ }
1604
+ };
1605
+ var PgColumn = class extends Column {
1606
+ constructor(table, config) {
1607
+ if (!config.uniqueName) {
1608
+ config.uniqueName = uniqueKeyName(table, [config.name]);
1609
+ }
1610
+ super(table, config);
1611
+ this.table = table;
1612
+ }
1613
+ static [entityKind] = "PgColumn";
1614
+ };
1615
+ var ExtraConfigColumn = class extends PgColumn {
1616
+ static [entityKind] = "ExtraConfigColumn";
1617
+ getSQLType() {
1618
+ return this.getSQLType();
1619
+ }
1620
+ indexConfig = {
1621
+ order: this.config.order ?? "asc",
1622
+ nulls: this.config.nulls ?? "last",
1623
+ opClass: this.config.opClass
1624
+ };
1625
+ defaultConfig = {
1626
+ order: "asc",
1627
+ nulls: "last",
1628
+ opClass: void 0
1629
+ };
1630
+ asc() {
1631
+ this.indexConfig.order = "asc";
1632
+ return this;
1633
+ }
1634
+ desc() {
1635
+ this.indexConfig.order = "desc";
1636
+ return this;
1637
+ }
1638
+ nullsFirst() {
1639
+ this.indexConfig.nulls = "first";
1640
+ return this;
1641
+ }
1642
+ nullsLast() {
1643
+ this.indexConfig.nulls = "last";
1644
+ return this;
1645
+ }
1646
+ /**
1647
+ * ### PostgreSQL documentation quote
1648
+ *
1649
+ * > An operator class with optional parameters can be specified for each column of an index.
1650
+ * The operator class identifies the operators to be used by the index for that column.
1651
+ * For example, a B-tree index on four-byte integers would use the int4_ops class;
1652
+ * this operator class includes comparison functions for four-byte integers.
1653
+ * In practice the default operator class for the column's data type is usually sufficient.
1654
+ * The main point of having operator classes is that for some data types, there could be more than one meaningful ordering.
1655
+ * For example, we might want to sort a complex-number data type either by absolute value or by real part.
1656
+ * We could do this by defining two operator classes for the data type and then selecting the proper class when creating an index.
1657
+ * More information about operator classes check:
1658
+ *
1659
+ * ### Useful links
1660
+ * https://www.postgresql.org/docs/current/sql-createindex.html
1661
+ *
1662
+ * https://www.postgresql.org/docs/current/indexes-opclass.html
1663
+ *
1664
+ * https://www.postgresql.org/docs/current/xindex.html
1665
+ *
1666
+ * ### Additional types
1667
+ * If you have the `pg_vector` extension installed in your database, you can use the
1668
+ * `vector_l2_ops`, `vector_ip_ops`, `vector_cosine_ops`, `vector_l1_ops`, `bit_hamming_ops`, `bit_jaccard_ops`, `halfvec_l2_ops`, `sparsevec_l2_ops` options, which are predefined types.
1669
+ *
1670
+ * **You can always specify any string you want in the operator class, in case Drizzle doesn't have it natively in its types**
1671
+ *
1672
+ * @param opClass
1673
+ * @returns
1674
+ */
1675
+ op(opClass) {
1676
+ this.indexConfig.opClass = opClass;
1677
+ return this;
1678
+ }
1679
+ };
1680
+ var IndexedColumn = class {
1681
+ static [entityKind] = "IndexedColumn";
1682
+ constructor(name, keyAsName, type, indexConfig) {
1683
+ this.name = name;
1684
+ this.keyAsName = keyAsName;
1685
+ this.type = type;
1686
+ this.indexConfig = indexConfig;
1687
+ }
1688
+ name;
1689
+ keyAsName;
1690
+ type;
1691
+ indexConfig;
1692
+ };
1693
+ var PgArrayBuilder = class extends PgColumnBuilder {
1694
+ static [entityKind] = "PgArrayBuilder";
1695
+ constructor(name, baseBuilder, size) {
1696
+ super(name, "array", "PgArray");
1697
+ this.config.baseBuilder = baseBuilder;
1698
+ this.config.size = size;
1699
+ }
1700
+ /** @internal */
1701
+ build(table) {
1702
+ const baseColumn = this.config.baseBuilder.build(table);
1703
+ return new PgArray(
1704
+ table,
1705
+ this.config,
1706
+ baseColumn
1707
+ );
1708
+ }
1709
+ };
1710
+ var PgArray = class _PgArray extends PgColumn {
1711
+ constructor(table, config, baseColumn, range) {
1712
+ super(table, config);
1713
+ this.baseColumn = baseColumn;
1714
+ this.range = range;
1715
+ this.size = config.size;
1716
+ }
1717
+ size;
1718
+ static [entityKind] = "PgArray";
1719
+ getSQLType() {
1720
+ return `${this.baseColumn.getSQLType()}[${typeof this.size === "number" ? this.size : ""}]`;
1721
+ }
1722
+ mapFromDriverValue(value) {
1723
+ if (typeof value === "string") {
1724
+ value = parsePgArray(value);
1725
+ }
1726
+ return value.map((v) => this.baseColumn.mapFromDriverValue(v));
1727
+ }
1728
+ mapToDriverValue(value, isNestedArray = false) {
1729
+ const a = value.map(
1730
+ (v) => v === null ? null : is(this.baseColumn, _PgArray) ? this.baseColumn.mapToDriverValue(v, true) : this.baseColumn.mapToDriverValue(v)
1731
+ );
1732
+ if (isNestedArray) return a;
1733
+ return makePgArray(a);
1734
+ }
1735
+ };
1736
+
1737
+ // ../../node_modules/.bun/drizzle-orm@0.44.7+ef50eaea70fa4f8c/node_modules/drizzle-orm/pg-core/columns/enum.js
1738
+ var PgEnumObjectColumnBuilder = class extends PgColumnBuilder {
1739
+ static [entityKind] = "PgEnumObjectColumnBuilder";
1740
+ constructor(name, enumInstance) {
1741
+ super(name, "string", "PgEnumObjectColumn");
1742
+ this.config.enum = enumInstance;
1743
+ }
1744
+ /** @internal */
1745
+ build(table) {
1746
+ return new PgEnumObjectColumn(
1747
+ table,
1748
+ this.config
1749
+ );
1750
+ }
1751
+ };
1752
+ var PgEnumObjectColumn = class extends PgColumn {
1753
+ static [entityKind] = "PgEnumObjectColumn";
1754
+ enum;
1755
+ enumValues = this.config.enum.enumValues;
1756
+ constructor(table, config) {
1757
+ super(table, config);
1758
+ this.enum = config.enum;
1759
+ }
1760
+ getSQLType() {
1761
+ return this.enum.enumName;
1762
+ }
1763
+ };
1764
+ var isPgEnumSym = Symbol.for("drizzle:isPgEnum");
1765
+ function isPgEnum(obj) {
1766
+ return !!obj && typeof obj === "function" && isPgEnumSym in obj && obj[isPgEnumSym] === true;
1767
+ }
1768
+ var PgEnumColumnBuilder = class extends PgColumnBuilder {
1769
+ static [entityKind] = "PgEnumColumnBuilder";
1770
+ constructor(name, enumInstance) {
1771
+ super(name, "string", "PgEnumColumn");
1772
+ this.config.enum = enumInstance;
1773
+ }
1774
+ /** @internal */
1775
+ build(table) {
1776
+ return new PgEnumColumn(
1777
+ table,
1778
+ this.config
1779
+ );
1780
+ }
1781
+ };
1782
+ var PgEnumColumn = class extends PgColumn {
1783
+ static [entityKind] = "PgEnumColumn";
1784
+ enum = this.config.enum;
1785
+ enumValues = this.config.enum.enumValues;
1786
+ constructor(table, config) {
1787
+ super(table, config);
1788
+ this.enum = config.enum;
1789
+ }
1790
+ getSQLType() {
1791
+ return this.enum.enumName;
1792
+ }
1793
+ };
1794
+
1795
+ // ../../node_modules/.bun/drizzle-orm@0.44.7+ef50eaea70fa4f8c/node_modules/drizzle-orm/subquery.js
1796
+ var Subquery = class {
1797
+ static [entityKind] = "Subquery";
1798
+ constructor(sql2, fields, alias, isWith = false, usedTables = []) {
1799
+ this._ = {
1800
+ brand: "Subquery",
1801
+ sql: sql2,
1802
+ selectedFields: fields,
1803
+ alias,
1804
+ isWith,
1805
+ usedTables
1806
+ };
1807
+ }
1808
+ // getSQL(): SQL<unknown> {
1809
+ // return new SQL([this]);
1810
+ // }
1811
+ };
1812
+ var WithSubquery = class extends Subquery {
1813
+ static [entityKind] = "WithSubquery";
1814
+ };
1815
+
1816
+ // ../../node_modules/.bun/drizzle-orm@0.44.7+ef50eaea70fa4f8c/node_modules/drizzle-orm/version.js
1817
+ var version = "0.44.7";
1818
+
1819
+ // ../../node_modules/.bun/drizzle-orm@0.44.7+ef50eaea70fa4f8c/node_modules/drizzle-orm/tracing.js
1820
+ var otel;
1821
+ var rawTracer;
1822
+ var tracer = {
1823
+ startActiveSpan(name, fn) {
1824
+ if (!otel) {
1825
+ return fn();
1826
+ }
1827
+ if (!rawTracer) {
1828
+ rawTracer = otel.trace.getTracer("drizzle-orm", version);
1829
+ }
1830
+ return iife(
1831
+ (otel2, rawTracer2) => rawTracer2.startActiveSpan(
1832
+ name,
1833
+ (span) => {
1834
+ try {
1835
+ return fn(span);
1836
+ } catch (e) {
1837
+ span.setStatus({
1838
+ code: otel2.SpanStatusCode.ERROR,
1839
+ message: e instanceof Error ? e.message : "Unknown error"
1840
+ // eslint-disable-line no-instanceof/no-instanceof
1841
+ });
1842
+ throw e;
1843
+ } finally {
1844
+ span.end();
1845
+ }
1846
+ }
1847
+ ),
1848
+ otel,
1849
+ rawTracer
1850
+ );
1851
+ }
1852
+ };
1853
+
1854
+ // ../../node_modules/.bun/drizzle-orm@0.44.7+ef50eaea70fa4f8c/node_modules/drizzle-orm/view-common.js
1855
+ var ViewBaseConfig = Symbol.for("drizzle:ViewBaseConfig");
1856
+
1857
+ // ../../node_modules/.bun/drizzle-orm@0.44.7+ef50eaea70fa4f8c/node_modules/drizzle-orm/table.js
1858
+ var Schema = Symbol.for("drizzle:Schema");
1859
+ var Columns = Symbol.for("drizzle:Columns");
1860
+ var ExtraConfigColumns = Symbol.for("drizzle:ExtraConfigColumns");
1861
+ var OriginalName = Symbol.for("drizzle:OriginalName");
1862
+ var BaseName = Symbol.for("drizzle:BaseName");
1863
+ var IsAlias = Symbol.for("drizzle:IsAlias");
1864
+ var ExtraConfigBuilder = Symbol.for("drizzle:ExtraConfigBuilder");
1865
+ var IsDrizzleTable = Symbol.for("drizzle:IsDrizzleTable");
1866
+ var Table = class {
1867
+ static [entityKind] = "Table";
1868
+ /** @internal */
1869
+ static Symbol = {
1870
+ Name: TableName,
1871
+ Schema,
1872
+ OriginalName,
1873
+ Columns,
1874
+ ExtraConfigColumns,
1875
+ BaseName,
1876
+ IsAlias,
1877
+ ExtraConfigBuilder
1878
+ };
1879
+ /**
1880
+ * @internal
1881
+ * Can be changed if the table is aliased.
1882
+ */
1883
+ [TableName];
1884
+ /**
1885
+ * @internal
1886
+ * Used to store the original name of the table, before any aliasing.
1887
+ */
1888
+ [OriginalName];
1889
+ /** @internal */
1890
+ [Schema];
1891
+ /** @internal */
1892
+ [Columns];
1893
+ /** @internal */
1894
+ [ExtraConfigColumns];
1895
+ /**
1896
+ * @internal
1897
+ * Used to store the table name before the transformation via the `tableCreator` functions.
1898
+ */
1899
+ [BaseName];
1900
+ /** @internal */
1901
+ [IsAlias] = false;
1902
+ /** @internal */
1903
+ [IsDrizzleTable] = true;
1904
+ /** @internal */
1905
+ [ExtraConfigBuilder] = void 0;
1906
+ constructor(name, schema, baseName) {
1907
+ this[TableName] = this[OriginalName] = name;
1908
+ this[Schema] = schema;
1909
+ this[BaseName] = baseName;
1910
+ }
1911
+ };
1912
+
1913
+ // ../../node_modules/.bun/drizzle-orm@0.44.7+ef50eaea70fa4f8c/node_modules/drizzle-orm/sql/sql.js
1914
+ var FakePrimitiveParam = class {
1915
+ static [entityKind] = "FakePrimitiveParam";
1916
+ };
1917
+ function isSQLWrapper(value) {
1918
+ return value !== null && value !== void 0 && typeof value.getSQL === "function";
1919
+ }
1920
+ function mergeQueries(queries) {
1921
+ const result = { sql: "", params: [] };
1922
+ for (const query of queries) {
1923
+ result.sql += query.sql;
1924
+ result.params.push(...query.params);
1925
+ if (query.typings?.length) {
1926
+ if (!result.typings) {
1927
+ result.typings = [];
1928
+ }
1929
+ result.typings.push(...query.typings);
1930
+ }
1931
+ }
1932
+ return result;
1933
+ }
1934
+ var StringChunk = class {
1935
+ static [entityKind] = "StringChunk";
1936
+ value;
1937
+ constructor(value) {
1938
+ this.value = Array.isArray(value) ? value : [value];
1939
+ }
1940
+ getSQL() {
1941
+ return new SQL([this]);
1942
+ }
1943
+ };
1944
+ var SQL = class _SQL {
1945
+ constructor(queryChunks) {
1946
+ this.queryChunks = queryChunks;
1947
+ for (const chunk of queryChunks) {
1948
+ if (is(chunk, Table)) {
1949
+ const schemaName = chunk[Table.Symbol.Schema];
1950
+ this.usedTables.push(
1951
+ schemaName === void 0 ? chunk[Table.Symbol.Name] : schemaName + "." + chunk[Table.Symbol.Name]
1952
+ );
1953
+ }
1954
+ }
1955
+ }
1956
+ static [entityKind] = "SQL";
1957
+ /** @internal */
1958
+ decoder = noopDecoder;
1959
+ shouldInlineParams = false;
1960
+ /** @internal */
1961
+ usedTables = [];
1962
+ append(query) {
1963
+ this.queryChunks.push(...query.queryChunks);
1964
+ return this;
1965
+ }
1966
+ toQuery(config) {
1967
+ return tracer.startActiveSpan("drizzle.buildSQL", (span) => {
1968
+ const query = this.buildQueryFromSourceParams(this.queryChunks, config);
1969
+ span?.setAttributes({
1970
+ "drizzle.query.text": query.sql,
1971
+ "drizzle.query.params": JSON.stringify(query.params)
1972
+ });
1973
+ return query;
1974
+ });
1975
+ }
1976
+ buildQueryFromSourceParams(chunks, _config) {
1977
+ const config = Object.assign({}, _config, {
1978
+ inlineParams: _config.inlineParams || this.shouldInlineParams,
1979
+ paramStartIndex: _config.paramStartIndex || { value: 0 }
1980
+ });
1981
+ const {
1982
+ casing,
1983
+ escapeName,
1984
+ escapeParam,
1985
+ prepareTyping,
1986
+ inlineParams,
1987
+ paramStartIndex
1988
+ } = config;
1989
+ return mergeQueries(chunks.map((chunk) => {
1990
+ if (is(chunk, StringChunk)) {
1991
+ return { sql: chunk.value.join(""), params: [] };
1992
+ }
1993
+ if (is(chunk, Name)) {
1994
+ return { sql: escapeName(chunk.value), params: [] };
1995
+ }
1996
+ if (chunk === void 0) {
1997
+ return { sql: "", params: [] };
1998
+ }
1999
+ if (Array.isArray(chunk)) {
2000
+ const result = [new StringChunk("(")];
2001
+ for (const [i, p] of chunk.entries()) {
2002
+ result.push(p);
2003
+ if (i < chunk.length - 1) {
2004
+ result.push(new StringChunk(", "));
2005
+ }
2006
+ }
2007
+ result.push(new StringChunk(")"));
2008
+ return this.buildQueryFromSourceParams(result, config);
2009
+ }
2010
+ if (is(chunk, _SQL)) {
2011
+ return this.buildQueryFromSourceParams(chunk.queryChunks, {
2012
+ ...config,
2013
+ inlineParams: inlineParams || chunk.shouldInlineParams
2014
+ });
2015
+ }
2016
+ if (is(chunk, Table)) {
2017
+ const schemaName = chunk[Table.Symbol.Schema];
2018
+ const tableName = chunk[Table.Symbol.Name];
2019
+ return {
2020
+ sql: schemaName === void 0 || chunk[IsAlias] ? escapeName(tableName) : escapeName(schemaName) + "." + escapeName(tableName),
2021
+ params: []
2022
+ };
2023
+ }
2024
+ if (is(chunk, Column)) {
2025
+ const columnName = casing.getColumnCasing(chunk);
2026
+ if (_config.invokeSource === "indexes") {
2027
+ return { sql: escapeName(columnName), params: [] };
2028
+ }
2029
+ const schemaName = chunk.table[Table.Symbol.Schema];
2030
+ return {
2031
+ sql: chunk.table[IsAlias] || schemaName === void 0 ? escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName) : escapeName(schemaName) + "." + escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName),
2032
+ params: []
2033
+ };
2034
+ }
2035
+ if (is(chunk, View)) {
2036
+ const schemaName = chunk[ViewBaseConfig].schema;
2037
+ const viewName = chunk[ViewBaseConfig].name;
2038
+ return {
2039
+ sql: schemaName === void 0 || chunk[ViewBaseConfig].isAlias ? escapeName(viewName) : escapeName(schemaName) + "." + escapeName(viewName),
2040
+ params: []
2041
+ };
2042
+ }
2043
+ if (is(chunk, Param)) {
2044
+ if (is(chunk.value, Placeholder)) {
2045
+ return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
2046
+ }
2047
+ const mappedValue = chunk.value === null ? null : chunk.encoder.mapToDriverValue(chunk.value);
2048
+ if (is(mappedValue, _SQL)) {
2049
+ return this.buildQueryFromSourceParams([mappedValue], config);
2050
+ }
2051
+ if (inlineParams) {
2052
+ return { sql: this.mapInlineParam(mappedValue, config), params: [] };
2053
+ }
2054
+ let typings = ["none"];
2055
+ if (prepareTyping) {
2056
+ typings = [prepareTyping(chunk.encoder)];
2057
+ }
2058
+ return { sql: escapeParam(paramStartIndex.value++, mappedValue), params: [mappedValue], typings };
2059
+ }
2060
+ if (is(chunk, Placeholder)) {
2061
+ return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
2062
+ }
2063
+ if (is(chunk, _SQL.Aliased) && chunk.fieldAlias !== void 0) {
2064
+ return { sql: escapeName(chunk.fieldAlias), params: [] };
2065
+ }
2066
+ if (is(chunk, Subquery)) {
2067
+ if (chunk._.isWith) {
2068
+ return { sql: escapeName(chunk._.alias), params: [] };
2069
+ }
2070
+ return this.buildQueryFromSourceParams([
2071
+ new StringChunk("("),
2072
+ chunk._.sql,
2073
+ new StringChunk(") "),
2074
+ new Name(chunk._.alias)
2075
+ ], config);
2076
+ }
2077
+ if (isPgEnum(chunk)) {
2078
+ if (chunk.schema) {
2079
+ return { sql: escapeName(chunk.schema) + "." + escapeName(chunk.enumName), params: [] };
2080
+ }
2081
+ return { sql: escapeName(chunk.enumName), params: [] };
2082
+ }
2083
+ if (isSQLWrapper(chunk)) {
2084
+ if (chunk.shouldOmitSQLParens?.()) {
2085
+ return this.buildQueryFromSourceParams([chunk.getSQL()], config);
2086
+ }
2087
+ return this.buildQueryFromSourceParams([
2088
+ new StringChunk("("),
2089
+ chunk.getSQL(),
2090
+ new StringChunk(")")
2091
+ ], config);
2092
+ }
2093
+ if (inlineParams) {
2094
+ return { sql: this.mapInlineParam(chunk, config), params: [] };
2095
+ }
2096
+ return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
2097
+ }));
2098
+ }
2099
+ mapInlineParam(chunk, { escapeString }) {
2100
+ if (chunk === null) {
2101
+ return "null";
2102
+ }
2103
+ if (typeof chunk === "number" || typeof chunk === "boolean") {
2104
+ return chunk.toString();
2105
+ }
2106
+ if (typeof chunk === "string") {
2107
+ return escapeString(chunk);
2108
+ }
2109
+ if (typeof chunk === "object") {
2110
+ const mappedValueAsString = chunk.toString();
2111
+ if (mappedValueAsString === "[object Object]") {
2112
+ return escapeString(JSON.stringify(chunk));
2113
+ }
2114
+ return escapeString(mappedValueAsString);
2115
+ }
2116
+ throw new Error("Unexpected param value: " + chunk);
2117
+ }
2118
+ getSQL() {
2119
+ return this;
2120
+ }
2121
+ as(alias) {
2122
+ if (alias === void 0) {
2123
+ return this;
2124
+ }
2125
+ return new _SQL.Aliased(this, alias);
2126
+ }
2127
+ mapWith(decoder) {
2128
+ this.decoder = typeof decoder === "function" ? { mapFromDriverValue: decoder } : decoder;
2129
+ return this;
2130
+ }
2131
+ inlineParams() {
2132
+ this.shouldInlineParams = true;
2133
+ return this;
2134
+ }
2135
+ /**
2136
+ * This method is used to conditionally include a part of the query.
2137
+ *
2138
+ * @param condition - Condition to check
2139
+ * @returns itself if the condition is `true`, otherwise `undefined`
2140
+ */
2141
+ if(condition) {
2142
+ return condition ? this : void 0;
2143
+ }
2144
+ };
2145
+ var Name = class {
2146
+ constructor(value) {
2147
+ this.value = value;
2148
+ }
2149
+ static [entityKind] = "Name";
2150
+ brand;
2151
+ getSQL() {
2152
+ return new SQL([this]);
2153
+ }
2154
+ };
2155
+ function isDriverValueEncoder(value) {
2156
+ return typeof value === "object" && value !== null && "mapToDriverValue" in value && typeof value.mapToDriverValue === "function";
2157
+ }
2158
+ var noopDecoder = {
2159
+ mapFromDriverValue: (value) => value
2160
+ };
2161
+ var noopEncoder = {
2162
+ mapToDriverValue: (value) => value
2163
+ };
2164
+ var noopMapper = {
2165
+ ...noopDecoder,
2166
+ ...noopEncoder
2167
+ };
2168
+ var Param = class {
2169
+ /**
2170
+ * @param value - Parameter value
2171
+ * @param encoder - Encoder to convert the value to a driver parameter
2172
+ */
2173
+ constructor(value, encoder = noopEncoder) {
2174
+ this.value = value;
2175
+ this.encoder = encoder;
2176
+ }
2177
+ static [entityKind] = "Param";
2178
+ brand;
2179
+ getSQL() {
2180
+ return new SQL([this]);
2181
+ }
2182
+ };
2183
+ function sql(strings, ...params) {
2184
+ const queryChunks = [];
2185
+ if (params.length > 0 || strings.length > 0 && strings[0] !== "") {
2186
+ queryChunks.push(new StringChunk(strings[0]));
2187
+ }
2188
+ for (const [paramIndex, param2] of params.entries()) {
2189
+ queryChunks.push(param2, new StringChunk(strings[paramIndex + 1]));
2190
+ }
2191
+ return new SQL(queryChunks);
2192
+ }
2193
+ ((sql2) => {
2194
+ function empty() {
2195
+ return new SQL([]);
2196
+ }
2197
+ sql2.empty = empty;
2198
+ function fromList(list) {
2199
+ return new SQL(list);
2200
+ }
2201
+ sql2.fromList = fromList;
2202
+ function raw(str) {
2203
+ return new SQL([new StringChunk(str)]);
2204
+ }
2205
+ sql2.raw = raw;
2206
+ function join2(chunks, separator) {
2207
+ const result = [];
2208
+ for (const [i, chunk] of chunks.entries()) {
2209
+ if (i > 0 && separator !== void 0) {
2210
+ result.push(separator);
2211
+ }
2212
+ result.push(chunk);
2213
+ }
2214
+ return new SQL(result);
2215
+ }
2216
+ sql2.join = join2;
2217
+ function identifier(value) {
2218
+ return new Name(value);
2219
+ }
2220
+ sql2.identifier = identifier;
2221
+ function placeholder2(name2) {
2222
+ return new Placeholder(name2);
2223
+ }
2224
+ sql2.placeholder = placeholder2;
2225
+ function param2(value, encoder) {
2226
+ return new Param(value, encoder);
2227
+ }
2228
+ sql2.param = param2;
2229
+ })(sql || (sql = {}));
2230
+ ((SQL2) => {
2231
+ class Aliased {
2232
+ constructor(sql2, fieldAlias) {
2233
+ this.sql = sql2;
2234
+ this.fieldAlias = fieldAlias;
2235
+ }
2236
+ static [entityKind] = "SQL.Aliased";
2237
+ /** @internal */
2238
+ isSelectionField = false;
2239
+ getSQL() {
2240
+ return this.sql;
2241
+ }
2242
+ /** @internal */
2243
+ clone() {
2244
+ return new Aliased(this.sql, this.fieldAlias);
2245
+ }
2246
+ }
2247
+ SQL2.Aliased = Aliased;
2248
+ })(SQL || (SQL = {}));
2249
+ var Placeholder = class {
2250
+ constructor(name2) {
2251
+ this.name = name2;
2252
+ }
2253
+ static [entityKind] = "Placeholder";
2254
+ getSQL() {
2255
+ return new SQL([this]);
2256
+ }
2257
+ };
2258
+ var IsDrizzleView = Symbol.for("drizzle:IsDrizzleView");
2259
+ var View = class {
2260
+ static [entityKind] = "View";
2261
+ /** @internal */
2262
+ [ViewBaseConfig];
2263
+ /** @internal */
2264
+ [IsDrizzleView] = true;
2265
+ constructor({ name: name2, schema, selectedFields, query }) {
2266
+ this[ViewBaseConfig] = {
2267
+ name: name2,
2268
+ originalName: name2,
2269
+ schema,
2270
+ selectedFields,
2271
+ query,
2272
+ isExisting: !query,
2273
+ isAlias: false
2274
+ };
2275
+ }
2276
+ getSQL() {
2277
+ return new SQL([this]);
2278
+ }
2279
+ };
2280
+ Column.prototype.getSQL = function() {
2281
+ return new SQL([this]);
2282
+ };
2283
+ Table.prototype.getSQL = function() {
2284
+ return new SQL([this]);
2285
+ };
2286
+ Subquery.prototype.getSQL = function() {
2287
+ return new SQL([this]);
2288
+ };
2289
+
2290
+ // ../../node_modules/.bun/drizzle-orm@0.44.7+ef50eaea70fa4f8c/node_modules/drizzle-orm/sql/expressions/conditions.js
2291
+ function bindIfParam(value, column) {
2292
+ if (isDriverValueEncoder(column) && !isSQLWrapper(value) && !is(value, Param) && !is(value, Placeholder) && !is(value, Column) && !is(value, Table) && !is(value, View)) {
2293
+ return new Param(value, column);
2294
+ }
2295
+ return value;
2296
+ }
2297
+ var eq = (left, right) => {
2298
+ return sql`${left} = ${bindIfParam(right, left)}`;
2299
+ };
2300
+ function and(...unfilteredConditions) {
2301
+ const conditions = unfilteredConditions.filter(
2302
+ (c) => c !== void 0
2303
+ );
2304
+ if (conditions.length === 0) {
2305
+ return void 0;
2306
+ }
2307
+ if (conditions.length === 1) {
2308
+ return new SQL(conditions);
2309
+ }
2310
+ return new SQL([
2311
+ new StringChunk("("),
2312
+ sql.join(conditions, new StringChunk(" and ")),
2313
+ new StringChunk(")")
2314
+ ]);
2315
+ }
2316
+ function inArray(column, values) {
2317
+ if (Array.isArray(values)) {
2318
+ if (values.length === 0) {
2319
+ return sql`false`;
2320
+ }
2321
+ return sql`${column} in ${values.map((v) => bindIfParam(v, column))}`;
2322
+ }
2323
+ return sql`${column} in ${bindIfParam(values, column)}`;
2324
+ }
2325
+ function isNull(value) {
2326
+ return sql`${value} is null`;
2327
+ }
2328
+
2329
+ // ../../node_modules/.bun/drizzle-orm@0.44.7+ef50eaea70fa4f8c/node_modules/drizzle-orm/sql/expressions/select.js
2330
+ function asc(column) {
2331
+ return sql`${column} asc`;
2332
+ }
2333
+ function desc(column) {
2334
+ return sql`${column} desc`;
2335
+ }
2336
+
2337
+ // ../../node_modules/.bun/drizzle-orm@0.44.7+ef50eaea70fa4f8c/node_modules/drizzle-orm/sql/functions/aggregate.js
2338
+ function count(expression) {
2339
+ return sql`count(${expression || sql.raw("*")})`.mapWith(Number);
2340
+ }
2341
+
2342
+ // ../orm/src/adapters/drizzle-adapter.ts
2343
+ var database;
2344
+ function ensureDatabase() {
2345
+ if (!database) {
2346
+ throw new Error("DrizzleAdapter: database has not been configured. Call DrizzleAdapter.configure(db).");
2347
+ }
2348
+ return database;
2349
+ }
2350
+ async function resolveList(result) {
2351
+ if (isPromiseLike(result)) {
2352
+ return result;
2353
+ }
2354
+ if (typeof result.all === "function") {
2355
+ return result.all();
2356
+ }
2357
+ if (typeof result.get === "function") {
2358
+ const item = await result.get();
2359
+ return item ? [item] : [];
2360
+ }
2361
+ return [];
2362
+ }
2363
+ function resolveWhere(table, where) {
2364
+ if (!where || typeof where !== "object") {
2365
+ return where;
2366
+ }
2367
+ const tableRecord = table;
2368
+ const clauses = Object.entries(where).filter(([, value]) => value !== void 0).map(([key, value]) => {
2369
+ const column = tableRecord[key];
2370
+ if (!column) {
2371
+ throw new Error(`DrizzleAdapter: unknown column "${key}" on provided table.`);
2372
+ }
2373
+ if (Array.isArray(value)) {
2374
+ return inArray(column, value);
2375
+ }
2376
+ if (value === null) {
2377
+ return isNull(column);
2378
+ }
2379
+ return eq(column, value);
2380
+ }).filter(Boolean);
2381
+ if (clauses.length === 0) {
2382
+ return void 0;
2383
+ }
2384
+ if (clauses.length === 1) {
2385
+ return clauses[0];
2386
+ }
2387
+ return and(...clauses);
2388
+ }
2389
+ function resolveOrder(table, orderBy) {
2390
+ if (!orderBy || orderBy.length === 0) {
2391
+ return void 0;
2392
+ }
2393
+ const tableRecord = table;
2394
+ return orderBy.map(({ column, direction }) => {
2395
+ const columnRef = tableRecord[column];
2396
+ if (!columnRef) {
2397
+ throw new Error(`DrizzleAdapter: unknown column "${column}" on provided table.`);
2398
+ }
2399
+ return direction === "desc" ? desc(columnRef) : asc(columnRef);
2400
+ });
2401
+ }
2402
+ async function resolveSingle(result) {
2403
+ if (isPromiseLike(result)) {
2404
+ const list = await result ?? [];
2405
+ return Array.isArray(list) ? list[0] ?? null : list ?? null;
2406
+ }
2407
+ if (typeof result.get === "function") {
2408
+ const item = await result.get();
2409
+ return item ?? null;
2410
+ }
2411
+ if (typeof result.all === "function") {
2412
+ const list = await result.all();
2413
+ return list[0] ?? null;
2414
+ }
2415
+ return null;
2416
+ }
2417
+ async function resolveMutation(result) {
2418
+ if (isPromiseLike(result)) {
2419
+ return result;
2420
+ }
2421
+ if ("returning" in result && typeof result.returning === "function") {
2422
+ const rows = await result.returning();
2423
+ return Array.isArray(rows) ? rows[0] ?? rows : rows;
2424
+ }
2425
+ if ("run" in result && typeof result.run === "function") {
2426
+ return result.run();
2427
+ }
2428
+ return result;
2429
+ }
2430
+ function isPromiseLike(value) {
2431
+ return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function";
2432
+ }
2433
+ var DrizzleAdapter = {
2434
+ configure(db) {
2435
+ database = db;
2436
+ },
2437
+ async findMany(table, options) {
2438
+ const db = ensureDatabase();
2439
+ let query = db.select().from(table);
2440
+ const { where, orderBy, limit, offset } = options ?? {};
2441
+ if (typeof query.where === "function") {
2442
+ const clause = resolveWhere(table, where);
2443
+ if (clause) {
2444
+ query = query.where(clause);
2445
+ }
2446
+ }
2447
+ if (typeof query.orderBy === "function") {
2448
+ const clauses = resolveOrder(table, orderBy);
2449
+ if (clauses && clauses.length > 0) {
2450
+ query = query.orderBy(...clauses);
2451
+ }
2452
+ }
2453
+ if (typeof query.limit === "function" && typeof limit === "number") {
2454
+ query = query.limit(limit);
2455
+ }
2456
+ if (typeof query.offset === "function" && typeof offset === "number") {
2457
+ query = query.offset(offset);
2458
+ }
2459
+ const rows = await resolveList(query);
2460
+ return rows;
2461
+ },
2462
+ async count(table, where) {
2463
+ const db = ensureDatabase();
2464
+ let query = db.select({ value: count() }).from(table);
2465
+ if (typeof query.where === "function") {
2466
+ const clause = resolveWhere(table, where);
2467
+ if (clause) {
2468
+ query = query.where(clause);
2469
+ }
2470
+ }
2471
+ const rows = await resolveList(query);
2472
+ const first = rows[0];
2473
+ const raw = first?.value ?? 0;
2474
+ const total = typeof raw === "bigint" ? Number(raw) : Number(raw);
2475
+ return Number.isNaN(total) ? 0 : total;
2476
+ },
2477
+ async findUnique(table, where) {
2478
+ const db = ensureDatabase();
2479
+ let query = db.select().from(table);
2480
+ if (typeof query.where === "function") {
2481
+ const clause = resolveWhere(table, where);
2482
+ if (clause) {
2483
+ query = query.where(clause);
2484
+ }
2485
+ }
2486
+ const row = await resolveSingle(query);
2487
+ if (row == null) {
2488
+ return null;
2489
+ }
2490
+ return row;
2491
+ },
2492
+ async create(table, data) {
2493
+ const db = ensureDatabase();
2494
+ const result = await resolveMutation(db.insert(table).values(data));
2495
+ return result;
2496
+ },
2497
+ async update(table, where, data) {
2498
+ const db = ensureDatabase();
2499
+ if (!db.update) {
2500
+ throw new Error("DrizzleAdapter: configured database does not support updates.");
2501
+ }
2502
+ const clause = resolveWhere(table, where);
2503
+ const query = db.update(table).set(data);
2504
+ const result = await resolveMutation(clause ? query.where(clause) : query);
2505
+ return result;
2506
+ },
2507
+ async delete(table, where) {
2508
+ const db = ensureDatabase();
2509
+ if (!db.delete) {
2510
+ throw new Error("DrizzleAdapter: configured database does not support deletes.");
2511
+ }
2512
+ const clause = resolveWhere(table, where);
2513
+ const query = db.delete(table);
2514
+ const result = await resolveMutation(clause ? query.where(clause) : query);
2515
+ return result;
2516
+ }
2517
+ };
2518
+
2519
+ // ../orm/src/Model.ts
2520
+ var DEFAULT_PAGINATION_SIZE = 15;
2521
+ var Model = class {
2522
+ static ormAdapter = DrizzleAdapter;
2523
+ static table;
2524
+ static recordType = void 0;
2525
+ static relationDefinitions;
2526
+ static relationTypes = {};
2527
+ static useAdapter(adapter) {
2528
+ this.ormAdapter = adapter;
2529
+ }
2530
+ static getAdapter() {
2531
+ return this.ormAdapter;
2532
+ }
2533
+ static async preparePersistencePayload(data) {
2534
+ return { ...data };
2535
+ }
2536
+ static getRelationDefinitions() {
2537
+ if (!Object.prototype.hasOwnProperty.call(this, "relationDefinitions") || !this.relationDefinitions) {
2538
+ this.relationDefinitions = /* @__PURE__ */ new Map();
2539
+ }
2540
+ return this.relationDefinitions;
2541
+ }
2542
+ static getRelationDefinition(name) {
2543
+ return this.getRelationDefinitions().get(name);
2544
+ }
2545
+ static resolveTable() {
2546
+ if (!this.table) {
2547
+ throw new Error(`${this.name}.table must be defined before using the model.`);
2548
+ }
2549
+ return this.table;
2550
+ }
2551
+ static async all() {
2552
+ const table = this.resolveTable();
2553
+ return this.getAdapter().findMany(table);
2554
+ }
2555
+ static async find(id, key = "id") {
2556
+ const table = this.resolveTable();
2557
+ const where = { [key]: id };
2558
+ return this.getAdapter().findUnique(table, where);
2559
+ }
2560
+ static async where(where) {
2561
+ const table = this.resolveTable();
2562
+ return this.getAdapter().findMany(table, { where });
2563
+ }
2564
+ static hasMany(name, related, foreignKey, localKey) {
2565
+ const definitions = this.getRelationDefinitions();
2566
+ definitions.set(name, {
2567
+ type: "hasMany",
2568
+ name,
2569
+ related,
2570
+ foreignKey,
2571
+ localKey
2572
+ });
2573
+ }
2574
+ static belongsTo(name, related, foreignKey, ownerKey) {
2575
+ const definitions = this.getRelationDefinitions();
2576
+ definitions.set(name, {
2577
+ type: "belongsTo",
2578
+ name,
2579
+ related,
2580
+ foreignKey,
2581
+ ownerKey
2582
+ });
2583
+ }
2584
+ static async orderBy(order, where) {
2585
+ const table = this.resolveTable();
2586
+ const orderBy = normalizeOrderBy(order);
2587
+ const options = { orderBy };
2588
+ if (where && Object.keys(where).length > 0) {
2589
+ options.where = where;
2590
+ }
2591
+ return this.getAdapter().findMany(table, options);
2592
+ }
2593
+ static async paginate(options = {}) {
2594
+ const table = this.resolveTable();
2595
+ const adapter = this.getAdapter();
2596
+ const requestedPage = typeof options.page === "number" ? options.page : 1;
2597
+ const sanitizedPage = Number.isFinite(requestedPage) && requestedPage >= 1 ? Math.floor(requestedPage) : 1;
2598
+ const requestedPerPage = typeof options.perPage === "number" ? options.perPage : DEFAULT_PAGINATION_SIZE;
2599
+ const perPage = Number.isFinite(requestedPerPage) && requestedPerPage >= 1 ? Math.floor(requestedPerPage) : DEFAULT_PAGINATION_SIZE;
2600
+ let total = 0;
2601
+ if (typeof adapter.count === "function") {
2602
+ total = await adapter.count(table, options.where);
2603
+ } else {
2604
+ const records = options.where ? await this.where(options.where) : await this.all();
2605
+ total = records.length;
2606
+ }
2607
+ const totalPages = total === 0 ? 1 : Math.max(1, Math.ceil(total / perPage));
2608
+ const currentPage = Math.min(sanitizedPage, totalPages);
2609
+ const offset = (currentPage - 1) * perPage;
2610
+ const orderByClause = options.orderBy ? normalizeOrderBy(options.orderBy) : void 0;
2611
+ const findOptions = {
2612
+ where: options.where,
2613
+ orderBy: orderByClause,
2614
+ limit: perPage,
2615
+ offset
2616
+ };
2617
+ const data = await adapter.findMany(table, findOptions);
2618
+ const from = total === 0 ? 0 : offset + 1;
2619
+ const to = total === 0 ? 0 : offset + data.length;
2620
+ const meta = {
2621
+ total,
2622
+ perPage,
2623
+ currentPage,
2624
+ totalPages,
2625
+ hasMore: currentPage < totalPages,
2626
+ from,
2627
+ to: Math.min(to, total)
2628
+ };
2629
+ return { data, meta };
2630
+ }
2631
+ static async withPaginate(relations, options = {}) {
2632
+ const result = await this.paginate(options);
2633
+ const relationList = normalizeRelations(relations);
2634
+ if (relationList.length === 0 || result.data.length === 0) {
2635
+ return result;
2636
+ }
2637
+ const records = result.data.map((record) => ({ ...record }));
2638
+ for (const relationName of relationList) {
2639
+ await this.loadRelationInto(records, relationName);
2640
+ }
2641
+ return {
2642
+ data: records,
2643
+ meta: result.meta
2644
+ };
2645
+ }
2646
+ static async create(data) {
2647
+ const table = this.resolveTable();
2648
+ const payload = await this.preparePersistencePayload(data);
2649
+ return this.getAdapter().create(table, payload);
2650
+ }
2651
+ static async update(where, data) {
2652
+ const table = this.resolveTable();
2653
+ const adapter = this.getAdapter();
2654
+ if (!adapter.update) {
2655
+ throw new Error("Configured adapter does not support update operations.");
2656
+ }
2657
+ const payload = await this.preparePersistencePayload(data);
2658
+ return adapter.update(table, where, payload);
2659
+ }
2660
+ static async delete(where) {
2661
+ const table = this.resolveTable();
2662
+ const adapter = this.getAdapter();
2663
+ if (!adapter.delete) {
2664
+ throw new Error("Configured adapter does not support delete operations.");
2665
+ }
2666
+ return adapter.delete(table, where);
2667
+ }
2668
+ static async with(relations, where) {
2669
+ const records = where ? await this.where(where) : await this.all();
2670
+ if (!records.length) {
2671
+ return records;
2672
+ }
2673
+ const relationList = normalizeRelations(relations);
2674
+ if (relationList.length === 0) {
2675
+ return records;
2676
+ }
2677
+ const copies = records.map((record) => ({ ...record }));
2678
+ for (const relationName of relationList) {
2679
+ await this.loadRelationInto(copies, relationName);
2680
+ }
2681
+ return copies;
2682
+ }
2683
+ static async loadRelationInto(records, relationName) {
2684
+ const definition = this.getRelationDefinition(relationName);
2685
+ if (!definition) {
2686
+ throw new Error(`${this.name}: unknown relation "${relationName}".`);
2687
+ }
2688
+ if (definition.type === "hasMany") {
2689
+ await this.loadHasMany(records, definition);
2690
+ return;
2691
+ }
2692
+ if (definition.type === "belongsTo") {
2693
+ await this.loadBelongsTo(records, definition);
2694
+ return;
2695
+ }
2696
+ }
2697
+ static async loadHasMany(records, definition) {
2698
+ const { related, foreignKey, localKey, name } = definition;
2699
+ const ownerValues = Array.from(
2700
+ new Set(records.map((record) => record[localKey]).filter((value) => value !== void 0 && value !== null))
2701
+ );
2702
+ if (ownerValues.length === 0) {
2703
+ records.forEach((record) => {
2704
+ record[name] = [];
2705
+ });
2706
+ return;
2707
+ }
2708
+ const relatedRecords = await related.where({ [foreignKey]: ownerValues });
2709
+ const grouped = /* @__PURE__ */ new Map();
2710
+ for (const item of relatedRecords) {
2711
+ const key = item[foreignKey];
2712
+ if (!grouped.has(key)) {
2713
+ grouped.set(key, []);
2714
+ }
2715
+ grouped.get(key)?.push({ ...item });
2716
+ }
2717
+ records.forEach((record) => {
2718
+ const key = record[localKey];
2719
+ record[name] = grouped.get(key) ?? [];
2720
+ });
2721
+ }
2722
+ static async loadBelongsTo(records, definition) {
2723
+ const { related, foreignKey, ownerKey, name } = definition;
2724
+ const foreignValues = Array.from(
2725
+ new Set(records.map((record) => record[foreignKey]).filter((value) => value !== void 0 && value !== null))
2726
+ );
2727
+ if (foreignValues.length === 0) {
2728
+ records.forEach((record) => {
2729
+ record[name] = null;
2730
+ });
2731
+ return;
2732
+ }
2733
+ const relatedRecords = await related.where({ [ownerKey]: foreignValues });
2734
+ const index = /* @__PURE__ */ new Map();
2735
+ for (const item of relatedRecords) {
2736
+ index.set(item[ownerKey], { ...item });
2737
+ }
2738
+ records.forEach((record) => {
2739
+ const key = record[foreignKey];
2740
+ record[name] = key == null ? null : index.get(key) ?? null;
2741
+ });
2742
+ }
2743
+ };
2744
+ function normalizeOrderBy(order) {
2745
+ if (Array.isArray(order) && !isOrderTuple(order)) {
2746
+ return order.map((expression) => toOrderDefinition(expression));
2747
+ }
2748
+ return [toOrderDefinition(order)];
2749
+ }
2750
+ function toOrderDefinition(expression) {
2751
+ if (typeof expression === "string") {
2752
+ return { column: expression, direction: "asc" };
2753
+ }
2754
+ if (isOrderTuple(expression)) {
2755
+ const [column, direction] = expression;
2756
+ return { column, direction };
2757
+ }
2758
+ return {
2759
+ column: expression.column,
2760
+ direction: expression.direction ?? "asc"
2761
+ };
2762
+ }
2763
+ function isOrderTuple(value) {
2764
+ return Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && (value[1] === "asc" || value[1] === "desc");
2765
+ }
2766
+ function normalizeRelations(relations) {
2767
+ if (Array.isArray(relations)) {
2768
+ return relations.map((relation) => relation.toString()).filter(Boolean);
2769
+ }
2770
+ if (typeof relations === "string" && relations) {
2771
+ return [relations];
2772
+ }
2773
+ return [];
2774
+ }
2775
+
2776
+ // src/auth/AuthenticatableModel.ts
2777
+ var AuthenticatableModel = class extends Model {
2778
+ static passwordField = "password";
2779
+ static passwordHashField = "passwordHash";
2780
+ static passwordHasher = null;
2781
+ static resolvePasswordField() {
2782
+ return this.passwordField ?? "password";
2783
+ }
2784
+ static resolvePasswordHashField() {
2785
+ return this.passwordHashField ?? "passwordHash";
2786
+ }
2787
+ static resolvePasswordHasher() {
2788
+ if (this.passwordHasher) {
2789
+ return this.passwordHasher;
2790
+ }
2791
+ const hasher = new ScryptHasher();
2792
+ this.passwordHasher = hasher;
2793
+ return hasher;
2794
+ }
2795
+ static async preparePersistencePayload(data) {
2796
+ const basePayload = await super.preparePersistencePayload(data);
2797
+ const passwordField = this.resolvePasswordField();
2798
+ if (!(passwordField in basePayload)) {
2799
+ return basePayload;
2800
+ }
2801
+ const payload = { ...basePayload };
2802
+ const plainPassword = payload[passwordField];
2803
+ const hashField = this.resolvePasswordHashField();
2804
+ if (typeof plainPassword === "string" && plainPassword.length > 0) {
2805
+ const hasher = this.resolvePasswordHasher();
2806
+ payload[hashField] = await hasher.hash(plainPassword);
2807
+ }
2808
+ if (passwordField !== hashField) {
2809
+ delete payload[passwordField];
2810
+ }
2811
+ return payload;
2812
+ }
2813
+ };
2814
+
2815
+ // src/http/dev-banner.ts
2816
+ import chalk from "chalk";
2817
+ import figlet from "figlet";
2818
+
2819
+ // package.json
2820
+ var package_default = {
2821
+ name: "@guren/server",
2822
+ version: "0.2.0-alpha.6",
2823
+ type: "module",
2824
+ license: "MIT",
2825
+ repository: {
2826
+ type: "git",
2827
+ url: "https://github.com/gurenjs/guren",
2828
+ directory: "packages/server"
2829
+ },
2830
+ homepage: "https://github.com/gurenjs/guren#readme",
2831
+ bugs: {
2832
+ url: "https://github.com/gurenjs/guren/issues"
2833
+ },
2834
+ publishConfig: {
2835
+ access: "public"
2836
+ },
2837
+ files: [
2838
+ "dist"
2839
+ ],
2840
+ main: "dist/index.js",
2841
+ types: "dist/index.d.ts",
2842
+ exports: {
2843
+ ".": {
2844
+ types: "./dist/index.d.ts",
2845
+ default: "./dist/index.js"
2846
+ },
2847
+ "./vite": {
2848
+ types: "./dist/vite/index.d.ts",
2849
+ default: "./dist/vite/index.js"
2850
+ }
2851
+ },
2852
+ scripts: {
2853
+ build: "tsup",
2854
+ dev: "bun --watch src/index.ts",
2855
+ typecheck: "tsc --noEmit",
2856
+ test: "bun test"
2857
+ },
2858
+ dependencies: {
2859
+ "@guren/inertia-client": "^0.2.0-alpha.6",
2860
+ chalk: "^5.3.0",
2861
+ consola: "^3.4.2",
2862
+ figlet: "^1.7.0",
2863
+ hono: "^4.4.0"
2864
+ },
2865
+ peerDependencies: {
2866
+ vite: ">=7.0.0"
2867
+ },
2868
+ devDependencies: {
2869
+ "@types/node": "^20.14.10",
2870
+ vite: "^7.0.0",
2871
+ tsup: "^8.5.0",
2872
+ typescript: "^5.4.0"
2873
+ }
2874
+ };
2875
+
2876
+ // src/http/dev-banner.ts
2877
+ function generateAsciiArt(text) {
2878
+ try {
2879
+ const rendered = figlet.textSync(text, {
2880
+ font: "Standard",
2881
+ horizontalLayout: "default",
2882
+ verticalLayout: "default"
2883
+ });
2884
+ return rendered;
2885
+ } catch (error) {
2886
+ console.error("Failed to generate FIGlet banner, falling back to plain text:", error);
2887
+ return text.toUpperCase();
2888
+ }
2889
+ }
2890
+ var GUREN_ASCII_ART = chalk.redBright.bold(generateAsciiArt("GUREN"));
2891
+ var GUREN_VERSION = package_default.version;
2892
+ function logDevServerBanner({
2893
+ hostname,
2894
+ port,
2895
+ assetsUrl = "http://localhost:5173"
2896
+ }) {
2897
+ const localUrl = `http://localhost:${port}`;
2898
+ const boundUrl = `http://${hostname}:${port}`;
2899
+ const boundLabel = hostname === "0.0.0.0" || hostname === "::" ? " (all interfaces)" : "";
2900
+ const header = [
2901
+ GUREN_ASCII_ART,
2902
+ chalk.magentaBright.bold(
2903
+ `Guren v${GUREN_VERSION} ignites \u2014 burning bright like a crimson lotus.`
2904
+ ),
2905
+ ""
2906
+ ];
2907
+ const detail = (label, value) => `${chalk.magentaBright(" \u2022")} ${chalk.bold(label.padEnd(14))}: ${chalk.cyanBright(value)}`;
2908
+ const banner = [
2909
+ ...header,
2910
+ detail("App URL", localUrl),
2911
+ detail("Bound address", `${boundUrl}${boundLabel}`),
2912
+ detail("Asset server", `${assetsUrl} (Vite)`),
2913
+ "",
2914
+ chalk.yellowBright("Press Ctrl+C to douse the flames."),
2915
+ ""
2916
+ ].join("\n");
2917
+ console.log(banner);
2918
+ }
2919
+
2920
+ // src/http/vite-dev-server.ts
2921
+ async function startViteDevServer(options = {}) {
2922
+ const { root = process.cwd(), config = {}, host = true, port } = options;
2923
+ const { createServer } = await import("vite");
2924
+ const mergedConfig = {
2925
+ clearScreen: false,
2926
+ ...config,
2927
+ root: config.root ?? root,
2928
+ server: {
2929
+ host,
2930
+ port,
2931
+ ...config.server ?? {}
2932
+ }
2933
+ };
2934
+ const server = await createServer(mergedConfig);
2935
+ await server.listen();
2936
+ const resolved = server.resolvedUrls;
2937
+ const localUrls = resolved?.local?.length ? resolved.local : [`http://${typeof host === "string" ? host : "localhost"}:${server.config.server.port ?? port ?? 5173}`];
2938
+ const networkUrls = resolved?.network ?? [];
2939
+ return {
2940
+ server,
2941
+ localUrl: localUrls[0],
2942
+ networkUrls
2943
+ };
2944
+ }
2945
+
2946
+ // src/http/Application.ts
2947
+ function getGlobalState() {
2948
+ return globalThis;
2949
+ }
2950
+ async function stopActiveBunServer() {
2951
+ const state = getGlobalState();
2952
+ const previous = state.__gurenActiveServer;
2953
+ if (!previous?.stop) {
2954
+ state.__gurenActiveServer = void 0;
2955
+ return;
2956
+ }
2957
+ try {
2958
+ await Promise.resolve(previous.stop());
2959
+ } catch (error) {
2960
+ console.warn("Failed to stop previous Bun server:", error);
2961
+ } finally {
2962
+ state.__gurenActiveServer = void 0;
2963
+ }
2964
+ }
2965
+ function setActiveBunServer(server) {
2966
+ getGlobalState().__gurenActiveServer = server;
2967
+ }
2968
+ var Application = class {
2969
+ constructor(options = {}) {
2970
+ this.options = options;
2971
+ this.hono = new Hono();
2972
+ this.authManager = new AuthManager();
2973
+ this.plugins = new PluginManager(() => this.resolveContext());
2974
+ this.registerDefaultProviders();
2975
+ if (Array.isArray(this.options.providers)) {
2976
+ this.plugins.addMany(this.options.providers);
2977
+ }
2978
+ }
2979
+ hono;
2980
+ plugins;
2981
+ context;
2982
+ authManager;
2983
+ viteDevServer;
2984
+ bunServer;
2985
+ viteTeardownRegistered = false;
2986
+ get auth() {
2987
+ return this.authManager;
2988
+ }
2989
+ /**
2990
+ * Mounts all routes that were defined through the Route DSL.
2991
+ */
2992
+ mountRoutes() {
2993
+ Route.mount(this.hono);
2994
+ }
2995
+ /**
2996
+ * Allows registering global middlewares directly on the underlying Hono app.
2997
+ */
2998
+ use(path, ...middleware) {
2999
+ this.hono.use(path, ...middleware);
3000
+ }
3001
+ /**
3002
+ * Executes the optional boot callback and mounts the registered routes.
3003
+ */
3004
+ async boot() {
3005
+ await this.plugins.registerAll();
3006
+ await this.options.boot?.(this.hono);
3007
+ this.mountRoutes();
3008
+ await this.plugins.bootAll();
3009
+ }
3010
+ /**
3011
+ * Fetch handler to integrate with Bun.serve or any standard Fetch runtime.
3012
+ */
3013
+ async fetch(request, env, executionCtx) {
3014
+ return this.hono.fetch(request, env, executionCtx);
3015
+ }
3016
+ /**
3017
+ * Convenience helper to start a Bun server when available.
3018
+ */
3019
+ async listen(options = {}) {
3020
+ if (!Bun) {
3021
+ throw new Error("Bun runtime is required to call Application.listen");
3022
+ }
3023
+ await stopActiveBunServer();
3024
+ const { port = 3e3, hostname = "0.0.0.0", assetsUrl, vite } = options;
3025
+ const envAssetsUrl = typeof process !== "undefined" ? process.env?.VITE_DEV_SERVER_URL : void 0;
3026
+ let resolvedAssetsUrl = assetsUrl ?? envAssetsUrl;
3027
+ const shouldStartVite = vite !== false && typeof process !== "undefined" && process.env?.NODE_ENV !== "production" && !resolvedAssetsUrl && process.env?.GUREN_DEV_VITE !== "0";
3028
+ if (shouldStartVite) {
3029
+ const viteOptions = typeof vite === "object" ? vite : void 0;
3030
+ try {
3031
+ const { server: server2, localUrl } = await startViteDevServer({
3032
+ root: viteOptions?.root ?? process.cwd(),
3033
+ config: viteOptions?.config,
3034
+ host: viteOptions?.host ?? true,
3035
+ port: viteOptions?.port
3036
+ });
3037
+ this.viteDevServer = server2;
3038
+ resolvedAssetsUrl = localUrl;
3039
+ if (typeof process !== "undefined") {
3040
+ process.env.VITE_DEV_SERVER_URL = resolvedAssetsUrl;
3041
+ }
3042
+ this.registerViteTeardown();
3043
+ } catch (error) {
3044
+ console.error("Failed to start Vite dev server:", error);
3045
+ process.exit(1);
3046
+ }
3047
+ }
3048
+ const server = Bun.serve({
3049
+ port,
3050
+ hostname,
3051
+ fetch: (request) => this.fetch(request)
3052
+ });
3053
+ this.bunServer = server;
3054
+ setActiveBunServer(server);
3055
+ const shouldLogBanner = typeof process === "undefined" || process.env?.NODE_ENV !== "production" && process.env?.GUREN_DEV_BANNER !== "0";
3056
+ if (shouldLogBanner) {
3057
+ this.logDevServerBanner({
3058
+ hostname,
3059
+ port,
3060
+ assetsUrl: resolvedAssetsUrl ?? "http://localhost:5173"
3061
+ });
3062
+ }
3063
+ }
3064
+ register(provider) {
3065
+ this.plugins.add(provider);
3066
+ return this;
3067
+ }
3068
+ registerMany(providers) {
3069
+ this.plugins.addMany(providers);
3070
+ return this;
3071
+ }
3072
+ /**
3073
+ * Logs the rich development server banner to the console.
3074
+ */
3075
+ logDevServerBanner(options) {
3076
+ logDevServerBanner(options);
3077
+ }
3078
+ resolveContext() {
3079
+ if (!this.context) {
3080
+ this.context = new ApplicationContext(this, this.authManager);
3081
+ }
3082
+ return this.context;
3083
+ }
3084
+ registerDefaultProviders() {
3085
+ this.plugins.add(InertiaViewProvider);
3086
+ this.plugins.add(AuthServiceProvider);
3087
+ }
3088
+ async closeViteDevServer() {
3089
+ if (!this.viteDevServer) {
3090
+ return;
3091
+ }
3092
+ try {
3093
+ await this.viteDevServer.close();
3094
+ } catch (error) {
3095
+ console.error("Error while shutting down Vite dev server:", error);
3096
+ } finally {
3097
+ this.viteDevServer = void 0;
3098
+ this.viteTeardownRegistered = false;
3099
+ }
3100
+ }
3101
+ registerViteTeardown() {
3102
+ if (this.viteTeardownRegistered || !this.viteDevServer || typeof process === "undefined") {
3103
+ return;
3104
+ }
3105
+ this.viteTeardownRegistered = true;
3106
+ const exitHandler = () => {
3107
+ this.closeViteDevServer().then(() => process.exit(0)).catch(() => process.exit(1));
3108
+ };
3109
+ process.once("SIGINT", exitHandler);
3110
+ process.once("SIGTERM", exitHandler);
3111
+ process.on("exit", () => {
3112
+ if (this.viteDevServer) {
3113
+ void this.viteDevServer.close();
3114
+ }
3115
+ });
3116
+ }
3117
+ };
3118
+
3119
+ // src/http/dev-assets.ts
3120
+ import { serveStatic } from "hono/bun";
3121
+ import { dirname, extname as extname2, resolve as resolve2 } from "path";
3122
+ import { fileURLToPath } from "url";
3123
+ import { createRequire } from "module";
3124
+
3125
+ // src/http/public-assets.ts
3126
+ import { extname, resolve } from "path";
3127
+ var DEFAULT_CACHE_CONTROL = "public, max-age=31536000, immutable";
3128
+ var DEFAULT_EXTENSIONS = [".svg", ".png", ".jpg", ".jpeg", ".gif", ".ico", ".webp", ".avif", ".webmanifest", ".txt"];
3129
+ var DEFAULT_CONTENT_TYPES = {
3130
+ ".svg": "image/svg+xml",
3131
+ ".png": "image/png",
3132
+ ".jpg": "image/jpeg",
3133
+ ".jpeg": "image/jpeg",
3134
+ ".gif": "image/gif",
3135
+ ".ico": "image/x-icon",
3136
+ ".webp": "image/webp",
3137
+ ".avif": "image/avif",
3138
+ ".webmanifest": "application/manifest+json",
3139
+ ".txt": "text/plain; charset=utf-8"
3140
+ };
3141
+ function registerRootPublicAssets(app, publicDir, config) {
3142
+ const normalized = normalizeConfig(config);
3143
+ if (!normalized) {
3144
+ return;
3145
+ }
3146
+ if (typeof Bun === "undefined") {
3147
+ console.warn("Root public asset serving is only available when running on Bun; skipping registration.");
3148
+ return;
3149
+ }
3150
+ const { extensions, cacheControlHeader, routePrefix, contentTypeMap } = normalized;
3151
+ const normalizedPrefix = routePrefix ? routePrefix.replace(/\/+$/u, "") || "/" : void 0;
3152
+ app.hono.use(async (ctx, next) => {
3153
+ const path = ctx.req.path;
3154
+ if (!path || path === "/" || path.startsWith("/public/")) {
3155
+ return next();
3156
+ }
3157
+ if (normalizedPrefix && !path.startsWith(normalizedPrefix)) {
3158
+ return next();
3159
+ }
3160
+ const extension = extname(path).toLowerCase();
3161
+ if (!extensions.has(extension)) {
3162
+ return next();
3163
+ }
3164
+ const relativePath = path.replace(/^\/+/, "");
3165
+ if (!relativePath) {
3166
+ return next();
3167
+ }
3168
+ const candidatePath = resolve(publicDir, relativePath);
3169
+ if (!candidatePath.startsWith(publicDir)) {
3170
+ return next();
3171
+ }
3172
+ const file = Bun.file(candidatePath);
3173
+ if (!await file.exists()) {
3174
+ return next();
3175
+ }
3176
+ const headers = new Headers({
3177
+ "Cache-Control": cacheControlHeader,
3178
+ "Content-Type": contentTypeMap?.[extension] ?? DEFAULT_CONTENT_TYPES[extension] ?? "application/octet-stream"
3179
+ });
3180
+ return new Response(file, { headers });
3181
+ });
3182
+ }
3183
+ function normalizeConfig(config) {
3184
+ if (config === false) {
3185
+ return void 0;
3186
+ }
3187
+ if (config === void 0 || config === true) {
3188
+ return {
3189
+ extensions: new Set(DEFAULT_EXTENSIONS),
3190
+ cacheControlHeader: DEFAULT_CACHE_CONTROL
3191
+ };
3192
+ }
3193
+ const enabled = config.enabled ?? true;
3194
+ if (!enabled) {
3195
+ return void 0;
3196
+ }
3197
+ const extensions = new Set(
3198
+ (config.extensions && config.extensions.length > 0 ? config.extensions : DEFAULT_EXTENSIONS).map(
3199
+ (ext) => normalizeExtension(ext)
3200
+ )
3201
+ );
3202
+ return {
3203
+ extensions,
3204
+ cacheControlHeader: config.cacheControlHeader ?? DEFAULT_CACHE_CONTROL,
3205
+ routePrefix: config.routePrefix,
3206
+ contentTypeMap: config.contentTypeMap
3207
+ };
3208
+ }
3209
+ function normalizeExtension(value) {
3210
+ if (!value) {
3211
+ return value;
3212
+ }
3213
+ return value.startsWith(".") ? value.toLowerCase() : `.${value.toLowerCase()}`;
3214
+ }
3215
+
3216
+ // src/http/dev-assets.ts
3217
+ var DEFAULT_PREFIX = "/resources/js";
3218
+ var DEFAULT_VENDOR_PATH = "/vendor/inertia-client.tsx";
3219
+ var DEFAULT_JSX_RUNTIME = "https://esm.sh/react@19.0.0/jsx-dev-runtime?dev";
3220
+ var require2 = createRequire(import.meta.url);
3221
+ var gurenInertiaClient = require2.resolve("@guren/inertia-client/app");
3222
+ function registerDevAssets(app, options) {
3223
+ if (typeof Bun === "undefined") {
3224
+ throw new Error("Bun runtime is required for dev asset serving.");
3225
+ }
3226
+ const moduleDir = options.importMeta ? dirname(fileURLToPath(options.importMeta.url)) : void 0;
3227
+ const resourcesDir = options.resourcesDir ?? (moduleDir ? resolve2(moduleDir, options.resourcesPath ?? "../resources") : void 0);
3228
+ if (!resourcesDir) {
3229
+ throw new Error("registerDevAssets requires either `resourcesDir` or `importMeta`.");
3230
+ }
3231
+ const prefix = options.prefix ?? DEFAULT_PREFIX;
3232
+ const cssDir = options.cssDir ?? resolve2(resourcesDir, "css");
3233
+ const cssRoute = options.cssRoute ?? deriveCssRoute(prefix);
3234
+ const inertiaClientPath = options.inertiaClientPath ?? DEFAULT_VENDOR_PATH;
3235
+ const inertiaClientSource = options.inertiaClientSource ?? gurenInertiaClient;
3236
+ const jsxRuntimeUrl = options.jsxRuntimeUrl ?? DEFAULT_JSX_RUNTIME;
3237
+ const resourcesJsDir = resolve2(resourcesDir, "js");
3238
+ const reactImportPattern = /from\s+['"]react['"]/u;
3239
+ const transpilerOptions = {
3240
+ target: "browser",
3241
+ jsx: "transform",
3242
+ jsxFactory: "React.createElement",
3243
+ jsxFragment: "React.Fragment",
3244
+ define: {
3245
+ "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV ?? "development")
3246
+ }
3247
+ };
3248
+ const tsxTranspiler = new Bun.Transpiler({ loader: "tsx", ...transpilerOptions });
3249
+ const tsTranspiler = new Bun.Transpiler({ loader: "ts", ...transpilerOptions });
3250
+ app.hono.get(`${prefix}/*`, (ctx) => handleTranspileRequest(ctx, resourcesJsDir, prefix, reactImportPattern, tsxTranspiler, tsTranspiler, jsxRuntimeUrl));
3251
+ if (cssDir) {
3252
+ const cssRewrite = createStaticRewrite(cssRoute);
3253
+ app.use(
3254
+ cssRoute,
3255
+ serveStatic({
3256
+ root: cssDir,
3257
+ rewriteRequestPath: cssRewrite
3258
+ })
3259
+ );
3260
+ }
3261
+ if (options.inertiaClient !== false) {
3262
+ const inertiaClientDir = dirname(inertiaClientSource);
3263
+ const inertiaClientBase = inertiaClientPath.replace(/[^/]*$/u, "") || "/";
3264
+ const inertiaClientPattern = `${inertiaClientBase.endsWith("/") ? inertiaClientBase : `${inertiaClientBase}/`}*`;
3265
+ const inertiaClientRequestPath = inertiaClientPath.slice(inertiaClientBase.length);
3266
+ app.hono.get(inertiaClientPattern, (ctx) => {
3267
+ const relativeRequest = ctx.req.path.slice(inertiaClientBase.length) || inertiaClientRequestPath;
3268
+ if (relativeRequest === inertiaClientRequestPath) {
3269
+ return transpileFile(inertiaClientSource, reactImportPattern, tsxTranspiler, tsTranspiler, jsxRuntimeUrl);
3270
+ }
3271
+ const candidatePath = resolve2(inertiaClientDir, relativeRequest);
3272
+ if (!candidatePath.startsWith(inertiaClientDir)) {
3273
+ return ctx.notFound();
3274
+ }
3275
+ return transpileFile(candidatePath, reactImportPattern, tsxTranspiler, tsTranspiler, jsxRuntimeUrl);
3276
+ });
3277
+ }
3278
+ const publicPathOption = options.publicPath === void 0 ? "../public" : options.publicPath;
3279
+ const publicDir = options.publicDir ?? (moduleDir && publicPathOption ? resolve2(moduleDir, publicPathOption) : void 0);
3280
+ const shouldServePublic = publicDir && publicPathOption !== false;
3281
+ if (shouldServePublic) {
3282
+ const publicRoute = options.publicRoute ?? "/public/*";
3283
+ const rewriteRequestPath = createStaticRewrite(publicRoute);
3284
+ app.use(
3285
+ publicRoute,
3286
+ serveStatic({
3287
+ root: publicDir,
3288
+ rewriteRequestPath
3289
+ })
3290
+ );
3291
+ if (options.favicon !== false) {
3292
+ app.hono.get("/favicon.ico", () => new Response(null, { status: 204 }));
3293
+ }
3294
+ registerRootPublicAssets(app, publicDir, options.rootPublicAssets);
3295
+ }
3296
+ }
3297
+ function createStaticRewrite(route) {
3298
+ const wildcardIndex = route.indexOf("*");
3299
+ const base = wildcardIndex >= 0 ? route.slice(0, wildcardIndex) : route;
3300
+ const normalizedBase = base.endsWith("/") ? base.slice(0, -1) : base;
3301
+ if (!normalizedBase) {
3302
+ return (path) => path || "/";
3303
+ }
3304
+ return (path) => {
3305
+ if (!path.startsWith(normalizedBase)) {
3306
+ return path || "/";
3307
+ }
3308
+ const remainder = path.slice(normalizedBase.length);
3309
+ if (!remainder) {
3310
+ return "/";
3311
+ }
3312
+ return remainder.startsWith("/") ? remainder : `/${remainder}`;
3313
+ };
3314
+ }
3315
+ async function handleTranspileRequest(ctx, resourcesJsDir, prefix, reactImportPattern, tsxTranspiler, tsTranspiler, jsxRuntimeUrl) {
3316
+ const relative = ctx.req.path.slice(prefix.length + 1);
3317
+ const fsPath = resolve2(resourcesJsDir, relative);
3318
+ if (!fsPath.startsWith(resourcesJsDir)) {
3319
+ return ctx.notFound();
3320
+ }
3321
+ return transpileFile(fsPath, reactImportPattern, tsxTranspiler, tsTranspiler, jsxRuntimeUrl);
3322
+ }
3323
+ async function transpileFile(fsPath, reactImportPattern, tsxTranspiler, tsTranspiler, jsxRuntimeUrl) {
3324
+ const candidates = buildCandidatePaths(fsPath);
3325
+ let filePath;
3326
+ let file;
3327
+ for (const candidate of candidates) {
3328
+ const bunFile = Bun.file(candidate);
3329
+ if (await bunFile.exists()) {
3330
+ filePath = candidate;
3331
+ file = bunFile;
3332
+ break;
3333
+ }
3334
+ }
3335
+ if (!file || !filePath) {
3336
+ return new Response("Not Found", { status: 404 });
3337
+ }
3338
+ const ext = extname2(filePath);
3339
+ let source = await file.text();
3340
+ if (ext === ".tsx" && !reactImportPattern.test(source)) {
3341
+ source = "import React from 'react'\n" + source;
3342
+ }
3343
+ if (ext === ".tsx" || ext === ".ts") {
3344
+ const transpiled = ext === ".tsx" ? tsxTranspiler.transformSync(source, {
3345
+ loader: "tsx",
3346
+ sourceMap: isDev() ? "inline" : false,
3347
+ filename: filePath
3348
+ }) : tsTranspiler.transformSync(source, {
3349
+ loader: "ts",
3350
+ sourceMap: isDev() ? "inline" : false,
3351
+ filename: filePath
3352
+ });
3353
+ const helpers = collectJsxHelpers(transpiled);
3354
+ const runtimeShim = helpers.size ? createJsxRuntimeShim(helpers, jsxRuntimeUrl) : "";
3355
+ return new Response(runtimeShim + transpiled, {
3356
+ headers: {
3357
+ "Content-Type": "application/javascript; charset=utf-8",
3358
+ "Cache-Control": isDev() ? "no-cache" : "public, max-age=31536000"
3359
+ }
3360
+ });
3361
+ }
3362
+ const body = await file.arrayBuffer();
1194
3363
  return new Response(body, {
1195
3364
  headers: {
1196
3365
  "Content-Type": file.type || "application/octet-stream",
@@ -1199,7 +3368,7 @@ async function transpileFile(fsPath, reactImportPattern, tsxTranspiler, tsTransp
1199
3368
  });
1200
3369
  }
1201
3370
  function buildCandidatePaths(fsPath) {
1202
- const ext = extname(fsPath);
3371
+ const ext = extname2(fsPath);
1203
3372
  if (ext) {
1204
3373
  return [fsPath];
1205
3374
  }
@@ -1230,26 +3399,49 @@ ${assignments.join("\n")}
1230
3399
  function isDev() {
1231
3400
  return (process.env.NODE_ENV ?? "development") !== "production";
1232
3401
  }
3402
+ function deriveCssRoute(prefix) {
3403
+ const base = prefix.endsWith("/js") ? prefix.slice(0, -3) : prefix;
3404
+ const normalizedBase = base.endsWith("/") ? base.slice(0, -1) : base;
3405
+ const resolvedBase = normalizedBase.startsWith("/") ? normalizedBase : `/${normalizedBase}`;
3406
+ return `${resolvedBase}/css/*`;
3407
+ }
1233
3408
 
1234
3409
  // src/http/inertia-assets.ts
1235
3410
  import { serveStatic as serveStatic2 } from "hono/bun";
1236
- import { dirname as dirname2, resolve as resolve2 } from "path";
3411
+ import { dirname as dirname2, resolve as resolve3, join } from "path";
1237
3412
  import { fileURLToPath as fileURLToPath2 } from "url";
3413
+ import { readFileSync } from "fs";
1238
3414
  var DEFAULT_STYLES_ENTRY = "/public/assets/app.css";
1239
3415
  var DEFAULT_SCRIPT_ENTRY = "/assets/app.js";
3416
+ var DEFAULT_VENDOR_CLIENT_PATH = "/vendor/inertia-client.tsx";
1240
3417
  function configureInertiaAssets(app, options) {
1241
3418
  const stylesEntry = options.stylesEntry ?? DEFAULT_STYLES_ENTRY;
1242
3419
  process.env.GUREN_INERTIA_STYLES = process.env.GUREN_INERTIA_STYLES ?? stylesEntry;
3420
+ const providedSsrEntry = options.ssrEntry;
3421
+ const providedSsrManifest = options.ssrManifest;
1243
3422
  const isProduction = process.env.NODE_ENV === "production";
1244
3423
  if (!isProduction) {
3424
+ const devSsrEntry = resolveDevSsrEntry(options);
3425
+ if (!process.env.GUREN_INERTIA_SSR_ENTRY && devSsrEntry) {
3426
+ process.env.GUREN_INERTIA_SSR_ENTRY = devSsrEntry;
3427
+ }
3428
+ if (!process.env.GUREN_INERTIA_SSR_MANIFEST) {
3429
+ process.env.GUREN_INERTIA_SSR_MANIFEST = providedSsrManifest ?? "";
3430
+ }
1245
3431
  registerDevAssets(app, options);
1246
3432
  return;
1247
3433
  }
1248
3434
  const scriptEntry = options.scriptEntry ?? DEFAULT_SCRIPT_ENTRY;
1249
3435
  process.env.GUREN_INERTIA_ENTRY = process.env.GUREN_INERTIA_ENTRY ?? scriptEntry;
3436
+ if (!process.env.GUREN_INERTIA_SSR_ENTRY && providedSsrEntry) {
3437
+ process.env.GUREN_INERTIA_SSR_ENTRY = providedSsrEntry;
3438
+ }
3439
+ if (!process.env.GUREN_INERTIA_SSR_MANIFEST && providedSsrManifest) {
3440
+ process.env.GUREN_INERTIA_SSR_MANIFEST = providedSsrManifest;
3441
+ }
1250
3442
  const moduleDir = options.importMeta ? dirname2(fileURLToPath2(options.importMeta.url)) : void 0;
1251
3443
  const publicPathOption = options.publicPath === void 0 ? "../public" : options.publicPath;
1252
- const publicDir = options.publicDir ?? (moduleDir && publicPathOption ? resolve2(moduleDir, publicPathOption) : void 0);
3444
+ const publicDir = options.publicDir ?? (moduleDir && publicPathOption ? resolve3(moduleDir, publicPathOption) : void 0);
1253
3445
  if (!publicDir || publicPathOption === false) {
1254
3446
  return;
1255
3447
  }
@@ -1265,6 +3457,243 @@ function configureInertiaAssets(app, options) {
1265
3457
  if (options.favicon !== false) {
1266
3458
  app.hono.get("/favicon.ico", () => new Response(null, { status: 204 }));
1267
3459
  }
3460
+ registerRootPublicAssets(app, publicDir, options.rootPublicAssets);
3461
+ if (isProduction && options.inertiaClient !== false) {
3462
+ try {
3463
+ let inertiaClientEntry;
3464
+ if (typeof import.meta.resolve === "function") {
3465
+ try {
3466
+ const resolved = import.meta.resolve("@guren/inertia-client/app", import.meta.url);
3467
+ inertiaClientEntry = fileURLToPath2(new URL(resolved));
3468
+ } catch {
3469
+ inertiaClientEntry = void 0;
3470
+ }
3471
+ }
3472
+ if (!inertiaClientEntry) {
3473
+ throw new Error("Unable to resolve @guren/inertia-client entry");
3474
+ }
3475
+ const inertiaClientDir = dirname2(inertiaClientEntry);
3476
+ const inertiaClientPath = options.inertiaClientPath ?? DEFAULT_VENDOR_CLIENT_PATH;
3477
+ const inertiaClientBase = inertiaClientPath.replace(/[^/]*$/u, "") || "/";
3478
+ const inertiaClientPattern = `${inertiaClientBase.endsWith("/") ? inertiaClientBase : `${inertiaClientBase}/`}*`;
3479
+ const inertiaClientRequestPath = inertiaClientPath.slice(inertiaClientBase.length);
3480
+ app.hono.get(inertiaClientPattern, async (ctx) => {
3481
+ const relativeRequest = ctx.req.path.slice(inertiaClientBase.length) || inertiaClientRequestPath;
3482
+ let targetPath;
3483
+ if (relativeRequest === inertiaClientRequestPath) {
3484
+ targetPath = join(inertiaClientDir, "app.js");
3485
+ } else {
3486
+ targetPath = resolve3(inertiaClientDir, relativeRequest);
3487
+ if (!targetPath.startsWith(inertiaClientDir)) {
3488
+ return ctx.notFound();
3489
+ }
3490
+ }
3491
+ const file = Bun.file(targetPath);
3492
+ if (!await file.exists()) {
3493
+ return ctx.notFound();
3494
+ }
3495
+ const contentType = file.type || "application/javascript; charset=utf-8";
3496
+ return new Response(file, {
3497
+ headers: {
3498
+ "Content-Type": contentType,
3499
+ "Cache-Control": "public, max-age=31536000"
3500
+ }
3501
+ });
3502
+ });
3503
+ } catch (error) {
3504
+ console.warn("Unable to resolve @guren/inertia-client/app for production serving.", error);
3505
+ }
3506
+ }
3507
+ }
3508
+ function autoConfigureInertiaAssets(app, options) {
3509
+ configureInertiaAssets(app, options);
3510
+ const moduleDir = options.importMeta ? dirname2(fileURLToPath2(options.importMeta.url)) : void 0;
3511
+ const resourcesDir = resolveResourcesDir(options, moduleDir);
3512
+ const ssrOutDir = options.ssrOutDir ?? ".guren/ssr";
3513
+ const importMapEntries = parseImportMap2(process.env.GUREN_INERTIA_IMPORT_MAP);
3514
+ const ssrEnabled = options.enableSsr ?? true;
3515
+ if (!moduleDir) {
3516
+ return;
3517
+ }
3518
+ const isProduction = (process.env.NODE_ENV ?? "development") === "production" && typeof process.env.VITE_DEV_SERVER_URL !== "string";
3519
+ if (!isProduction) {
3520
+ const devServerUrl = options.devServerUrl ?? process.env.VITE_DEV_SERVER_URL ?? "http://localhost:5173";
3521
+ const normalizedDevServerUrl = normalizeDevServerUrl(devServerUrl);
3522
+ process.env.GUREN_INERTIA_ENTRY = `${normalizedDevServerUrl}/resources/js/dev-entry.ts`;
3523
+ process.env.GUREN_INERTIA_STYLES = "";
3524
+ importMapEntries["@guren/inertia-client"] = DEFAULT_VENDOR_CLIENT_PATH;
3525
+ if (ssrEnabled) {
3526
+ const ssrEntryPath = options.ssrEntry ?? (resourcesDir ? resolve3(resourcesDir, "js/ssr.tsx") : void 0);
3527
+ if (ssrEntryPath) {
3528
+ process.env.GUREN_INERTIA_SSR_ENTRY = ssrEntryPath;
3529
+ }
3530
+ process.env.GUREN_INERTIA_SSR_MANIFEST = "";
3531
+ } else {
3532
+ process.env.GUREN_INERTIA_SSR_ENTRY = "";
3533
+ process.env.GUREN_INERTIA_SSR_MANIFEST = "";
3534
+ }
3535
+ process.env.GUREN_INERTIA_IMPORT_MAP = JSON.stringify(importMapEntries);
3536
+ return;
3537
+ }
3538
+ const clientManifest = loadViteManifest(
3539
+ [
3540
+ resolve3(moduleDir, "../public/assets/manifest.json"),
3541
+ resolve3(moduleDir, "../public/assets/.vite/manifest.json")
3542
+ ],
3543
+ "client"
3544
+ );
3545
+ const clientEntry = clientManifest?.["resources/js/app.tsx"];
3546
+ const clientEntryFile = getManifestFile(clientEntry);
3547
+ const clientCssFiles = getManifestCss(clientEntry);
3548
+ if (clientEntryFile) {
3549
+ process.env.GUREN_INERTIA_ENTRY = `/public/assets/${clientEntryFile.replace(/^\//u, "")}`;
3550
+ }
3551
+ if (clientCssFiles?.length) {
3552
+ process.env.GUREN_INERTIA_STYLES = clientCssFiles.map((href) => `/public/assets/${href.replace(/^\//u, "")}`).join(",");
3553
+ }
3554
+ importMapEntries["@guren/inertia-client"] = DEFAULT_VENDOR_CLIENT_PATH;
3555
+ if (!ssrEnabled) {
3556
+ if (Object.keys(importMapEntries).length > 0) {
3557
+ process.env.GUREN_INERTIA_IMPORT_MAP = JSON.stringify(importMapEntries);
3558
+ }
3559
+ process.env.GUREN_INERTIA_SSR_ENTRY = "";
3560
+ process.env.GUREN_INERTIA_SSR_MANIFEST = "";
3561
+ return;
3562
+ }
3563
+ const ssrManifestPaths = [
3564
+ options.ssrManifest,
3565
+ resolve3(moduleDir, `../${ssrOutDir}/manifest.json`),
3566
+ resolve3(moduleDir, `../${ssrOutDir}/.vite/manifest.json`),
3567
+ resolve3(moduleDir, `../${ssrOutDir}/ssr-manifest.json`),
3568
+ resolve3(moduleDir, "../build/ssr/manifest.json"),
3569
+ resolve3(moduleDir, "../build/ssr/.vite/manifest.json"),
3570
+ resolve3(moduleDir, "../build/ssr/ssr-manifest.json"),
3571
+ resolve3(moduleDir, "../public/assets/.ssr/manifest.json"),
3572
+ resolve3(moduleDir, "../public/assets/.ssr/.vite/manifest.json"),
3573
+ resolve3(moduleDir, "../public/assets/.ssr/ssr-manifest.json"),
3574
+ resolve3(moduleDir, "../public/assets/.vite/ssr-manifest.json")
3575
+ ].filter((value) => Boolean(value));
3576
+ const ssrManifest = loadViteManifest(ssrManifestPaths, "SSR");
3577
+ const ssrEntry = ssrManifest?.["resources/js/ssr.tsx"];
3578
+ const ssrEntryFile = getManifestFile(ssrEntry);
3579
+ const ssrEntryRoot = deriveAssetRoot(ssrManifest, resolve3(moduleDir, `../${ssrOutDir}`));
3580
+ if (ssrEntryFile && ssrEntryRoot) {
3581
+ process.env.GUREN_INERTIA_SSR_ENTRY = resolve3(ssrEntryRoot, ssrEntryFile.replace(/^\//u, ""));
3582
+ }
3583
+ if (Object.keys(importMapEntries).length > 0) {
3584
+ process.env.GUREN_INERTIA_IMPORT_MAP = JSON.stringify(importMapEntries);
3585
+ }
3586
+ if (ssrManifest?.__path__) {
3587
+ process.env.GUREN_INERTIA_SSR_MANIFEST = ssrManifest.__path__;
3588
+ }
3589
+ }
3590
+ function resolveDevSsrEntry(options) {
3591
+ if (options.ssrEntry) {
3592
+ return options.ssrEntry;
3593
+ }
3594
+ if (options.resourcesDir) {
3595
+ return resolve3(options.resourcesDir, "js/ssr.tsx");
3596
+ }
3597
+ const moduleDir = options.importMeta ? dirname2(fileURLToPath2(options.importMeta.url)) : void 0;
3598
+ if (!moduleDir) {
3599
+ return void 0;
3600
+ }
3601
+ const resourcesPath = options.resourcesPath ?? "../resources";
3602
+ const resourcesDir = resolve3(moduleDir, resourcesPath);
3603
+ return resolve3(resourcesDir, "js/ssr.tsx");
3604
+ }
3605
+ function normalizeDevServerUrl(value) {
3606
+ if (!value) {
3607
+ return value;
3608
+ }
3609
+ const trimmed = value.trim();
3610
+ if (!trimmed) {
3611
+ return trimmed;
3612
+ }
3613
+ const stripped = trimmed.replace(/\/+$/u, "");
3614
+ return stripped.length > 0 ? stripped : "/";
3615
+ }
3616
+ function loadViteManifest(candidatePaths, label) {
3617
+ const command = label === "SSR" ? "bunx vite build --ssr" : "bunx vite build";
3618
+ for (const manifestPath of candidatePaths) {
3619
+ try {
3620
+ const raw = readFileSync(manifestPath, "utf8");
3621
+ const manifest = JSON.parse(raw);
3622
+ Object.defineProperty(manifest, "__path__", {
3623
+ value: manifestPath,
3624
+ enumerable: false
3625
+ });
3626
+ return manifest;
3627
+ } catch (error) {
3628
+ if (error.code !== "ENOENT") {
3629
+ console.warn(`Unable to load ${label} Vite manifest at ${manifestPath}.`, error);
3630
+ return void 0;
3631
+ }
3632
+ }
3633
+ }
3634
+ if (candidatePaths.length) {
3635
+ console.warn(
3636
+ `Unable to load ${label} Vite manifest. Checked paths:
3637
+ ${candidatePaths.map((p) => ` - ${p}`).join("\n")}
3638
+ Run \`${command}\` before starting in production.`
3639
+ );
3640
+ }
3641
+ return void 0;
3642
+ }
3643
+ function deriveAssetRoot(manifest, fallback) {
3644
+ if (!manifest?.__path__) {
3645
+ return fallback;
3646
+ }
3647
+ return resolve3(dirname2(manifest.__path__), "..");
3648
+ }
3649
+ function getManifestFile(entry) {
3650
+ if (!entry) {
3651
+ return void 0;
3652
+ }
3653
+ if (Array.isArray(entry)) {
3654
+ return entry[0];
3655
+ }
3656
+ if (typeof entry === "string") {
3657
+ return entry;
3658
+ }
3659
+ if ("file" in entry && typeof entry.file === "string") {
3660
+ return entry.file;
3661
+ }
3662
+ return void 0;
3663
+ }
3664
+ function getManifestCss(entry) {
3665
+ if (!entry || Array.isArray(entry) || typeof entry === "string") {
3666
+ return void 0;
3667
+ }
3668
+ return entry.css;
3669
+ }
3670
+ function resolveResourcesDir(options, moduleDir) {
3671
+ if (options.resourcesDir) {
3672
+ return options.resourcesDir;
3673
+ }
3674
+ if (!moduleDir) {
3675
+ return void 0;
3676
+ }
3677
+ const resourcesPath = options.resourcesPath ?? "../resources";
3678
+ return resolve3(moduleDir, resourcesPath);
3679
+ }
3680
+ function parseImportMap2(value) {
3681
+ if (!value) {
3682
+ return {};
3683
+ }
3684
+ try {
3685
+ const parsed = JSON.parse(value);
3686
+ const result = {};
3687
+ for (const [key, entry] of Object.entries(parsed)) {
3688
+ if (typeof entry === "string" && entry.length > 0) {
3689
+ result[key] = entry;
3690
+ }
3691
+ }
3692
+ return result;
3693
+ } catch (error) {
3694
+ console.warn("Failed to parse GUREN_INERTIA_IMPORT_MAP from environment. Expected JSON object.", error);
3695
+ return {};
3696
+ }
1268
3697
  }
1269
3698
 
1270
3699
  // src/http/request.ts
@@ -1321,15 +3750,16 @@ var Controller = class {
1321
3750
  }
1322
3751
  return auth;
1323
3752
  }
1324
- inertia(component, props, options = {}) {
3753
+ async inertia(component, props, options = {}) {
1325
3754
  const ctx = this.ctx;
1326
3755
  const { url: overrideUrl, ...rest } = options;
1327
3756
  const url = overrideUrl ?? ctx.req.path ?? ctx.req.url ?? "";
1328
- return inertia(component, props, {
3757
+ const response = await inertia(component, props, {
1329
3758
  ...rest,
1330
3759
  url,
1331
3760
  request: ctx.req.raw
1332
3761
  });
3762
+ return response;
1333
3763
  }
1334
3764
  json(data, init = {}) {
1335
3765
  return new Response(JSON.stringify(data), {
@@ -1350,7 +3780,9 @@ var Controller = class {
1350
3780
  });
1351
3781
  }
1352
3782
  redirect(url, options = {}) {
1353
- const { status = 302, headers } = options;
3783
+ const requestMethod = this.request.method?.toUpperCase?.();
3784
+ const defaultStatus = requestMethod && requestMethod !== "GET" ? 303 : 302;
3785
+ const { status = defaultStatus, headers } = options;
1354
3786
  return new Response(null, {
1355
3787
  status,
1356
3788
  headers: {
@@ -1365,13 +3797,18 @@ var Controller = class {
1365
3797
  function defineMiddleware(handler) {
1366
3798
  return handler;
1367
3799
  }
3800
+
3801
+ // src/index.ts
3802
+ ensureErrorStackTracePolyfill();
1368
3803
  export {
1369
3804
  Application,
1370
3805
  ApplicationContext,
1371
3806
  AuthManager,
1372
3807
  AuthServiceProvider,
3808
+ AuthenticatableModel,
1373
3809
  BaseUserProvider,
1374
3810
  Controller,
3811
+ GUREN_ASCII_ART,
1375
3812
  InertiaViewProvider,
1376
3813
  MemorySessionStore,
1377
3814
  ModelUserProvider,
@@ -1380,6 +3817,7 @@ export {
1380
3817
  SessionGuard,
1381
3818
  ViewEngine,
1382
3819
  attachAuthContext,
3820
+ autoConfigureInertiaAssets,
1383
3821
  configureInertiaAssets,
1384
3822
  createSessionMiddleware,
1385
3823
  defineMiddleware,
@@ -1387,8 +3825,10 @@ export {
1387
3825
  getSessionFromContext,
1388
3826
  gurenVitePlugin,
1389
3827
  inertia,
3828
+ logDevServerBanner,
1390
3829
  parseRequestPayload,
1391
3830
  registerDevAssets,
1392
3831
  requireAuthenticated,
1393
- requireGuest
3832
+ requireGuest,
3833
+ startViteDevServer
1394
3834
  };