@supalive/core 1.2.1 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/dist/index-4Nis7Wnk.d.ts +1973 -0
  2. package/dist/index-4Nis7Wnk.d.ts.map +1 -0
  3. package/dist/index-Ca58CrWX.d.ts +2103 -0
  4. package/dist/index-Ca58CrWX.d.ts.map +1 -0
  5. package/dist/index-DDK9ZIYb.d.ts +2103 -0
  6. package/dist/index-DDK9ZIYb.d.ts.map +1 -0
  7. package/dist/index-Oz3eyddt.d.ts +1974 -0
  8. package/dist/index-Oz3eyddt.d.ts.map +1 -0
  9. package/dist/mysql-D0pFocWL.d.ts +109 -0
  10. package/dist/mysql-D0pFocWL.d.ts.map +1 -0
  11. package/dist/mysql-DF-dZHi7.d.ts +109 -0
  12. package/dist/mysql-DF-dZHi7.d.ts.map +1 -0
  13. package/dist/mysql-QWBVXBjM.d.ts +109 -0
  14. package/dist/mysql-QWBVXBjM.d.ts.map +1 -0
  15. package/dist/mysql-fECZYP_m.d.ts +109 -0
  16. package/dist/mysql-fECZYP_m.d.ts.map +1 -0
  17. package/dist/object-storage-4t7JvpuK.d.ts +67 -0
  18. package/dist/object-storage-4t7JvpuK.d.ts.map +1 -0
  19. package/dist/postgres-C1qWlB--.d.ts +113 -0
  20. package/dist/postgres-C1qWlB--.d.ts.map +1 -0
  21. package/dist/postgres-CKtJ62S4.d.ts +113 -0
  22. package/dist/postgres-CKtJ62S4.d.ts.map +1 -0
  23. package/dist/postgres-DdqpjjYF.d.ts +113 -0
  24. package/dist/postgres-DdqpjjYF.d.ts.map +1 -0
  25. package/dist/postgres-DhCgxVOr.d.ts +113 -0
  26. package/dist/postgres-DhCgxVOr.d.ts.map +1 -0
  27. package/dist/procedure-Ze1GE-N9.js.map +1 -1
  28. package/dist/src/client/index.d.ts +1 -1
  29. package/dist/src/client/index.js +7 -1
  30. package/dist/src/client/index.js.map +1 -1
  31. package/dist/src/exports/mysql.d.ts +1 -1
  32. package/dist/src/exports/postgres.d.ts +1 -1
  33. package/dist/src/exports/procedure.d.ts +1 -1
  34. package/dist/src/exports/schema-sql.d.ts +1 -1
  35. package/dist/src/exports/schema-sql.d.ts.map +1 -1
  36. package/dist/src/exports/schema-sql.js +8 -1
  37. package/dist/src/exports/schema-sql.js.map +1 -1
  38. package/dist/src/exports/server.d.ts +9 -7
  39. package/dist/src/exports/server.d.ts.map +1 -1
  40. package/dist/src/exports/server.js +14 -7
  41. package/dist/src/exports/server.js.map +1 -1
  42. package/dist/src/exports/storage.d.ts +56 -0
  43. package/dist/src/exports/storage.d.ts.map +1 -0
  44. package/dist/src/exports/storage.js +62 -0
  45. package/dist/src/exports/storage.js.map +1 -0
  46. package/dist/src/exports/types.d.ts +2 -2
  47. package/dist/types_server-AN8OiTEx.d.ts +302 -0
  48. package/dist/types_server-AN8OiTEx.d.ts.map +1 -0
  49. package/dist/types_server-C9owgeSs.d.ts +302 -0
  50. package/dist/types_server-C9owgeSs.d.ts.map +1 -0
  51. package/dist/types_server-D5JDD_Dp.d.ts +430 -0
  52. package/dist/types_server-D5JDD_Dp.d.ts.map +1 -0
  53. package/dist/types_server-Dxx_Xx86.d.ts +430 -0
  54. package/dist/types_server-Dxx_Xx86.d.ts.map +1 -0
  55. package/package.json +15 -1
@@ -0,0 +1,113 @@
1
+ import { Bn as DbType, Gn as SqlBuilder, Gr as ReadEntry, Hn as PooledClient, Jr as WriteEntry, Kn as TxDatabase, Ln as CoreInitLockCtx, Rn as Database, Un as PreparedQueries, Vn as LazyCommitTsParam, mr as CommitLogEntry, qn as CacheLayer, zn as DbQueryResult } from "./index-Ca58CrWX.js";
2
+ import { Pool, PoolConfig } from "pg";
3
+ import { Logger } from "pino";
4
+
5
+ //#region src/db/postgres.d.ts
6
+ declare class PgDatabase implements Database {
7
+ constructor(logger: Logger, config: PoolConfig, pool?: Pool | undefined);
8
+ private logger;
9
+ config: PoolConfig;
10
+ private pool;
11
+ readonly sqlBuilder: SqlBuilder;
12
+ readonly dbType: DbType;
13
+ columnTypes: Map<string, Map<string, string>>;
14
+ protected sqlCache: Map<string, string>;
15
+ /**
16
+ * Fetches actual column types from Postgres for `table` and returns a
17
+ * map of DB column name → PG type string (as produced by `format_type`,
18
+ * e.g. `bigint`, `integer`, `character varying(32)`, `text[]`, `jsonb`).
19
+ * No caching here — see {@link getColumnTypes} for the cached path.
20
+ */
21
+ loadColumnTypesFromPg(table: string): Promise<Map<string, string>>;
22
+ /**
23
+ * Synchronous column-type lookup. The apply path calls this on every
24
+ * batched write, so it can't await — populate the cache via
25
+ * {@link bootstrapColumnTypes} at server start. Throws if `table` is
26
+ * missing (programmer error / bootstrap skipped).
27
+ */
28
+ getColumnTypes(table: string): Map<string, string> | null;
29
+ /**
30
+ * Eagerly load column types into the in-memory cache. With a Redis
31
+ * client supplied, attempts the cache key first and falls through to
32
+ * Postgres on miss (writing the result back to Redis). This is the
33
+ * "one server queries PG, the rest read from Redis" pattern for cold
34
+ * starts in a multi-instance deploy. Without Redis, always queries PG.
35
+ *
36
+ * Pass `tables` to limit the load to a specific list; otherwise every
37
+ * user table in the connected database is loaded.
38
+ *
39
+ * The Redis cache key should encode whatever invalidates types in your
40
+ * environment (typically a schema version / deploy version). The
41
+ * subscriber in supalive-server.ts is expected to publish a reload
42
+ * signal after migrations and invoke {@link invalidateColumnTypes}.
43
+ */
44
+ bootstrapColumnTypes(opts: {
45
+ redis?: CacheLayer;
46
+ cacheKey: string;
47
+ tables?: string[];
48
+ }): Promise<void>;
49
+ /**
50
+ * Invalidate cached types (and dependent SQL) for `table`, or the entire
51
+ * cache if `table` is omitted. The Redis-pubsub reload signal in
52
+ * supalive-server.ts is expected to call this on schema changes.
53
+ */
54
+ private invalidateColumnTypes;
55
+ /** Enumerate the user-defined tables in the connected database — used
56
+ * by bootstrapColumnTypes() when no explicit list is provided. */
57
+ private listUserTables;
58
+ getCoreVersion(): Promise<bigint>;
59
+ coreMigrationStatements(toVersion: bigint): string[];
60
+ withCoreInitLock(fn: (ctx: CoreInitLockCtx) => Promise<void>): Promise<void>;
61
+ query<T = any>(sql: string, params?: unknown[]): Promise<DbQueryResult<T>>;
62
+ getClient(): Promise<PooledClient>;
63
+ getTransactionClient(): Promise<TxDatabase>;
64
+ /** Internal: replace this instance's caches with shared references from
65
+ * a parent. Used by PgDatabase.getTransactionClient. */
66
+ adoptCaches(columnTypes: Map<string, Map<string, string>>, sqlCache: Map<string, string>): void;
67
+ getLatestSnapshotTimestamp(): Promise<bigint>;
68
+ updateLatestSnapshotTimestamp(commitTs: bigint): Promise<void>;
69
+ getMinSnapshotTimestamp(): Promise<bigint>;
70
+ updateMinSnapshotTimestamp(ts: bigint): Promise<void>;
71
+ getNextTimestamp(): Promise<bigint>;
72
+ attachPrevDataToWriteSet(writeSet: WriteEntry[], readSet: ReadEntry[]): Promise<void>;
73
+ prepareCommitWrites(readSet: ReadEntry[], writeSet: WriteEntry[], commitTs: LazyCommitTsParam): Promise<PreparedQueries>;
74
+ private pgPrepareBatchWrites;
75
+ private pgPrepareInsertSingle;
76
+ private pgPrepareInsertBatch;
77
+ private pgPrepareUpdateSingle;
78
+ private pgPrepareUpdateBatch;
79
+ private pgPrepareDeleteSingle;
80
+ private pgPrepareDeleteBatch;
81
+ private buildOrGetInsertSql;
82
+ private buildOrGetUpdateSql;
83
+ private buildOrGetDeleteSql;
84
+ private pgPrepareCommitLogs;
85
+ /**
86
+ * Point-only OCC check. For each genuine point read, compare the row's
87
+ * current commit_ts against the value captured at read time. A `null`
88
+ * expectedCommitTs means "row didn't exist when we read"; any row found
89
+ * now is a conflict. Reads whose row is being written in this same txn
90
+ * are skipped — the CAS UPDATE/DELETE already validated those.
91
+ */
92
+ private pgPrepareValidatePointReadsByCommitTs;
93
+ commitWrites(beginTs: bigint, queries: PreparedQueries, commitTs: bigint): Promise<{
94
+ success: boolean;
95
+ }>;
96
+ private pgApplyWrites;
97
+ /**
98
+ * Point-only OCC check. For each genuine point read, compare the row's
99
+ * current commit_ts against the value captured at read time. A `null`
100
+ * expectedCommitTs means "row didn't exist when we read"; any row found
101
+ * now is a conflict. Reads whose row is being written in this same txn
102
+ * are skipped — the CAS UPDATE/DELETE already validated those.
103
+ */
104
+ private validatePointReadsByCommitTs;
105
+ pruneCommitLogsBefore(ts: bigint): Promise<bigint>;
106
+ getMinCommitLogTs(): Promise<bigint | null>;
107
+ getCommitLogsBetweenTs(beginTs: bigint, endTs: bigint, tableIds: Uint8Array[]): Promise<CommitLogEntry[]>;
108
+ getCommitLogsSinceTs(sinceTs: bigint, excludeTs: bigint, tableIds: Uint8Array[]): Promise<CommitLogEntry[]>;
109
+ close(): Promise<void>;
110
+ }
111
+ //#endregion
112
+ export { PgDatabase as t };
113
+ //# sourceMappingURL=postgres-C1qWlB--.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres-C1qWlB--.d.ts","names":[],"sources":["../src/db/postgres.ts"],"mappings":";;;;;cAiBa,UAAA,YAAsB,QAAA;cAE/B,MAAA,EAAQ,MAAA,EACR,MAAA,EAAQ,UAAA,EACR,IAAA,GAAM,IAAA;EAAA,QAWA,MAAA;EACD,MAAA,EAAQ,UAAA;EAAA,QACP,IAAA;EAAA,SACC,UAAA,EAAY,UAAA;EAAA,SACZ,MAAA,EAAQ,MAAA;EAMV,WAAA,EAAa,GAAA,SAAY,GAAA;EAAA,UAGtB,QAAA,EAAU,GAAA;EAHY;;;;;;EAW1B,qBAAA,CAAsB,KAAA,WAAgB,OAAA,CAAQ,GAAA;EAoDhD;;;;;;EA5BJ,cAAA,CAAe,KAAA,WAAgB,GAAA;EAyJ4B;;;;;;;;;;;;;;;EAjIrD,oBAAA,CAAqB,IAAA;IACzB,KAAA,GAAQ,UAAA;IACR,QAAA;IACA,MAAA;EAAA,IACE,OAAA;EAyRD;;;;;EAAA,QA/OK,qBAAA;EA23BsF;;EAAA,QA72BhF,cAAA;EAUR,cAAA,IAAkB,OAAA;EAWxB,uBAAA,CAAw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AAA;EAmBxF,oBAAA,CAAqB,OAAA,UAAiB,SAAA,UAAmB,QAAA,EAAU,UAAA,KAAe,OAAA,CAAQ,cAAA;EAmB1F,KAAA,IAAS,OAAA;AAAA"}
@@ -0,0 +1,113 @@
1
+ import { Bn as DbType, Gn as SqlBuilder, Gr as ReadEntry, Hn as PooledClient, Jr as WriteEntry, Kn as TxDatabase, Ln as CoreInitLockCtx, Rn as Database, Un as PreparedQueries, Vn as LazyCommitTsParam, mr as CommitLogEntry, qn as CacheLayer, zn as DbQueryResult } from "./index-DDK9ZIYb.js";
2
+ import { Pool, PoolConfig } from "pg";
3
+ import { Logger } from "pino";
4
+
5
+ //#region src/db/postgres.d.ts
6
+ declare class PgDatabase implements Database {
7
+ constructor(logger: Logger, config: PoolConfig, pool?: Pool | undefined);
8
+ private logger;
9
+ config: PoolConfig;
10
+ private pool;
11
+ readonly sqlBuilder: SqlBuilder;
12
+ readonly dbType: DbType;
13
+ columnTypes: Map<string, Map<string, string>>;
14
+ protected sqlCache: Map<string, string>;
15
+ /**
16
+ * Fetches actual column types from Postgres for `table` and returns a
17
+ * map of DB column name → PG type string (as produced by `format_type`,
18
+ * e.g. `bigint`, `integer`, `character varying(32)`, `text[]`, `jsonb`).
19
+ * No caching here — see {@link getColumnTypes} for the cached path.
20
+ */
21
+ loadColumnTypesFromPg(table: string): Promise<Map<string, string>>;
22
+ /**
23
+ * Synchronous column-type lookup. The apply path calls this on every
24
+ * batched write, so it can't await — populate the cache via
25
+ * {@link bootstrapColumnTypes} at server start. Throws if `table` is
26
+ * missing (programmer error / bootstrap skipped).
27
+ */
28
+ getColumnTypes(table: string): Map<string, string> | null;
29
+ /**
30
+ * Eagerly load column types into the in-memory cache. With a Redis
31
+ * client supplied, attempts the cache key first and falls through to
32
+ * Postgres on miss (writing the result back to Redis). This is the
33
+ * "one server queries PG, the rest read from Redis" pattern for cold
34
+ * starts in a multi-instance deploy. Without Redis, always queries PG.
35
+ *
36
+ * Pass `tables` to limit the load to a specific list; otherwise every
37
+ * user table in the connected database is loaded.
38
+ *
39
+ * The Redis cache key should encode whatever invalidates types in your
40
+ * environment (typically a schema version / deploy version). The
41
+ * subscriber in supalive-server.ts is expected to publish a reload
42
+ * signal after migrations and invoke {@link invalidateColumnTypes}.
43
+ */
44
+ bootstrapColumnTypes(opts: {
45
+ redis?: CacheLayer;
46
+ cacheKey: string;
47
+ tables?: string[];
48
+ }): Promise<void>;
49
+ /**
50
+ * Invalidate cached types (and dependent SQL) for `table`, or the entire
51
+ * cache if `table` is omitted. The Redis-pubsub reload signal in
52
+ * supalive-server.ts is expected to call this on schema changes.
53
+ */
54
+ private invalidateColumnTypes;
55
+ /** Enumerate the user-defined tables in the connected database — used
56
+ * by bootstrapColumnTypes() when no explicit list is provided. */
57
+ private listUserTables;
58
+ getCoreVersion(): Promise<bigint>;
59
+ coreMigrationStatements(toVersion: bigint): string[];
60
+ withCoreInitLock(fn: (ctx: CoreInitLockCtx) => Promise<void>): Promise<void>;
61
+ query<T = any>(sql: string, params?: unknown[]): Promise<DbQueryResult<T>>;
62
+ getClient(): Promise<PooledClient>;
63
+ getTransactionClient(): Promise<TxDatabase>;
64
+ /** Internal: replace this instance's caches with shared references from
65
+ * a parent. Used by PgDatabase.getTransactionClient. */
66
+ adoptCaches(columnTypes: Map<string, Map<string, string>>, sqlCache: Map<string, string>): void;
67
+ getLatestSnapshotTimestamp(): Promise<bigint>;
68
+ updateLatestSnapshotTimestamp(commitTs: bigint): Promise<void>;
69
+ getMinSnapshotTimestamp(): Promise<bigint>;
70
+ updateMinSnapshotTimestamp(ts: bigint): Promise<void>;
71
+ getNextTimestamp(): Promise<bigint>;
72
+ attachPrevDataToWriteSet(writeSet: WriteEntry[], readSet: ReadEntry[]): Promise<void>;
73
+ prepareCommitWrites(readSet: ReadEntry[], writeSet: WriteEntry[], commitTs: LazyCommitTsParam): Promise<PreparedQueries>;
74
+ private pgPrepareBatchWrites;
75
+ private pgPrepareInsertSingle;
76
+ private pgPrepareInsertBatch;
77
+ private pgPrepareUpdateSingle;
78
+ private pgPrepareUpdateBatch;
79
+ private pgPrepareDeleteSingle;
80
+ private pgPrepareDeleteBatch;
81
+ private buildOrGetInsertSql;
82
+ private buildOrGetUpdateSql;
83
+ private buildOrGetDeleteSql;
84
+ private pgPrepareCommitLogs;
85
+ /**
86
+ * Point-only OCC check. For each genuine point read, compare the row's
87
+ * current commit_ts against the value captured at read time. A `null`
88
+ * expectedCommitTs means "row didn't exist when we read"; any row found
89
+ * now is a conflict. Reads whose row is being written in this same txn
90
+ * are skipped — the CAS UPDATE/DELETE already validated those.
91
+ */
92
+ private pgPrepareValidatePointReadsByCommitTs;
93
+ commitWrites(beginTs: bigint, queries: PreparedQueries, commitTs: bigint): Promise<{
94
+ success: boolean;
95
+ }>;
96
+ private pgApplyWrites;
97
+ /**
98
+ * Point-only OCC check. For each genuine point read, compare the row's
99
+ * current commit_ts against the value captured at read time. A `null`
100
+ * expectedCommitTs means "row didn't exist when we read"; any row found
101
+ * now is a conflict. Reads whose row is being written in this same txn
102
+ * are skipped — the CAS UPDATE/DELETE already validated those.
103
+ */
104
+ private validatePointReadsByCommitTs;
105
+ pruneCommitLogsBefore(ts: bigint): Promise<bigint>;
106
+ getMinCommitLogTs(): Promise<bigint | null>;
107
+ getCommitLogsBetweenTs(beginTs: bigint, endTs: bigint, tableIds: Uint8Array[]): Promise<CommitLogEntry[]>;
108
+ getCommitLogsSinceTs(sinceTs: bigint, excludeTs: bigint, tableIds: Uint8Array[]): Promise<CommitLogEntry[]>;
109
+ close(): Promise<void>;
110
+ }
111
+ //#endregion
112
+ export { PgDatabase as t };
113
+ //# sourceMappingURL=postgres-CKtJ62S4.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres-CKtJ62S4.d.ts","names":[],"sources":["../src/db/postgres.ts"],"mappings":";;;;;cAiBa,UAAA,YAAsB,QAAA;cAE/B,MAAA,EAAQ,MAAA,EACR,MAAA,EAAQ,UAAA,EACR,IAAA,GAAM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AA;EAAA,QA2BN,qBAAA;EAAA,QAkBM,oBAAA;EAAA,QA+DN,qBAAA;EAAA,QAwBM,oBAAA;EAAA,QAsEN,qBAAA;EAAA,QAgBM,oBAAA;EAAA,QAiDN,mBAAA;EAAA,QAqBA,mBAAA;EAAA,QA4BA,mBAAA;EAAA,QAcM,mBAAA;EA3qBR;;;;;;;EAAA,QAytBE,qCAAA;EAkDF,YAAA,CACJ,OAAA,UACA,OAAA,EAAS,eAAA,EACT,QAAA,WACC,OAAA;IAAU,OAAA;EAAA;EAAA,QAqCC,aAAA;EApwBa;;;;;;;EAAA,QA+2Bb,4BAAA;EA0CR,qBAAA,CAAsB,EAAA,WAAa,OAAA;EAQnC,iBAAA,IAAqB,OAAA;EAQrB,sBAAA,CAAuB,OAAA,UAAiB,KAAA,UAAe,QAAA,EAAU,UAAA,KAAe,OAAA,CAAQ,cAAA;EAmBxF,oBAAA,CAAqB,OAAA,UAAiB,SAAA,UAAmB,QAAA,EAAU,UAAA,KAAe,OAAA,CAAQ,cAAA;EAmB1F,KAAA,IAAS,OAAA;AAAA"}
@@ -0,0 +1,113 @@
1
+ import { An as DbType, Dn as CoreInitLockCtx, Fn as SqlBuilder, Fr as ReadEntry, In as TxDatabase, Ln as CacheLayer, Mn as PooledClient, Nn as PreparedQueries, On as Database, Rr as WriteEntry, ir as CommitLogEntry, jn as LazyCommitTsParam, kn as DbQueryResult } from "./index-4Nis7Wnk.js";
2
+ import { Pool, PoolConfig } from "pg";
3
+ import { Logger } from "pino";
4
+
5
+ //#region src/db/postgres.d.ts
6
+ declare class PgDatabase implements Database {
7
+ constructor(logger: Logger, config: PoolConfig, pool?: Pool | undefined);
8
+ private logger;
9
+ config: PoolConfig;
10
+ private pool;
11
+ readonly sqlBuilder: SqlBuilder;
12
+ readonly dbType: DbType;
13
+ columnTypes: Map<string, Map<string, string>>;
14
+ protected sqlCache: Map<string, string>;
15
+ /**
16
+ * Fetches actual column types from Postgres for `table` and returns a
17
+ * map of DB column name → PG type string (as produced by `format_type`,
18
+ * e.g. `bigint`, `integer`, `character varying(32)`, `text[]`, `jsonb`).
19
+ * No caching here — see {@link getColumnTypes} for the cached path.
20
+ */
21
+ loadColumnTypesFromPg(table: string): Promise<Map<string, string>>;
22
+ /**
23
+ * Synchronous column-type lookup. The apply path calls this on every
24
+ * batched write, so it can't await — populate the cache via
25
+ * {@link bootstrapColumnTypes} at server start. Throws if `table` is
26
+ * missing (programmer error / bootstrap skipped).
27
+ */
28
+ getColumnTypes(table: string): Map<string, string> | null;
29
+ /**
30
+ * Eagerly load column types into the in-memory cache. With a Redis
31
+ * client supplied, attempts the cache key first and falls through to
32
+ * Postgres on miss (writing the result back to Redis). This is the
33
+ * "one server queries PG, the rest read from Redis" pattern for cold
34
+ * starts in a multi-instance deploy. Without Redis, always queries PG.
35
+ *
36
+ * Pass `tables` to limit the load to a specific list; otherwise every
37
+ * user table in the connected database is loaded.
38
+ *
39
+ * The Redis cache key should encode whatever invalidates types in your
40
+ * environment (typically a schema version / deploy version). The
41
+ * subscriber in supalive-server.ts is expected to publish a reload
42
+ * signal after migrations and invoke {@link invalidateColumnTypes}.
43
+ */
44
+ bootstrapColumnTypes(opts: {
45
+ redis?: CacheLayer;
46
+ cacheKey: string;
47
+ tables?: string[];
48
+ }): Promise<void>;
49
+ /**
50
+ * Invalidate cached types (and dependent SQL) for `table`, or the entire
51
+ * cache if `table` is omitted. The Redis-pubsub reload signal in
52
+ * supalive-server.ts is expected to call this on schema changes.
53
+ */
54
+ private invalidateColumnTypes;
55
+ /** Enumerate the user-defined tables in the connected database — used
56
+ * by bootstrapColumnTypes() when no explicit list is provided. */
57
+ private listUserTables;
58
+ getCoreVersion(): Promise<bigint>;
59
+ coreMigrationStatements(toVersion: bigint): string[];
60
+ withCoreInitLock(fn: (ctx: CoreInitLockCtx) => Promise<void>): Promise<void>;
61
+ query<T = any>(sql: string, params?: unknown[]): Promise<DbQueryResult<T>>;
62
+ getClient(): Promise<PooledClient>;
63
+ getTransactionClient(): Promise<TxDatabase>;
64
+ /** Internal: replace this instance's caches with shared references from
65
+ * a parent. Used by PgDatabase.getTransactionClient. */
66
+ adoptCaches(columnTypes: Map<string, Map<string, string>>, sqlCache: Map<string, string>): void;
67
+ getLatestSnapshotTimestamp(): Promise<bigint>;
68
+ updateLatestSnapshotTimestamp(commitTs: bigint): Promise<void>;
69
+ getMinSnapshotTimestamp(): Promise<bigint>;
70
+ updateMinSnapshotTimestamp(ts: bigint): Promise<void>;
71
+ getNextTimestamp(): Promise<bigint>;
72
+ attachPrevDataToWriteSet(writeSet: WriteEntry[], readSet: ReadEntry[]): Promise<void>;
73
+ prepareCommitWrites(readSet: ReadEntry[], writeSet: WriteEntry[], commitTs: LazyCommitTsParam): Promise<PreparedQueries>;
74
+ private pgPrepareBatchWrites;
75
+ private pgPrepareInsertSingle;
76
+ private pgPrepareInsertBatch;
77
+ private pgPrepareUpdateSingle;
78
+ private pgPrepareUpdateBatch;
79
+ private pgPrepareDeleteSingle;
80
+ private pgPrepareDeleteBatch;
81
+ private buildOrGetInsertSql;
82
+ private buildOrGetUpdateSql;
83
+ private buildOrGetDeleteSql;
84
+ private pgPrepareCommitLogs;
85
+ /**
86
+ * Point-only OCC check. For each genuine point read, compare the row's
87
+ * current commit_ts against the value captured at read time. A `null`
88
+ * expectedCommitTs means "row didn't exist when we read"; any row found
89
+ * now is a conflict. Reads whose row is being written in this same txn
90
+ * are skipped — the CAS UPDATE/DELETE already validated those.
91
+ */
92
+ private pgPrepareValidatePointReadsByCommitTs;
93
+ commitWrites(beginTs: bigint, queries: PreparedQueries, commitTs: bigint): Promise<{
94
+ success: boolean;
95
+ }>;
96
+ private pgApplyWrites;
97
+ /**
98
+ * Point-only OCC check. For each genuine point read, compare the row's
99
+ * current commit_ts against the value captured at read time. A `null`
100
+ * expectedCommitTs means "row didn't exist when we read"; any row found
101
+ * now is a conflict. Reads whose row is being written in this same txn
102
+ * are skipped — the CAS UPDATE/DELETE already validated those.
103
+ */
104
+ private validatePointReadsByCommitTs;
105
+ pruneCommitLogsBefore(ts: bigint): Promise<bigint>;
106
+ getMinCommitLogTs(): Promise<bigint | null>;
107
+ getCommitLogsBetweenTs(beginTs: bigint, endTs: bigint, tableIds: Uint8Array[]): Promise<CommitLogEntry[]>;
108
+ getCommitLogsSinceTs(sinceTs: bigint, excludeTs: bigint, tableIds: Uint8Array[]): Promise<CommitLogEntry[]>;
109
+ close(): Promise<void>;
110
+ }
111
+ //#endregion
112
+ export { PgDatabase as t };
113
+ //# sourceMappingURL=postgres-DdqpjjYF.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres-DdqpjjYF.d.ts","names":[],"sources":["../src/db/postgres.ts"],"mappings":";;;;;cAiBa,UAAA,YAAsB,QAAA;cAE/B,MAAA,EAAQ,MAAA,EACR,MAAA,EAAQ,UAAA,EACR,IAAA,GAAM,IAAA;EAAA,QAWA,MAAA;EACD,MAAA,EAAQ,UAAA;EAAA,QACP,IAAA;EAAA,SACC,UAAA,EAAY,UAAA;EAAA,SACZ,MAAA,EAAQ,MAAA;EAMV,WAAA,EAAa,GAAA,SAAY,GAAA;EAAA,UAGtB,QAAA,EAAU,GAAA;EAHY;;;;;;EAW1B,qBAAA,CAAsB,KAAA,WAAgB,OAAA,CAAQ,GAAA;EAoDhD;;;;;;EA5BJ,cAAA,CAAe,KAAA,WAAgB,GAAA;EAyJ4B;;;;;;;;;;;;;;;EAjIrD,oBAAA,CAAqB,IAAA;IACzB,KAAA,GAAQ,UAAA;IACR,QAAA;IACA,MAAA;EAAA,IACE,OAAA;EAyRD;;;;;EAAA,QA/OK,qBAAA;EA23BsF;;EAAA,QA72BhF,cAAA;EAUR,cAAA,IAAkB,OAAA;EAWxB,uBAAA,CAAwB,SAAA;EAUlB,gBAAA,CAAiB,EAAA,GAAK,GAAA,EAAK,eAAA,KAAoB,OAAA,SAAgB,OAAA;EAsC/D,KAAA,UAAe,GAAA,UAAa,MAAA,eAAyB,OAAA,CAAQ,aAAA,CAAc,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{ An as DbType, Dn as CoreInitLockCtx, Fn as SqlBuilder, Fr as ReadEntry, In as TxDatabase, Ln as CacheLayer, Mn as PooledClient, Nn as PreparedQueries, On as Database, Rr as WriteEntry, ir as CommitLogEntry, jn as LazyCommitTsParam, kn as DbQueryResult } from "./index-Oz3eyddt.js";
2
+ import { Pool, PoolConfig } from "pg";
3
+ import { Logger } from "pino";
4
+
5
+ //#region src/db/postgres.d.ts
6
+ declare class PgDatabase implements Database {
7
+ constructor(logger: Logger, config: PoolConfig, pool?: Pool | undefined);
8
+ private logger;
9
+ config: PoolConfig;
10
+ private pool;
11
+ readonly sqlBuilder: SqlBuilder;
12
+ readonly dbType: DbType;
13
+ columnTypes: Map<string, Map<string, string>>;
14
+ protected sqlCache: Map<string, string>;
15
+ /**
16
+ * Fetches actual column types from Postgres for `table` and returns a
17
+ * map of DB column name → PG type string (as produced by `format_type`,
18
+ * e.g. `bigint`, `integer`, `character varying(32)`, `text[]`, `jsonb`).
19
+ * No caching here — see {@link getColumnTypes} for the cached path.
20
+ */
21
+ loadColumnTypesFromPg(table: string): Promise<Map<string, string>>;
22
+ /**
23
+ * Synchronous column-type lookup. The apply path calls this on every
24
+ * batched write, so it can't await — populate the cache via
25
+ * {@link bootstrapColumnTypes} at server start. Throws if `table` is
26
+ * missing (programmer error / bootstrap skipped).
27
+ */
28
+ getColumnTypes(table: string): Map<string, string> | null;
29
+ /**
30
+ * Eagerly load column types into the in-memory cache. With a Redis
31
+ * client supplied, attempts the cache key first and falls through to
32
+ * Postgres on miss (writing the result back to Redis). This is the
33
+ * "one server queries PG, the rest read from Redis" pattern for cold
34
+ * starts in a multi-instance deploy. Without Redis, always queries PG.
35
+ *
36
+ * Pass `tables` to limit the load to a specific list; otherwise every
37
+ * user table in the connected database is loaded.
38
+ *
39
+ * The Redis cache key should encode whatever invalidates types in your
40
+ * environment (typically a schema version / deploy version). The
41
+ * subscriber in supalive-server.ts is expected to publish a reload
42
+ * signal after migrations and invoke {@link invalidateColumnTypes}.
43
+ */
44
+ bootstrapColumnTypes(opts: {
45
+ redis?: CacheLayer;
46
+ cacheKey: string;
47
+ tables?: string[];
48
+ }): Promise<void>;
49
+ /**
50
+ * Invalidate cached types (and dependent SQL) for `table`, or the entire
51
+ * cache if `table` is omitted. The Redis-pubsub reload signal in
52
+ * supalive-server.ts is expected to call this on schema changes.
53
+ */
54
+ private invalidateColumnTypes;
55
+ /** Enumerate the user-defined tables in the connected database — used
56
+ * by bootstrapColumnTypes() when no explicit list is provided. */
57
+ private listUserTables;
58
+ getCoreVersion(): Promise<bigint>;
59
+ coreMigrationStatements(toVersion: bigint): string[];
60
+ withCoreInitLock(fn: (ctx: CoreInitLockCtx) => Promise<void>): Promise<void>;
61
+ query<T = any>(sql: string, params?: unknown[]): Promise<DbQueryResult<T>>;
62
+ getClient(): Promise<PooledClient>;
63
+ getTransactionClient(): Promise<TxDatabase>;
64
+ /** Internal: replace this instance's caches with shared references from
65
+ * a parent. Used by PgDatabase.getTransactionClient. */
66
+ adoptCaches(columnTypes: Map<string, Map<string, string>>, sqlCache: Map<string, string>): void;
67
+ getLatestSnapshotTimestamp(): Promise<bigint>;
68
+ updateLatestSnapshotTimestamp(commitTs: bigint): Promise<void>;
69
+ getMinSnapshotTimestamp(): Promise<bigint>;
70
+ updateMinSnapshotTimestamp(ts: bigint): Promise<void>;
71
+ getNextTimestamp(): Promise<bigint>;
72
+ attachPrevDataToWriteSet(writeSet: WriteEntry[], readSet: ReadEntry[]): Promise<void>;
73
+ prepareCommitWrites(readSet: ReadEntry[], writeSet: WriteEntry[], commitTs: LazyCommitTsParam): Promise<PreparedQueries>;
74
+ private pgPrepareBatchWrites;
75
+ private pgPrepareInsertSingle;
76
+ private pgPrepareInsertBatch;
77
+ private pgPrepareUpdateSingle;
78
+ private pgPrepareUpdateBatch;
79
+ private pgPrepareDeleteSingle;
80
+ private pgPrepareDeleteBatch;
81
+ private buildOrGetInsertSql;
82
+ private buildOrGetUpdateSql;
83
+ private buildOrGetDeleteSql;
84
+ private pgPrepareCommitLogs;
85
+ /**
86
+ * Point-only OCC check. For each genuine point read, compare the row's
87
+ * current commit_ts against the value captured at read time. A `null`
88
+ * expectedCommitTs means "row didn't exist when we read"; any row found
89
+ * now is a conflict. Reads whose row is being written in this same txn
90
+ * are skipped — the CAS UPDATE/DELETE already validated those.
91
+ */
92
+ private pgPrepareValidatePointReadsByCommitTs;
93
+ commitWrites(beginTs: bigint, queries: PreparedQueries, commitTs: bigint): Promise<{
94
+ success: boolean;
95
+ }>;
96
+ private pgApplyWrites;
97
+ /**
98
+ * Point-only OCC check. For each genuine point read, compare the row's
99
+ * current commit_ts against the value captured at read time. A `null`
100
+ * expectedCommitTs means "row didn't exist when we read"; any row found
101
+ * now is a conflict. Reads whose row is being written in this same txn
102
+ * are skipped — the CAS UPDATE/DELETE already validated those.
103
+ */
104
+ private validatePointReadsByCommitTs;
105
+ pruneCommitLogsBefore(ts: bigint): Promise<bigint>;
106
+ getMinCommitLogTs(): Promise<bigint | null>;
107
+ getCommitLogsBetweenTs(beginTs: bigint, endTs: bigint, tableIds: Uint8Array[]): Promise<CommitLogEntry[]>;
108
+ getCommitLogsSinceTs(sinceTs: bigint, excludeTs: bigint, tableIds: Uint8Array[]): Promise<CommitLogEntry[]>;
109
+ close(): Promise<void>;
110
+ }
111
+ //#endregion
112
+ export { PgDatabase as t };
113
+ //# sourceMappingURL=postgres-DhCgxVOr.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres-DhCgxVOr.d.ts","names":[],"sources":["../src/db/postgres.ts"],"mappings":";;;;;cAiBa,UAAA,YAAsB,QAAA;cAE/B,MAAA,EAAQ,MAAA,EACR,MAAA,EAAQ,UAAA,EACR,IAAA,GAAM,IAAA;EAAA,QAWA,MAAA;EACD,MAAA,EAAQ,UAAA;EAAA,QACP,IAAA;EAAA,SACC,UAAA,EAAY,UAAA;EAAA,SACZ,MAAA,EAAQ,MAAA;EAMV,WAAA,EAAa,GAAA,SAAY,GAAA;EA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A;EAAA,QA4BA,mBAAA;EAAA,QAcM,mBAAA;EA3qBR;;;;;;;EAAA,QAytBE,qCAAA;EAkDF,YAAA,CACJ,OAAA,UACA,OAAA,EAAS,eAAA,EACT,QAAA,WACC,OAAA;IAAU,OAAA;EAAA;EAAA,QAqCC,aAAA;EApwBa;;;;;;;EAAA,QA+2Bb,4BAAA;EA0CR,qBAAA,CAAsB,EAAA,WAAa,OAAA;EAQnC,iBAAA,IAAqB,OAAA;EAQrB,sBAAA,CAAuB,OAAA,UAAiB,KAAA,UAAe,QAAA,EAAU,UAAA,KAAe,OAAA,CAAQ,cAAA;EAmBxF,oBAAA,CAAqB,OAAA,UAAiB,SAAA,UAAmB,QAAA,EAAU,UAAA,KAAe,OAAA,CAAQ,cAAA;EAmB1F,KAAA,IAAS,OAAA;AAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"procedure-Ze1GE-N9.js","names":[],"sources":["../src/router/procedure.ts"],"sourcesContent":["import type { ZodType } from \"zod\";\nimport type { DbReader, DbWriter } from \"../db/context\";\nimport type { SupaliveDb } from \"../db/realtime_db\";\n\n// ─── Context Types ───────────────────────────────────────────────────────────\n\n/**\n * Query context passed to query handlers.\n * Contains database reader and user-defined server context.\n */\nexport interface QueryCtx<TContext = unknown> {\n /** Database reader for queries */\n db: DbReader;\n /** User-defined server context (auth, requestId, etc.) */\n serverCtx?: TContext;\n}\n\n/**\n * Mutation context passed to mutation handlers.\n * Contains database writer and user-defined server context.\n */\nexport interface MutationCtx<TContext = unknown> {\n /** Database writer for mutations (includes insert/update/delete) */\n db: DbWriter;\n /** User-defined server context (auth, requestId, etc.) */\n serverCtx?: TContext;\n}\n\n/**\n * Action context passed to action handlers.\n * Contains the full SupaliveDb for both queries and mutations, plus user-defined server context.\n */\nexport interface ActionCtx<TContext = unknown> {\n /** Full database interface for queries and mutations */\n db: SupaliveDb;\n /** User-defined server context (auth, requestId, etc.) */\n serverCtx?: TContext;\n}\n\n/**\n * Job context passed to job handlers. Structurally identical to\n * {@link ActionCtx}: a job is a server-only procedure that runs\n * non-transactionally against the full {@link SupaliveDb} and may perform\n * external work, but it is triggered by the scheduler over HTTP (a cron tick\n * or a precise one-shot) rather than by a connected client. `serverCtx` is\n * the system context built by the server's `jobContext` factory.\n */\nexport interface JobCtx<TContext = unknown> {\n /** Full database interface for queries and mutations */\n db: SupaliveDb;\n /** System server context built by the server for scheduler-triggered runs */\n serverCtx?: TContext;\n}\n\n/**\n * Context handed to `caller.<proc>.runQuery` / `.runMutation` when invoking one\n * procedure from inside another. Pass the caller handler's own `ctx` — its `db`\n * carries the parent's live transaction (a {@link DbReader}/{@link DbWriter}) or,\n * inside an action, the full {@link SupaliveDb}. The caller uses this to decide\n * whether the nested call joins the parent's snapshot (queries) or runs as an\n * independent sub-transaction (mutations).\n */\nexport interface ParentCtx<TContext = unknown> {\n db: DbReader | DbWriter | SupaliveDb;\n serverCtx?: TContext | undefined;\n}\n\n// ─── Procedure Types ─────────────────────────────────────────────────────────\n\nexport type QueryFn<TInput, TResult, TContext = unknown> = (\n ctx: QueryCtx<TContext>,\n input: TInput,\n) => Promise<TResult>;\n\nexport type MutationFn<TInput, TResult, TContext = unknown> = (\n ctx: MutationCtx<TContext>,\n input: TInput,\n) => Promise<TResult>;\n\nexport type ActionFn<TInput, TResult, TContext = unknown> = (\n ctx: ActionCtx<TContext>,\n input: TInput,\n) => Promise<TResult>;\n\nexport type JobFn<TInput, TResult, TContext = unknown> = (\n ctx: JobCtx<TContext>,\n input: TInput,\n) => Promise<TResult>;\n\n/**\n * Per-procedure override for the cache/subscription segmentation key.\n *\n * omitted | undefined → fall back to `config.getUserId(serverCtx)` (default)\n * false → no identity in hash; cache/sub shared across all users\n * string → a static identity literal (e.g. \"public\" or a tenant id)\n * function → compute from serverCtx + input (sync)\n *\n * When the result of a query is identical regardless of who calls it, set\n * this to a literal (or `false`) so a single cache entry serves everyone.\n *\n * The function form intentionally takes `serverCtx` (not the full `QueryCtx`)\n * because identity is resolved before any DB read is issued.\n */\nexport type QueryIdentitySpec<TInput, TContext> =\n | false\n | string\n | ((serverCtx: TContext, input: TInput) => string | null | undefined);\n\nexport interface BaseProcedure<\n TInput, TResult,\n TType extends \"query\" | \"mutation\" | \"action\" | \"job\",\n TContext = unknown,\n TInternal extends boolean = boolean\n> {\n readonly _type: \"procedure\";\n readonly procedureType: TType;\n readonly inputSchema: ZodType<TInput>;\n readonly fn: QueryFn<TInput, TResult, TContext> | MutationFn<TInput, TResult, TContext> | ActionFn<TInput, TResult, TContext> | JobFn<TInput, TResult, TContext>;\n readonly internal: TInternal;\n}\n\nexport interface QueryProcedure<\n TInput, TResult,\n TContext = unknown,\n TInternal extends boolean = boolean\n> extends BaseProcedure<TInput, TResult, \"query\", TContext, TInternal> {\n readonly procedureType: \"query\";\n readonly fn: QueryFn<TInput, TResult, TContext>;\n readonly queryIdentity?: QueryIdentitySpec<TInput, TContext>;\n}\n\nexport interface MutationProcedure<\n TInput, TResult,\n TContext = unknown,\n TInternal extends boolean = boolean\n> extends BaseProcedure<TInput, TResult, \"mutation\", TContext, TInternal> {\n readonly procedureType: \"mutation\";\n readonly fn: MutationFn<TInput, TResult, TContext>;\n}\n\nexport interface ActionProcedure<\n TInput, TResult,\n TContext = unknown,\n TInternal extends boolean = boolean\n> extends BaseProcedure<TInput, TResult, \"action\", TContext, TInternal> {\n readonly procedureType: \"action\";\n readonly fn: ActionFn<TInput, TResult, TContext>;\n}\n\n/**\n * A scheduler-triggered, server-only procedure. Runs like an action (full\n * db, non-transactional, may do external work) but is dispatched by the\n * server's HTTP job endpoint on a cron tick or a precise one-shot rather\n * than over the client WebSocket. Always {@link internal}: true, so it is\n * never reachable via `call`/`subscribe`.\n */\nexport interface JobProcedure<\n TInput, TResult,\n TContext = unknown,\n> extends BaseProcedure<TInput, TResult, \"job\", TContext, true> {\n readonly procedureType: \"job\";\n readonly fn: JobFn<TInput, TResult, TContext>;\n /**\n * Cron expression for a recurring job (e.g. `\"0 3 * * *\"`). Declared crons\n * are synced to the scheduler at server startup. Omit for a job that is\n * only ever invoked as a precise one-shot via the scheduler API.\n */\n readonly cron?: string;\n}\n\nexport type AnyProcedure<TContext = unknown> =\n | QueryProcedure<any, any, TContext>\n | MutationProcedure<any, any, TContext>\n | ActionProcedure<any, any, TContext>\n | JobProcedure<any, any, TContext>;\n\n// ─── Procedure Configuration Types ───────────────────────────────────────────\n\nexport interface QueryConfig<TInput, TResult, TContext = unknown> {\n /** Zod schema for input validation */\n args: ZodType<TInput>;\n /** The query handler function */\n handler: QueryFn<TInput, TResult, TContext>;\n /** Mark as internal (server-only). Default: false */\n internal?: boolean;\n /**\n * Override the cache/subscription segmentation key for this procedure.\n * See {@link QueryIdentitySpec}. Omit to keep the default (per-user) behavior.\n */\n queryIdentity?: QueryIdentitySpec<TInput, TContext>;\n}\n\nexport interface MutationConfig<TInput, TResult, TContext = unknown> {\n /** Zod schema for input validation */\n args: ZodType<TInput>;\n /** The mutation handler function */\n handler: MutationFn<TInput, TResult, TContext>;\n /** Mark as internal (server-only). Default: false */\n internal?: boolean;\n}\n\nexport interface ActionConfig<TInput, TResult, TContext = unknown> {\n /** Zod schema for input validation */\n args: ZodType<TInput>;\n /** The action handler function */\n handler: ActionFn<TInput, TResult, TContext>;\n /** Mark as internal (server-only). Default: false */\n internal?: boolean;\n}\n\nexport interface JobConfig<TInput, TResult, TContext = unknown> {\n /** Zod schema for the job payload */\n args: ZodType<TInput>;\n /** The job handler function */\n handler: JobFn<TInput, TResult, TContext>;\n /**\n * Cron expression for a recurring schedule (e.g. `\"0 3 * * *\"`). Omit for a\n * job that is only invoked as a precise one-shot.\n */\n cron?: string;\n}\n\n/** Extract input type from a procedure */\nexport type InputOf<T> = T extends BaseProcedure<infer I, any, any, any> ? I : never;\n\n/** Extract output type from a procedure */\nexport type OutputOf<T> = T extends BaseProcedure<any, infer O, any, any> ? O : never;\n\n/** Extract procedure type (query/mutation) */\nexport type TypeOf<T> = T extends BaseProcedure<any, any, infer Type, any> ? Type : never;\n\n/** Extract server context type from a procedure */\nexport type ContextOf<T> = T extends BaseProcedure<any, any, any, infer C> ? C : never;\n\n/**\n * Create a query builder with a pre-defined context type.\n * This allows you to define the context type once and have it inferred\n * automatically in all your query handlers.\n * \n * @example\n * // Define your server context\n * interface ServerContext {\n * auth: { userId: string };\n * requestId: string;\n * }\n * \n * // Create a typed query builder\n * const query = createQueryBuilder<ServerContext>();\n * \n * // Use it - context type is automatically inferred!\n * const getUser = query({\n * args: z.object({ id: z.string() }),\n * handler: async (ctx, { id }) => {\n * // ctx.db for database queries\n * const user = await ctx.db.query(UsersSchema).find(id);\n * // ctx.context for server context\n * console.log(ctx.context.requestId);\n * return user;\n * }\n * });\n */\nexport function createQueryBuilder<TContext = unknown>() {\n return function query<TInput, TResult, const TInternal extends boolean = false>(\n config: QueryConfig<TInput, TResult, TContext> & { internal?: TInternal }\n ): QueryProcedure<TInput, TResult, TContext, TInternal> {\n return {\n _type: \"procedure\",\n procedureType: \"query\",\n inputSchema: config.args,\n fn: config.handler,\n internal: (config.internal ?? false) as TInternal,\n queryIdentity: config.queryIdentity,\n };\n };\n}\n\n// ─── Mutation Builder Factory ────────────────────────────────────────────────\n\n/**\n * Create a mutation builder with a pre-defined context type.\n * This allows you to define the context type once and have it inferred\n * automatically in all your mutation handlers.\n * \n * @example\n * // Define your server context\n * interface ServerContext {\n * auth: { userId: string };\n * requestId: string;\n * }\n * \n * // Create a typed mutation builder\n * const mutation = createMutationBuilder<ServerContext>();\n * \n * // Use it - context type is automatically inferred!\n * const createUser = mutation({\n * args: z.object({ name: z.string() }),\n * handler: async (ctx, { name }) => {\n * // ctx.db for mutations\n * await ctx.db.insert(UsersSchema, id, { name });\n * // ctx.context for server context\n * console.log(ctx.context.requestId);\n * return { success: true };\n * }\n * });\n */\nexport function createMutationBuilder<TContext = unknown>() {\n return function mutation<TInput, TResult, const TInternal extends boolean = false>(\n config: MutationConfig<TInput, TResult, TContext> & { internal?: TInternal }\n ): MutationProcedure<TInput, TResult, TContext, TInternal> {\n return {\n _type: \"procedure\",\n procedureType: \"mutation\",\n inputSchema: config.args,\n fn: config.handler,\n internal: (config.internal ?? false) as TInternal,\n };\n };\n}\n\n// ─── Action Builder Factory ──────────────────────────────────────────────────\n\n/**\n * Create an action builder with a pre-defined context type.\n * Actions have access to the full SupaliveDb for both queries and mutations.\n *\n * @example\n * // Define your server context\n * interface ServerContext {\n * auth: { userId: string };\n * requestId: string;\n * }\n *\n * // Create a typed action builder\n * const action = createActionBuilder<ServerContext>();\n *\n * // Use it - context type is automatically inferred!\n * const processOrder = action({\n * args: z.object({ orderId: z.string() }),\n * handler: async (ctx, { orderId }) => {\n * // ctx.db for full database access\n * const order = await ctx.db.query(async (db) => {\n * return db.query(OrdersSchema).find(orderId);\n * });\n * await ctx.db.mutation(async (db) => {\n * await db.update(OrdersSchema, orderId, { status: \"processed\" });\n * });\n * // ctx.context for server context\n * console.log(ctx.context.requestId);\n * return { success: true };\n * }\n * });\n */\nexport function createActionBuilder<TContext = unknown>() {\n return function action<TInput, TResult, const TInternal extends boolean = false>(\n config: ActionConfig<TInput, TResult, TContext> & { internal?: TInternal }\n ): ActionProcedure<TInput, TResult, TContext, TInternal> {\n return {\n _type: \"procedure\",\n procedureType: \"action\",\n inputSchema: config.args,\n fn: config.handler,\n internal: (config.internal ?? false) as TInternal,\n };\n };\n}\n\n// ─── Job Builder Factory ─────────────────────────────────────────────────────\n\n/**\n * Create a job builder with a pre-defined context type. A job is a\n * server-only procedure invoked by the scheduler over HTTP — either on its\n * declared `cron` schedule or as a precise one-shot enqueued via the\n * server's job API. Jobs run like actions (full db, non-transactional) and\n * are always internal, so they are never reachable from a client.\n *\n * @example\n * const job = createJobBuilder<ServerContext>();\n *\n * export const cleanupOtps = job({\n * cron: \"0 * * * *\", // hourly\n * args: z.object({}),\n * handler: async (ctx) => {\n * await ctx.db.mutation(async (db) => { ... });\n * return { ok: true };\n * },\n * });\n */\nexport function createJobBuilder<TContext = unknown>() {\n return function job<TInput, TResult>(\n config: JobConfig<TInput, TResult, TContext>\n ): JobProcedure<TInput, TResult, TContext> {\n return {\n _type: \"procedure\",\n procedureType: \"job\",\n inputSchema: config.args,\n fn: config.handler,\n internal: true,\n cron: config.cron,\n };\n };\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqQA,SAAgB,qBAAyC;CACvD,OAAO,SAAS,MACd,QACsD;EACtD,OAAO;GACL,OAAO;GACP,eAAe;GACf,aAAa,OAAO;GACpB,IAAI,OAAO;GACX,UAAW,OAAO,YAAY;GAC9B,eAAe,OAAO;EACxB;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,SAAgB,wBAA4C;CAC1D,OAAO,SAAS,SACd,QACyD;EACzD,OAAO;GACL,OAAO;GACP,eAAe;GACf,aAAa,OAAO;GACpB,IAAI,OAAO;GACX,UAAW,OAAO,YAAY;EAChC;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,SAAgB,sBAA0C;CACxD,OAAO,SAAS,OACd,QACuD;EACvD,OAAO;GACL,OAAO;GACP,eAAe;GACf,aAAa,OAAO;GACpB,IAAI,OAAO;GACX,UAAW,OAAO,YAAY;EAChC;CACF;AACF;;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,mBAAuC;CACrD,OAAO,SAAS,IACd,QACyC;EACzC,OAAO;GACL,OAAO;GACP,eAAe;GACf,aAAa,OAAO;GACpB,IAAI,OAAO;GACX,UAAU;GACV,MAAM,OAAO;EACf;CACF;AACF"}
1
+ {"version":3,"file":"procedure-Ze1GE-N9.js","names":[],"sources":["../src/router/procedure.ts"],"sourcesContent":["import type { ZodType } from \"zod\";\nimport type { DbReader, DbWriter } from \"../db/context\";\nimport type { SupaliveDb } from \"../db/realtime_db\";\nimport type { ObjectStorage } from \"../storage\";\nimport type { JobClient } from \"../jobs/scheduler\";\n\n// ─── Context Types ───────────────────────────────────────────────────────────\n\n/**\n * Query context passed to query handlers.\n * Contains database reader and user-defined server context.\n */\nexport interface QueryCtx<TContext = unknown> {\n /** Database reader for queries */\n db: DbReader;\n /** User-defined server context (auth, requestId, etc.) */\n serverCtx?: TContext;\n}\n\n/**\n * Mutation context passed to mutation handlers.\n * Contains database writer and user-defined server context.\n */\nexport interface MutationCtx<TContext = unknown> {\n /** Database writer for mutations (includes insert/update/delete) */\n db: DbWriter;\n /** User-defined server context (auth, requestId, etc.) */\n serverCtx?: TContext;\n}\n\n/**\n * Action context passed to action handlers.\n *\n * Actions are the \"external I/O\" tier: they hold the full {@link SupaliveDb}\n * (queries + mutations) and are the ONLY context that also carries side-effect\n * services — {@link ObjectStorage} for uploads/downloads and a {@link JobClient}\n * for scheduling precise one-shots. Queries/mutations stay pure (db only) so\n * they remain cacheable and transaction-scoped.\n */\nexport interface ActionCtx<TContext = unknown> {\n /** Full database interface for queries and mutations */\n db: SupaliveDb;\n /** Object storage, when the server was configured with one (see\n * `SupaliveServerConfig.storage`); `undefined` otherwise. The usual home\n * for upload/download presigning. */\n storage: ObjectStorage;\n /** Job scheduler client for enqueueing precise one-shots, when the server\n * was configured with a `scheduler`; `undefined` otherwise. Scheduling is\n * network I/O, so it belongs in actions, never inside a DB transaction. */\n scheduler: JobClient;\n /** User-defined server context (auth, requestId, etc.) */\n serverCtx?: TContext;\n}\n\n/**\n * Job context passed to job handlers. Structurally identical to\n * {@link ActionCtx}: a job is a server-only procedure that runs\n * non-transactionally against the full {@link SupaliveDb} and may perform\n * external work, but it is triggered by the scheduler over HTTP (a cron tick\n * or a precise one-shot) rather than by a connected client. `serverCtx` is\n * the system context built by the server's `jobContext` factory.\n */\nexport interface JobCtx<TContext = unknown> {\n /** Full database interface for queries and mutations */\n db: SupaliveDb;\n /** System server context built by the server for scheduler-triggered runs */\n serverCtx?: TContext;\n}\n\n/**\n * Context handed to `caller.<proc>.runQuery` / `.runMutation` when invoking one\n * procedure from inside another. Pass the caller handler's own `ctx` — its `db`\n * carries the parent's live transaction (a {@link DbReader}/{@link DbWriter}) or,\n * inside an action, the full {@link SupaliveDb}. The caller uses this to decide\n * whether the nested call joins the parent's snapshot (queries) or runs as an\n * independent sub-transaction (mutations).\n */\nexport interface ParentCtx<TContext = unknown> {\n db: DbReader | DbWriter | SupaliveDb;\n serverCtx?: TContext | undefined;\n}\n\n// ─── Procedure Types ─────────────────────────────────────────────────────────\n\nexport type QueryFn<TInput, TResult, TContext = unknown> = (\n ctx: QueryCtx<TContext>,\n input: TInput,\n) => Promise<TResult>;\n\nexport type MutationFn<TInput, TResult, TContext = unknown> = (\n ctx: MutationCtx<TContext>,\n input: TInput,\n) => Promise<TResult>;\n\nexport type ActionFn<TInput, TResult, TContext = unknown> = (\n ctx: ActionCtx<TContext>,\n input: TInput,\n) => Promise<TResult>;\n\nexport type JobFn<TInput, TResult, TContext = unknown> = (\n ctx: JobCtx<TContext>,\n input: TInput,\n) => Promise<TResult>;\n\n/**\n * Per-procedure override for the cache/subscription segmentation key.\n *\n * omitted | undefined → fall back to `config.getUserId(serverCtx)` (default)\n * false → no identity in hash; cache/sub shared across all users\n * string → a static identity literal (e.g. \"public\" or a tenant id)\n * function → compute from serverCtx + input (sync)\n *\n * When the result of a query is identical regardless of who calls it, set\n * this to a literal (or `false`) so a single cache entry serves everyone.\n *\n * The function form intentionally takes `serverCtx` (not the full `QueryCtx`)\n * because identity is resolved before any DB read is issued.\n */\nexport type QueryIdentitySpec<TInput, TContext> =\n | false\n | string\n | ((serverCtx: TContext, input: TInput) => string | null | undefined);\n\nexport interface BaseProcedure<\n TInput, TResult,\n TType extends \"query\" | \"mutation\" | \"action\" | \"job\",\n TContext = unknown,\n TInternal extends boolean = boolean\n> {\n readonly _type: \"procedure\";\n readonly procedureType: TType;\n readonly inputSchema: ZodType<TInput>;\n readonly fn: QueryFn<TInput, TResult, TContext> | MutationFn<TInput, TResult, TContext> | ActionFn<TInput, TResult, TContext> | JobFn<TInput, TResult, TContext>;\n readonly internal: TInternal;\n}\n\nexport interface QueryProcedure<\n TInput, TResult,\n TContext = unknown,\n TInternal extends boolean = boolean\n> extends BaseProcedure<TInput, TResult, \"query\", TContext, TInternal> {\n readonly procedureType: \"query\";\n readonly fn: QueryFn<TInput, TResult, TContext>;\n readonly queryIdentity?: QueryIdentitySpec<TInput, TContext>;\n}\n\nexport interface MutationProcedure<\n TInput, TResult,\n TContext = unknown,\n TInternal extends boolean = boolean\n> extends BaseProcedure<TInput, TResult, \"mutation\", TContext, TInternal> {\n readonly procedureType: \"mutation\";\n readonly fn: MutationFn<TInput, TResult, TContext>;\n}\n\nexport interface ActionProcedure<\n TInput, TResult,\n TContext = unknown,\n TInternal extends boolean = boolean\n> extends BaseProcedure<TInput, TResult, \"action\", TContext, TInternal> {\n readonly procedureType: \"action\";\n readonly fn: ActionFn<TInput, TResult, TContext>;\n}\n\n/**\n * A scheduler-triggered, server-only procedure. Runs like an action (full\n * db, non-transactional, may do external work) but is dispatched by the\n * server's HTTP job endpoint on a cron tick or a precise one-shot rather\n * than over the client WebSocket. Always {@link internal}: true, so it is\n * never reachable via `call`/`subscribe`.\n */\nexport interface JobProcedure<\n TInput, TResult,\n TContext = unknown,\n> extends BaseProcedure<TInput, TResult, \"job\", TContext, true> {\n readonly procedureType: \"job\";\n readonly fn: JobFn<TInput, TResult, TContext>;\n /**\n * Cron expression for a recurring job (e.g. `\"0 3 * * *\"`). Declared crons\n * are synced to the scheduler at server startup. Omit for a job that is\n * only ever invoked as a precise one-shot via the scheduler API.\n */\n readonly cron?: string;\n}\n\nexport type AnyProcedure<TContext = unknown> =\n | QueryProcedure<any, any, TContext>\n | MutationProcedure<any, any, TContext>\n | ActionProcedure<any, any, TContext>\n | JobProcedure<any, any, TContext>;\n\n// ─── Procedure Configuration Types ───────────────────────────────────────────\n\nexport interface QueryConfig<TInput, TResult, TContext = unknown> {\n /** Zod schema for input validation */\n args: ZodType<TInput>;\n /** The query handler function */\n handler: QueryFn<TInput, TResult, TContext>;\n /** Mark as internal (server-only). Default: false */\n internal?: boolean;\n /**\n * Override the cache/subscription segmentation key for this procedure.\n * See {@link QueryIdentitySpec}. Omit to keep the default (per-user) behavior.\n */\n queryIdentity?: QueryIdentitySpec<TInput, TContext>;\n}\n\nexport interface MutationConfig<TInput, TResult, TContext = unknown> {\n /** Zod schema for input validation */\n args: ZodType<TInput>;\n /** The mutation handler function */\n handler: MutationFn<TInput, TResult, TContext>;\n /** Mark as internal (server-only). Default: false */\n internal?: boolean;\n}\n\nexport interface ActionConfig<TInput, TResult, TContext = unknown> {\n /** Zod schema for input validation */\n args: ZodType<TInput>;\n /** The action handler function */\n handler: ActionFn<TInput, TResult, TContext>;\n /** Mark as internal (server-only). Default: false */\n internal?: boolean;\n}\n\nexport interface JobConfig<TInput, TResult, TContext = unknown> {\n /** Zod schema for the job payload */\n args: ZodType<TInput>;\n /** The job handler function */\n handler: JobFn<TInput, TResult, TContext>;\n /**\n * Cron expression for a recurring schedule (e.g. `\"0 3 * * *\"`). Omit for a\n * job that is only invoked as a precise one-shot.\n */\n cron?: string;\n}\n\n/** Extract input type from a procedure */\nexport type InputOf<T> = T extends BaseProcedure<infer I, any, any, any> ? I : never;\n\n/** Extract output type from a procedure */\nexport type OutputOf<T> = T extends BaseProcedure<any, infer O, any, any> ? O : never;\n\n/** Extract procedure type (query/mutation) */\nexport type TypeOf<T> = T extends BaseProcedure<any, any, infer Type, any> ? Type : never;\n\n/** Extract server context type from a procedure */\nexport type ContextOf<T> = T extends BaseProcedure<any, any, any, infer C> ? C : never;\n\n/**\n * Create a query builder with a pre-defined context type.\n * This allows you to define the context type once and have it inferred\n * automatically in all your query handlers.\n * \n * @example\n * // Define your server context\n * interface ServerContext {\n * auth: { userId: string };\n * requestId: string;\n * }\n * \n * // Create a typed query builder\n * const query = createQueryBuilder<ServerContext>();\n * \n * // Use it - context type is automatically inferred!\n * const getUser = query({\n * args: z.object({ id: z.string() }),\n * handler: async (ctx, { id }) => {\n * // ctx.db for database queries\n * const user = await ctx.db.query(UsersSchema).find(id);\n * // ctx.context for server context\n * console.log(ctx.context.requestId);\n * return user;\n * }\n * });\n */\nexport function createQueryBuilder<TContext = unknown>() {\n return function query<TInput, TResult, const TInternal extends boolean = false>(\n config: QueryConfig<TInput, TResult, TContext> & { internal?: TInternal }\n ): QueryProcedure<TInput, TResult, TContext, TInternal> {\n return {\n _type: \"procedure\",\n procedureType: \"query\",\n inputSchema: config.args,\n fn: config.handler,\n internal: (config.internal ?? false) as TInternal,\n queryIdentity: config.queryIdentity,\n };\n };\n}\n\n// ─── Mutation Builder Factory ────────────────────────────────────────────────\n\n/**\n * Create a mutation builder with a pre-defined context type.\n * This allows you to define the context type once and have it inferred\n * automatically in all your mutation handlers.\n * \n * @example\n * // Define your server context\n * interface ServerContext {\n * auth: { userId: string };\n * requestId: string;\n * }\n * \n * // Create a typed mutation builder\n * const mutation = createMutationBuilder<ServerContext>();\n * \n * // Use it - context type is automatically inferred!\n * const createUser = mutation({\n * args: z.object({ name: z.string() }),\n * handler: async (ctx, { name }) => {\n * // ctx.db for mutations\n * await ctx.db.insert(UsersSchema, id, { name });\n * // ctx.context for server context\n * console.log(ctx.context.requestId);\n * return { success: true };\n * }\n * });\n */\nexport function createMutationBuilder<TContext = unknown>() {\n return function mutation<TInput, TResult, const TInternal extends boolean = false>(\n config: MutationConfig<TInput, TResult, TContext> & { internal?: TInternal }\n ): MutationProcedure<TInput, TResult, TContext, TInternal> {\n return {\n _type: \"procedure\",\n procedureType: \"mutation\",\n inputSchema: config.args,\n fn: config.handler,\n internal: (config.internal ?? false) as TInternal,\n };\n };\n}\n\n// ─── Action Builder Factory ──────────────────────────────────────────────────\n\n/**\n * Create an action builder with a pre-defined context type.\n * Actions have access to the full SupaliveDb for both queries and mutations.\n *\n * @example\n * // Define your server context\n * interface ServerContext {\n * auth: { userId: string };\n * requestId: string;\n * }\n *\n * // Create a typed action builder\n * const action = createActionBuilder<ServerContext>();\n *\n * // Use it - context type is automatically inferred!\n * const processOrder = action({\n * args: z.object({ orderId: z.string() }),\n * handler: async (ctx, { orderId }) => {\n * // ctx.db for full database access\n * const order = await ctx.db.query(async (db) => {\n * return db.query(OrdersSchema).find(orderId);\n * });\n * await ctx.db.mutation(async (db) => {\n * await db.update(OrdersSchema, orderId, { status: \"processed\" });\n * });\n * // ctx.context for server context\n * console.log(ctx.context.requestId);\n * return { success: true };\n * }\n * });\n */\nexport function createActionBuilder<TContext = unknown>() {\n return function action<TInput, TResult, const TInternal extends boolean = false>(\n config: ActionConfig<TInput, TResult, TContext> & { internal?: TInternal }\n ): ActionProcedure<TInput, TResult, TContext, TInternal> {\n return {\n _type: \"procedure\",\n procedureType: \"action\",\n inputSchema: config.args,\n fn: config.handler,\n internal: (config.internal ?? false) as TInternal,\n };\n };\n}\n\n// ─── Job Builder Factory ─────────────────────────────────────────────────────\n\n/**\n * Create a job builder with a pre-defined context type. A job is a\n * server-only procedure invoked by the scheduler over HTTP — either on its\n * declared `cron` schedule or as a precise one-shot enqueued via the\n * server's job API. Jobs run like actions (full db, non-transactional) and\n * are always internal, so they are never reachable from a client.\n *\n * @example\n * const job = createJobBuilder<ServerContext>();\n *\n * export const cleanupOtps = job({\n * cron: \"0 * * * *\", // hourly\n * args: z.object({}),\n * handler: async (ctx) => {\n * await ctx.db.mutation(async (db) => { ... });\n * return { ok: true };\n * },\n * });\n */\nexport function createJobBuilder<TContext = unknown>() {\n return function job<TInput, TResult>(\n config: JobConfig<TInput, TResult, TContext>\n ): JobProcedure<TInput, TResult, TContext> {\n return {\n _type: \"procedure\",\n procedureType: \"job\",\n inputSchema: config.args,\n fn: config.handler,\n internal: true,\n cron: config.cron,\n };\n };\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoRA,SAAgB,qBAAyC;CACvD,OAAO,SAAS,MACd,QACsD;EACtD,OAAO;GACL,OAAO;GACP,eAAe;GACf,aAAa,OAAO;GACpB,IAAI,OAAO;GACX,UAAW,OAAO,YAAY;GAC9B,eAAe,OAAO;EACxB;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,SAAgB,wBAA4C;CAC1D,OAAO,SAAS,SACd,QACyD;EACzD,OAAO;GACL,OAAO;GACP,eAAe;GACf,aAAa,OAAO;GACpB,IAAI,OAAO;GACX,UAAW,OAAO,YAAY;EAChC;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,SAAgB,sBAA0C;CACxD,OAAO,SAAS,OACd,QACuD;EACvD,OAAO;GACL,OAAO;GACP,eAAe;GACf,aAAa,OAAO;GACpB,IAAI,OAAO;GACX,UAAW,OAAO,YAAY;EAChC;CACF;AACF;;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,mBAAuC;CACrD,OAAO,SAAS,IACd,QACyC;EACzC,OAAO;GACL,OAAO;GACP,eAAe;GACf,aAAa,OAAO;GACpB,IAAI,OAAO;GACX,UAAU;GACV,MAAM,OAAO;EACf;CACF;AACF"}
@@ -1,2 +1,2 @@
1
- import { $ as ProcedureNames, $n as AndPredicate, $t as ColumnCodec, Ar as RawPointReadSchema, At as SupaliveDb, Br as WriteOp, Bt as DbWriter, Cr as QueryCacheEntrySchema, Ct as QueryFn, Dr as RangeRead, Er as QuerySpec, Et as createActionBuilder, Fr as ReadEntry, Ft as QueryDefinition, G as RPCError, Hr as bytesFromJson, Ir as ReadEntrySchema, It as ResultOf, J as ActionProcedures, K as WSClientOptions, Lr as RetryConfig, Lt as _resetGlobalDefs, Mn as PooledClient, Mr as RawRangeReadSchema, Mt as AnyQueryDef, Nr as RawReadEntry, Nt as DefsToMap, On as Database, Or as RangeReadSchema, Ot as createMutationBuilder, Pn as RawClient, Pr as RawReadEntrySchema, Pt as ParamsOf, Q as MutationProcedures, Rr as WriteEntry, Rt as defineQuery, Sn as defineSchema, Sr as QueryCacheEntry, St as QueryCtx, Tr as QueryCacheMetadataSchema, Tt as TypeOf, U as ClientPublicState, Ur as normalizeIdToBytes, Vr as WriteOpSchema, Vt as TxContext, W as HeartbeatOptions, Wr as normalizeToBytes, Y as AppRouter, Zt as matchesPredicate, _r as OrPredicateSchema, _t as MutationCtx, a as CallOptions, ar as CommitTs, at as router, br as Predicate, bt as OutputOf, c as LiveQueryHandle, cn as InsertData, cr as DEFAULT_RETRY, ct as ActionFn, d as WSClientMethods, dr as LiveResult, dt as ContextOf, er as AndPredicateSchema, et as PublicProcedures, f as createClient, fr as MutationResult, gn as SchemaCodecs, gr as OrPredicate, gt as MutationConfig, hr as OccConflictError, i as createCaller, ir as CommitLogEntry, jr as RawRangeRead, jt as sleep, kn as DbQueryResult, kr as RawPointRead, kt as createQueryBuilder, l as LiveQueryState, ln as Model, lr as LeafPredicate, lt as ActionProcedure, mr as OccAbortError, n as CallerFromRouter, nr as CachedPgMetadata, nt as RegisteredProcedure, o as ClientFromProcedures, or as CompareOperator, ot as ActionConfig, pr as NO_RETRY, q as WsClientManager, r as CallerOptions, rn as ComputedFieldConfig, rr as CachedPgMetadataSchema, rt as Router, s as ClientOptions, sn as InferSchema, sr as CompareOperatorSchema, st as ActionCtx, t as CallerFromProcedures, tr as BigIntSchema, tt as QueryProcedures, u as LiveQueryStatus, ur as LeafPredicateSchema, ut as AnyProcedure, vn as SchemaColumnsOptions, vr as PointRead, vt as MutationFn, wr as QueryCacheMetadata, wt as QueryProcedure, xn as defineComputedField, xr as PredicateSchema, xt as QueryConfig, yn as SchemaDefinition, yr as PointReadSchema, yt as MutationProcedure, zr as WriteEntrySchema, zt as DbReader } from "../../index-DJYvJYR4.js";
1
+ import { $ as ProcedureNames, $r as normalizeIdToBytes, Ar as Predicate, Br as RawPointReadSchema, Bt as SupaliveDb, Cr as NO_RETRY, Ct as QueryFn, Dr as OrPredicateSchema, En as SchemaCodecs, Er as OrPredicate, Et as createActionBuilder, Fr as QueryCacheMetadataSchema, G as RPCError, Gr as ReadEntry, Gt as QueryDefinition, Hn as PooledClient, Hr as RawRangeReadSchema, Ht as AnyQueryDef, Ir as QuerySpec, J as ActionProcedures, Jr as WriteEntry, Jt as defineQuery, K as WSClientOptions, Kr as ReadEntrySchema, Kt as ResultOf, Lr as RangeRead, Mn as defineSchema, Mr as QueryCacheEntry, Nr as QueryCacheEntrySchema, On as SchemaColumnsOptions, Or as PointRead, Ot as createMutationBuilder, Pr as QueryCacheMetadata, Q as MutationProcedures, Qr as bytesFromJson, Rn as Database, Rr as RangeReadSchema, Sr as MutationResult, St as QueryCtx, Tr as OccConflictError, Tt as TypeOf, U as ClientPublicState, Ur as RawReadEntry, Ut as DefsToMap, Vr as RawRangeRead, Vt as sleep, W as HeartbeatOptions, Wn as RawClient, Wr as RawReadEntrySchema, Wt as ParamsOf, Xr as WriteOp, Xt as DbWriter, Y as AppRouter, Yr as WriteEntrySchema, Yt as DbReader, Zr as WriteOpSchema, Zt as TxContext, _n as InferSchema, _r as CompareOperatorSchema, _t as MutationCtx, a as CallOptions, at as router, br as LeafPredicateSchema, bt as OutputOf, c as LiveQueryHandle, ct as ActionFn, d as WSClientMethods, dr as BigIntSchema, dt as ContextOf, ei as normalizeToBytes, et as PublicProcedures, f as createClient, fr as CachedPgMetadata, gr as CompareOperator, gt as MutationConfig, hr as CommitTs, i as createCaller, jn as defineComputedField, jr as PredicateSchema, kn as SchemaDefinition, kr as PointReadSchema, kt as createQueryBuilder, l as LiveQueryState, ln as ColumnCodec, lr as AndPredicate, lt as ActionProcedure, mr as CommitLogEntry, n as CallerFromRouter, nt as RegisteredProcedure, o as ClientFromProcedures, ot as ActionConfig, pn as ComputedFieldConfig, pr as CachedPgMetadataSchema, q as WsClientManager, qr as RetryConfig, qt as _resetGlobalDefs, r as CallerOptions, rt as Router, s as ClientOptions, sn as matchesPredicate, st as ActionCtx, t as CallerFromProcedures, tt as QueryProcedures, u as LiveQueryStatus, ur as AndPredicateSchema, ut as AnyProcedure, vn as InsertData, vr as DEFAULT_RETRY, vt as MutationFn, wr as OccAbortError, wt as QueryProcedure, xr as LiveResult, xt as QueryConfig, yn as Model, yr as LeafPredicate, yt as MutationProcedure, zn as DbQueryResult, zr as RawPointRead } from "../../index-DDK9ZIYb.js";
2
2
  export { type ActionConfig, type ActionCtx, type ActionFn, type ActionProcedure, type ActionProcedures, AndPredicate, AndPredicateSchema, type AnyProcedure, type AnyQueryDef, type AppRouter, BigIntSchema, CachedPgMetadata, CachedPgMetadataSchema, type CallOptions, CallerFromProcedures, CallerFromRouter, CallerOptions, type ClientFromProcedures, type ClientOptions, type ClientPublicState, type ColumnCodec, CommitLogEntry, CommitTs, CompareOperator, CompareOperatorSchema, type ComputedFieldConfig, type ContextOf, DEFAULT_RETRY, type Database, type DbQueryResult, DbReader, DbReader as ReadContext, DbWriter, DbWriter as WritableContext, type DefsToMap, type HeartbeatOptions, type InferSchema, type InsertData, LeafPredicate, LeafPredicateSchema, type LiveQueryHandle, type LiveQueryState, type LiveQueryStatus, LiveResult, type Model, type MutationConfig, type MutationCtx, type MutationFn, type MutationProcedure, type MutationProcedures, MutationResult, NO_RETRY, OccAbortError, OccConflictError, OrPredicate, OrPredicateSchema, type OutputOf, type ParamsOf, PointRead, PointReadSchema, type PooledClient, Predicate, PredicateSchema, type ProcedureNames, type PublicProcedures, QueryCacheEntry, QueryCacheEntrySchema, QueryCacheMetadata, QueryCacheMetadataSchema, type QueryConfig, type QueryCtx, type QueryDefinition, type QueryFn, type QueryProcedure, type QueryProcedures, QuerySpec, RPCError, RangeRead, RangeReadSchema, type RawClient, RawPointRead, RawPointReadSchema, RawRangeRead, RawRangeReadSchema, RawReadEntry, RawReadEntrySchema, ReadEntry, ReadEntrySchema, type RegisteredProcedure, type ResultOf, RetryConfig, type Router, type SchemaCodecs, type SchemaColumnsOptions, type SchemaDefinition, SupaliveDb, TxContext, type TypeOf, type WSClientMethods, type WSClientOptions, WriteEntry, WriteEntrySchema, WriteOp, WriteOpSchema, WsClientManager, _resetGlobalDefs, bytesFromJson, createActionBuilder, createCaller, createClient, createMutationBuilder, createQueryBuilder, defineComputedField, defineQuery, defineSchema, matchesPredicate, normalizeIdToBytes, normalizeToBytes, router, sleep };
@@ -1086,10 +1086,14 @@ function createCaller(options) {
1086
1086
  const registry = getContextRegistry(inContext ?? "default");
1087
1087
  const cache = /* @__PURE__ */ new Map();
1088
1088
  let db;
1089
+ let storage;
1090
+ let scheduler;
1089
1091
  return new Proxy({}, { get(_target, procedureName) {
1090
1092
  if (typeof procedureName !== "string") return;
1091
1093
  if (procedureName == "init") return async (config) => {
1092
1094
  db = config.db;
1095
+ storage = config.storage;
1096
+ scheduler = config.scheduler;
1093
1097
  };
1094
1098
  const procedure = registry.getProcedure(procedureName);
1095
1099
  if (!procedure) throw new Error(`Procedure "${procedureName}" not found`);
@@ -1158,7 +1162,9 @@ function createCaller(options) {
1158
1162
  const validatedInput = validateInput(input);
1159
1163
  const ctx = {
1160
1164
  db,
1161
- serverCtx
1165
+ serverCtx,
1166
+ storage,
1167
+ scheduler
1162
1168
  };
1163
1169
  return procedure.fn(ctx, validatedInput);
1164
1170
  },