@supalive/core 1.19.0 → 1.20.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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 { 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\";\nimport pino from \"pino\";\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: pino.LogFn;\n info: pino.LogFn;\n warn: pino.LogFn;\n error: pino.LogFn;\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 * The parent handler's own span, carried through to a nested\n * `runQuery`/`runMutation`. Used ONLY as an explicit fallback parent: the\n * nested call normally links implicitly through the ambient OTEL context\n * (the parent handler already runs inside its operation span's context).\n * This span is consulted only when the ambient context is root — e.g. a\n * detached/fire-and-forget internal call.\n */\n span?: Span;\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
+ {"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\";\nimport pino from \"pino\";\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: pino.LogFn;\n info: pino.LogFn;\n warn: pino.LogFn;\n error: pino.LogFn;\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 /** Object storage (R2 / S3) for server-side reads/writes from a job */\n storage: ObjectStorage;\n /** Job client for scheduling precise one-shots from inside a job */\n scheduler: JobClient;\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 * The parent handler's own span, carried through to a nested\n * `runQuery`/`runMutation`. Used ONLY as an explicit fallback parent: the\n * nested call normally links implicitly through the ambient OTEL context\n * (the parent handler already runs inside its operation span's context).\n * This span is consulted only when the ambient context is root — e.g. a\n * detached/fire-and-forget internal call.\n */\n span?: Span;\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 ActionProcedures, $n as RawClient, $r as RawReadEntry, $t as ResultOf, Ar as LeafPredicateSchema, At as QueryFn, Br as Predicate, Cn as ComputedFieldConfig, Cr as CachedPgMetadataSchema, Ct as MutationConfig, Dn as InferSchema, Dr as CompareOperatorSchema, Dt as OutputOf, Er as CompareOperator, Et as MutationProcedure, Fr as OccConflictError, Ft as createMutationBuilder, G as ClientLogLevel, Gr as QueryCacheMetadataSchema, Hn as defineSchema, Hr as QueryCacheEntry, In as SchemaCodecs, Ir as OrPredicate, It as createQueryBuilder, J as HeartbeatOptions, Jn as DbQueryResult, Jr as RangeReadSchema, Jt as sleep, K as ClientLogger, Kr as QuerySpec, Lr as OrPredicateSchema, Mr as MutationResult, Mt as TypeOf, Nr as NO_RETRY, Nt as createActionBuilder, On as InsertData, Or as DEFAULT_RETRY, Ot as QueryConfig, Pr as OccAbortError, Q as createConsoleLogger, Qr as RawRangeReadSchema, Qt as QueryDefinition, Rn as SchemaColumnsOptions, Rr as PointRead, Sr as CachedPgMetadata, Tr as CommitTs, Tt as MutationFn, Ur as QueryCacheEntrySchema, Vn as defineComputedField, Vr as PredicateSchema, W as ClientEvent, Wr as QueryCacheMetadata, X as WSClientOptions, Xr as RawPointReadSchema, Xt as DefsToMap, Y as RPCError, Yr as RawPointRead, Yt as AnyQueryDef, Z as WsClientManager, Zn as PooledClient, Zr as RawRangeRead, Zt as ParamsOf, _n as matchesPredicate, _t as HandlerLogger, a as createCaller, ai as WriteEntrySchema, at as PublicProcedures, br as AndPredicateSchema, c as ClientOptions, ci as bytesFromJson, ct as Router, d as LiveQueryStatus, dt as ActionConfig, ei as RawReadEntrySchema, en as _resetGlobalDefs, et as AppRouter, f as WSClientMethods, ft as ActionCtx, gt as ContextOf, ht as AnyProcedure, i as CallerOptions, ii as WriteEntry, in as TxContext, it as ProcedureNames, jr as LiveResult, jt as QueryProcedure, kn as Model, kr as LeafPredicate, kt as QueryCtx, l as LiveQueryHandle, li as normalizeIdToBytes, mt as ActionProcedure, n as CallerFromProcedures, ni as ReadEntrySchema, nn as DbReader, o as CallOptions, oi as WriteOp, ot as QueryProcedures, p as createClient, pt as ActionFn, q as ClientPublicState, qn as Database, qr as RangeRead, qt as SupaliveDb, r as CallerFromRouter, ri as RetryConfig, rn as DbWriter, rt as MutationProcedures, s as ClientFromProcedures, si as WriteOpSchema, st as RegisteredProcedure, t as CallerClientInitConfig, ti as ReadEntry, tn as defineQuery, u as LiveQueryState, ui as normalizeToBytes, ut as router, vt as HandlerObservability, wr as CommitLogEntry, wt as MutationCtx, xr as BigIntSchema, yn as ColumnCodec, yr as AndPredicate, zn as SchemaDefinition, zr as PointReadSchema } from "../../index-CKo6HvJc.js";
1
+ import { $ as ActionProcedures, $n as RawClient, $r as RawReadEntry, $t as ResultOf, Ar as LeafPredicateSchema, At as QueryFn, Br as Predicate, Cn as ComputedFieldConfig, Cr as CachedPgMetadataSchema, Ct as MutationConfig, Dn as InferSchema, Dr as CompareOperatorSchema, Dt as OutputOf, Er as CompareOperator, Et as MutationProcedure, Fr as OccConflictError, Ft as createMutationBuilder, G as ClientLogLevel, Gr as QueryCacheMetadataSchema, Hn as defineSchema, Hr as QueryCacheEntry, In as SchemaCodecs, Ir as OrPredicate, It as createQueryBuilder, J as HeartbeatOptions, Jn as DbQueryResult, Jr as RangeReadSchema, Jt as sleep, K as ClientLogger, Kr as QuerySpec, Lr as OrPredicateSchema, Mr as MutationResult, Mt as TypeOf, Nr as NO_RETRY, Nt as createActionBuilder, On as InsertData, Or as DEFAULT_RETRY, Ot as QueryConfig, Pr as OccAbortError, Q as createConsoleLogger, Qr as RawRangeReadSchema, Qt as QueryDefinition, Rn as SchemaColumnsOptions, Rr as PointRead, Sr as CachedPgMetadata, Tr as CommitTs, Tt as MutationFn, Ur as QueryCacheEntrySchema, Vn as defineComputedField, Vr as PredicateSchema, W as ClientEvent, Wr as QueryCacheMetadata, X as WSClientOptions, Xr as RawPointReadSchema, Xt as DefsToMap, Y as RPCError, Yr as RawPointRead, Yt as AnyQueryDef, Z as WsClientManager, Zn as PooledClient, Zr as RawRangeRead, Zt as ParamsOf, _n as matchesPredicate, _t as HandlerLogger, a as createCaller, ai as WriteEntrySchema, at as PublicProcedures, br as AndPredicateSchema, c as ClientOptions, ci as bytesFromJson, ct as Router, d as LiveQueryStatus, dt as ActionConfig, ei as RawReadEntrySchema, en as _resetGlobalDefs, et as AppRouter, f as WSClientMethods, ft as ActionCtx, gt as ContextOf, ht as AnyProcedure, i as CallerOptions, ii as WriteEntry, in as TxContext, it as ProcedureNames, jr as LiveResult, jt as QueryProcedure, kn as Model, kr as LeafPredicate, kt as QueryCtx, l as LiveQueryHandle, li as normalizeIdToBytes, mt as ActionProcedure, n as CallerFromProcedures, ni as ReadEntrySchema, nn as DbReader, o as CallOptions, oi as WriteOp, ot as QueryProcedures, p as createClient, pt as ActionFn, q as ClientPublicState, qn as Database, qr as RangeRead, qt as SupaliveDb, r as CallerFromRouter, ri as RetryConfig, rn as DbWriter, rt as MutationProcedures, s as ClientFromProcedures, si as WriteOpSchema, st as RegisteredProcedure, t as CallerClientInitConfig, ti as ReadEntry, tn as defineQuery, u as LiveQueryState, ui as normalizeToBytes, ut as router, vt as HandlerObservability, wr as CommitLogEntry, wt as MutationCtx, xr as BigIntSchema, yn as ColumnCodec, yr as AndPredicate, zn as SchemaDefinition, zr as PointReadSchema } from "../../index-DsBAE32T.js";
2
2
  export { type ActionConfig, type ActionCtx, type ActionFn, type ActionProcedure, type ActionProcedures, AndPredicate, AndPredicateSchema, type AnyProcedure, type AnyQueryDef, type AppRouter, BigIntSchema, CachedPgMetadata, CachedPgMetadataSchema, type CallOptions, 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 };
@@ -1286,6 +1286,8 @@ function createCaller(options) {
1286
1286
  const validatedInput = validateInput(input);
1287
1287
  const ctx = {
1288
1288
  db,
1289
+ storage,
1290
+ scheduler,
1289
1291
  serverCtx,
1290
1292
  log: callerLog()
1291
1293
  };