@supalive/core 1.14.0 → 1.15.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.
@@ -1,12 +1,71 @@
1
- import { a as createJobBuilder, d as z$1, i as createActionBuilder, l as patchZod$1, n as getContextRegistry, o as createMutationBuilder, r as router, s as createQueryBuilder, t as ContextRegistry } from "../../router-Kgrlci8X.js";
1
+ import { a as createJobBuilder, i as createActionBuilder, n as getContextRegistry, o as createMutationBuilder, r as router, s as createQueryBuilder, t as ContextRegistry } from "../../router-DP2ThAwh.js";
2
2
  import { n as tableNameToId } from "../../table-id-DyrJBKAQ.js";
3
3
  import { n as stableStringify, r as supaliveStringify, t as groupByToMap } from "../../helper-zdJT5FUc.js";
4
4
  import { a as jsonPathExtract, i as jsonPathExists, n as buildPredicateSql, o as matchesPredicate, r as jsonContains, t as QueryBuilder } from "../../query-Xw2hi6TB.js";
5
5
  import { i as shouldTrackSchema, n as defineSchema, r as schemaRegistry, t as defineComputedField } from "../../schema-DRtz5h5l.js";
6
- //#region src/exports/procedure.ts
7
- const z = z$1;
8
- const patchZod = patchZod$1;
6
+ //#region src/router/zod_patch.ts
7
+ /**
8
+ * Patch all Zod schema types on the given `z` namespace with `.modelName(name)`.
9
+ * Must be called with the same `z` instance the consumer uses so the prototypes
10
+ * match. Runs once per unique `z` instance (tracked via a WeakSet).
11
+ */
12
+ function patchZod(zInstance) {
13
+ const key = "supalive_model_name_ext";
14
+ const patchedInstances = globalThis[key] ??= /* @__PURE__ */ new Set();
15
+ if (patchedInstances.has(zInstance)) return;
16
+ patchedInstances.add(zInstance);
17
+ const patched = /* @__PURE__ */ new Set();
18
+ const samples = [
19
+ zInstance.string(),
20
+ zInstance.number(),
21
+ zInstance.boolean(),
22
+ zInstance.bigint(),
23
+ zInstance.date(),
24
+ zInstance.object({}),
25
+ zInstance.array(zInstance.string()),
26
+ zInstance.enum(["_"]),
27
+ zInstance.literal("_"),
28
+ zInstance.null(),
29
+ zInstance.undefined(),
30
+ zInstance.any(),
31
+ zInstance.unknown(),
32
+ zInstance.void(),
33
+ zInstance.never(),
34
+ zInstance.nan(),
35
+ zInstance.record(zInstance.string(), zInstance.string()),
36
+ zInstance.union([zInstance.string(), zInstance.number()]),
37
+ zInstance.intersection(zInstance.string(), zInstance.string()),
38
+ zInstance.tuple([zInstance.string()]),
39
+ zInstance.promise(zInstance.string()),
40
+ zInstance.custom(),
41
+ zInstance.coerce.string(),
42
+ zInstance.coerce.number(),
43
+ zInstance.coerce.boolean(),
44
+ zInstance.coerce.bigint(),
45
+ zInstance.coerce.date(),
46
+ zInstance.string().optional(),
47
+ zInstance.string().nullable(),
48
+ zInstance.string().default(""),
49
+ zInstance.string().pipe(zInstance.string()),
50
+ zInstance.string().transform(() => "")
51
+ ];
52
+ for (const inst of samples) {
53
+ const proto = Object.getPrototypeOf(inst);
54
+ if (patched.has(proto)) continue;
55
+ patched.add(proto);
56
+ const metaDesc = Object.getOwnPropertyDescriptor(proto, "meta");
57
+ if (!metaDesc || !metaDesc.get) continue;
58
+ if (proto.modelName) continue;
59
+ Object.defineProperty(proto, "modelName", {
60
+ value: function modelName(name) {
61
+ return this.meta({ __genType: name });
62
+ },
63
+ writable: true,
64
+ configurable: true
65
+ });
66
+ }
67
+ }
9
68
  //#endregion
10
- export { ContextRegistry, QueryBuilder, buildPredicateSql, createActionBuilder, createJobBuilder, createMutationBuilder, createQueryBuilder, defineComputedField, defineSchema, getContextRegistry, groupByToMap, jsonContains, jsonPathExists, jsonPathExtract, matchesPredicate, patchZod, router, schemaRegistry, shouldTrackSchema, stableStringify, supaliveStringify, tableNameToId, z };
69
+ export { ContextRegistry, QueryBuilder, buildPredicateSql, createActionBuilder, createJobBuilder, createMutationBuilder, createQueryBuilder, defineComputedField, defineSchema, getContextRegistry, groupByToMap, jsonContains, jsonPathExists, jsonPathExtract, matchesPredicate, patchZod, router, schemaRegistry, shouldTrackSchema, stableStringify, supaliveStringify, tableNameToId };
11
70
 
12
71
  //# sourceMappingURL=procedure.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"procedure.js","names":["_z","_patchZod"],"sources":["../../../src/exports/procedure.ts"],"sourcesContent":["export * from \"../router/index\";\nexport * from \"../db/query\";\nexport * from \"../db/schema\";\nexport * from \"../helper\";\n\n// Re-export z (with .modelName() already patched at import time)\nimport { z as _z, patchZod as _patchZod } from \"../router/procedure\";\nexport const z = _z;\nexport const patchZod = _patchZod;\n\n// eslint-disable-next-line @typescript-eslint/no-namespace\ndeclare module \"zod\" {\n interface ZodType<Output, Input, Internals> {\n /**\n * Rename the generated model class in @supalive codegen output.\n * Purely metadata has no runtime effect beyond setting `.meta({ __genType: name })`.\n */\n modelName(name: string): this;\n }\n}"],"mappings":";;;;;;AAOA,MAAa,IAAIA;AACjB,MAAa,WAAWC"}
1
+ {"version":3,"file":"procedure.js","names":[],"sources":["../../../src/router/zod_patch.ts"],"sourcesContent":["// ─── Zod .modelName() extension ─────────────────────────────────────────────\n// Patches every Zod schema type with a `.modelName(\"Name\")` method that sets\n// `__genType` metadata for codegen model renaming.\n//\n// Zod v4: `z.string` is a factory — `z.string.prototype` is NOT the real class\n// prototype. We collect the actual prototypes by creating one instance per type,\n// then patch each unique prototype once.\n\nimport type { ZodType } from \"zod\";\nimport * as z from \"zod\";\n\n/**\n * Patch all Zod schema types on the given `z` namespace with `.modelName(name)`.\n * Must be called with the same `z` instance the consumer uses so the prototypes\n * match. Runs once per unique `z` instance (tracked via a WeakSet).\n */\nexport function patchZod(zInstance: typeof z): void {\n const key = \"supalive_model_name_ext\";\n const patchedInstances: Set<object> = (globalThis as any)[key] ??= new Set();\n if (patchedInstances.has(zInstance)) return;\n patchedInstances.add(zInstance);\n\n const patched = new Set<object>();\n const samples: ZodType[] = [\n zInstance.string(), zInstance.number(), zInstance.boolean(), zInstance.bigint(), zInstance.date(),\n zInstance.object({}), zInstance.array(zInstance.string()), zInstance.enum([\"_\"]),\n zInstance.literal(\"_\"), zInstance.null(), zInstance.undefined(), zInstance.any(), zInstance.unknown(),\n zInstance.void(), zInstance.never(), zInstance.nan(), zInstance.record(zInstance.string(), zInstance.string()),\n zInstance.union([zInstance.string(), zInstance.number()]), zInstance.intersection(zInstance.string(), zInstance.string()),\n zInstance.tuple([zInstance.string()]), zInstance.promise(zInstance.string()), zInstance.custom(),\n zInstance.coerce.string(), zInstance.coerce.number(), zInstance.coerce.boolean(),\n zInstance.coerce.bigint(), zInstance.coerce.date(),\n zInstance.string().optional(), zInstance.string().nullable(), zInstance.string().default(\"\"),\n zInstance.string().pipe(zInstance.string()), zInstance.string().transform(() => \"\"),\n ];\n for (const inst of samples) {\n const proto = Object.getPrototypeOf(inst);\n if (patched.has(proto)) continue;\n patched.add(proto);\n const metaDesc = Object.getOwnPropertyDescriptor(proto, \"meta\");\n if (!metaDesc || !metaDesc.get) continue;\n if ((proto as any).modelName) continue;\n Object.defineProperty(proto, \"modelName\", {\n value: function modelName(name: string) {\n return this.meta({ __genType: name });\n },\n writable: true,\n configurable: true,\n });\n }\n}"],"mappings":";;;;;;;;;;;AAgBA,SAAgB,SAAS,WAA2B;CAChD,MAAM,MAAM;CACZ,MAAM,mBAAgC,WAAoB,yBAAS,IAAI,IAAI;CAC3E,IAAI,iBAAiB,IAAI,SAAS,GAAG;CACrC,iBAAiB,IAAI,SAAS;CAE9B,MAAM,0BAAU,IAAI,IAAY;CAChC,MAAM,UAAqB;EACvB,UAAU,OAAO;EAAG,UAAU,OAAO;EAAG,UAAU,QAAQ;EAAG,UAAU,OAAO;EAAG,UAAU,KAAK;EAChG,UAAU,OAAO,CAAC,CAAC;EAAG,UAAU,MAAM,UAAU,OAAO,CAAC;EAAG,UAAU,KAAK,CAAC,GAAG,CAAC;EAC/E,UAAU,QAAQ,GAAG;EAAG,UAAU,KAAK;EAAG,UAAU,UAAU;EAAG,UAAU,IAAI;EAAG,UAAU,QAAQ;EACpG,UAAU,KAAK;EAAG,UAAU,MAAM;EAAG,UAAU,IAAI;EAAG,UAAU,OAAO,UAAU,OAAO,GAAG,UAAU,OAAO,CAAC;EAC7G,UAAU,MAAM,CAAC,UAAU,OAAO,GAAG,UAAU,OAAO,CAAC,CAAC;EAAG,UAAU,aAAa,UAAU,OAAO,GAAG,UAAU,OAAO,CAAC;EACxH,UAAU,MAAM,CAAC,UAAU,OAAO,CAAC,CAAC;EAAG,UAAU,QAAQ,UAAU,OAAO,CAAC;EAAG,UAAU,OAAO;EAC/F,UAAU,OAAO,OAAO;EAAG,UAAU,OAAO,OAAO;EAAG,UAAU,OAAO,QAAQ;EAC/E,UAAU,OAAO,OAAO;EAAG,UAAU,OAAO,KAAK;EACjD,UAAU,OAAO,CAAC,CAAC,SAAS;EAAG,UAAU,OAAO,CAAC,CAAC,SAAS;EAAG,UAAU,OAAO,CAAC,CAAC,QAAQ,EAAE;EAC3F,UAAU,OAAO,CAAC,CAAC,KAAK,UAAU,OAAO,CAAC;EAAG,UAAU,OAAO,CAAC,CAAC,gBAAgB,EAAE;CACtF;CACA,KAAK,MAAM,QAAQ,SAAS;EACxB,MAAM,QAAQ,OAAO,eAAe,IAAI;EACxC,IAAI,QAAQ,IAAI,KAAK,GAAG;EACxB,QAAQ,IAAI,KAAK;EACjB,MAAM,WAAW,OAAO,yBAAyB,OAAO,MAAM;EAC9D,IAAI,CAAC,YAAY,CAAC,SAAS,KAAK;EAChC,IAAK,MAAc,WAAW;EAC9B,OAAO,eAAe,OAAO,aAAa;GACtC,OAAO,SAAS,UAAU,MAAc;IACpC,OAAO,KAAK,KAAK,EAAE,WAAW,KAAK,CAAC;GACxC;GACA,UAAU;GACV,cAAc;EAClB,CAAC;CACL;AACJ"}
@@ -1,4 +1,4 @@
1
- import { Pn as SchemaDefinition, Rn as schemaRegistry } from "../../index-f7mNbMhq.js";
1
+ import { In as schemaRegistry, Mn as SchemaDefinition } from "../../index-Ddr4NiPf.js";
2
2
 
3
3
  //#region src/db/schema-sql.d.ts
4
4
  type SqlDialect = "postgres" | "mysql";
@@ -1,7 +1,7 @@
1
- import { $n as InvalidateWritesetParams, Bt as ScheduleHandle, E as Context, Ft as IncomingJobRequest, Hn as Database, Ht as SupaliveDb, It as JobClient, Lt as JobScheduler, Mt as DevScheduler, Nt as DevSchedulerOptions, Pt as EnqueueOptions, Qn as AffectedSubscription, Rt as QStashScheduler, Vt as ScheduledJobDef, Zn as CacheLayer, ar as UnregisterSubscriptionParams, dr as UpdateSubscriptionReadSetParamsSchema, er as InvalidateWritesetParamsSchema, fr as UpdateSubscriptionReadSetResult, ir as RegisterSubscriptionResult, nr as RegisterSubscriptionParams, or as UnregisterSubscriptionParamsSchema, rr as RegisterSubscriptionParamsSchema, rt as Router, sr as UnregisterSubscriptionResult, tr as InvalidateWritesetResult, ur as UpdateSubscriptionReadSetParams, zt as QStashSchedulerOptions } from "../../index-f7mNbMhq.js";
2
- import { t as MySqlDatabase } from "../../mysql-BX5hfgfE.js";
3
- import { t as PgDatabase } from "../../postgres-EUz8TYFn.js";
4
- import { C as SubManagerLink, S as SubManagerClient, b as SupaliveServerConfig, p as DatabaseConfig, u as SubId, x as UpstashConfig, y as SubscriptionManagerConfig } from "../../types_server-B7elBQyz.js";
1
+ import { $n as InvalidateWritesetResult, At as DevScheduler, Bn as Database, Bt as SupaliveDb, E as Context, Ft as JobScheduler, It as QStashScheduler, Lt as QStashSchedulerOptions, Mt as EnqueueOptions, Nt as IncomingJobRequest, Pt as JobClient, Qn as InvalidateWritesetParamsSchema, Rt as ScheduleHandle, Xn as AffectedSubscription, Yn as CacheLayer, Zn as InvalidateWritesetParams, ar as UnregisterSubscriptionResult, cr as UpdateSubscriptionReadSetParams, er as RegisterSubscriptionParams, ir as UnregisterSubscriptionParamsSchema, jt as DevSchedulerOptions, lr as UpdateSubscriptionReadSetParamsSchema, nr as RegisterSubscriptionResult, rr as UnregisterSubscriptionParams, rt as Router, tr as RegisterSubscriptionParamsSchema, ur as UpdateSubscriptionReadSetResult, zt as ScheduledJobDef } from "../../index-Ddr4NiPf.js";
2
+ import { t as MySqlDatabase } from "../../mysql-DWj2q3qR.js";
3
+ import { t as PgDatabase } from "../../postgres-D0M1ri-C.js";
4
+ import { C as SubManagerLink, S as SubManagerClient, b as SupaliveServerConfig, p as DatabaseConfig, u as SubId, x as UpstashConfig, y as SubscriptionManagerConfig } from "../../types_server-BSiGxbqb.js";
5
5
  import pino, { Level } from "pino";
6
6
  import Redis$1 from "ioredis";
7
7
 
@@ -1,4 +1,4 @@
1
- import { n as getContextRegistry, u as primaryOnlyConn } from "../../router-Kgrlci8X.js";
1
+ import { l as primaryOnlyConn, n as getContextRegistry } from "../../router-DP2ThAwh.js";
2
2
  import { n as stableStringify, r as supaliveStringify, t as groupByToMap } from "../../helper-zdJT5FUc.js";
3
3
  import { r as evaluateCacheFreshness } from "../../overlap-checker-Kz7B_jsp.js";
4
4
  import { i as AuthenticationError, o as ClientMessageSchema } from "../../types_client_rpc-ByGwoRCL.js";
@@ -1,6 +1,6 @@
1
- import { $r as WriteEntrySchema, A as ResponseMessageSchema, Ar as OrPredicate, B as SubscriptionUpdateMessageSchema, Br as QuerySpec, C as ClientMessageSchema, Cr as LeafPredicate, D as ErrorMessage, Dr as NO_RETRY, E as Context, Er as MutationResult, F as SubscribeMessage, Fr as PredicateSchema, Gr as RawRangeRead, H as UnsubscribeMessageSchema, Hr as RangeReadSchema, I as SubscribeMessageSchema, Ir as QueryCacheEntry, Jr as RawReadEntrySchema, Kr as RawRangeReadSchema, L as SubscriptionGoneMessage, Lr as QueryCacheEntrySchema, M as ServerMessageSchema, Mr as PointRead, N as ServerPingMessage, Nr as PointReadSchema, O as IsInternal, Or as OccAbortError, P as ServerPingMessageSchema, Pr as Predicate, Qr as WriteEntry, R as SubscriptionGoneMessageSchema, Rr as QueryCacheMetadata, S as ClientMessage, Sr as DEFAULT_RETRY, T as ConnectedMessageSchema, Tr as LiveResult, Ur as RawPointRead, V as UnsubscribeMessage, Vr as RangeRead, Wr as RawPointReadSchema, Xr as ReadEntrySchema, Yr as ReadEntry, Zr as RetryConfig, _ as AuthSuccessMessage, _r as CachedPgMetadataSchema, b as CallMessage, br as CompareOperator, ei as WriteOp, g as AuthMessageSchema, gr as CachedPgMetadata, h as AuthMessage, hr as BigIntSchema, ii as normalizeToBytes, j as ServerMessage, jr as OrPredicateSchema, k as ResponseMessage, kr as OccConflictError, m as AuthFailedMessageSchema, mr as AndPredicateSchema, ni as bytesFromJson, p as AuthFailedMessage, pr as AndPredicate, qr as RawReadEntry, ri as normalizeIdToBytes, ti as WriteOpSchema, v as AuthSuccessMessageSchema, vr as CommitLogEntry, w as ConnectedMessage, wr as LeafPredicateSchema, x as CallMessageSchema, xr as CompareOperatorSchema, y as AuthenticationError, yr as CommitTs, z as SubscriptionUpdateMessage, zr as QueryCacheMetadataSchema } from "../../index-f7mNbMhq.js";
1
+ import { $r as WriteOpSchema, A as ResponseMessageSchema, Ar as PointRead, B as SubscriptionUpdateMessageSchema, Br as RangeReadSchema, C as ClientMessageSchema, Cr as LiveResult, D as ErrorMessage, Dr as OccConflictError, E as Context, Er as OccAbortError, F as SubscribeMessage, Fr as QueryCacheEntrySchema, Gr as RawReadEntry, H as UnsubscribeMessageSchema, Hr as RawPointReadSchema, I as SubscribeMessageSchema, Ir as QueryCacheMetadata, Jr as ReadEntrySchema, Kr as RawReadEntrySchema, L as SubscriptionGoneMessage, Lr as QueryCacheMetadataSchema, M as ServerMessageSchema, Mr as Predicate, N as ServerPingMessage, Nr as PredicateSchema, O as IsInternal, Or as OrPredicate, P as ServerPingMessageSchema, Pr as QueryCacheEntry, Qr as WriteOp, R as SubscriptionGoneMessageSchema, Rr as QuerySpec, S as ClientMessage, Sr as LeafPredicateSchema, T as ConnectedMessageSchema, Tr as NO_RETRY, Ur as RawRangeRead, V as UnsubscribeMessage, Vr as RawPointRead, Wr as RawRangeReadSchema, Xr as WriteEntry, Yr as RetryConfig, Zr as WriteEntrySchema, _ as AuthSuccessMessage, _r as CommitTs, b as CallMessage, br as DEFAULT_RETRY, dr as AndPredicate, ei as bytesFromJson, fr as AndPredicateSchema, g as AuthMessageSchema, gr as CommitLogEntry, h as AuthMessage, hr as CachedPgMetadataSchema, j as ServerMessage, jr as PointReadSchema, k as ResponseMessage, kr as OrPredicateSchema, m as AuthFailedMessageSchema, mr as CachedPgMetadata, ni as normalizeToBytes, p as AuthFailedMessage, pr as BigIntSchema, qr as ReadEntry, ti as normalizeIdToBytes, v as AuthSuccessMessageSchema, vr as CompareOperator, w as ConnectedMessage, wr as MutationResult, x as CallMessageSchema, xr as LeafPredicate, y as AuthenticationError, yr as CompareOperatorSchema, z as SubscriptionUpdateMessage, zr as RangeRead } from "../../index-Ddr4NiPf.js";
2
2
  import { n as stableStringify, r as supaliveStringify, t as groupByToMap } from "../../helper-CiacMqje.js";
3
- import { _ as RpcCorsConfig, a as RemoteSubscriptionMessage, b as SupaliveServerConfig, c as RemoteSubscriptionUpdateSchema, d as SubscriptionEntry, f as AppPubSubConfig, g as RpcConfig, h as PostgresConfig, i as RemoteRecomputeRaceSchema, l as Session, m as MySQLConfig, n as PendingMutation, o as RemoteSubscriptionMessageSchema, p as DatabaseConfig, r as RemoteRecomputeRace, s as RemoteSubscriptionUpdate, t as InstanceId, u as SubId, v as RpcRateLimitConfig, x as UpstashConfig, y as SubscriptionManagerConfig } from "../../types_server-B7elBQyz.js";
3
+ import { _ as RpcCorsConfig, a as RemoteSubscriptionMessage, b as SupaliveServerConfig, c as RemoteSubscriptionUpdateSchema, d as SubscriptionEntry, f as AppPubSubConfig, g as RpcConfig, h as PostgresConfig, i as RemoteRecomputeRaceSchema, l as Session, m as MySQLConfig, n as PendingMutation, o as RemoteSubscriptionMessageSchema, p as DatabaseConfig, r as RemoteRecomputeRace, s as RemoteSubscriptionUpdate, t as InstanceId, u as SubId, v as RpcRateLimitConfig, x as UpstashConfig, y as SubscriptionManagerConfig } from "../../types_server-BSiGxbqb.js";
4
4
 
5
5
  //#region src/utils.d.ts
6
6
  declare function envBool(name: string, defaultValue?: boolean): boolean;
@@ -0,0 +1,523 @@
1
+ import { $n as InvalidateWritesetResult, Bn as Database, Bt as SupaliveDb, Ft as JobScheduler, Xn as AffectedSubscription, Yn as CacheLayer, Zn as InvalidateWritesetParams, ar as UnregisterSubscriptionResult, cr as UpdateSubscriptionReadSetParams, er as RegisterSubscriptionParams, nr as RegisterSubscriptionResult, nt as RegisteredProcedure, or as UnregisterSubscriptionsParams, rr as UnregisterSubscriptionParams, sr as UnregisterSubscriptionsResult, ur as UpdateSubscriptionReadSetResult, wr as MutationResult } from "./index-Ddr4NiPf.js";
2
+ import { r as ObjectStorage } from "./object-storage-354KU6Mj.js";
3
+ import z from "zod";
4
+ import { IncomingMessage } from "http";
5
+ import { WebSocket } from "ws";
6
+ import { Level } from "pino";
7
+ import { Redis } from "ioredis";
8
+
9
+ //#region src/server/sub-manager-client.d.ts
10
+ /**
11
+ * Callback the app server registers to process invalidations that were
12
+ * deferred during a sub-manager outage. When the sub-manager reconnects and
13
+ * the buffered writeSets are flushed in one batched RPC, the resulting
14
+ * `affected[]` is handed to this callback — which is expected to do the
15
+ * same work as the normal per-mutation `reexecuteAffectedQuery` path.
16
+ */
17
+ type AffectedHandler = (affected: AffectedSubscription[]) => Promise<void>;
18
+ /**
19
+ * Callback the app server registers to drive recovery on sub-manager
20
+ * reconnect. Iterates `serverSubscriptions`, reads `sl:reg:<subId>` from
21
+ * Redis, and re-registers each known sub. Resolves when complete; only then
22
+ * does the client's buffer flush and gated calls release.
23
+ */
24
+ type RecoveryDriver = () => Promise<void>;
25
+ /**
26
+ * The transport-agnostic contract the app server uses to talk to the
27
+ * subscription manager. Implemented by:
28
+ *
29
+ * • {@link SubManagerClient} — the WebSocket RPC client, for a sub-manager
30
+ * running in its own process (`subManagerUrl`); and
31
+ * • the object returned by `SubscriptionManager.localLink()` — a direct
32
+ * in-process link when the manager is embedded in the app server (no
33
+ * socket, no port, no serialization).
34
+ *
35
+ * Injecting this into `SupaliveServerConfig.subManager` lets a deployment run
36
+ * combined (one process) now and split the sub-manager out later by switching
37
+ * back to `subManagerUrl`, with no other code changes.
38
+ */
39
+ interface SubManagerLink {
40
+ registerSubscription(params: RegisterSubscriptionParams): Promise<RegisterSubscriptionResult>;
41
+ registerSubscriptionBatch(params: RegisterSubscriptionParams[]): Promise<RegisterSubscriptionResult[]>;
42
+ updateSubscriptionReadSet(params: UpdateSubscriptionReadSetParams): Promise<UpdateSubscriptionReadSetResult>;
43
+ unregisterSubscription(params: UnregisterSubscriptionParams): Promise<UnregisterSubscriptionResult>;
44
+ unregisterSubscriptions(params: UnregisterSubscriptionsParams): Promise<UnregisterSubscriptionsResult>;
45
+ invalidateWriteset(params: InvalidateWritesetParams): Promise<InvalidateWritesetResult>;
46
+ /**
47
+ * Register recovery for the reconnect path. A no-op for the in-process link,
48
+ * which never disconnects.
49
+ */
50
+ setRecoveryDriver(driver: RecoveryDriver): void;
51
+ /**
52
+ * Register the post-recovery batched-invalidate handler. A no-op for the
53
+ * in-process link.
54
+ */
55
+ setAffectedHandler(handler: AffectedHandler): void;
56
+ }
57
+ interface SubManagerClientOptions {
58
+ url: string;
59
+ /**
60
+ * Maximum number of buffered WriteEntry records held during an outage.
61
+ * If exceeded, the buffer is dropped — the commit-log replay path during
62
+ * the next register call will catch up any missed invalidations, at the
63
+ * cost of a brief recompute spike. Default 50_000 entries.
64
+ */
65
+ invalidateBufferLimit?: number;
66
+ }
67
+ /**
68
+ * RPC client for the (single) sub-manager process.
69
+ *
70
+ * Design (Convex-inspired):
71
+ * • The sub-manager is in-memory and ephemeral. There is no version
72
+ * protocol, no client-side registration registry, no OUT_OF_SYNC
73
+ * replay logic. All recovery is driven from the app server using
74
+ * state it already has (`serverSubscriptions`) plus registration
75
+ * records persisted to Redis at `sl:reg:<subId>`.
76
+ *
77
+ * • Out-of-order `updateSubscriptionReadSet` calls are filtered server
78
+ * side using `lastSnapshotTs` (monotonic DB commit timestamp).
79
+ *
80
+ * • On rpc-websockets reconnect, the client:
81
+ * 1. Transitions to `busy` (any in-flight `invalidateWriteset`
82
+ * buffers its writeSet).
83
+ * 2. Invokes the app server's `recoveryDriver` to re-register all
84
+ * known subs.
85
+ * 3. Flushes the buffer as one batched `invalidateWriteset` RPC and
86
+ * hands the resulting `affected[]` to `affectedHandler`.
87
+ * 4. Transitions to `ready`.
88
+ *
89
+ * • During an extended outage, the buffer is bounded; if exceeded, it
90
+ * is dropped and we rely on the commit-log replay built into
91
+ * `SubscriptionWorker.register()` to catch each sub up on the next
92
+ * re-register.
93
+ */
94
+ declare class SubManagerClient implements SubManagerLink {
95
+ private client;
96
+ private state;
97
+ private hasConnectedOnce;
98
+ /** Resolves whenever state transitions to 'ready'. Replaced on each busy→ready cycle. */
99
+ private readyPromise;
100
+ private resolveReady;
101
+ /** Writeset entries accumulated while state === 'busy'. Flushed as one RPC after recovery. */
102
+ private bufferedWriteSets;
103
+ private readonly bufferLimit;
104
+ private bufferDroppedDuringOutage;
105
+ private recoveryDriver?;
106
+ private affectedHandler?;
107
+ constructor(urlOrOptions: string | SubManagerClientOptions);
108
+ /**
109
+ * Wire up the app-server-driven recovery. Must be called before any
110
+ * disconnect/reconnect cycle for buffered writeSets to be flushed and
111
+ * subscriptions re-registered.
112
+ */
113
+ setRecoveryDriver(driver: RecoveryDriver): void;
114
+ /**
115
+ * Wire up the handler invoked when batched invalidate results land
116
+ * after recovery. The handler is expected to drive
117
+ * `reexecuteAffectedQuery` for each entry.
118
+ */
119
+ setAffectedHandler(handler: AffectedHandler): void;
120
+ registerSubscription(params: RegisterSubscriptionParams): Promise<RegisterSubscriptionResult>;
121
+ registerSubscriptionBatch(params: RegisterSubscriptionParams[]): Promise<RegisterSubscriptionResult[]>;
122
+ updateSubscriptionReadSet(params: UpdateSubscriptionReadSetParams): Promise<UpdateSubscriptionReadSetResult>;
123
+ unregisterSubscription(params: UnregisterSubscriptionParams): Promise<UnregisterSubscriptionResult>;
124
+ unregisterSubscriptions(params: UnregisterSubscriptionsParams): Promise<UnregisterSubscriptionsResult>;
125
+ /**
126
+ * Sends the writeSet to the sub-manager for invalidation, OR buffers it
127
+ * if the client is currently disconnected / recovering. Returns
128
+ * `{ affected: [] }` while buffering — the actual `affected` from the
129
+ * buffered batch is delivered via the registered `affectedHandler`
130
+ * after recovery completes.
131
+ */
132
+ invalidateWriteset(params: InvalidateWritesetParams): Promise<InvalidateWritesetResult>;
133
+ /**
134
+ * Single point through which RPCs go. Throws on transport / server error.
135
+ * `registerSubscription`, `updateSubscriptionReadSet`, and
136
+ * `unregisterSubscription` are NOT gated on the ready state: during a
137
+ * disconnect they will fail at the socket layer, and during recovery
138
+ * (which itself uses these methods) gating would deadlock.
139
+ */
140
+ private call;
141
+ private appendToBuffer;
142
+ private flushBuffer;
143
+ private markBusy;
144
+ private markReady;
145
+ private handleClose;
146
+ private handleOpen;
147
+ private runRecovery;
148
+ /**
149
+ * Test/inspection helpers.
150
+ */
151
+ /** @internal */
152
+ isReady(): boolean;
153
+ /** @internal */
154
+ bufferSize(): number;
155
+ }
156
+ //#endregion
157
+ //#region src/config.d.ts
158
+ /** CORS policy for the HTTP RPC endpoint. */
159
+ interface RpcCorsConfig {
160
+ /**
161
+ * Allowed origins. `"*"` sends `Access-Control-Allow-Origin: *`; a list
162
+ * echoes back a request's `Origin` only when it matches (and sets `Vary`).
163
+ * Omit `cors` entirely to send no CORS headers (same-origin only).
164
+ */
165
+ origins: string[] | "*";
166
+ }
167
+ /** Rate-limit policy for the HTTP RPC endpoint (fixed window, per instance). */
168
+ interface RpcRateLimitConfig {
169
+ /** Window length in ms. Default 60000. */
170
+ windowMs?: number;
171
+ /** Max requests per window per key. Default 120. */
172
+ max?: number;
173
+ /**
174
+ * Derive the limiter key from the request. Default: client IP
175
+ * (`X-Forwarded-For` first hop, else socket address). Return a stable string.
176
+ */
177
+ keyBy?: (req: IncomingMessage) => string;
178
+ }
179
+ /**
180
+ * Enables a one-shot HTTP RPC transport for `query`/`mutation`/`action`
181
+ * (no subscriptions — those stay WebSocket-only). Lets clients that don't need
182
+ * live queries call procedures without holding a socket open. Omit to disable
183
+ * the endpoint entirely.
184
+ */
185
+ interface RpcConfig<TContext = unknown> {
186
+ /**
187
+ * The single endpoint path. Default `/_rpc`. Every procedure is called as
188
+ * `POST {path}` with `{ name, input }` in the body — the name is never in the
189
+ * URL. Keep this distinct from `jobPath`.
190
+ */
191
+ path?: string;
192
+ /**
193
+ * Map an HTTP request to the auth `data` handed to `verifyAuth` (the same
194
+ * callback the WebSocket path uses). Default: `Authorization: Bearer <token>`
195
+ * → `{ token }`. Return `undefined` for an anonymous request.
196
+ */
197
+ auth?: (req: IncomingMessage) => Record<string, unknown> | undefined;
198
+ /** CORS policy. Omit for same-origin only (no CORS headers). */
199
+ cors?: RpcCorsConfig;
200
+ /** Rate limiting. Omit for defaults (120/min per IP); set `false` to disable. */
201
+ rateLimit?: RpcRateLimitConfig | false;
202
+ }
203
+ interface UpstashConfig {
204
+ url: string;
205
+ token: string;
206
+ redisUrl: string;
207
+ }
208
+ /** Database configuration for PostgreSQL */
209
+ interface PostgresConfig {
210
+ type: "postgres";
211
+ connectionString: string;
212
+ /** Optional max connections for the Postgres connection pool. Defaults to 10.*/
213
+ maxConnections?: number;
214
+ /** Optional min connections for the Postgres connection pool. Defaults to 1.*/
215
+ minConnections?: number;
216
+ /** Optional idle timeout for Postgres connections in milliseconds. Defaults to 30000 (30 seconds). */
217
+ idleTimeoutMillis?: number;
218
+ /** Optional connection timeout for acquiring Postgres connections in milliseconds. Defaults to 7000 (7 seconds). */
219
+ connectionTimeoutMillis?: number;
220
+ }
221
+ /** Database configuration for MySQL */
222
+ interface MySQLConfig {
223
+ type: "mysql";
224
+ connectionString: string;
225
+ /** Optional max connections for the MySQL connection pool. Defaults to 20.*/
226
+ maxConnections?: number;
227
+ /** Optional min connections for the MySQL connection pool. Defaults to 1.*/
228
+ minConnections?: number;
229
+ /** Optional idle timeout for MySQL connections in milliseconds. Defaults to 30000 (30 seconds). */
230
+ idleTimeoutMillis?: number;
231
+ /** Optional connection timeout for acquiring MySQL connections in milliseconds. Defaults to 7000 (7 seconds). */
232
+ connectionTimeoutMillis?: number;
233
+ /** Optional flag to queue connection requests when pool is exhausted. Defaults to true (queue requests). */
234
+ queueLimit?: number;
235
+ }
236
+ type DatabaseConfig = PostgresConfig | MySQLConfig;
237
+ /**
238
+ * Configuration for the Supalive WebSocket server.
239
+ */
240
+ interface SupaliveServerConfig<TContext = Record<string, unknown>> {
241
+ /** Server port (default: 3000) */
242
+ port?: number;
243
+ /** Server host (default: "0.0.0.0") */
244
+ host?: string;
245
+ cacheLayer: CacheLayer;
246
+ redisSubClient: Redis;
247
+ /**
248
+ * Subscription Manager WebSocket URL for RPC communication.
249
+ * A single sub-manager process owns all subscription state for this
250
+ * deployment. Internally it spawns N logical workers (configured on the
251
+ * sub-manager side) and routes by hash(subId) to spread CPU across them.
252
+ *
253
+ * Provide EITHER this OR {@link subManager} (an in-process link). Exactly
254
+ * one is required.
255
+ */
256
+ subManagerUrl?: string;
257
+ /**
258
+ * In-process subscription-manager link, as an alternative to
259
+ * {@link subManagerUrl}. Use this to embed the sub-manager in the same
260
+ * process as the app server (obtain it from
261
+ * `new SubscriptionManager({ listen: false, inline: true, ... }).localLink()`).
262
+ * The server then talks to the manager via direct method calls — no socket,
263
+ * no port, no serialization. Split the sub-manager into its own process
264
+ * later by switching back to `subManagerUrl` with no other changes.
265
+ */
266
+ subManager?: SubManagerLink;
267
+ /** Database instance */
268
+ database: SupaliveDb;
269
+ /**
270
+ * Optional authentication callback.
271
+ * Called when client sends auth message.
272
+ * Return null to reject authentication.
273
+ */
274
+ verifyAuth?: (data: Record<string, unknown>, sessionId: string) => Promise<TContext | null>;
275
+ /**
276
+ * Server context name for procedure routing.
277
+ * Must match the router's contextName.
278
+ */
279
+ contextName?: string;
280
+ /**
281
+ * Session TTL in seconds (default: 3600 = 1 hour).
282
+ * Sessions are kept alive while connected and expire after disconnect.
283
+ */
284
+ sessionTtlSeconds?: number;
285
+ /**
286
+ * Enable detailed logging.
287
+ */
288
+ logLevel?: Level;
289
+ /**
290
+ * Extract user ID from context for cache key generation.
291
+ * If not provided, caching is disabled (each sub recomputes independently).
292
+ */
293
+ getUserId?: (ctx: TContext | undefined) => string | null;
294
+ /**
295
+ * Cache TTL in seconds (default: 3600).
296
+ * How long query results are cached in Redis.
297
+ */
298
+ cacheTtlSeconds?: number;
299
+ /**
300
+ * Scheduler backing the job system. When provided, the server exposes an
301
+ * HTTP endpoint (`{jobPath}/<jobName>`) that the scheduler POSTs to, and
302
+ * syncs every registered recurring (cron) job at startup. Omit to disable
303
+ * jobs entirely. Use `DevScheduler` locally and `QStashScheduler` in prod.
304
+ */
305
+ scheduler: JobScheduler;
306
+ /**
307
+ * Builds the system server context handed to a job handler's `serverCtx`.
308
+ * Jobs run without a client, so this is where a deployment injects its
309
+ * "system"/service identity. Called per job invocation.
310
+ */
311
+ jobContext?: () => TContext | Promise<TContext>;
312
+ /**
313
+ * Absolute, externally-reachable base URL of this server (no trailing
314
+ * slash), e.g. `https://api.example.com` in prod or `http://127.0.0.1:3000`
315
+ * in dev. Used to build the job endpoint the scheduler calls.
316
+ */
317
+ publicUrl: string;
318
+ /**
319
+ * URL path prefix for the job webhook endpoint. Default `/_jobs`. The full
320
+ * endpoint for a job is `{publicUrl}{jobPath}/<jobName>`.
321
+ */
322
+ jobPath?: string;
323
+ /**
324
+ * Enable the one-shot HTTP RPC transport (query/mutation/action over a
325
+ * single `POST {rpc.path}` endpoint, with `{ name, input }` in the body).
326
+ * Uses the same `verifyAuth` as the WebSocket path. Omit to disable. See
327
+ * {@link RpcConfig}.
328
+ */
329
+ rpc?: RpcConfig<TContext>;
330
+ /**
331
+ * Object storage, exposed to every procedure as `ctx.storage`. When set,
332
+ * query/mutation/action/job handlers can presign uploads/downloads and
333
+ * resolve public URLs without reaching for a module-level singleton. Omit
334
+ * to leave `ctx.storage` undefined (handlers should treat uploads as
335
+ * unconfigured). Build one with `S3CompatibleStorage` from
336
+ * `@supalive/core/storage`.
337
+ */
338
+ storage: ObjectStorage;
339
+ /**
340
+ * Optional application-level Redis pub/sub for cross-instance app messages
341
+ * that are NOT part of the subscription/cache machinery — e.g. auth-token
342
+ * revocations, feature-flag flips, targeted cache busts.
343
+ *
344
+ * The server subscribes to `channels` on its EXISTING Redis subscribe
345
+ * connection (no extra connection) and hands each received message to
346
+ * `onMessage`. Publish from anywhere with
347
+ * `server.publishAppMessage(channel, message)`, which rides the shared
348
+ * command connection. Messages are opaque strings — the app owns encoding.
349
+ */
350
+ appPubSub?: AppPubSubConfig;
351
+ }
352
+ /**
353
+ * App-level pub/sub wiring (see {@link SupaliveServerConfig.appPubSub}). A thin,
354
+ * generic cross-instance message bus layered on the server's Redis connections.
355
+ */
356
+ interface AppPubSubConfig {
357
+ /** Channels this instance subscribes to. */
358
+ channels: string[];
359
+ /**
360
+ * Handler for a message received on one of `channels`. Errors are caught and
361
+ * logged by the server, so a throwing handler can't crash the subscriber.
362
+ */
363
+ onMessage: (channel: string, message: string) => void | Promise<void>;
364
+ }
365
+ interface SubscriptionManagerConfig {
366
+ /**
367
+ * Port for the rpc-websockets listener. Required unless {@link listen} is
368
+ * `false` (embedded/in-process mode, where no socket is opened).
369
+ */
370
+ port?: number;
371
+ /**
372
+ * Upstash/Redis connection for the worker's own cache layer. Required in
373
+ * the default (own-pool) mode; omit when reusing an existing {@link cache}
374
+ * via {@link inline}.
375
+ */
376
+ upstash?: {
377
+ url: string;
378
+ token: string;
379
+ redisUrl: string;
380
+ };
381
+ /**
382
+ * Database connection the worker builds its own pool from. Required in the
383
+ * default mode; omit when reusing an existing {@link db} via {@link inline}.
384
+ */
385
+ database?: DatabaseConfig;
386
+ cacheTTLSeconds: number;
387
+ /**
388
+ * Open the rpc-websockets listener (default `true`). Set to `false` to
389
+ * embed the manager in another process and drive it via
390
+ * {@link SubscriptionManager.localLink}.
391
+ */
392
+ listen?: boolean;
393
+ /**
394
+ * Run the subscription worker inline on the main event loop instead of a
395
+ * `worker_threads` Worker (default `false`). Eliminates the postMessage /
396
+ * structured-clone hop, at the cost of no cross-core parallelism — always a
397
+ * single worker. Intended for embedded (`listen: false`) deployments with
398
+ * light realtime load. Provide {@link db} + {@link cache} to reuse the host
399
+ * server's pool/cache rather than opening new ones.
400
+ */
401
+ inline?: boolean;
402
+ /** In-process `Database` to reuse in {@link inline} mode (borrowed; not closed on stop). */
403
+ db?: Database;
404
+ /** In-process `CacheLayer` to reuse in {@link inline} mode. */
405
+ cache?: CacheLayer;
406
+ /**
407
+ * Number of logical workers inside the sub-manager process.
408
+ *
409
+ * Subscriptions are routed by FNV-1a(subId) % workers so that all operations
410
+ * for a given subId always land on the same worker (preserving the existing
411
+ * `instances: Set<string>` dedup). Each worker owns an independent
412
+ * subscriptions Map; on invalidate, all workers scan their own slice in
413
+ * parallel (logically — JS still runs one at a time inside one event loop,
414
+ * but per-worker scans are smaller so total work is split N ways).
415
+ *
416
+ * Defaults to `SUPALIVE_SUB_MANAGER_WORKERS` env var if set, else 1.
417
+ */
418
+ workers?: number;
419
+ /**
420
+ * Connection pool size *per worker*. If omitted, falls back to
421
+ * `floor(database.maxConnections / workers)` (min 1) so the total pool
422
+ * size stays close to the legacy single-worker configuration.
423
+ */
424
+ maxConnectionsPerWorker?: number;
425
+ }
426
+ //#endregion
427
+ //#region src/server/types_server.d.ts
428
+ type InstanceId = string;
429
+ type SubId = string;
430
+ /** Local tracking of an active subscription (per-session) */
431
+ interface SubscriptionEntry {
432
+ subId: SubId;
433
+ cacheKey: string;
434
+ subscribedTimes: number;
435
+ }
436
+ /**
437
+ * A mutation that has been validated and parked on the per-session FIFO
438
+ * queue, waiting for the in-flight mutation on this socket to finish. Each
439
+ * `handleCall` for a mutation owns one of these and awaits its own
440
+ * resolve/reject so it can send the response.
441
+ */
442
+ interface PendingMutation<TContext = Record<string, unknown>> {
443
+ procedure: RegisteredProcedure<TContext>;
444
+ validatedInput: unknown;
445
+ resolve: (result: MutationResult<unknown>) => void;
446
+ reject: (err: unknown) => void;
447
+ }
448
+ /** WebSocket session (runtime, with WebSocket) */
449
+ interface Session<TContext = Record<string, unknown>> {
450
+ id: string;
451
+ ws: WebSocket;
452
+ /** Auth context from verifyAuth callback */
453
+ serverCtx?: TContext;
454
+ subIds: Set<string>;
455
+ /**
456
+ * Per-socket FIFO mutation queue. at most one mutation
457
+ * drains at a time so a single client cannot saturate the OCC retry
458
+ * loop or fan out concurrent commits that race the same rows.
459
+ */
460
+ mutationQueue: PendingMutation<TContext>[];
461
+ mutationInFlight: boolean;
462
+ /** Per-socket count of currently executing actions. */
463
+ actionInFlight: number;
464
+ /**
465
+ * Wall-clock of the last inbound frame (text message, ws-ping, or ws-pong).
466
+ * Used by the per-session heartbeat to terminate sockets that have gone
467
+ * silent past `CLIENT_TIMEOUT_MS`.
468
+ */
469
+ lastReceivedAt: number;
470
+ /**
471
+ * Wall-clock of the last outbound frame. Gates the idle-only app-level
472
+ * ping so a busy session (frequent sub:updates etc.) doesn't emit a
473
+ * redundant `{type:"ping"}` on every heartbeat tick.
474
+ */
475
+ lastSentAt: number;
476
+ /**
477
+ * Per-session combined heartbeat. Single `setInterval` that handles
478
+ * both dead-TCP detection (ws-ping or terminate) and client-watchdog
479
+ * refresh (idle-only app-level ping) on each tick.
480
+ */
481
+ heartbeatTimer: ReturnType<typeof setInterval> | null;
482
+ }
483
+ declare const RemoteSubscriptionUpdateSchema: z.ZodObject<{
484
+ type: z.ZodLiteral<"update">;
485
+ subId: z.ZodString;
486
+ data: z.ZodUnknown;
487
+ dataHash: z.ZodString;
488
+ originInstance: z.ZodString;
489
+ ts: z.ZodOptional<z.ZodString>;
490
+ }, z.core.$strip>;
491
+ type RemoteSubscriptionUpdate = z.infer<typeof RemoteSubscriptionUpdateSchema>;
492
+ declare const RemoteRecomputeRaceSchema: z.ZodObject<{
493
+ type: z.ZodLiteral<"recompute-race">;
494
+ subId: z.ZodString;
495
+ cacheKey: z.ZodString;
496
+ queryName: z.ZodString;
497
+ args: z.ZodUnknown;
498
+ notifyInstances: z.ZodArray<z.ZodString>;
499
+ commitTs: z.ZodString;
500
+ originInstance: z.ZodString;
501
+ }, z.core.$strip>;
502
+ type RemoteRecomputeRace = z.infer<typeof RemoteRecomputeRaceSchema>;
503
+ declare const RemoteSubscriptionMessageSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
504
+ type: z.ZodLiteral<"update">;
505
+ subId: z.ZodString;
506
+ data: z.ZodUnknown;
507
+ dataHash: z.ZodString;
508
+ originInstance: z.ZodString;
509
+ ts: z.ZodOptional<z.ZodString>;
510
+ }, z.core.$strip>, z.ZodObject<{
511
+ type: z.ZodLiteral<"recompute-race">;
512
+ subId: z.ZodString;
513
+ cacheKey: z.ZodString;
514
+ queryName: z.ZodString;
515
+ args: z.ZodUnknown;
516
+ notifyInstances: z.ZodArray<z.ZodString>;
517
+ commitTs: z.ZodString;
518
+ originInstance: z.ZodString;
519
+ }, z.core.$strip>], "type">;
520
+ type RemoteSubscriptionMessage = z.infer<typeof RemoteSubscriptionMessageSchema>;
521
+ //#endregion
522
+ export { SubManagerLink as C, SubManagerClient as S, RpcCorsConfig as _, RemoteSubscriptionMessage as a, SupaliveServerConfig as b, RemoteSubscriptionUpdateSchema as c, SubscriptionEntry as d, AppPubSubConfig as f, RpcConfig as g, PostgresConfig as h, RemoteRecomputeRaceSchema as i, Session as l, MySQLConfig as m, PendingMutation as n, RemoteSubscriptionMessageSchema as o, DatabaseConfig as p, RemoteRecomputeRace as r, RemoteSubscriptionUpdate as s, InstanceId as t, SubId as u, RpcRateLimitConfig as v, UpstashConfig as x, SubscriptionManagerConfig as y };
523
+ //# sourceMappingURL=types_server-BSiGxbqb.d.ts.map