@supalive/core 1.15.0 → 1.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index-B2nE1y9E.d.ts +2384 -0
- package/dist/index-B2nE1y9E.d.ts.map +1 -0
- package/dist/index-B4UxN1ZL.d.ts +2365 -0
- package/dist/index-B4UxN1ZL.d.ts.map +1 -0
- package/dist/index-B5hAqW3O.d.ts +2402 -0
- package/dist/index-B5hAqW3O.d.ts.map +1 -0
- package/dist/index-B8JFAyw4.d.ts +2377 -0
- package/dist/index-B8JFAyw4.d.ts.map +1 -0
- package/dist/index-BI3MfAyI.d.ts +2399 -0
- package/dist/index-BI3MfAyI.d.ts.map +1 -0
- package/dist/index-BL90lDw7.d.ts +2400 -0
- package/dist/index-BL90lDw7.d.ts.map +1 -0
- package/dist/index-BvryqYUm.d.ts +2394 -0
- package/dist/index-BvryqYUm.d.ts.map +1 -0
- package/dist/index-CfcrWLLm.d.ts +2377 -0
- package/dist/index-CfcrWLLm.d.ts.map +1 -0
- package/dist/index-DYkOBnw_.d.ts +2378 -0
- package/dist/index-DYkOBnw_.d.ts.map +1 -0
- package/dist/index-DcM2uKpT.d.ts +2393 -0
- package/dist/index-DcM2uKpT.d.ts.map +1 -0
- package/dist/index-DsvdhOKL.d.ts +2400 -0
- package/dist/index-DsvdhOKL.d.ts.map +1 -0
- package/dist/index-ggi1DrSG.d.ts +2336 -0
- package/dist/index-ggi1DrSG.d.ts.map +1 -0
- package/dist/mysql-07ROfbBZ.d.ts +114 -0
- package/dist/mysql-07ROfbBZ.d.ts.map +1 -0
- package/dist/mysql-BJaQhVGE.d.ts +114 -0
- package/dist/mysql-BJaQhVGE.d.ts.map +1 -0
- package/dist/mysql-BKs5PTSR.d.ts +114 -0
- package/dist/mysql-BKs5PTSR.d.ts.map +1 -0
- package/dist/mysql-BTigT6mP.d.ts +114 -0
- package/dist/mysql-BTigT6mP.d.ts.map +1 -0
- package/dist/mysql-C7Km_lgc.d.ts +114 -0
- package/dist/mysql-C7Km_lgc.d.ts.map +1 -0
- package/dist/mysql-CXymz1Eu.d.ts +114 -0
- package/dist/mysql-CXymz1Eu.d.ts.map +1 -0
- package/dist/mysql-ClUK7S2j.js +623 -0
- package/dist/mysql-ClUK7S2j.js.map +1 -0
- package/dist/mysql-CtpWqOhO.d.ts +114 -0
- package/dist/mysql-CtpWqOhO.d.ts.map +1 -0
- package/dist/mysql-Cxro4f6T.d.ts +114 -0
- package/dist/mysql-Cxro4f6T.d.ts.map +1 -0
- package/dist/mysql-DNiYIZCK.d.ts +114 -0
- package/dist/mysql-DNiYIZCK.d.ts.map +1 -0
- package/dist/mysql-DS1s1c5M.d.ts +114 -0
- package/dist/mysql-DS1s1c5M.d.ts.map +1 -0
- package/dist/mysql-fTKZ1zaF.js +623 -0
- package/dist/mysql-fTKZ1zaF.js.map +1 -0
- package/dist/mysql-qTszEKAU.d.ts +114 -0
- package/dist/mysql-qTszEKAU.d.ts.map +1 -0
- package/dist/mysql-qW13LcGQ.d.ts +114 -0
- package/dist/mysql-qW13LcGQ.d.ts.map +1 -0
- package/dist/overlap-checker-1TwhkAwy.js +259 -0
- package/dist/overlap-checker-1TwhkAwy.js.map +1 -0
- package/dist/overlap-checker-CGlxWcyb.js +259 -0
- package/dist/overlap-checker-CGlxWcyb.js.map +1 -0
- package/dist/postgres-B0fqJe1X.d.ts +118 -0
- package/dist/postgres-B0fqJe1X.d.ts.map +1 -0
- package/dist/postgres-B5-5vgLJ.d.ts +118 -0
- package/dist/postgres-B5-5vgLJ.d.ts.map +1 -0
- package/dist/postgres-BATDLPml.d.ts +118 -0
- package/dist/postgres-BATDLPml.d.ts.map +1 -0
- package/dist/postgres-BUVYjnaT.d.ts +118 -0
- package/dist/postgres-BUVYjnaT.d.ts.map +1 -0
- package/dist/postgres-Bk_8PFRT.d.ts +118 -0
- package/dist/postgres-Bk_8PFRT.d.ts.map +1 -0
- package/dist/postgres-Bx79_JEy.d.ts +118 -0
- package/dist/postgres-Bx79_JEy.d.ts.map +1 -0
- package/dist/postgres-C3w741VH.d.ts +118 -0
- package/dist/postgres-C3w741VH.d.ts.map +1 -0
- package/dist/postgres-CAZYYgbZ.d.ts +118 -0
- package/dist/postgres-CAZYYgbZ.d.ts.map +1 -0
- package/dist/postgres-CN03Espg.js +868 -0
- package/dist/postgres-CN03Espg.js.map +1 -0
- package/dist/postgres-CRPJdZx2.js +868 -0
- package/dist/postgres-CRPJdZx2.js.map +1 -0
- package/dist/postgres-DCXnKaJr.d.ts +118 -0
- package/dist/postgres-DCXnKaJr.d.ts.map +1 -0
- package/dist/postgres-DgCYPf0j.d.ts +118 -0
- package/dist/postgres-DgCYPf0j.d.ts.map +1 -0
- package/dist/postgres-Dnshux6k.d.ts +118 -0
- package/dist/postgres-Dnshux6k.d.ts.map +1 -0
- package/dist/postgres-bhVzeRf2.d.ts +118 -0
- package/dist/postgres-bhVzeRf2.d.ts.map +1 -0
- package/dist/query-LJranz0c.js +795 -0
- package/dist/query-LJranz0c.js.map +1 -0
- package/dist/query-q1ZvKrZO.js +762 -0
- package/dist/query-q1ZvKrZO.js.map +1 -0
- package/dist/realtime_db-B0Tin87E.js +312 -0
- package/dist/realtime_db-B0Tin87E.js.map +1 -0
- package/dist/realtime_db-DVhhasJj.js +312 -0
- package/dist/realtime_db-DVhhasJj.js.map +1 -0
- package/dist/router-Bk0eLfmB.js +285 -0
- package/dist/router-Bk0eLfmB.js.map +1 -0
- package/dist/router-DP2ThAwh.js.map +1 -1
- package/dist/src/client/index.d.ts +2 -2
- package/dist/src/client/index.js +95 -20
- package/dist/src/client/index.js.map +1 -1
- package/dist/src/exports/mysql.d.ts +1 -1
- package/dist/src/exports/mysql.js +1 -1
- package/dist/src/exports/postgres.d.ts +1 -1
- package/dist/src/exports/postgres.js +1 -1
- package/dist/src/exports/procedure.d.ts +2 -2
- package/dist/src/exports/procedure.js +1 -1
- package/dist/src/exports/schema-sql.d.ts +1 -1
- package/dist/src/exports/server.d.ts +13 -6
- package/dist/src/exports/server.d.ts.map +1 -1
- package/dist/src/exports/server.js +802 -252
- package/dist/src/exports/server.js.map +1 -1
- package/dist/src/exports/sub-manager-worker-entry.js +1 -1
- package/dist/src/exports/types.d.ts +2 -2
- package/dist/src/exports/types.js +1 -1
- package/dist/sub-worker-dispatch-D7jfw6ys.js +826 -0
- package/dist/sub-worker-dispatch-D7jfw6ys.js.map +1 -0
- package/dist/sub-worker-dispatch-qiSs5Xkm.js +826 -0
- package/dist/sub-worker-dispatch-qiSs5Xkm.js.map +1 -0
- package/dist/types_client_rpc-CWZmlWmM.js +145 -0
- package/dist/types_client_rpc-CWZmlWmM.js.map +1 -0
- package/dist/types_client_rpc-D4td5W0Y.js +141 -0
- package/dist/types_client_rpc-D4td5W0Y.js.map +1 -0
- package/dist/types_server-AXVa_2mF.d.ts +684 -0
- package/dist/types_server-AXVa_2mF.d.ts.map +1 -0
- package/dist/types_server-BhC19R2a.js.map +1 -1
- package/dist/types_server-BmIgDd8d.d.ts +614 -0
- package/dist/types_server-BmIgDd8d.d.ts.map +1 -0
- package/dist/types_server-C6B9_b1R.d.ts +662 -0
- package/dist/types_server-C6B9_b1R.d.ts.map +1 -0
- package/dist/types_server-CUPM08l2.d.ts +684 -0
- package/dist/types_server-CUPM08l2.d.ts.map +1 -0
- package/dist/types_server-CtYRmHdO.d.ts +684 -0
- package/dist/types_server-CtYRmHdO.d.ts.map +1 -0
- package/dist/types_server-DHRi8bGO.d.ts +684 -0
- package/dist/types_server-DHRi8bGO.d.ts.map +1 -0
- package/dist/types_server-DRr5yKy1.d.ts +655 -0
- package/dist/types_server-DRr5yKy1.d.ts.map +1 -0
- package/dist/types_server-DmCbve3w.d.ts +684 -0
- package/dist/types_server-DmCbve3w.d.ts.map +1 -0
- package/dist/types_server-DoeybfmY.d.ts +684 -0
- package/dist/types_server-DoeybfmY.d.ts.map +1 -0
- package/dist/types_server-Gs_vSVaS.d.ts +655 -0
- package/dist/types_server-Gs_vSVaS.d.ts.map +1 -0
- package/dist/types_server-ILUmPFvk.d.ts +614 -0
- package/dist/types_server-ILUmPFvk.d.ts.map +1 -0
- package/dist/types_server-JK14NE0j.d.ts +684 -0
- package/dist/types_server-JK14NE0j.d.ts.map +1 -0
- package/dist/types_server-hYv2--1M.d.ts +684 -0
- package/dist/types_server-hYv2--1M.d.ts.map +1 -0
- package/dist/types_server-kkQJDSjA.d.ts +684 -0
- package/dist/types_server-kkQJDSjA.d.ts.map +1 -0
- package/package.json +2 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"router-Bk0eLfmB.js","names":[],"sources":["../src/router/procedure.ts","../src/router/router.ts"],"sourcesContent":["import type { ZodType } from \"zod\";\nimport type { Span } from \"@opentelemetry/api\";\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 * Minimal request-scoped logger exposed as `ctx.log`. Structurally satisfied by\n * a pino logger, so the server hands its own child logger straight through; the\n * interface keeps handler code decoupled from pino. Bound with `reqId`, the\n * procedure name, and (when tracing is enabled) the `traceId`, so every line a\n * handler writes correlates to its request and trace.\n */\nexport interface HandlerLogger {\n debug(...args: any[]): void;\n info(...args: any[]): void;\n warn(...args: any[]): void;\n error(...args: any[]): void;\n}\n\n/**\n * A {@link HandlerLogger} that discards everything. Used as `ctx.log` for direct\n * internal-caller invocations (which run outside the server's request logger), so\n * handler code can ALWAYS call `ctx.log.info(...)` without a null check.\n */\nexport const noopLogger: HandlerLogger = {\n debug() {},\n info() {},\n warn() {},\n error() {},\n};\n\n/**\n * Observability handles present on a handler context. `log` is ALWAYS present\n * (the server binds a request-correlated logger; direct internal-caller\n * invocations get interal logger, so handlers never null-check it.\n */\nexport interface HandlerObservability {\n /** Request-scoped logger, correlated to this operation (reqId + trace id). */\n log: HandlerLogger;\n /** The active OpenTelemetry span for this operation. Add attributes/events or\n * parent child spans off it. A non-recording no-op span when tracing is off. */\n span?: Span;\n}\n\n/**\n * Query context passed to query handlers.\n * Contains database reader and user-defined server context.\n */\n/** Options for the per-handler connection-routing methods (see {@link QueryCtx}). */\nexport interface ConnOpts {\n /**\n * Force the PRIMARY (writer) connection even inside a query/action —\n * read-your-writes. On `useReplicaConn` this overrides the replica choice.\n */\n readOwnWrite?: boolean;\n}\n\nexport interface QueryCtx<TContext = unknown> extends HandlerObservability {\n /** Database reader for queries */\n db: DbReader;\n /** User-defined server context (auth, requestId, etc.) */\n serverCtx?: TContext;\n /**\n * Route this query's reads to the PRIMARY (writer) connection. Must be called\n * BEFORE any read (throws otherwise). A no-op when reads already run on primary\n * (no replica configured, or a primary-only path like a live query).\n */\n usePrimaryConn(opts?: ConnOpts): void;\n /**\n * Route this query's reads to the read REPLICA, if one is configured. Must be\n * called BEFORE any read. `{ readOwnWrite: true }` forces the PRIMARY instead.\n */\n useReplicaConn(opts?: ConnOpts): void;\n}\n\n/**\n * No-op connection routing for query paths that genuinely ALWAYS run on the\n * primary — live subscription re-execution and mutation handlers. Spread into\n * the ctx so `ctx.usePrimaryConn()`/`useReplicaConn()` are always callable but\n * inert (there is only ever the primary connection to bind).\n *\n * For a nested `runQuery` that JOINS a parent transaction, use {@link parentConn}\n * instead — there the connection isn't necessarily the primary.\n */\nexport const primaryOnlyConn: Pick<QueryCtx, \"usePrimaryConn\" | \"useReplicaConn\"> = {\n usePrimaryConn: () => { },\n useReplicaConn: () => { },\n};\n\n/**\n * No-op connection routing for a nested `runQuery` that JOINS a parent\n * transaction (a `runQuery` called with a query/mutation `parentCtx`). The knobs\n * always use the PARENT's connection because the read connection is fixed to the\n * parent transaction's — which may be the PRIMARY or the REPLICA, depending on\n * how the parent query was routed.\n *\n * They MUST be inert: a nested query shares the parent's snapshot + readSet, so\n * calling `useConnection` here would either repoint the parent's connection\n * mid-flight (before its first read) or throw (after it) — either way corrupting\n * the parent transaction. A handler that needs to force primary therefore cannot\n * do so while nested under a replica-routed parent (it inherits the replica,\n * which is already safe w.r.t. the client's `minTs` floor); call it via an\n * action-parent `runQuery` instead, which opens a fresh routed read.\n */\nexport const parentConn: Pick<QueryCtx, \"usePrimaryConn\" | \"useReplicaConn\"> = {\n usePrimaryConn: () => { },\n useReplicaConn: () => { },\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> extends HandlerObservability {\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 * No-op on a mutation — writes (and their reads) always run on the primary.\n * Present so a `MutationCtx` stays structurally assignable to `QueryCtx`, i.e.\n * a mutation can reuse a `(ctx: QueryCtx) => …` read helper.\n */\n usePrimaryConn(opts?: ConnOpts): void;\n /** No-op on a mutation (always primary). See {@link usePrimaryConn}. */\n useReplicaConn(opts?: ConnOpts): void;\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> extends HandlerObservability {\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> extends HandlerObservability {\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 * The parent handler's request logger, the caller handler's\n * own `ctx` carries it through, so a nested `runQuery`/`runMutation` logs\n * under the SAME request logger (reqId/trace correlation preserved).\n */\n log: HandlerLogger;\n}\n\n/**\n * The slice of the server's {@link Observability} an internal caller needs to\n * build per-call loggers (see `createCaller().init({ obs })`). Structural, so an\n * `Observability` instance satisfies it without the caller depending on it.\n */\nexport interface CallerObservability {\n lazyChildLogger(fields: Record<string, unknown>): HandlerLogger;\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 outputSchema?: ZodType<any>;\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 * Optional Zod schema describing return-type overrides for codegen.\n * Only the fields you specify are overridden; everything else is inferred\n * from the handler's TypeScript return type. Use `.modelName(\"Name\")`\n * on a Zod object to rename the generated model class.\n */\n returns?: ZodType<any>;\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 * Optional Zod schema describing return-type overrides for codegen.\n * Only the fields you specify are overridden; everything else is inferred\n * from the handler's TypeScript return type.\n */\n returns?: ZodType<any>;\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 * Optional Zod schema describing return-type overrides for codegen.\n * Only the fields you specify are overridden; everything else is inferred\n * from the handler's TypeScript return type.\n */\n returns?: ZodType<any>;\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 outputSchema: config.returns,\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 outputSchema: config.returns,\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 outputSchema: config.returns,\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}","import type { AnyProcedure } from \"./procedure\";\n\n// ─── Router Types ────────────────────────────────────────────────────────────\n\n/**\n * A router maps procedure names (keys) to their definitions.\n * This is the type that's exported from your app and used by the client.\n */\nexport type Router<TProcedures extends Record<string, AnyProcedure<TContext>>, TContext = unknown> = {\n _type: \"router\";\n procedures: TProcedures;\n contextName: string;\n};\n\n/**\n * Inferred AppRouter type from router() call.\n * Captures the full procedure map for client type inference.\n */\nexport type AppRouter<\n TProcedures extends Record<string, AnyProcedure<TContext>> = Record<string, AnyProcedure>,\n TContext = unknown\n> = Router<TProcedures, TContext>;\n\n// ─── Type Helpers for Client ─────────────────────────────────────────────────\n\n/** Get query procedures only from a router */\nexport type QueryProcedures<T extends Record<string, AnyProcedure>> = {\n [K in keyof T as T[K] extends { procedureType: \"query\" } ? K : never]: T[K];\n};\n\n/** Get mutation procedures only from a router */\nexport type MutationProcedures<T extends Record<string, AnyProcedure>> = {\n [K in keyof T as T[K] extends { procedureType: \"mutation\" } ? K : never]: T[K];\n};\n\n/** Get action procedures only from a router */\nexport type ActionProcedures<T extends Record<string, AnyProcedure>> = {\n [K in keyof T as T[K] extends { procedureType: \"action\" } ? K : never]: T[K];\n};\n\n/** Get job procedures only from a router */\nexport type JobProcedures<T extends Record<string, AnyProcedure>> = {\n [K in keyof T as T[K] extends { procedureType: \"job\" } ? K : never]: T[K];\n};\n\n/** Get public (non-internal) procedures - for client type safety */\nexport type PublicProcedures<T extends Record<string, AnyProcedure>> = Pick<\n T,\n { [K in keyof T]: T[K] extends { internal: true } ? never : K }[keyof T]\n>;\n\n/** Extract procedure names from a router */\nexport type ProcedureNames<T extends Router<any>> =\n T extends Router<infer P> ? keyof P : never;\n\nexport type RouterConfig<T> = {\n procedures: T;\n contextName?: string;\n};\n\n/**\n* Create a router from procedure definitions.\n* Procedure names are inferred from the object keys.\n* \n* @example\n* const appRouter = router({\n* procedures: {\n* getUser,\n* createUser,\n* internalGetAll,\n* },\n* });\n* \n* export type AppRouter = typeof appRouter;\n*/\nexport function router<TProcedures extends Record<string, AnyProcedure<any>>, TContext = unknown>(\n config: RouterConfig<TProcedures>,\n): Router<TProcedures, TContext> {\n const registry = getContextRegistry(config.contextName ?? \"default\");\n\n // Register all procedures at router creation time\n for (const [name, proc] of Object.entries(config.procedures)) {\n registry.registerProcedure(name, proc);\n }\n\n\n return {\n _type: \"router\",\n procedures: config.procedures,\n contextName: config.contextName ?? \"default\",\n };\n}\n\nexport interface RegisteredProcedure<TContext = unknown> {\n name: string;\n type: \"query\" | \"mutation\" | \"action\" | \"job\";\n internal: boolean;\n inputSchema: AnyProcedure<TContext>[\"inputSchema\"];\n fn: AnyProcedure<TContext>[\"fn\"];\n /** Only present for `type === \"query\"`. See `QueryIdentitySpec`. */\n queryIdentity?: false | string | ((serverCtx: TContext | undefined, input: unknown) => string | null | undefined);\n /** Only present for `type === \"job\"`. Cron expression for recurring jobs. */\n cron?: string;\n}\n\n\nconst contextRegistry = new Map<string, ContextRegistry>();\n\nexport function getContextRegistry(inContext: string): ContextRegistry {\n let registry = contextRegistry.get(inContext);\n if (!registry) {\n registry = new ContextRegistry();\n contextRegistry.set(inContext, registry);\n }\n return registry;\n}\n\nexport class ContextRegistry {\n procedureRegistry = new Map<string, RegisteredProcedure<any>>();\n internalProcedureNames = new Set<string>();\n\n registerProcedure<TContext>(name: string, proc: AnyProcedure<TContext>): void {\n if (this.procedureRegistry.has(name)) {\n throw new Error(\n `[router] Procedure \"${name}\" is already registered. ` +\n `Each procedure name must be unique across the application.`\n );\n }\n\n // Track internal procedures by name\n if (proc.internal) {\n this.markInternalProcedure(name);\n }\n\n const queryIdentity =\n proc.procedureType === \"query\"\n ? (proc as { queryIdentity?: RegisteredProcedure<TContext>[\"queryIdentity\"] }).queryIdentity\n : undefined;\n\n const cron =\n proc.procedureType === \"job\"\n ? (proc as { cron?: string }).cron\n : undefined;\n\n this.procedureRegistry.set(name, {\n name,\n type: proc.procedureType,\n internal: proc.internal,\n inputSchema: proc.inputSchema,\n fn: proc.fn,\n queryIdentity,\n cron,\n });\n }\n\n /** Get a registered procedure by name (runtime lookup) */\n getProcedure<TContext = unknown>(name: string): RegisteredProcedure<TContext> | undefined {\n return this.procedureRegistry.get(name);\n }\n\n /** Get all registered procedure names */\n getProcedureNames(): string[] {\n return [...this.procedureRegistry.keys()];\n }\n\n /** Get all registered procedures */\n getAllProcedures(): Map<string, RegisteredProcedure> {\n return new Map(this.procedureRegistry);\n }\n\n /** Get all registered job procedures (server-only, scheduler-triggered). */\n getJobProcedures(): RegisteredProcedure[] {\n return [...this.procedureRegistry.values()].filter((p) => p.type === \"job\");\n }\n\n /** Clear the registry (for testing only) */\n clearRegistry(): void {\n this.procedureRegistry.clear();\n this.clearInternalProcedures();\n }\n\n markInternalProcedure(name: string): void {\n this.internalProcedureNames.add(name);\n }\n\n isInternalProcedure(name: string): boolean {\n return this.internalProcedureNames.has(name);\n }\n\n clearInternalProcedures(): void {\n this.internalProcedureNames.clear();\n }\n}"],"mappings":"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"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"router-DP2ThAwh.js","names":[],"sources":["../src/router/procedure.ts","../src/router/router.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 */\n/** Options for the per-handler connection-routing methods (see {@link QueryCtx}). */\nexport interface ConnOpts {\n /**\n * Force the PRIMARY (writer) connection even inside a query/action —\n * read-your-writes. On `useReplicaConn` this overrides the replica choice.\n */\n readOwnWrite?: boolean;\n}\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 * Route this query's reads to the PRIMARY (writer) connection. Must be called\n * BEFORE any read (throws otherwise). A no-op when reads already run on primary\n * (no replica configured, or a primary-only path like a live query).\n */\n usePrimaryConn(opts?: ConnOpts): void;\n /**\n * Route this query's reads to the read REPLICA, if one is configured. Must be\n * called BEFORE any read. `{ readOwnWrite: true }` forces the PRIMARY instead.\n */\n useReplicaConn(opts?: ConnOpts): void;\n}\n\n/**\n * No-op connection routing for query paths that genuinely ALWAYS run on the\n * primary — live subscription re-execution and mutation handlers. Spread into\n * the ctx so `ctx.usePrimaryConn()`/`useReplicaConn()` are always callable but\n * inert (there is only ever the primary connection to bind).\n *\n * For a nested `runQuery` that JOINS a parent transaction, use {@link parentConn}\n * instead — there the connection isn't necessarily the primary.\n */\nexport const primaryOnlyConn: Pick<QueryCtx, \"usePrimaryConn\" | \"useReplicaConn\"> = {\n usePrimaryConn: () => { },\n useReplicaConn: () => { },\n};\n\n/**\n * No-op connection routing for a nested `runQuery` that JOINS a parent\n * transaction (a `runQuery` called with a query/mutation `parentCtx`). The knobs\n * always use the PARENT's connection because the read connection is fixed to the\n * parent transaction's — which may be the PRIMARY or the REPLICA, depending on\n * how the parent query was routed.\n *\n * They MUST be inert: a nested query shares the parent's snapshot + readSet, so\n * calling `useConnection` here would either repoint the parent's connection\n * mid-flight (before its first read) or throw (after it) — either way corrupting\n * the parent transaction. A handler that needs to force primary therefore cannot\n * do so while nested under a replica-routed parent (it inherits the replica,\n * which is already safe w.r.t. the client's `minTs` floor); call it via an\n * action-parent `runQuery` instead, which opens a fresh routed read.\n */\nexport const parentConn: Pick<QueryCtx, \"usePrimaryConn\" | \"useReplicaConn\"> = {\n usePrimaryConn: () => { },\n useReplicaConn: () => { },\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 * No-op on a mutation — writes (and their reads) always run on the primary.\n * Present so a `MutationCtx` stays structurally assignable to `QueryCtx`, i.e.\n * a mutation can reuse a `(ctx: QueryCtx) => …` read helper.\n */\n usePrimaryConn(opts?: ConnOpts): void;\n /** No-op on a mutation (always primary). See {@link usePrimaryConn}. */\n useReplicaConn(opts?: ConnOpts): void;\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 outputSchema?: ZodType<any>;\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 * Optional Zod schema describing return-type overrides for codegen.\n * Only the fields you specify are overridden; everything else is inferred\n * from the handler's TypeScript return type. Use `.modelName(\"Name\")`\n * on a Zod object to rename the generated model class.\n */\n returns?: ZodType<any>;\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 * Optional Zod schema describing return-type overrides for codegen.\n * Only the fields you specify are overridden; everything else is inferred\n * from the handler's TypeScript return type.\n */\n returns?: ZodType<any>;\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 * Optional Zod schema describing return-type overrides for codegen.\n * Only the fields you specify are overridden; everything else is inferred\n * from the handler's TypeScript return type.\n */\n returns?: ZodType<any>;\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 outputSchema: config.returns,\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 outputSchema: config.returns,\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 outputSchema: config.returns,\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}","import type { AnyProcedure } from \"./procedure\";\n\n// ─── Router Types ────────────────────────────────────────────────────────────\n\n/**\n * A router maps procedure names (keys) to their definitions.\n * This is the type that's exported from your app and used by the client.\n */\nexport type Router<TProcedures extends Record<string, AnyProcedure<TContext>>, TContext = unknown> = {\n _type: \"router\";\n procedures: TProcedures;\n contextName: string;\n};\n\n/**\n * Inferred AppRouter type from router() call.\n * Captures the full procedure map for client type inference.\n */\nexport type AppRouter<\n TProcedures extends Record<string, AnyProcedure<TContext>> = Record<string, AnyProcedure>,\n TContext = unknown\n> = Router<TProcedures, TContext>;\n\n// ─── Type Helpers for Client ─────────────────────────────────────────────────\n\n/** Get query procedures only from a router */\nexport type QueryProcedures<T extends Record<string, AnyProcedure>> = {\n [K in keyof T as T[K] extends { procedureType: \"query\" } ? K : never]: T[K];\n};\n\n/** Get mutation procedures only from a router */\nexport type MutationProcedures<T extends Record<string, AnyProcedure>> = {\n [K in keyof T as T[K] extends { procedureType: \"mutation\" } ? K : never]: T[K];\n};\n\n/** Get action procedures only from a router */\nexport type ActionProcedures<T extends Record<string, AnyProcedure>> = {\n [K in keyof T as T[K] extends { procedureType: \"action\" } ? K : never]: T[K];\n};\n\n/** Get job procedures only from a router */\nexport type JobProcedures<T extends Record<string, AnyProcedure>> = {\n [K in keyof T as T[K] extends { procedureType: \"job\" } ? K : never]: T[K];\n};\n\n/** Get public (non-internal) procedures - for client type safety */\nexport type PublicProcedures<T extends Record<string, AnyProcedure>> = Pick<\n T,\n { [K in keyof T]: T[K] extends { internal: true } ? never : K }[keyof T]\n>;\n\n/** Extract procedure names from a router */\nexport type ProcedureNames<T extends Router<any>> =\n T extends Router<infer P> ? keyof P : never;\n\nexport type RouterConfig<T> = {\n procedures: T;\n contextName?: string;\n};\n\n/**\n* Create a router from procedure definitions.\n* Procedure names are inferred from the object keys.\n* \n* @example\n* const appRouter = router({\n* procedures: {\n* getUser,\n* createUser,\n* internalGetAll,\n* },\n* });\n* \n* export type AppRouter = typeof appRouter;\n*/\nexport function router<TProcedures extends Record<string, AnyProcedure<any>>, TContext = unknown>(\n config: RouterConfig<TProcedures>,\n): Router<TProcedures, TContext> {\n const registry = getContextRegistry(config.contextName ?? \"default\");\n\n // Register all procedures at router creation time\n for (const [name, proc] of Object.entries(config.procedures)) {\n registry.registerProcedure(name, proc);\n }\n\n\n return {\n _type: \"router\",\n procedures: config.procedures,\n contextName: config.contextName ?? \"default\",\n };\n}\n\nexport interface RegisteredProcedure<TContext = unknown> {\n name: string;\n type: \"query\" | \"mutation\" | \"action\" | \"job\";\n internal: boolean;\n inputSchema: AnyProcedure<TContext>[\"inputSchema\"];\n fn: AnyProcedure<TContext>[\"fn\"];\n /** Only present for `type === \"query\"`. See `QueryIdentitySpec`. */\n queryIdentity?: false | string | ((serverCtx: TContext | undefined, input: unknown) => string | null | undefined);\n /** Only present for `type === \"job\"`. Cron expression for recurring jobs. */\n cron?: string;\n}\n\n\nconst contextRegistry = new Map<string, ContextRegistry>();\n\nexport function getContextRegistry(inContext: string): ContextRegistry {\n let registry = contextRegistry.get(inContext);\n if (!registry) {\n registry = new ContextRegistry();\n contextRegistry.set(inContext, registry);\n }\n return registry;\n}\n\nexport class ContextRegistry {\n procedureRegistry = new Map<string, RegisteredProcedure<any>>();\n internalProcedureNames = new Set<string>();\n\n registerProcedure<TContext>(name: string, proc: AnyProcedure<TContext>): void {\n if (this.procedureRegistry.has(name)) {\n throw new Error(\n `[router] Procedure \"${name}\" is already registered. ` +\n `Each procedure name must be unique across the application.`\n );\n }\n\n // Track internal procedures by name\n if (proc.internal) {\n this.markInternalProcedure(name);\n }\n\n const queryIdentity =\n proc.procedureType === \"query\"\n ? (proc as { queryIdentity?: RegisteredProcedure<TContext>[\"queryIdentity\"] }).queryIdentity\n : undefined;\n\n const cron =\n proc.procedureType === \"job\"\n ? (proc as { cron?: string }).cron\n : undefined;\n\n this.procedureRegistry.set(name, {\n name,\n type: proc.procedureType,\n internal: proc.internal,\n inputSchema: proc.inputSchema,\n fn: proc.fn,\n queryIdentity,\n cron,\n });\n }\n\n /** Get a registered procedure by name (runtime lookup) */\n getProcedure<TContext = unknown>(name: string): RegisteredProcedure<TContext> | undefined {\n return this.procedureRegistry.get(name);\n }\n\n /** Get all registered procedure names */\n getProcedureNames(): string[] {\n return [...this.procedureRegistry.keys()];\n }\n\n /** Get all registered procedures */\n getAllProcedures(): Map<string, RegisteredProcedure> {\n return new Map(this.procedureRegistry);\n }\n\n /** Get all registered job procedures (server-only, scheduler-triggered). */\n getJobProcedures(): RegisteredProcedure[] {\n return [...this.procedureRegistry.values()].filter((p) => p.type === \"job\");\n }\n\n /** Clear the registry (for testing only) */\n clearRegistry(): void {\n this.procedureRegistry.clear();\n this.clearInternalProcedures();\n }\n\n markInternalProcedure(name: string): void {\n this.internalProcedureNames.add(name);\n }\n\n isInternalProcedure(name: string): boolean {\n return this.internalProcedureNames.has(name);\n }\n\n clearInternalProcedures(): void {\n this.internalProcedureNames.clear();\n }\n}"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"router-DP2ThAwh.js","names":[],"sources":["../src/router/procedure.ts","../src/router/router.ts"],"sourcesContent":["import type { ZodType } from \"zod\";\nimport type { Span } from \"@opentelemetry/api\";\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 * Minimal request-scoped logger exposed as `ctx.log`. Structurally satisfied by\n * a pino logger, so the server hands its own child logger straight through; the\n * interface keeps handler code decoupled from pino. Bound with `reqId`, the\n * procedure name, and (when tracing is enabled) the `traceId`, so every line a\n * handler writes correlates to its request and trace.\n */\nexport interface HandlerLogger {\n debug(...args: any[]): void;\n info(...args: any[]): void;\n warn(...args: any[]): void;\n error(...args: any[]): void;\n}\n\n/**\n * A {@link HandlerLogger} that discards everything. Used where a handler runs\n * without a real logger — e.g. as `ctx.log` in tests — so `ctx.log` stays\n * non-nullable and handler code never null-checks it.\n */\nexport const noopLogger: HandlerLogger = {\n debug() {},\n info() {},\n warn() {},\n error() {},\n};\n\n/**\n * Observability handles present on a handler context. `log` is ALWAYS present:\n * the server binds a request-correlated logger, and direct internal-caller\n * invocations build a per-procedure child logger from the caller's observability —\n * handlers never null-check it.\n */\nexport interface HandlerObservability {\n /** Logger correlated to this operation — request-scoped (reqId + trace id) on\n * the server path, a per-procedure child logger on internal-caller paths. */\n log: HandlerLogger;\n /** The active OpenTelemetry span for this operation. Add attributes/events or\n * parent child spans off it. A non-recording no-op span when tracing is off. */\n span?: Span;\n}\n\n/**\n * Query context passed to query handlers.\n * Contains database reader and user-defined server context.\n */\n/** Options for the per-handler connection-routing methods (see {@link QueryCtx}). */\nexport interface ConnOpts {\n /**\n * Force the PRIMARY (writer) connection even inside a query/action —\n * read-your-writes. On `useReplicaConn` this overrides the replica choice.\n */\n readOwnWrite?: boolean;\n}\n\nexport interface QueryCtx<TContext = unknown> extends HandlerObservability {\n /** Database reader for queries */\n db: DbReader;\n /** User-defined server context (auth, requestId, etc.) */\n serverCtx?: TContext;\n /**\n * Route this query's reads to the PRIMARY (writer) connection. Must be called\n * BEFORE any read (throws otherwise). A no-op when reads already run on primary\n * (no replica configured, or a primary-only path like a live query).\n */\n usePrimaryConn(opts?: ConnOpts): void;\n /**\n * Route this query's reads to the read REPLICA, if one is configured. Must be\n * called BEFORE any read. `{ readOwnWrite: true }` forces the PRIMARY instead.\n */\n useReplicaConn(opts?: ConnOpts): void;\n}\n\n/**\n * No-op connection routing for query paths that genuinely ALWAYS run on the\n * primary — live subscription re-execution and mutation handlers. Spread into\n * the ctx so `ctx.usePrimaryConn()`/`useReplicaConn()` are always callable but\n * inert (there is only ever the primary connection to bind).\n *\n * For a nested `runQuery` that JOINS a parent transaction, use {@link parentConn}\n * instead — there the connection isn't necessarily the primary.\n */\nexport const primaryOnlyConn: Pick<QueryCtx, \"usePrimaryConn\" | \"useReplicaConn\"> = {\n usePrimaryConn: () => { },\n useReplicaConn: () => { },\n};\n\n/**\n * No-op connection routing for a nested `runQuery` that JOINS a parent\n * transaction (a `runQuery` called with a query/mutation `parentCtx`). The knobs\n * always use the PARENT's connection because the read connection is fixed to the\n * parent transaction's — which may be the PRIMARY or the REPLICA, depending on\n * how the parent query was routed.\n *\n * They MUST be inert: a nested query shares the parent's snapshot + readSet, so\n * calling `useConnection` here would either repoint the parent's connection\n * mid-flight (before its first read) or throw (after it) — either way corrupting\n * the parent transaction. A handler that needs to force primary therefore cannot\n * do so while nested under a replica-routed parent (it inherits the replica,\n * which is already safe w.r.t. the client's `minTs` floor); call it via an\n * action-parent `runQuery` instead, which opens a fresh routed read.\n */\nexport const parentConn: Pick<QueryCtx, \"usePrimaryConn\" | \"useReplicaConn\"> = {\n usePrimaryConn: () => { },\n useReplicaConn: () => { },\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> extends HandlerObservability {\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 * No-op on a mutation — writes (and their reads) always run on the primary.\n * Present so a `MutationCtx` stays structurally assignable to `QueryCtx`, i.e.\n * a mutation can reuse a `(ctx: QueryCtx) => …` read helper.\n */\n usePrimaryConn(opts?: ConnOpts): void;\n /** No-op on a mutation (always primary). See {@link usePrimaryConn}. */\n useReplicaConn(opts?: ConnOpts): void;\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> extends HandlerObservability {\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> extends HandlerObservability {\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 * The parent handler's own logger, carried through to a nested\n * `runQuery`/`runMutation` so the nested call logs under the SAME logger as\n * its parent (reqId/trace correlation preserved).\n */\n log: HandlerLogger;\n}\n\n/**\n * The slice of the server's {@link Observability} an internal caller needs to\n * build per-call loggers (see `createCaller().init({ obs })`). Structural, so an\n * `Observability` instance satisfies it without the caller depending on it.\n */\nexport interface CallerObservability {\n lazyChildLogger(fields: Record<string, unknown>): HandlerLogger;\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 outputSchema?: ZodType<any>;\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 * Optional Zod schema describing return-type overrides for codegen.\n * Only the fields you specify are overridden; everything else is inferred\n * from the handler's TypeScript return type. Use `.modelName(\"Name\")`\n * on a Zod object to rename the generated model class.\n */\n returns?: ZodType<any>;\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 * Optional Zod schema describing return-type overrides for codegen.\n * Only the fields you specify are overridden; everything else is inferred\n * from the handler's TypeScript return type.\n */\n returns?: ZodType<any>;\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 * Optional Zod schema describing return-type overrides for codegen.\n * Only the fields you specify are overridden; everything else is inferred\n * from the handler's TypeScript return type.\n */\n returns?: ZodType<any>;\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 outputSchema: config.returns,\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 outputSchema: config.returns,\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 outputSchema: config.returns,\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}","import type { AnyProcedure } from \"./procedure\";\n\n// ─── Router Types ────────────────────────────────────────────────────────────\n\n/**\n * A router maps procedure names (keys) to their definitions.\n * This is the type that's exported from your app and used by the client.\n */\nexport type Router<TProcedures extends Record<string, AnyProcedure<TContext>>, TContext = unknown> = {\n _type: \"router\";\n procedures: TProcedures;\n contextName: string;\n};\n\n/**\n * Inferred AppRouter type from router() call.\n * Captures the full procedure map for client type inference.\n */\nexport type AppRouter<\n TProcedures extends Record<string, AnyProcedure<TContext>> = Record<string, AnyProcedure>,\n TContext = unknown\n> = Router<TProcedures, TContext>;\n\n// ─── Type Helpers for Client ─────────────────────────────────────────────────\n\n/** Get query procedures only from a router */\nexport type QueryProcedures<T extends Record<string, AnyProcedure>> = {\n [K in keyof T as T[K] extends { procedureType: \"query\" } ? K : never]: T[K];\n};\n\n/** Get mutation procedures only from a router */\nexport type MutationProcedures<T extends Record<string, AnyProcedure>> = {\n [K in keyof T as T[K] extends { procedureType: \"mutation\" } ? K : never]: T[K];\n};\n\n/** Get action procedures only from a router */\nexport type ActionProcedures<T extends Record<string, AnyProcedure>> = {\n [K in keyof T as T[K] extends { procedureType: \"action\" } ? K : never]: T[K];\n};\n\n/** Get job procedures only from a router */\nexport type JobProcedures<T extends Record<string, AnyProcedure>> = {\n [K in keyof T as T[K] extends { procedureType: \"job\" } ? K : never]: T[K];\n};\n\n/** Get public (non-internal) procedures - for client type safety */\nexport type PublicProcedures<T extends Record<string, AnyProcedure>> = Pick<\n T,\n { [K in keyof T]: T[K] extends { internal: true } ? never : K }[keyof T]\n>;\n\n/** Extract procedure names from a router */\nexport type ProcedureNames<T extends Router<any>> =\n T extends Router<infer P> ? keyof P : never;\n\nexport type RouterConfig<T> = {\n procedures: T;\n contextName?: string;\n};\n\n/**\n* Create a router from procedure definitions.\n* Procedure names are inferred from the object keys.\n* \n* @example\n* const appRouter = router({\n* procedures: {\n* getUser,\n* createUser,\n* internalGetAll,\n* },\n* });\n* \n* export type AppRouter = typeof appRouter;\n*/\nexport function router<TProcedures extends Record<string, AnyProcedure<any>>, TContext = unknown>(\n config: RouterConfig<TProcedures>,\n): Router<TProcedures, TContext> {\n const registry = getContextRegistry(config.contextName ?? \"default\");\n\n // Register all procedures at router creation time\n for (const [name, proc] of Object.entries(config.procedures)) {\n registry.registerProcedure(name, proc);\n }\n\n\n return {\n _type: \"router\",\n procedures: config.procedures,\n contextName: config.contextName ?? \"default\",\n };\n}\n\nexport interface RegisteredProcedure<TContext = unknown> {\n name: string;\n type: \"query\" | \"mutation\" | \"action\" | \"job\";\n internal: boolean;\n inputSchema: AnyProcedure<TContext>[\"inputSchema\"];\n fn: AnyProcedure<TContext>[\"fn\"];\n /** Only present for `type === \"query\"`. See `QueryIdentitySpec`. */\n queryIdentity?: false | string | ((serverCtx: TContext | undefined, input: unknown) => string | null | undefined);\n /** Only present for `type === \"job\"`. Cron expression for recurring jobs. */\n cron?: string;\n}\n\n\nconst contextRegistry = new Map<string, ContextRegistry>();\n\nexport function getContextRegistry(inContext: string): ContextRegistry {\n let registry = contextRegistry.get(inContext);\n if (!registry) {\n registry = new ContextRegistry();\n contextRegistry.set(inContext, registry);\n }\n return registry;\n}\n\nexport class ContextRegistry {\n procedureRegistry = new Map<string, RegisteredProcedure<any>>();\n internalProcedureNames = new Set<string>();\n\n registerProcedure<TContext>(name: string, proc: AnyProcedure<TContext>): void {\n if (this.procedureRegistry.has(name)) {\n throw new Error(\n `[router] Procedure \"${name}\" is already registered. ` +\n `Each procedure name must be unique across the application.`\n );\n }\n\n // Track internal procedures by name\n if (proc.internal) {\n this.markInternalProcedure(name);\n }\n\n const queryIdentity =\n proc.procedureType === \"query\"\n ? (proc as { queryIdentity?: RegisteredProcedure<TContext>[\"queryIdentity\"] }).queryIdentity\n : undefined;\n\n const cron =\n proc.procedureType === \"job\"\n ? (proc as { cron?: string }).cron\n : undefined;\n\n this.procedureRegistry.set(name, {\n name,\n type: proc.procedureType,\n internal: proc.internal,\n inputSchema: proc.inputSchema,\n fn: proc.fn,\n queryIdentity,\n cron,\n });\n }\n\n /** Get a registered procedure by name (runtime lookup) */\n getProcedure<TContext = unknown>(name: string): RegisteredProcedure<TContext> | undefined {\n return this.procedureRegistry.get(name);\n }\n\n /** Get all registered procedure names */\n getProcedureNames(): string[] {\n return [...this.procedureRegistry.keys()];\n }\n\n /** Get all registered procedures */\n getAllProcedures(): Map<string, RegisteredProcedure> {\n return new Map(this.procedureRegistry);\n }\n\n /** Get all registered job procedures (server-only, scheduler-triggered). */\n getJobProcedures(): RegisteredProcedure[] {\n return [...this.procedureRegistry.values()].filter((p) => p.type === \"job\");\n }\n\n /** Clear the registry (for testing only) */\n clearRegistry(): void {\n this.procedureRegistry.clear();\n this.clearInternalProcedures();\n }\n\n markInternalProcedure(name: string): void {\n this.internalProcedureNames.add(name);\n }\n\n isInternalProcedure(name: string): boolean {\n return this.internalProcedureNames.has(name);\n }\n\n clearInternalProcedures(): void {\n this.internalProcedureNames.clear();\n }\n}"],"mappings":"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"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $ as
|
|
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 };
|
|
1
|
+
import { $ as ActionProcedures, $n as RawClient, $r as RawReadEntrySchema, $t as ResultOf, Ar as LiveResult, At as QueryFn, Br as PredicateSchema, Cn as ComputedFieldConfig, Cr as CommitLogEntry, Ct as MutationConfig, Dn as InferSchema, Dr as DEFAULT_RETRY, Dt as OutputOf, Er as CompareOperatorSchema, Et as MutationProcedure, Fr as OrPredicate, Ft as createMutationBuilder, G as ClientLogLevel, Gr as QuerySpec, Hn as defineSchema, Hr as QueryCacheEntrySchema, In as SchemaCodecs, Ir as OrPredicateSchema, It as createQueryBuilder, J as HeartbeatOptions, Jn as DbQueryResult, Jr as RawPointRead, Jt as sleep, K as ClientLogger, Kr as RangeRead, Lr as PointRead, Mr as NO_RETRY, Mt as TypeOf, Nr as OccAbortError, Nt as createActionBuilder, On as InsertData, Or as LeafPredicate, Ot as QueryConfig, Pr as OccConflictError, Q as createConsoleLogger, Qr as RawReadEntry, Qt as QueryDefinition, Rn as SchemaColumnsOptions, Rr as PointReadSchema, Sr as CachedPgMetadataSchema, Tr as CompareOperator, Tt as MutationFn, Ur as QueryCacheMetadata, Vn as defineComputedField, Vr as QueryCacheEntry, W as ClientEvent, Wr as QueryCacheMetadataSchema, X as WSClientOptions, Xr as RawRangeRead, Xt as DefsToMap, Y as RPCError, Yr as RawPointReadSchema, Yt as AnyQueryDef, Z as WsClientManager, Zn as PooledClient, Zr as RawRangeReadSchema, Zt as ParamsOf, _n as matchesPredicate, _t as HandlerLogger, a as createCaller, ai as WriteOp, at as PublicProcedures, br as BigIntSchema, c as ClientOptions, ci as normalizeIdToBytes, ct as Router, d as LiveQueryStatus, dt as ActionConfig, ei as ReadEntry, en as _resetGlobalDefs, et as AppRouter, f as WSClientMethods, ft as ActionCtx, gt as ContextOf, ht as AnyProcedure, i as CallerOptions, ii as WriteEntrySchema, in as TxContext, it as ProcedureNames, jr as MutationResult, jt as QueryProcedure, kn as Model, kr as LeafPredicateSchema, kt as QueryCtx, l as LiveQueryHandle, li as normalizeToBytes, mt as ActionProcedure, n as CallerFromProcedures, ni as RetryConfig, nn as DbReader, o as CallOptions, oi as WriteOpSchema, ot as QueryProcedures, p as createClient, pt as ActionFn, q as ClientPublicState, qn as Database, qr as RangeReadSchema, qt as SupaliveDb, r as CallerFromRouter, ri as WriteEntry, rn as DbWriter, rt as MutationProcedures, s as ClientFromProcedures, si as bytesFromJson, st as RegisteredProcedure, t as CallerClientInitConfig, ti as ReadEntrySchema, tn as defineQuery, u as LiveQueryState, ut as router, vr as AndPredicate, vt as HandlerObservability, wr as CommitTs, wt as MutationCtx, xr as CachedPgMetadata, yn as ColumnCodec, yr as AndPredicateSchema, zn as SchemaDefinition, zr as Predicate } from "../../index-B5hAqW3O.js";
|
|
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, CallerClientInitConfig, CallerFromProcedures, CallerFromRouter, CallerOptions, type ClientEvent, type ClientFromProcedures, type ClientLogLevel, type ClientLogger, 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 HandlerLogger, type HandlerObservability, 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, createConsoleLogger, createMutationBuilder, createQueryBuilder, defineComputedField, defineQuery, defineSchema, matchesPredicate, normalizeIdToBytes, normalizeToBytes, router, sleep };
|
package/dist/src/client/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { c as parentConn, i as createActionBuilder, l as primaryOnlyConn, n as getContextRegistry, o as createMutationBuilder, r as router, s as createQueryBuilder } from "../../router-DP2ThAwh.js";
|
|
2
2
|
import { r as supaliveStringify } from "../../helper-zdJT5FUc.js";
|
|
3
|
-
import { o as matchesPredicate } from "../../query-
|
|
3
|
+
import { o as matchesPredicate } from "../../query-LJranz0c.js";
|
|
4
4
|
import { n as defineSchema, t as defineComputedField } from "../../schema-DRtz5h5l.js";
|
|
5
5
|
import { C as normalizeIdToBytes, S as bytesFromJson, _ as RawRangeReadSchema, a as DEFAULT_RETRY, b as WriteEntrySchema, c as OccAbortError, d as PointReadSchema, f as PredicateSchema, g as RawPointReadSchema, h as RangeReadSchema, i as CompareOperatorSchema, l as OccConflictError, m as QueryCacheMetadataSchema, n as BigIntSchema, o as LeafPredicateSchema, p as QueryCacheEntrySchema, r as CachedPgMetadataSchema, s as NO_RETRY, t as AndPredicateSchema, u as OrPredicateSchema, v as RawReadEntrySchema, w as normalizeToBytes, x as WriteOpSchema, y as ReadEntrySchema } from "../../types_db-OUou3o2Z.js";
|
|
6
|
-
import { l as ServerMessageSchema } from "../../types_client_rpc-
|
|
7
|
-
import { a as TxContext, i as DbWriter, n as sleep, r as DbReader, t as SupaliveDb } from "../../realtime_db-
|
|
6
|
+
import { l as ServerMessageSchema } from "../../types_client_rpc-CWZmlWmM.js";
|
|
7
|
+
import { a as TxContext, i as DbWriter, n as sleep, r as DbReader, t as SupaliveDb } from "../../realtime_db-B0Tin87E.js";
|
|
8
8
|
import { n as resolveReadRouting, t as makeConnRouting } from "../../read-routing-BUcQAwnd.js";
|
|
9
9
|
import { sha1 } from "hash-wasm";
|
|
10
10
|
//#region src/db/query_definition.ts
|
|
@@ -78,6 +78,23 @@ var RPCError = class extends Error {
|
|
|
78
78
|
this.code = code;
|
|
79
79
|
}
|
|
80
80
|
};
|
|
81
|
+
const LEVEL_ORDER = {
|
|
82
|
+
debug: 10,
|
|
83
|
+
info: 20,
|
|
84
|
+
warn: 30,
|
|
85
|
+
error: 40
|
|
86
|
+
};
|
|
87
|
+
/** Console-backed logger that drops anything below `level`. `"silent"` mutes all. */
|
|
88
|
+
function createConsoleLogger(level = "warn") {
|
|
89
|
+
const enabled = (l) => level !== "silent" && LEVEL_ORDER[l] >= LEVEL_ORDER[level];
|
|
90
|
+
const noop = () => {};
|
|
91
|
+
return {
|
|
92
|
+
debug: enabled("debug") ? (m, ...a) => console.debug(`[WSClient] ${m}`, ...a) : noop,
|
|
93
|
+
info: enabled("info") ? (m, ...a) => console.info(`[WSClient] ${m}`, ...a) : noop,
|
|
94
|
+
warn: enabled("warn") ? (m, ...a) => console.warn(`[WSClient] ${m}`, ...a) : noop,
|
|
95
|
+
error: enabled("error") ? (m, ...a) => console.error(`[WSClient] ${m}`, ...a) : noop
|
|
96
|
+
};
|
|
97
|
+
}
|
|
81
98
|
var WsClientManager = class {
|
|
82
99
|
ws = null;
|
|
83
100
|
options;
|
|
@@ -123,7 +140,9 @@ var WsClientManager = class {
|
|
|
123
140
|
throttling = false;
|
|
124
141
|
visibilityListener = null;
|
|
125
142
|
onlineListener = null;
|
|
143
|
+
log;
|
|
126
144
|
constructor(options) {
|
|
145
|
+
this.log = options.logger ?? createConsoleLogger(options.logLevel ?? "warn");
|
|
127
146
|
this.options = {
|
|
128
147
|
reconnectionTimeout: 18e4,
|
|
129
148
|
reconnect: {
|
|
@@ -166,6 +185,11 @@ var WsClientManager = class {
|
|
|
166
185
|
if (this.connectionState == "connected" || this.connectionState == "connecting") return;
|
|
167
186
|
this.connectionState = "connecting";
|
|
168
187
|
this.emitState();
|
|
188
|
+
this.log.debug(`connecting to ${this.options.url}`);
|
|
189
|
+
this.emitEvent({
|
|
190
|
+
type: "connecting",
|
|
191
|
+
detail: this.options.url
|
|
192
|
+
});
|
|
169
193
|
return new Promise(async (resolve, reject) => {
|
|
170
194
|
this.pendingConnectResolve = () => {
|
|
171
195
|
this.pendingConnectResolve = null;
|
|
@@ -337,7 +361,8 @@ var WsClientManager = class {
|
|
|
337
361
|
id,
|
|
338
362
|
procedure,
|
|
339
363
|
input,
|
|
340
|
-
minTs: this.highWaterTs > 0n ? this.highWaterTs.toString() : void 0
|
|
364
|
+
minTs: this.highWaterTs > 0n ? this.highWaterTs.toString() : void 0,
|
|
365
|
+
trace: this.traceparent()
|
|
341
366
|
});
|
|
342
367
|
});
|
|
343
368
|
}
|
|
@@ -420,14 +445,15 @@ var WsClientManager = class {
|
|
|
420
445
|
this.subscriptions.delete(pendingKey);
|
|
421
446
|
this.rejectJoiners(parked, err);
|
|
422
447
|
}
|
|
423
|
-
|
|
448
|
+
this.log.warn(`Failed to re-subscribe ${sub.procedure}:`, err);
|
|
424
449
|
}
|
|
425
450
|
});
|
|
426
451
|
this.send({
|
|
427
452
|
type: "subscribe",
|
|
428
453
|
id,
|
|
429
454
|
procedure: sub.procedure,
|
|
430
|
-
input: sub.input
|
|
455
|
+
input: sub.input,
|
|
456
|
+
trace: this.traceparent()
|
|
431
457
|
});
|
|
432
458
|
}
|
|
433
459
|
}
|
|
@@ -529,7 +555,8 @@ var WsClientManager = class {
|
|
|
529
555
|
type: "subscribe",
|
|
530
556
|
id,
|
|
531
557
|
procedure,
|
|
532
|
-
input
|
|
558
|
+
input,
|
|
559
|
+
trace: this.traceparent()
|
|
533
560
|
});
|
|
534
561
|
timeout = setTimeout(() => {
|
|
535
562
|
if (this.pendingRequests.has(id)) {
|
|
@@ -584,11 +611,11 @@ var WsClientManager = class {
|
|
|
584
611
|
try {
|
|
585
612
|
data = JSON.parse(dataValue);
|
|
586
613
|
} catch {
|
|
587
|
-
|
|
614
|
+
this.log.warn("Failed to parse server message as JSON:", dataValue);
|
|
588
615
|
}
|
|
589
616
|
const parsed = ServerMessageSchema.safeParse(data);
|
|
590
617
|
if (!parsed.success) {
|
|
591
|
-
|
|
618
|
+
this.log.warn("Invalid server message:", parsed.error.issues, data);
|
|
592
619
|
return;
|
|
593
620
|
}
|
|
594
621
|
const message = parsed.data;
|
|
@@ -597,6 +624,8 @@ var WsClientManager = class {
|
|
|
597
624
|
this.connectionState = "connected";
|
|
598
625
|
this.reconnectAttempts = 0;
|
|
599
626
|
this.lastSuccessfulConnectionTime = Date.now();
|
|
627
|
+
this.log.info("connected");
|
|
628
|
+
this.emitEvent({ type: "connected" });
|
|
600
629
|
const token = await this.options.token?.();
|
|
601
630
|
if (token) {
|
|
602
631
|
this.authState = "pending";
|
|
@@ -640,7 +669,10 @@ var WsClientManager = class {
|
|
|
640
669
|
this.handleSubscriptionGone(message);
|
|
641
670
|
break;
|
|
642
671
|
case "ping": break;
|
|
643
|
-
default:
|
|
672
|
+
default: {
|
|
673
|
+
const _exhaustive = message;
|
|
674
|
+
this.log.warn("Unhandled server message type:", _exhaustive);
|
|
675
|
+
}
|
|
644
676
|
}
|
|
645
677
|
}
|
|
646
678
|
/**
|
|
@@ -683,7 +715,7 @@ var WsClientManager = class {
|
|
|
683
715
|
try {
|
|
684
716
|
sub.onGone?.(message.reason);
|
|
685
717
|
} catch (e) {
|
|
686
|
-
|
|
718
|
+
this.log.error("onGone listener threw:", e);
|
|
687
719
|
}
|
|
688
720
|
}
|
|
689
721
|
handleClose() {
|
|
@@ -692,6 +724,8 @@ var WsClientManager = class {
|
|
|
692
724
|
this.authState = "pending";
|
|
693
725
|
this.ws = null;
|
|
694
726
|
this.stopInactivityWatchdog();
|
|
727
|
+
this.log.info("disconnected");
|
|
728
|
+
this.emitEvent({ type: "disconnected" });
|
|
695
729
|
this.options.onDisconnect?.();
|
|
696
730
|
this.pendingConnectReject?.(new RPCError("Connection closed before ready", "DISCONNECTED"));
|
|
697
731
|
for (const pending of this.pendingRequests.values()) pending.reject(new RPCError("Connection closed", "DISCONNECTED"));
|
|
@@ -700,6 +734,11 @@ var WsClientManager = class {
|
|
|
700
734
|
if (!this.explicitlyClosed && this.options.reconnect?.enabled) this.scheduleReconnect();
|
|
701
735
|
}
|
|
702
736
|
handleError(err) {
|
|
737
|
+
this.log.warn("connection error:", err);
|
|
738
|
+
this.emitEvent({
|
|
739
|
+
type: "error",
|
|
740
|
+
detail: err.message
|
|
741
|
+
});
|
|
703
742
|
this.options.onError?.(err);
|
|
704
743
|
}
|
|
705
744
|
startInactivityWatchdog() {
|
|
@@ -726,7 +765,7 @@ var WsClientManager = class {
|
|
|
726
765
|
*/
|
|
727
766
|
closeAndReconnect(reason) {
|
|
728
767
|
if (this.connectionState === "disconnected") return;
|
|
729
|
-
|
|
768
|
+
this.log.warn(`closeAndReconnect: ${reason}`);
|
|
730
769
|
const oldWs = this.ws;
|
|
731
770
|
if (oldWs) {
|
|
732
771
|
oldWs.onmessage = null;
|
|
@@ -774,7 +813,7 @@ var WsClientManager = class {
|
|
|
774
813
|
}
|
|
775
814
|
scheduleReconnect() {
|
|
776
815
|
if (this.reconnectAttempts >= (this.options.reconnect?.maxAttempts ?? 5)) {
|
|
777
|
-
|
|
816
|
+
this.log.error("Max reconnection attempts reached");
|
|
778
817
|
const giveUp = new RPCError("Max reconnection attempts reached", "DISCONNECTED");
|
|
779
818
|
for (const q of this.queuedCalls) q.reject(giveUp);
|
|
780
819
|
this.queuedCalls = [];
|
|
@@ -784,9 +823,14 @@ var WsClientManager = class {
|
|
|
784
823
|
const base = (this.options.reconnect?.delay ?? 1e3) * Math.pow(this.options.reconnect?.backoff ?? 1.5, this.reconnectAttempts);
|
|
785
824
|
const delay = base + base * (Math.random() - .5);
|
|
786
825
|
this.reconnectAttempts++;
|
|
826
|
+
this.log.info(`reconnecting (attempt ${this.reconnectAttempts}) in ${Math.round(delay)}ms`);
|
|
827
|
+
this.emitEvent({
|
|
828
|
+
type: "reconnecting",
|
|
829
|
+
attempt: this.reconnectAttempts
|
|
830
|
+
});
|
|
787
831
|
this.reconnectTimer = setTimeout(() => {
|
|
788
832
|
this.connect().catch((err) => {
|
|
789
|
-
|
|
833
|
+
this.log.warn("Reconnection failed:", err);
|
|
790
834
|
});
|
|
791
835
|
}, delay);
|
|
792
836
|
}
|
|
@@ -803,7 +847,17 @@ var WsClientManager = class {
|
|
|
803
847
|
for (const l of this.stateListeners) try {
|
|
804
848
|
l(next);
|
|
805
849
|
} catch (e) {
|
|
806
|
-
|
|
850
|
+
this.log.error("state listener threw:", e);
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
/** Fire the optional structured lifecycle event; never lets a throwing hook
|
|
854
|
+
* break the client. */
|
|
855
|
+
emitEvent(event) {
|
|
856
|
+
if (!this.options.onEvent) return;
|
|
857
|
+
try {
|
|
858
|
+
this.options.onEvent(event);
|
|
859
|
+
} catch (e) {
|
|
860
|
+
this.log.error("onEvent listener threw:", e);
|
|
807
861
|
}
|
|
808
862
|
}
|
|
809
863
|
async ensureConnected() {
|
|
@@ -812,6 +866,10 @@ var WsClientManager = class {
|
|
|
812
866
|
send(message) {
|
|
813
867
|
if (this.ws && this.ws.readyState === WS_OPEN) this.ws.send(supaliveStringify(message));
|
|
814
868
|
}
|
|
869
|
+
/** Current W3C traceparent from the optional hook, or undefined. */
|
|
870
|
+
traceparent() {
|
|
871
|
+
return this.options.getTraceparent?.() ?? void 0;
|
|
872
|
+
}
|
|
815
873
|
cleanup() {
|
|
816
874
|
this.connectionState = "disconnected";
|
|
817
875
|
this.authState = "pending";
|
|
@@ -852,6 +910,10 @@ function createClient(options) {
|
|
|
852
910
|
reconnect: options.reconnect,
|
|
853
911
|
heartbeat: options.heartbeat,
|
|
854
912
|
throttle: options.throttle,
|
|
913
|
+
logger: options.logger,
|
|
914
|
+
logLevel: options.logLevel,
|
|
915
|
+
onEvent: options.onEvent,
|
|
916
|
+
getTraceparent: options.getTraceparent,
|
|
855
917
|
onConnect: options.onConnect,
|
|
856
918
|
onDisconnect: options.onDisConnect
|
|
857
919
|
});
|
|
@@ -1110,7 +1172,7 @@ var LiveQueryHandleImpl = class {
|
|
|
1110
1172
|
* `useReplicaConn()` resolves to the replica whenever one is configured. With no
|
|
1111
1173
|
* replica configured every branch resolves to the primary.
|
|
1112
1174
|
*/
|
|
1113
|
-
async function runRoutedCallerQuery(db, serverCtx, fn) {
|
|
1175
|
+
async function runRoutedCallerQuery(db, serverCtx, fn, log) {
|
|
1114
1176
|
const routing = await resolveReadRouting(db, await db.impl.getLatestSnapshotTimestamp(), 0n);
|
|
1115
1177
|
return (await db.queryInternalOn({
|
|
1116
1178
|
impl: routing.primaryImpl,
|
|
@@ -1119,6 +1181,7 @@ async function runRoutedCallerQuery(db, serverCtx, fn) {
|
|
|
1119
1181
|
return fn({
|
|
1120
1182
|
db: dbCtx,
|
|
1121
1183
|
serverCtx,
|
|
1184
|
+
log,
|
|
1122
1185
|
...makeConnRouting(dbCtx, routing)
|
|
1123
1186
|
});
|
|
1124
1187
|
})).data;
|
|
@@ -1136,13 +1199,19 @@ function createCaller(options) {
|
|
|
1136
1199
|
let db;
|
|
1137
1200
|
let storage;
|
|
1138
1201
|
let scheduler;
|
|
1202
|
+
let obs;
|
|
1139
1203
|
return new Proxy({}, { get(_target, procedureName) {
|
|
1140
1204
|
if (typeof procedureName !== "string") return;
|
|
1141
1205
|
if (procedureName == "init") return async (config) => {
|
|
1142
1206
|
db = config.db;
|
|
1143
1207
|
storage = config.storage;
|
|
1144
1208
|
scheduler = config.scheduler;
|
|
1209
|
+
obs = config.obs;
|
|
1145
1210
|
};
|
|
1211
|
+
const callerLog = () => obs.lazyChildLogger({
|
|
1212
|
+
caller: "internal",
|
|
1213
|
+
procedure: procedureName
|
|
1214
|
+
});
|
|
1146
1215
|
const procedure = registry.getProcedure(procedureName);
|
|
1147
1216
|
if (!procedure) throw new Error(`Procedure "${procedureName}" not found`);
|
|
1148
1217
|
if (registry.isInternalProcedure(procedureName) && !isInternal) throw new Error(`Procedure "${procedureName}" is internal only`);
|
|
@@ -1156,7 +1225,7 @@ function createCaller(options) {
|
|
|
1156
1225
|
query: async (input, serverCtx) => {
|
|
1157
1226
|
if (procedure.type !== "query") throw new Error(`Procedure "${procedureName}" is not a query`);
|
|
1158
1227
|
const validatedInput = validateInput(input);
|
|
1159
|
-
return runRoutedCallerQuery(db, serverCtx, (ctx) => procedure.fn(ctx, validatedInput));
|
|
1228
|
+
return runRoutedCallerQuery(db, serverCtx, (ctx) => procedure.fn(ctx, validatedInput), callerLog());
|
|
1160
1229
|
},
|
|
1161
1230
|
runQuery: async (input, parentCtx) => {
|
|
1162
1231
|
if (procedure.type !== "query") throw new Error(`Procedure "${procedureName}" is not a query`);
|
|
@@ -1165,11 +1234,12 @@ function createCaller(options) {
|
|
|
1165
1234
|
const ctx = {
|
|
1166
1235
|
db: parentCtx.db,
|
|
1167
1236
|
serverCtx: parentCtx.serverCtx,
|
|
1237
|
+
log: parentCtx.log,
|
|
1168
1238
|
...parentConn
|
|
1169
1239
|
};
|
|
1170
1240
|
return procedure.fn(ctx, validatedInput);
|
|
1171
1241
|
}
|
|
1172
|
-
return runRoutedCallerQuery(parentCtx.db, parentCtx.serverCtx, (ctx) => procedure.fn(ctx, validatedInput));
|
|
1242
|
+
return runRoutedCallerQuery(parentCtx.db, parentCtx.serverCtx, (ctx) => procedure.fn(ctx, validatedInput), parentCtx.log);
|
|
1173
1243
|
},
|
|
1174
1244
|
mutate: async (input, serverCtx) => {
|
|
1175
1245
|
if (procedure.type !== "mutation") throw new Error(`Procedure "${procedureName}" is not a mutation`);
|
|
@@ -1178,6 +1248,7 @@ function createCaller(options) {
|
|
|
1178
1248
|
const ctx = {
|
|
1179
1249
|
db: dbCtx,
|
|
1180
1250
|
serverCtx,
|
|
1251
|
+
log: callerLog(),
|
|
1181
1252
|
...primaryOnlyConn
|
|
1182
1253
|
};
|
|
1183
1254
|
return procedure.fn(ctx, validatedInput);
|
|
@@ -1190,6 +1261,7 @@ function createCaller(options) {
|
|
|
1190
1261
|
const ctx = {
|
|
1191
1262
|
db: dbCtx,
|
|
1192
1263
|
serverCtx: parentCtx.serverCtx,
|
|
1264
|
+
log: parentCtx.log,
|
|
1193
1265
|
...primaryOnlyConn
|
|
1194
1266
|
};
|
|
1195
1267
|
if (parentCtx.db instanceof TxContext) ctx.db.appendInternalReadSet(parentCtx.db.internalGetReadSet());
|
|
@@ -1202,6 +1274,7 @@ function createCaller(options) {
|
|
|
1202
1274
|
const ctx = {
|
|
1203
1275
|
db,
|
|
1204
1276
|
serverCtx,
|
|
1277
|
+
log: callerLog(),
|
|
1205
1278
|
storage,
|
|
1206
1279
|
scheduler
|
|
1207
1280
|
};
|
|
@@ -1212,7 +1285,8 @@ function createCaller(options) {
|
|
|
1212
1285
|
const validatedInput = validateInput(input);
|
|
1213
1286
|
const ctx = {
|
|
1214
1287
|
db,
|
|
1215
|
-
serverCtx
|
|
1288
|
+
serverCtx,
|
|
1289
|
+
log: callerLog()
|
|
1216
1290
|
};
|
|
1217
1291
|
return procedure.fn(ctx, validatedInput);
|
|
1218
1292
|
},
|
|
@@ -1222,6 +1296,7 @@ function createCaller(options) {
|
|
|
1222
1296
|
const ctx = {
|
|
1223
1297
|
db: dbCtx,
|
|
1224
1298
|
serverCtx,
|
|
1299
|
+
log: callerLog(),
|
|
1225
1300
|
...primaryOnlyConn
|
|
1226
1301
|
};
|
|
1227
1302
|
return procedure.fn(ctx, validatedInput);
|
|
@@ -1233,6 +1308,6 @@ function createCaller(options) {
|
|
|
1233
1308
|
} });
|
|
1234
1309
|
}
|
|
1235
1310
|
//#endregion
|
|
1236
|
-
export { AndPredicateSchema, BigIntSchema, CachedPgMetadataSchema, CompareOperatorSchema, DEFAULT_RETRY, DbReader, DbReader as ReadContext, DbWriter, DbWriter as WritableContext, LeafPredicateSchema, NO_RETRY, OccAbortError, OccConflictError, OrPredicateSchema, PointReadSchema, PredicateSchema, QueryCacheEntrySchema, QueryCacheMetadataSchema, RPCError, RangeReadSchema, RawPointReadSchema, RawRangeReadSchema, RawReadEntrySchema, ReadEntrySchema, SupaliveDb, TxContext, WriteEntrySchema, WriteOpSchema, WsClientManager, _resetGlobalDefs, bytesFromJson, createActionBuilder, createCaller, createClient, createMutationBuilder, createQueryBuilder, defineComputedField, defineQuery, defineSchema, matchesPredicate, normalizeIdToBytes, normalizeToBytes, router, sleep };
|
|
1311
|
+
export { AndPredicateSchema, BigIntSchema, CachedPgMetadataSchema, CompareOperatorSchema, DEFAULT_RETRY, DbReader, DbReader as ReadContext, DbWriter, DbWriter as WritableContext, LeafPredicateSchema, NO_RETRY, OccAbortError, OccConflictError, OrPredicateSchema, PointReadSchema, PredicateSchema, QueryCacheEntrySchema, QueryCacheMetadataSchema, RPCError, RangeReadSchema, RawPointReadSchema, RawRangeReadSchema, RawReadEntrySchema, ReadEntrySchema, SupaliveDb, TxContext, WriteEntrySchema, WriteOpSchema, WsClientManager, _resetGlobalDefs, bytesFromJson, createActionBuilder, createCaller, createClient, createConsoleLogger, createMutationBuilder, createQueryBuilder, defineComputedField, defineQuery, defineSchema, matchesPredicate, normalizeIdToBytes, normalizeToBytes, router, sleep };
|
|
1237
1312
|
|
|
1238
1313
|
//# sourceMappingURL=index.js.map
|