1import { Mutation, type MutationOptions } from "./mutation.ts";
2import type { MutationAction, Serializable, SerializableValue } from "./types.ts";
3
4/**
5 * Every element of a fixed argument tuple passes the {@link Serializable} check.
6 *
7 * The recursion deliberately walks head/tail and treats the non-tuple tail as
8 * valid: any construct that inspects the whole tuple instead (`keyof`, `length`,
9 * a mapped type, or `[...infer A]` reconstruction) forces resolution of the
10 * `NoInfer`-wrapped argument type and misfires on the `async function` mutate
11 * form, which is common. The cost is that a purely variadic mutate signature
12 * (`mutate: (...xs: NonSerializable[])`) reaches the `true` base case unchecked;
13 * fixed and leading-fixed parameters are still validated.
14 */
15type AllSerializable<Args extends unknown[]> = Args extends [infer Head, ...infer Tail]
16 ? [Head] extends [Serializable<Head>] ? AllSerializable<Tail> : false
17 : true;
18
19/**
20 * Compile-time guard for the serializable-argument rule, expressed as `define`'s
21 * trailing rest parameter: an empty tuple (nothing to pass) when the rule holds,
22 * a one-element tuple otherwise, so a non-serializable `auth: true` call fails on
23 * argument count at the call site. It rides a separate parameter rather than an
24 * intersection on the options object, which is the sole inference source for
25 * `Args` (via `mutate`) and collapses under intersection; and rather than a
26 * type-parameter bound, which silently goes permissive against inferred
27 * arguments. Scoped and unauthenticated mutations are unconstrained.
28 */
29type SerializableArgsGuard<Args extends unknown[], Auth> = Auth extends true ? AllSerializable<Args> extends true ? []
30 : [error: "auth:true mutation arguments must be serializable"]
31 : [];
32
33export interface MutationClientConfig {
34 context: {};
35 optimisticHelpers: {};
36 userContext: {};
37 authScopes: string;
38}
39
40const defaultDeepEquals = (a: unknown, b: unknown): boolean => JSON.stringify(a) === JSON.stringify(b);
41
42// Declared locally to avoid depending on node types.
43declare const process: { env: { NODE_ENV?: string } };
44
45export interface MutationClientOptions<
46 Context extends object,
47 OptimisticHelpers extends object,
48 UserContext extends object = {},
49 AuthScopes extends string = never,
50> {
51 context: Context;
52 getOptimisticHelpers: (
53 events: OptimisticEvents,
54 ) => OptimisticHelpers;
55 reportError: (message: string, error: unknown) => void;
56 reportSuccess?: (message: string) => void;
57 /**
58 * Compare two values for deep equality. Used with a mutation's `snapshot` to
59 * determine if the optimistic state has changed from the initial snapshot.
60 * @default JSON.stringify based comparison
61 */
62 deepEquals?: (a: unknown, b: unknown) => boolean;
63 /**
64 * When false, all mutation run functions will throw an error.
65 * Useful for preventing mutations during SSR.
66 * @default true
67 */
68 enabled?: boolean;
69 /** To support authenticated mutations, define a function that returns additional context. */
70 userContext?: Reactive<UserContext | null>;
71 /**
72 * Subsets of authentication for different permission levels, used at the
73 * define site with `auth: "<scope>"`. A scoped mutation is allowed only when
74 * a user is available and its scope reads `true`; unlike `auth: true`, it is
75 * never routed to `handleUnauthenticated`.
76 */
77 authScopes?: Record<AuthScopes, Reactive<boolean>>;
78 /**
79 * Called instead of running an authenticated mutation when no user is
80 * available. The action is JSON serializable and can be stored, then passed
81 * to {@linkcode MutationClient.run} once the user signs in.
82 */
83 handleUnauthenticated?: (
84 this: { context: Context },
85 action: MutationAction,
86 mutation: Mutation<SerializableValue[], unknown>,
87 ) => void;
88}
89
90export interface Reactive<T> {
91 get: () => T;
92 sub: (onChange: () => void) => () => void;
93}
94
95export interface OptimisticEvents {
96 onRestore: (cb: () => void) => void;
97 onRefetch: (cb: () => Promise<void>) => void;
98}
99
100export class MutationClient<
101 Context extends object,
102 OptimisticHelpers extends object,
103 UserContext extends object = {},
104 AuthScopes extends string = never,
105> {
106 context: Context;
107 userContext?: Reactive<UserContext | null>;
108 authScopes?: { [scope: string]: Reactive<boolean> };
109 handleUnauthenticated?: (action: MutationAction, mutation: Mutation<SerializableValue[], unknown>) => void;
110 getOptimisticHelpers: (event: OptimisticEvents) => OptimisticHelpers;
111 reportError: (message: string, error: unknown) => void;
112 reportSuccess?: (message: string) => void;
113 deepEquals: (a: unknown, b: unknown) => boolean;
114 enabled: boolean;
115 #mutations: Map<string, Mutation<SerializableValue[], unknown>> = new Map();
116
117 constructor(options: MutationClientOptions<Context, OptimisticHelpers, UserContext, AuthScopes>) {
118 this.context = options.context;
119 this.userContext = options.userContext;
120 this.authScopes = options.authScopes;
121 this.handleUnauthenticated = options.handleUnauthenticated;
122 this.getOptimisticHelpers = options.getOptimisticHelpers;
123 this.reportError = options.reportError;
124 this.reportSuccess = options.reportSuccess;
125 this.deepEquals = options.deepEquals ?? defaultDeepEquals;
126 this.enabled = options.enabled ?? true;
127 }
128
129 /**
130 * Define a standard mutation.
131 *
132 * Only an `auth: true` mutation attempted without a user builds a serializable
133 * {@link MutationAction} for replay after sign-in, so only its arguments must
134 * be serializable, enforced by {@link SerializableArgsGuard}. That check is a
135 * {@link Serializable} mapped type rather than a concrete value type so
136 * `interface` arguments type-check, and the leaf set stays extensible via
137 * {@link SerializableLeaves}. Scoped (`auth: "<scope>"`) and unauthenticated
138 * mutations never produce an action and leave their arguments unconstrained.
139 */
140 define<
141 const Args extends unknown[],
142 Result,
143 const Auth extends boolean | AuthScopes = false,
144 >(
145 options: MutationOptions<
146 Args,
147 Result,
148 Auth,
149 { context: Context; optimisticHelpers: OptimisticHelpers; userContext: UserContext; authScopes: AuthScopes }
150 >,
151 ..._serializable: SerializableArgsGuard<NoInfer<Args>, NoInfer<Auth>>
152 ): Mutation<Args, Result> {
153 if (typeof options.auth === "string" && !this.authScopes?.[options.auth]) {
154 throw new Error(`Unknown auth scope "${options.auth}".`);
155 }
156 if (this.#mutations.has(options.id)) {
157 // Hot reload re-evaluates defining modules against the same client, so
158 // a duplicate is assumed to be a replacement unless this is positively
159 // a production build. The `typeof` guard supports unbundled browsers;
160 // bundled browser builds inline NODE_ENV but leave `typeof process`
161 // alone, which downgrades them to the replace-and-warn path.
162 if (typeof process !== "undefined" && process.env.NODE_ENV === "production") {
163 throw new Error(`Mutation id "${options.id}" is already registered.`);
164 }
165 console.error(`Mutation id "${options.id}" registered twice; assuming hot reload and replacing it.`);
166 }
167 const mutation = new Mutation<Args, Result>(
168 this,
169 // `Mutation` runs these with this client's context and helpers.
170 options as MutationOptions<Args, Result, boolean | string, MutationClientConfig>,
171 );
172 this.#mutations.set(options.id, mutation as unknown as Mutation<SerializableValue[], unknown>);
173 return mutation;
174 }
175
176 /**
177 * Re-run a mutation from a stored {@linkcode MutationAction}, such as one
178 * captured by `handleUnauthenticated` before the user signed in. Results are
179 * reported through the global handlers.
180 */
181 run(action: Pick<MutationAction, "id" | "args">): void {
182 const mutation = this.#mutations.get(action.id);
183 if (!mutation) throw new Error(`Mutation id "${action.id}" is not registered.`);
184 mutation.run(...action.args);
185 }
186}