durable-db 0.1.13 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/dist/arktypeConfig-DdIO8VV1.d.ts +6130 -0
  2. package/dist/{arktypeConfig-CTCJm4vA.js → arktypeConfig-DxP0OcV_.js} +1014 -1033
  3. package/dist/cli/bin.d.ts +1 -1
  4. package/dist/cli/bin.js +2 -10
  5. package/dist/cli/index.d.ts +40 -34
  6. package/dist/cli/index.js +4 -9
  7. package/dist/{cli-m2H7mQpa.js → cli-BUSZTS2D.js} +213 -49
  8. package/dist/context/index.d.ts +50 -2
  9. package/dist/context/index.js +119 -5
  10. package/dist/db/index.d.ts +4 -4
  11. package/dist/db/index.js +10 -12
  12. package/dist/{debug-DmBrUmwe.js → debug-Cz8KzMft.js} +23 -27
  13. package/dist/{defineDatabase-Bjws1Jkd.d.ts → defineDatabase-CHmTgZTx.d.ts} +4 -5
  14. package/dist/{defineDatabase-BD3k1L7d.js → defineDatabase-CHmzpzFf.js} +2 -4
  15. package/dist/discovery-gHeLq8jk.d.ts +11 -0
  16. package/dist/{index-AbdSa1Mk.d.ts → index-M4Jp_PFM.d.ts} +2 -1
  17. package/dist/index.d.ts +4 -4
  18. package/dist/index.js +5 -8
  19. package/dist/{kysely-BH7QZBZw.js → kysely-Be6KwFZC.js} +45 -31
  20. package/dist/migrations/generator.d.ts +14 -17
  21. package/dist/migrations/generator.js +202 -5
  22. package/dist/migrations/snapshot.d.ts +1 -1
  23. package/dist/migrations/snapshot.js +91 -3
  24. package/dist/{parser-CL3Nlmsy.js → parser-DR57GOjv.js} +58 -61
  25. package/dist/registry.d.ts +10 -11
  26. package/dist/registry.js +3 -5
  27. package/dist/schema.d.ts +5 -2
  28. package/dist/schema.js +6 -3
  29. package/dist/snapshot-CaG5xnE2.d.ts +48 -0
  30. package/dist/{state-DtZ70cBR.js → state-OVuoHRC9.js} +3 -5
  31. package/dist/testing/index.d.ts +4 -5
  32. package/dist/testing/index.js +6 -10
  33. package/dist/transport/protocol.d.ts +7 -8
  34. package/dist/transport/protocol.js +34 -3
  35. package/dist/transport/websocket.d.ts +4 -5
  36. package/dist/transport/websocket.js +103 -3
  37. package/dist/vite/durableDb.d.ts +7 -7
  38. package/dist/vite/durableDb.js +29 -31
  39. package/package.json +12 -12
  40. package/dist/arktypeConfig--4OgOv4U.d.ts +0 -6
  41. package/dist/context-kIVZbhye.js +0 -121
  42. package/dist/generator-KHBZaOI1.js +0 -202
  43. package/dist/index-BhRiKZ4j.d.ts +0 -51
  44. package/dist/protocol-DEubbBbR.js +0 -35
  45. package/dist/push-BY3lfh-R.js +0 -8
  46. package/dist/push-DiHH52-G.js +0 -190
  47. package/dist/schema-BCjqTRvV.d.ts +0 -6
  48. package/dist/schema-IFq7ovQq.js +0 -8
  49. package/dist/snapshot-DMW6j2Ix.js +0 -93
  50. package/dist/snapshot-DOerumb7.d.ts +0 -125
  51. package/dist/state-vav3VCId.js +0 -5
  52. package/dist/websocket-eao2rnHL.js +0 -104
@@ -1,2 +1,50 @@
1
- import { a as setTenantIdResolver, i as hasTenantId, n as getInstanceKey, r as getTenantId, t as getDevInstanceKeySuffix } from "../index-BhRiKZ4j.js";
2
- export { getDevInstanceKeySuffix, getInstanceKey, getTenantId, hasTenantId, setTenantIdResolver };
1
+ //#region src/context/index.d.ts
2
+ /**
3
+ * Configure a tenant ID resolver.
4
+ *
5
+ * The resolver is called at the moment a database operation needs the tenant ID —
6
+ * by which point request middleware (auth, session, etc.) has already completed.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * import { setTenantIdResolver } from 'durable-db/context';
11
+ * import { getRequestInfo } from 'rwsdk/worker';
12
+ *
13
+ * setTenantIdResolver(() => getRequestInfo().ctx.session!.shop);
14
+ * ```
15
+ */
16
+ export declare function setTenantIdResolver(resolver: (() => string) | null): void;
17
+ export declare function getTenantId(): string;
18
+ /**
19
+ * Check if a tenant ID resolver is configured (or a Durable Object context
20
+ * can supply the tenant).
21
+ */
22
+ export declare function hasTenantId(): boolean;
23
+ /**
24
+ * Get the dev epoch for instance key suffixing
25
+ * Only used in development to allow database resets
26
+ *
27
+ * Returns null in production or if no dev state exists
28
+ *
29
+ * @deprecated The epoch is now baked into generated stubs at build time via
30
+ * the `virtual:durable-db/__devEpoch` module — this function
31
+ * cannot read the dev state inside workerd (no filesystem) and returns null
32
+ * there. Import `devEpoch` / `applyDevEpoch` from the virtual module instead.
33
+ */
34
+ export declare function getDevInstanceKeySuffix(): string | null;
35
+ /**
36
+ * Get a database instance key, optionally suffixed with dev epoch
37
+ *
38
+ * In development, this appends an epoch suffix to enable database resets.
39
+ * In production, this returns the base key unchanged.
40
+ *
41
+ * @deprecated Generated stubs apply the epoch automatically via
42
+ * `applyDevEpoch` from `virtual:durable-db/__devEpoch`. This
43
+ * function only works in Node (it reads the dev state from disk) and is the
44
+ * identity inside workerd — combining it with the generated stubs would
45
+ * also double-suffix keys. Import from the virtual module instead.
46
+ *
47
+ * @param baseKey - The base instance key (e.g., tenant ID or 'global')
48
+ */
49
+ export declare function getInstanceKey(baseKey: string): string;
50
+ //#endregion
@@ -1,5 +1,119 @@
1
- import "../debug-DmBrUmwe.js";
2
- import "../state-DtZ70cBR.js";
3
- import { a as setTenantIdResolver, i as hasTenantId, n as getInstanceKey, r as getTenantId, t as getDevInstanceKeySuffix } from "../context-kIVZbhye.js";
4
-
5
- export { getDevInstanceKeySuffix, getInstanceKey, getTenantId, hasTenantId, setTenantIdResolver };
1
+ import { s as __toCommonJS } from "../debug-Cz8KzMft.js";
2
+ import { f as state_exports, s as init_state } from "../state-OVuoHRC9.js";
3
+ //#region src/context/index.ts
4
+ /**
5
+ * Tenant ID resolver for framework integration.
6
+ */
7
+ let tenantIdResolver = null;
8
+ /**
9
+ * Configure a tenant ID resolver.
10
+ *
11
+ * The resolver is called at the moment a database operation needs the tenant ID —
12
+ * by which point request middleware (auth, session, etc.) has already completed.
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * import { setTenantIdResolver } from 'durable-db/context';
17
+ * import { getRequestInfo } from 'rwsdk/worker';
18
+ *
19
+ * setTenantIdResolver(() => getRequestInfo().ctx.session!.shop);
20
+ * ```
21
+ */
22
+ function setTenantIdResolver(resolver) {
23
+ tenantIdResolver = resolver;
24
+ }
25
+ /**
26
+ * Get the current tenant ID from the configured resolver.
27
+ *
28
+ * @throws Error if no resolver is configured
29
+ *
30
+ * @example
31
+ * ```ts
32
+ * import { getTenantId } from 'durable-db/context';
33
+ *
34
+ * async function myHandler() {
35
+ * const tenantId = getTenantId();
36
+ * // ...
37
+ * }
38
+ * ```
39
+ */
40
+ /**
41
+ * Inside a Durable Object the instance key IS the tenant (per-tenant DBs key
42
+ * their instances by tenant id, plus an optional `__dev_<epoch>` suffix in
43
+ * dev). The registry publishes its DoContext store getter on globalThis — see
44
+ * the note there for why this is not a module import — so getTenantId() works
45
+ * in action handlers without the worker-side resolver, which the DO execution
46
+ * context never registers.
47
+ */
48
+ function tenantIdFromDoContext() {
49
+ const getStore = globalThis[Symbol.for("durable-db.doContext")];
50
+ const key = getStore?.()?.instanceKey;
51
+ if (!key || key === "global") return null;
52
+ const suffixAt = key.lastIndexOf("__dev_");
53
+ return suffixAt === -1 ? key : key.slice(0, suffixAt);
54
+ }
55
+ function getTenantId() {
56
+ if (tenantIdResolver) return tenantIdResolver();
57
+ const doTenant = tenantIdFromDoContext();
58
+ if (doTenant) return doTenant;
59
+ throw new Error("getTenantId() called without a resolver. Call setTenantIdResolver() first.");
60
+ }
61
+ /**
62
+ * Check if a tenant ID resolver is configured (or a Durable Object context
63
+ * can supply the tenant).
64
+ */
65
+ function hasTenantId() {
66
+ return tenantIdResolver !== null || tenantIdFromDoContext() !== null;
67
+ }
68
+ /**
69
+ * One-time warning guard: we only log an unexpected dev-epoch load failure
70
+ * once per process so Vite HMR / repeated lookups don't spam stderr.
71
+ */
72
+ let loggedDevEpochFailure = false;
73
+ /**
74
+ * Get the dev epoch for instance key suffixing
75
+ * Only used in development to allow database resets
76
+ *
77
+ * Returns null in production or if no dev state exists
78
+ *
79
+ * @deprecated The epoch is now baked into generated stubs at build time via
80
+ * the `virtual:durable-db/__devEpoch` module — this function
81
+ * cannot read the dev state inside workerd (no filesystem) and returns null
82
+ * there. Import `devEpoch` / `applyDevEpoch` from the virtual module instead.
83
+ */
84
+ function getDevInstanceKeySuffix() {
85
+ if (process.env.NODE_ENV === "production") return null;
86
+ try {
87
+ const { getDevEpoch } = (init_state(), __toCommonJS(state_exports));
88
+ return getDevEpoch(process.cwd());
89
+ } catch (e) {
90
+ const code = e?.code;
91
+ if (code !== "MODULE_NOT_FOUND" && code !== "ERR_MODULE_NOT_FOUND" && !loggedDevEpochFailure) {
92
+ loggedDevEpochFailure = true;
93
+ const message = e instanceof Error ? e.message : String(e);
94
+ console.warn(`[durable-db] Could not load dev epoch state (continuing without it): ${message}`);
95
+ }
96
+ return null;
97
+ }
98
+ }
99
+ /**
100
+ * Get a database instance key, optionally suffixed with dev epoch
101
+ *
102
+ * In development, this appends an epoch suffix to enable database resets.
103
+ * In production, this returns the base key unchanged.
104
+ *
105
+ * @deprecated Generated stubs apply the epoch automatically via
106
+ * `applyDevEpoch` from `virtual:durable-db/__devEpoch`. This
107
+ * function only works in Node (it reads the dev state from disk) and is the
108
+ * identity inside workerd — combining it with the generated stubs would
109
+ * also double-suffix keys. Import from the virtual module instead.
110
+ *
111
+ * @param baseKey - The base instance key (e.g., tenant ID or 'global')
112
+ */
113
+ function getInstanceKey(baseKey) {
114
+ const suffix = getDevInstanceKeySuffix();
115
+ if (!suffix) return baseKey;
116
+ return `${baseKey}__dev_${suffix}`;
117
+ }
118
+ //#endregion
119
+ export { getDevInstanceKeySuffix, getInstanceKey, getTenantId, hasTenantId, setTenantIdResolver };
@@ -1,4 +1,4 @@
1
- import { t as type } from "../arktypeConfig--4OgOv4U.js";
2
- import { a as ActionInfo, c as DatabaseDefinition, d as InferArgs, f as ParsedDatabaseFile, i as ActionContext, l as DatabaseInfo, n as Action, o as ArgsSchema, r as ActionConfig, s as DatabaseConfig, t as defineDatabase, u as DrizzleToKysely } from "../defineDatabase-Bjws1Jkd.js";
3
- import { _ as CreateKyselyOptions, a as QueryResult, c as DrizzleDefaultsPlugin, d as dateSerializers, f as Migration, g as SqliteDurableObject, h as Migrations, i as KyselyPlugin, l as SchemaPlugin, m as MigrationSchemaConflictError, n as CompiledQuery, o as studio, p as MigrationAttemptInfo, r as Kysely, s as DateSerializePlugin, t as CamelCasePlugin, u as createDrizzlePlugins, v as SqlExecutor, y as createKyselyFromSql } from "../index-AbdSa1Mk.js";
4
- export { Action, ActionConfig, ActionContext, ActionInfo, ArgsSchema, CamelCasePlugin, CompiledQuery, CreateKyselyOptions, DatabaseConfig, DatabaseDefinition, DatabaseInfo, DateSerializePlugin, DrizzleDefaultsPlugin, DrizzleToKysely, InferArgs, Kysely, KyselyPlugin, Migration, MigrationAttemptInfo, MigrationSchemaConflictError, Migrations, ParsedDatabaseFile, QueryResult, SchemaPlugin, SqlExecutor, SqliteDurableObject, createDrizzlePlugins, createKyselyFromSql, dateSerializers, defineDatabase, studio, type };
1
+ import { t as type } from "../arktypeConfig-DdIO8VV1.js";
2
+ import { a as ActionInfo, c as DatabaseDefinition, d as InferArgs, f as ParsedDatabaseFile, i as ActionContext, l as DatabaseInfo, n as Action, o as ArgsSchema, r as ActionConfig, s as DatabaseConfig, t as defineDatabase, u as DrizzleToKysely } from "../defineDatabase-CHmTgZTx.js";
3
+ import { _ as CreateKyselyOptions, a as QueryResult, c as DrizzleDefaultsPlugin, d as dateSerializers, f as Migration, g as SqliteDurableObject, h as Migrations, i as KyselyPlugin, l as SchemaPlugin, m as MigrationSchemaConflictError, n as CompiledQuery, o as studio, p as MigrationAttemptInfo, r as Kysely, s as DateSerializePlugin, t as CamelCasePlugin, u as createDrizzlePlugins, v as SqlExecutor, y as createKyselyFromSql } from "../index-M4Jp_PFM.js";
4
+ export { type Action, type ActionConfig, type ActionContext, type ActionInfo, type ArgsSchema, CamelCasePlugin, type CompiledQuery, type CreateKyselyOptions, type DatabaseConfig, type DatabaseDefinition, type DatabaseInfo, DateSerializePlugin, DrizzleDefaultsPlugin, type DrizzleToKysely, type InferArgs, type Kysely, type KyselyPlugin, type Migration, type MigrationAttemptInfo, MigrationSchemaConflictError, type Migrations, type ParsedDatabaseFile, type QueryResult, SchemaPlugin, type SqlExecutor, SqliteDurableObject, createDrizzlePlugins, createKyselyFromSql, dateSerializers, defineDatabase, studio, type };
package/dist/db/index.js CHANGED
@@ -1,11 +1,10 @@
1
- import { i as init_debug, n as debugMigrations } from "../debug-DmBrUmwe.js";
2
- import { t as type } from "../arktypeConfig-CTCJm4vA.js";
3
- import { n as defineDatabase } from "../defineDatabase-BD3k1L7d.js";
4
- import { a as createDrizzlePlugins, i as SchemaPlugin, n as DateSerializePlugin, o as dateSerializers, r as DrizzleDefaultsPlugin, t as createKyselyFromSql } from "../kysely-BH7QZBZw.js";
1
+ import { i as init_debug, n as debugMigrations } from "../debug-Cz8KzMft.js";
2
+ import { t as type } from "../arktypeConfig-DxP0OcV_.js";
3
+ import { n as defineDatabase } from "../defineDatabase-CHmzpzFf.js";
4
+ import { a as createDrizzlePlugins, i as SchemaPlugin, n as DateSerializePlugin, o as dateSerializers, r as DrizzleDefaultsPlugin, t as createKyselyFromSql } from "../kysely-Be6KwFZC.js";
5
5
  import { DurableObject } from "cloudflare:workers";
6
6
  import { CamelCasePlugin } from "kysely";
7
7
  import { studio } from "@outerbase/browsable-durable-object";
8
-
9
8
  //#region src/db/SqliteDurableObject.ts
10
9
  init_debug();
11
10
  /**
@@ -149,8 +148,8 @@ var SqliteDurableObject = class extends DurableObject {
149
148
  * Execute raw SQL statement
150
149
  * Used by migrations for direct SQL execution
151
150
  */
152
- execSql(sql$1) {
153
- this.sql.exec(sql$1);
151
+ execSql(sql) {
152
+ this.sql.exec(sql);
154
153
  }
155
154
  /**
156
155
  * Run pending migrations with PITR safety.
@@ -235,9 +234,9 @@ var SqliteDurableObject = class extends DurableObject {
235
234
  }
236
235
  if (restoreScheduled) {
237
236
  const attempts = this.getMigrationAttempts();
238
- const remaining = Math.max(0, MAX_PITR_ATTEMPTS + 1 - attempts.attemptCount);
237
+ const remaining = Math.max(0, 4 - attempts.attemptCount);
239
238
  const pendingNames = Array.from(new Set(pending.map((p) => p.name))).join(", ");
240
- console.error(`[database] Migration failed (attempt ${attempts.attemptCount}/${MAX_PITR_ATTEMPTS + 1}, ${remaining} PITR-protected retries remaining). Restoring to pre-migration bookmark. Pending: ${pendingNames || "(none)"}.`, error);
239
+ console.error(`[database] Migration failed (attempt ${attempts.attemptCount}/4, ${remaining} PITR-protected retries remaining). Restoring to pre-migration bookmark. Pending: ${pendingNames || "(none)"}.`, error);
241
240
  this.ctx.abort("Restoring to pre-migration bookmark");
242
241
  }
243
242
  }
@@ -377,7 +376,7 @@ var SqliteDurableObject = class extends DurableObject {
377
376
  async getMigrationStatus() {
378
377
  const attempts = this.getMigrationAttempts();
379
378
  const pitrAvailable = await this.checkPitrAvailable();
380
- const pitrAttemptsRemaining = pitrAvailable ? Math.max(0, MAX_PITR_ATTEMPTS + 1 - attempts.attemptCount) : 0;
379
+ const pitrAttemptsRemaining = pitrAvailable ? Math.max(0, 4 - attempts.attemptCount) : 0;
381
380
  const appliedSet = /* @__PURE__ */ new Set();
382
381
  try {
383
382
  const rows = this.sql.exec("SELECT DISTINCT name FROM __migrations").toArray();
@@ -434,6 +433,5 @@ var SqliteDurableObject = class extends DurableObject {
434
433
  ws.close(1011, "Unexpected error");
435
434
  }
436
435
  };
437
-
438
436
  //#endregion
439
- export { CamelCasePlugin, DateSerializePlugin, DrizzleDefaultsPlugin, MigrationSchemaConflictError, SchemaPlugin, SqliteDurableObject, createDrizzlePlugins, createKyselyFromSql, dateSerializers, defineDatabase, studio, type };
437
+ export { CamelCasePlugin, DateSerializePlugin, DrizzleDefaultsPlugin, MigrationSchemaConflictError, SchemaPlugin, SqliteDurableObject, createDrizzlePlugins, createKyselyFromSql, dateSerializers, defineDatabase, studio, type };
@@ -1,40 +1,37 @@
1
- import { createRequire } from "node:module";
2
-
3
- //#region rolldown:runtime
1
+ import "node:module";
2
+ //#region \0rolldown/runtime.js
4
3
  var __defProp = Object.defineProperty;
5
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
7
6
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __esmMin = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
9
- var __export = (all, symbols) => {
10
- let target = {};
11
- for (var name in all) {
12
- __defProp(target, name, {
13
- get: all[name],
14
- enumerable: true
15
- });
16
- }
17
- if (symbols) {
18
- __defProp(target, Symbol.toStringTag, { value: "Module" });
7
+ var __esmMin = (fn, res, err) => () => {
8
+ if (err) throw err[0];
9
+ try {
10
+ return fn && (res = fn(fn = 0)), res;
11
+ } catch (e) {
12
+ throw err = [e], e;
19
13
  }
14
+ };
15
+ var __exportAll = (all, no_symbols) => {
16
+ let target = {};
17
+ for (var name in all) __defProp(target, name, {
18
+ get: all[name],
19
+ enumerable: true
20
+ });
21
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
20
22
  return target;
21
23
  };
22
24
  var __copyProps = (to, from, except, desc) => {
23
- if (from && typeof from === "object" || typeof from === "function") {
24
- for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
25
- key = keys[i];
26
- if (!__hasOwnProp.call(to, key) && key !== except) {
27
- __defProp(to, key, {
28
- get: ((k) => from[k]).bind(null, key),
29
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
30
- });
31
- }
32
- }
25
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
26
+ key = keys[i];
27
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
28
+ get: ((k) => from[k]).bind(null, key),
29
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
30
+ });
33
31
  }
34
32
  return to;
35
33
  };
36
34
  var __toCommonJS = (mod) => __hasOwnProp.call(mod, "module.exports") ? mod["module.exports"] : __copyProps(__defProp({}, "__esModule", { value: true }), mod);
37
-
38
35
  //#endregion
39
36
  //#region src/utils/debug.ts
40
37
  function readDebugEnv() {
@@ -93,6 +90,5 @@ var init_debug = __esmMin((() => {
93
90
  debugCli = createDebug("database:cli");
94
91
  debugMigrations = createDebug("database:migrations");
95
92
  }));
96
-
97
93
  //#endregion
98
- export { __esmMin as a, init_debug as i, debugMigrations as n, __export as o, debugVite as r, __toCommonJS as s, debugCli as t };
94
+ export { __esmMin as a, init_debug as i, debugMigrations as n, __exportAll as o, debugVite as r, __toCommonJS as s, debugCli as t };
@@ -1,9 +1,8 @@
1
+ import { n as type } from "./arktypeConfig-DdIO8VV1.js";
1
2
  import { SQLiteTableWithColumns } from "drizzle-orm/sqlite-core";
2
3
  import { Kysely } from "kysely";
3
4
  import { Kyselify } from "drizzle-orm/kysely";
4
-
5
5
  //#region src/db/types.d.ts
6
-
7
6
  /**
8
7
  * Base type for ArkType schema definitions.
9
8
  * This represents any valid arktype definition object.
@@ -29,14 +28,14 @@ interface DatabaseConfig<TSchema extends Record<string, SQLiteTableWithColumns<a
29
28
  /**
30
29
  * Convert a Drizzle schema to Kysely database types using drizzle-kysely
31
30
  */
32
- type DrizzleToKysely<TSchema extends Record<string, SQLiteTableWithColumns<any>>> = { [K in keyof TSchema]: TSchema[K] extends SQLiteTableWithColumns<any> ? Kyselify<TSchema[K]> : never };
31
+ type DrizzleToKysely<TSchema extends Record<string, SQLiteTableWithColumns<any>>> = { [K in keyof TSchema]: TSchema[K] extends SQLiteTableWithColumns<any> ? Kyselify<TSchema[K]> : never; };
33
32
  /**
34
33
  * ArkType helpers – mirror Ark's own API:
35
34
  * - arkType.validate<Def> → definition shape with DSL validation/autocomplete
36
35
  * - arkType.infer<Def> → inferred output type
37
36
  */
38
- type ArkDef<Def> = arkType.validate<Def>;
39
- type InferArgs<Def> = arkType.infer<Def>;
37
+ type ArkDef<Def> = type.validate<Def>;
38
+ type InferArgs<Def> = type.infer<Def>;
40
39
  /**
41
40
  * Context passed to action handlers
42
41
  */
@@ -1,5 +1,4 @@
1
- import { t as type } from "./arktypeConfig-CTCJm4vA.js";
2
-
1
+ import { t as type } from "./arktypeConfig-DxP0OcV_.js";
3
2
  //#region src/db/defineDatabase.ts
4
3
  /**
5
4
  * Non-enumerable property the source `action()` stashes on the function it
@@ -67,6 +66,5 @@ function defineDatabase(_config) {
67
66
  destroyDatabase
68
67
  };
69
68
  }
70
-
71
69
  //#endregion
72
- export { defineDatabase as n, ACTION_TEST_META as t };
70
+ export { defineDatabase as n, ACTION_TEST_META as t };
@@ -0,0 +1,11 @@
1
+ import "vite";
2
+ //#region src/vite/modules/discovery.d.ts
3
+ /** One place database definitions are discovered from. */
4
+ interface DatabaseSource {
5
+ /** Directory, relative to the project root or absolute. */
6
+ dir: string;
7
+ /** Prepended to every database name found here (`<prefix>-<file>`). */
8
+ prefix?: string;
9
+ }
10
+ //#endregion
11
+ export { DatabaseSource as t };
@@ -1,9 +1,10 @@
1
+ import "./arktypeConfig-DdIO8VV1.js";
2
+ import "./defineDatabase-CHmTgZTx.js";
1
3
  import { SQLiteTableWithColumns } from "drizzle-orm/sqlite-core";
2
4
  import { DurableObject } from "cloudflare:workers";
3
5
  import { CamelCasePlugin, CamelCasePlugin as CamelCasePlugin$1, CompiledQuery, Kysely, Kysely as Kysely$1, KyselyPlugin, KyselyPlugin as KyselyPlugin$1, PluginTransformQueryArgs, PluginTransformResultArgs, QueryResult, QueryResult as QueryResult$1, RootOperationNode, UnknownRow } from "kysely";
4
6
  import { Table } from "drizzle-orm";
5
7
  import { studio } from "@outerbase/browsable-durable-object";
6
-
7
8
  //#region src/db/kysely.d.ts
8
9
  /**
9
10
  * SQL executor function type
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { t as type } from "./arktypeConfig--4OgOv4U.js";
2
- import { c as DatabaseDefinition, d as InferArgs, i as ActionContext, n as Action, r as ActionConfig, s as DatabaseConfig, t as defineDatabase, u as DrizzleToKysely } from "./defineDatabase-Bjws1Jkd.js";
3
- import { a as setTenantIdResolver, i as hasTenantId, r as getTenantId } from "./index-BhRiKZ4j.js";
4
- import { a as integer, c as real, d as uniqueIndex, i as index, l as table, n as blob, o as numeric, r as foreignKey, s as primaryKey, t as AnySQLiteColumn, u as text } from "./schema-BCjqTRvV.js";
1
+ import { t as type } from "./arktypeConfig-DdIO8VV1.js";
2
+ import { c as DatabaseDefinition, d as InferArgs, i as ActionContext, n as Action, r as ActionConfig, s as DatabaseConfig, t as defineDatabase, u as DrizzleToKysely } from "./defineDatabase-CHmTgZTx.js";
3
+ import { getTenantId, hasTenantId, setTenantIdResolver } from "./context/index.js";
4
+ import { AnySQLiteColumn, blob, foreignKey, index, integer, numeric, primaryKey, real, table, text, uniqueIndex } from "./schema.js";
5
5
  import { Kysely } from "kysely";
6
6
  export { type Action, type ActionConfig, type ActionContext, type AnySQLiteColumn, type DatabaseConfig, type DatabaseDefinition, type DrizzleToKysely, type InferArgs, type Kysely, blob, defineDatabase, foreignKey, getTenantId, hasTenantId, index, integer, numeric, primaryKey, real, setTenantIdResolver, table, text, type, uniqueIndex };
package/dist/index.js CHANGED
@@ -1,8 +1,5 @@
1
- import "./debug-DmBrUmwe.js";
2
- import { t as type } from "./arktypeConfig-CTCJm4vA.js";
3
- import { n as defineDatabase } from "./defineDatabase-BD3k1L7d.js";
4
- import { a as numeric, c as table, i as integer, l as text, n as foreignKey, o as primaryKey, r as index, s as real, t as blob, u as uniqueIndex } from "./schema-IFq7ovQq.js";
5
- import "./state-DtZ70cBR.js";
6
- import { a as setTenantIdResolver, i as hasTenantId, r as getTenantId } from "./context-kIVZbhye.js";
7
-
8
- export { blob, defineDatabase, foreignKey, getTenantId, hasTenantId, index, integer, numeric, primaryKey, real, setTenantIdResolver, table, text, type, uniqueIndex };
1
+ import { t as type } from "./arktypeConfig-DxP0OcV_.js";
2
+ import { n as defineDatabase } from "./defineDatabase-CHmzpzFf.js";
3
+ import { blob, foreignKey, index, integer, numeric, primaryKey, real, table, text, uniqueIndex } from "./schema.js";
4
+ import { getTenantId, hasTenantId, setTenantIdResolver } from "./context/index.js";
5
+ export { blob, defineDatabase, foreignKey, getTenantId, hasTenantId, index, integer, numeric, primaryKey, real, setTenantIdResolver, table, text, type, uniqueIndex };
@@ -2,7 +2,6 @@ import { SQLiteSyncDialect, getTableConfig } from "drizzle-orm/sqlite-core";
2
2
  import { toCamelCase, toSnakeCase } from "drizzle-orm/casing";
3
3
  import { CamelCasePlugin, ColumnNode, ColumnUpdateNode, InsertQueryNode, Kysely, PrimitiveValueListNode, SqliteDialect, TableNode, ValueListNode, ValueNode, ValuesNode, sql } from "kysely";
4
4
  import { Table, getTableColumns, getTableName, is, isSQLWrapper } from "drizzle-orm";
5
-
6
5
  //#region src/db/plugins.ts
7
6
  /**
8
7
  * Schema-aware CamelCasePlugin that uses Drizzle schema for column name mapping.
@@ -116,7 +115,8 @@ var DrizzleDefaultsPlugin = class {
116
115
  else throw new Error("Unsupported row node type in insert query");
117
116
  const processedValues = originalValues.map((val, idx) => {
118
117
  if (val.kind === "DefaultInsertValueNode") {
119
- const colDef = tableDefaults[providedColumns[idx].column.name];
118
+ const colName = providedColumns[idx].column.name;
119
+ const colDef = tableDefaults[colName];
120
120
  if (colDef?.defaultFn) return createValueNode(colDef.defaultFn());
121
121
  }
122
122
  return val;
@@ -163,17 +163,36 @@ var DrizzleDefaultsPlugin = class {
163
163
  * SQLite stores dates as TEXT in ISO format (without timezone)
164
164
  */
165
165
  const dateSerializers = {
166
+ /**
167
+ * Serialize a Date to SQLite format
168
+ * Converts to ISO string, removes timezone info
169
+ */
166
170
  serialize(value) {
167
171
  return value.toISOString().replace("T", " ").slice(0, 19);
168
172
  },
173
+ /**
174
+ * Deserialize a SQLite date string to Date
175
+ * Parses assuming UTC timezone
176
+ */
169
177
  deserialize(value) {
170
178
  const normalized = value.replace(" ", "T");
171
179
  if (/(?:Z|[+-]\d{2}:?\d{2})$/.test(normalized)) return new Date(normalized);
172
180
  return /* @__PURE__ */ new Date(normalized + "Z");
173
181
  },
182
+ /**
183
+ * Check if a string looks like an ISO date
184
+ */
174
185
  isDateString(value) {
175
186
  return /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}/.test(value);
176
187
  },
188
+ /**
189
+ * Check if a string matches exactly the format produced by serialize()
190
+ * (and SQLite's CURRENT_TIMESTAMP): `YYYY-MM-DD HH:MM:SS`.
191
+ *
192
+ * The read path only deserializes strings in this exact format. Anything
193
+ * else — full ISO strings with a 'T' separator, timezone, or milliseconds —
194
+ * was stored by the user as a plain string and must round-trip verbatim.
195
+ */
177
196
  isSerializedDateString(value) {
178
197
  return /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(value);
179
198
  }
@@ -314,10 +333,7 @@ var BooleanDeserializePlugin = class {
314
333
  */
315
334
  function assertValidSchema(schema) {
316
335
  if (schema === null || typeof schema !== "object" || Array.isArray(schema)) throw new Error(`[db] Invalid schema: expected a record of Drizzle tables (e.g. { users, posts }), got ${Array.isArray(schema) ? "array" : schema === null ? "null" : typeof schema}.`);
317
- for (const [key, value] of Object.entries(schema)) if (!is(value, Table)) {
318
- const got = value === null ? "null" : value === void 0 ? "undefined" : typeof value;
319
- throw new Error(`[db] Invalid schema: '${key}' is not a Drizzle table (got ${got}). Make sure every value is defined with table() from 'durable-db/schema'.`);
320
- }
336
+ for (const [key, value] of Object.entries(schema)) if (!is(value, Table)) throw new Error(`[db] Invalid schema: '${key}' is not a Drizzle table (got ${value === null ? "null" : value === void 0 ? "undefined" : typeof value}). Make sure every value is defined with table() from 'durable-db/schema'.`);
321
337
  }
322
338
  /**
323
339
  * Create all recommended plugins for use with Drizzle schemas.
@@ -339,7 +355,6 @@ function createDrizzlePlugins(schema, camelCase = true) {
339
355
  plugins.push(new BooleanDeserializePlugin(schema));
340
356
  return plugins;
341
357
  }
342
-
343
358
  //#endregion
344
359
  //#region src/db/kysely.ts
345
360
  const MAX_BOUND_PARAMETERS = 100;
@@ -382,16 +397,16 @@ function escapeLiteral(value) {
382
397
  *
383
398
  * Exported for tests.
384
399
  */
385
- function inlineParameters(sql$1, parameters) {
400
+ function inlineParameters(sql, parameters) {
386
401
  let out = "";
387
402
  let p = 0;
388
- for (let i = 0; i < sql$1.length; i++) {
389
- const ch = sql$1[i];
403
+ for (let i = 0; i < sql.length; i++) {
404
+ const ch = sql[i];
390
405
  if (ch === "'" || ch === "\"") {
391
406
  let j = i + 1;
392
- while (j < sql$1.length) {
393
- if (sql$1[j] === ch) {
394
- if (sql$1[j + 1] === ch) {
407
+ while (j < sql.length) {
408
+ if (sql[j] === ch) {
409
+ if (sql[j + 1] === ch) {
395
410
  j += 2;
396
411
  continue;
397
412
  }
@@ -399,21 +414,21 @@ function inlineParameters(sql$1, parameters) {
399
414
  }
400
415
  j++;
401
416
  }
402
- out += sql$1.slice(i, j + 1);
417
+ out += sql.slice(i, j + 1);
403
418
  i = j;
404
419
  continue;
405
420
  }
406
- if (ch === "-" && sql$1[i + 1] === "-") {
407
- let j = sql$1.indexOf("\n", i);
408
- if (j === -1) j = sql$1.length;
409
- out += sql$1.slice(i, j);
421
+ if (ch === "-" && sql[i + 1] === "-") {
422
+ let j = sql.indexOf("\n", i);
423
+ if (j === -1) j = sql.length;
424
+ out += sql.slice(i, j);
410
425
  i = j - 1;
411
426
  continue;
412
427
  }
413
- if (ch === "/" && sql$1[i + 1] === "*") {
414
- let j = sql$1.indexOf("*/", i + 2);
415
- j = j === -1 ? sql$1.length : j + 2;
416
- out += sql$1.slice(i, j);
428
+ if (ch === "/" && sql[i + 1] === "*") {
429
+ let j = sql.indexOf("*/", i + 2);
430
+ j = j === -1 ? sql.length : j + 2;
431
+ out += sql.slice(i, j);
417
432
  i = j - 1;
418
433
  continue;
419
434
  }
@@ -432,8 +447,8 @@ function inlineParameters(sql$1, parameters) {
432
447
  */
433
448
  var CloudflareSqliteDriver = class {
434
449
  sql;
435
- constructor(sql$1) {
436
- this.sql = sql$1;
450
+ constructor(sql) {
451
+ this.sql = sql;
437
452
  }
438
453
  async init() {}
439
454
  async acquireConnection() {
@@ -455,13 +470,13 @@ var CloudflareSqliteDriver = class {
455
470
  /**
456
471
  * Helper to create a CompiledQuery object
457
472
  */
458
- function createCompiledQuery(sql$1, parameters = []) {
473
+ function createCompiledQuery(sql, parameters = []) {
459
474
  return {
460
- sql: sql$1,
475
+ sql,
461
476
  parameters,
462
477
  query: {
463
478
  kind: "RawNode",
464
- sqlFragments: [sql$1],
479
+ sqlFragments: [sql],
465
480
  parameters: []
466
481
  }
467
482
  };
@@ -471,8 +486,8 @@ function createCompiledQuery(sql$1, parameters = []) {
471
486
  */
472
487
  var CloudflareSqliteConnection = class {
473
488
  sql;
474
- constructor(sql$1) {
475
- this.sql = sql$1;
489
+ constructor(sql) {
490
+ this.sql = sql;
476
491
  }
477
492
  async executeQuery(compiledQuery) {
478
493
  let queryStr = compiledQuery.sql;
@@ -532,6 +547,5 @@ function createKyselyFromSql(sqlStorage, options = {}) {
532
547
  plugins: allPlugins
533
548
  });
534
549
  }
535
-
536
550
  //#endregion
537
- export { createDrizzlePlugins as a, SchemaPlugin as i, DateSerializePlugin as n, dateSerializers as o, DrizzleDefaultsPlugin as r, createKyselyFromSql as t };
551
+ export { createDrizzlePlugins as a, SchemaPlugin as i, DateSerializePlugin as n, dateSerializers as o, DrizzleDefaultsPlugin as r, createKyselyFromSql as t };