primitive-functions 0.3.0-alpha.8 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/testing.d.ts ADDED
@@ -0,0 +1,323 @@
1
+ /**
2
+ * Test doubles for a server function's `ctx` and `step`, for unit tests that
3
+ * run a handler offline under Node.
4
+ *
5
+ * ```ts
6
+ * import { createTestContext, createTestStep } from "primitive-functions/testing";
7
+ *
8
+ * const ctx = createTestContext({
9
+ * runId: "run-1",
10
+ * configVar: async () => "doc-1",
11
+ * });
12
+ * const step = createTestStep();
13
+ *
14
+ * await handler(input, ctx, step);
15
+ * ```
16
+ *
17
+ * Override only the members the test reads. The override types are derived
18
+ * from `FunctionContext` and `FunctionStep`, so an override that no longer
19
+ * matches the declaration is a compile error. A member the test did not
20
+ * override throws `TEST_MEMBER_NOT_PROVIDED`, naming itself, when it is called
21
+ * (or, for a data member such as `ctx.runId`, read).
22
+ *
23
+ * For an object-form handler, pass `auth` (what `authorize` resolved) and,
24
+ * when the code under test checks the caller again, `reauthorize`. With
25
+ * either, the result is typed `FunctionContext & FunctionAuthorizedContext`:
26
+ *
27
+ * ```ts
28
+ * const ctx = createTestContext({
29
+ * auth: { userId: "member" },
30
+ * reauthorize: async () => ({ userId: "member" }),
31
+ * });
32
+ * ```
33
+ *
34
+ * With `auth` given, `reauthorize` must resolve the `auth` type. A deny fake
35
+ * rejects instead, as `authorize` does: `async () => { throw … }`.
36
+ *
37
+ * For tests only: a function bundle that imports this module is refused by
38
+ * `config push`.
39
+ *
40
+ * @module
41
+ */
42
+
43
+ import type {
44
+ Db3Handle,
45
+ Db3ModelNames,
46
+ Db3TypeKeys,
47
+ FunctionAuthorizedContext,
48
+ FunctionContext,
49
+ FunctionStep,
50
+ } from "primitive-functions";
51
+
52
+ type AnyFunction = (...args: any) => any;
53
+
54
+ // Each declared call signature of `T` as an `[args, result]` pair. Matching
55
+ // four signatures yields each overload once, and a single signature once. A
56
+ // generic signature's type parameters take their constraints here, so a
57
+ // signature keyed by a db3 type or a model name is split by key below.
58
+ //
59
+ // Against several target signatures TypeScript checks a generic source with
60
+ // its type parameters erased to `any`, so a lone generic signature whose
61
+ // result depends on its key (`ctx.prompts.run` once a tree declares a prompt)
62
+ // fails the four-signature match. Such a signature is matched alone.
63
+ type Signatures<T> = T extends {
64
+ (...args: infer A1): infer R1;
65
+ (...args: infer A2): infer R2;
66
+ (...args: infer A3): infer R3;
67
+ (...args: infer A4): infer R4;
68
+ }
69
+ ? [A1, R1] | [A2, R2] | [A3, R3] | [A4, R4]
70
+ : T extends (...args: infer A) => infer R
71
+ ? [A, R]
72
+ : never;
73
+
74
+ // The intersection of `F<K>` for each `K` of a union, each `F<K>` kept whole
75
+ // (a union of overload overrides stays a union inside it).
76
+ type EachOf<U> = (U extends unknown ? (x: U) => void : never) extends (x: infer I) => void ? I : never;
77
+
78
+ // `FunctionContext` as declared, to instantiate `ctx.db3`'s typed overloads
79
+ // for one db3 type at a time. Not exported (see `export {}` at the end).
80
+ declare const declaredContext: FunctionContext;
81
+ type TypedDb3<K extends Db3TypeKeys> = typeof declaredContext.db3<K>;
82
+
83
+ type Db3TypeOverride<K> = K extends Db3TypeKeys ? { override: TestFunctionOverride<TypedDb3<K>> } : never;
84
+
85
+ type Db3ModelOverride<TModels, TQueries, M> = M extends keyof TModels
86
+ ? { override: TestFunctionOverride<Db3Handle<Pick<TModels, M>, TQueries>["model"]> }
87
+ : never;
88
+
89
+ // `model` on a typed db3 handle, one model name at a time: what an override
90
+ // returns for a name must fit that model's row, and an override that takes no
91
+ // name, or any name, answers for every model of the type.
92
+ type Db3HandleModelOverride<TModels, TQueries> = string extends Db3ModelNames<TModels>
93
+ ? TestFunctionOverride<Db3Handle<TModels, TQueries>["model"]>
94
+ : EachOf<Db3ModelOverride<TModels, TQueries, Db3ModelNames<TModels>>> extends infer O
95
+ ? O extends { override: unknown }
96
+ ? O["override"]
97
+ : never
98
+ : never;
99
+
100
+ // An object whose every member is a function or, recursively, another such
101
+ // object: a namespace of `ctx` (`ctx.users`, `ctx.api.groups`).
102
+ type IsNamespace<T> = [T] extends [object]
103
+ ? [T] extends [AnyFunction]
104
+ ? false
105
+ : [keyof T] extends [never]
106
+ ? false
107
+ : false extends { [K in keyof T]-?: T[K] extends AnyFunction ? true : IsNamespace<T[K]> }[keyof T]
108
+ ? false
109
+ : true
110
+ : false;
111
+
112
+ /**
113
+ * What a function override may be for a member declared as `T`: a function
114
+ * whose parameters match one of `T`'s declared signatures and whose result is
115
+ * a {@link TestPartialResult} of that signature's result.
116
+ *
117
+ * An overloaded member accepts an implementation of any one overload; annotate
118
+ * its parameters, since no single overload types them.
119
+ *
120
+ * @beta
121
+ */
122
+ export type TestFunctionOverride<T> =
123
+ Signatures<T> extends infer S
124
+ ? S extends [infer A extends any[], infer R]
125
+ ? (...args: A) => TestPartialResult<R>
126
+ : never
127
+ : never;
128
+
129
+ /**
130
+ * What a `ctx.db3` override may be: a {@link TestFunctionOverride} of
131
+ * `ctx.db3`. In a tree whose pushed types declare db3 types, its typed call
132
+ * forms are checked one declared type at a time, and a typed handle's `model`
133
+ * one model name at a time: an override that takes no `type` (or any `type`)
134
+ * returns a handle that must fit every declared type, so a field of the wrong
135
+ * type in a row it returns is a compile error. Leave the `type` parameter off
136
+ * a `db3` override, or type it `string`.
137
+ *
138
+ * @beta
139
+ */
140
+ export type TestDb3Override = string extends Db3TypeKeys
141
+ ? TestFunctionOverride<FunctionContext["db3"]>
142
+ : EachOf<Db3TypeOverride<Db3TypeKeys>> extends infer O
143
+ ? O extends { override: unknown }
144
+ ? O["override"]
145
+ : never
146
+ : never;
147
+
148
+ /**
149
+ * A declared result with every field optional, at any depth: through a
150
+ * `Promise`, into objects and arrays, and into the functions the result holds
151
+ * (whose own results are partial in the same way). A field the override does
152
+ * return keeps its declared type.
153
+ *
154
+ * ```ts
155
+ * // ctx.db3 returns a handle; the test returns only what its code calls.
156
+ * createTestContext({ db3: () => ({ model: () => ({ query }) }) });
157
+ * ```
158
+ *
159
+ * The double does not complete what an override returns: a method the test
160
+ * left out of a partial handle is simply absent.
161
+ *
162
+ * @beta
163
+ */
164
+ export type TestPartialResult<T> =
165
+ T extends PromiseLike<infer U>
166
+ ? Promise<TestPartialResult<U>>
167
+ : T extends AnyFunction
168
+ ? TestFunctionOverride<T>
169
+ : T extends Db3Handle<infer TModels, infer TQueries>
170
+ ? { [K in keyof T]?: K extends "model" ? Db3HandleModelOverride<TModels, TQueries> : TestPartialResult<T[K]> }
171
+ : T extends object
172
+ ? // `& object` keeps a primitive from passing for an object where
173
+ // TypeScript skips its all-optional ("weak") type check: inside
174
+ // the per-type and per-model intersections above.
175
+ { [K in keyof T]?: TestPartialResult<T[K]> } & object
176
+ : T;
177
+
178
+ /**
179
+ * The override for one member declared as `T`: a {@link TestNamespaceOverrides}
180
+ * for a namespace, a {@link TestFunctionOverride} for a function, and a value of
181
+ * the declared type for a data member.
182
+ *
183
+ * @beta
184
+ */
185
+ export type TestMemberOverride<T> =
186
+ IsNamespace<T> extends true
187
+ ? TestNamespaceOverrides<T>
188
+ : [T] extends [AnyFunction]
189
+ ? TestFunctionOverride<T>
190
+ : T;
191
+
192
+ /**
193
+ * Overrides for a namespace declared as `T`, every member optional. At run
194
+ * time a namespace override must be a plain object (an object literal, or one
195
+ * with a `null` prototype): the double builds its own namespace from the
196
+ * members it holds, so every member the test left out throws by name. A class
197
+ * instance, an array or a function is refused when the double is created; the
198
+ * type cannot tell a class instance from a plain object of the same shape.
199
+ *
200
+ * @beta
201
+ */
202
+ export type TestNamespaceOverrides<T> = { [K in keyof T]?: TestMemberOverride<T[K]> };
203
+
204
+ /**
205
+ * The overrides {@link createTestContext} accepts: any member of
206
+ * `FunctionContext`, each typed from its declaration, plus `auth` and
207
+ * `reauthorize` for an object-form handler.
208
+ *
209
+ * @typeParam TAuth - The type of `ctx.auth`, inferred from the `auth` override.
210
+ * A `reauthorize` override is checked against it and does not widen it.
211
+ * @beta
212
+ */
213
+ export type TestContextOverrides<TAuth = unknown> = Omit<TestNamespaceOverrides<FunctionContext>, "db3"> & {
214
+ /** `ctx.db3`: see {@link TestDb3Override}. */
215
+ db3?: TestDb3Override;
216
+ /** `ctx.auth` for an object-form handler: what its `authorize` resolved. */
217
+ auth?: TAuth;
218
+ /**
219
+ * `ctx.reauthorize` for an object-form handler: what asking `authorize`
220
+ * again resolves, or a rejection for a deny. Checked against the `auth`
221
+ * type; it does not widen it. Left out, calling it throws
222
+ * `TEST_MEMBER_NOT_PROVIDED`.
223
+ */
224
+ reauthorize?: FunctionAuthorizedContext<NoInfer<TAuth>>["reauthorize"];
225
+ };
226
+
227
+ /**
228
+ * The overrides {@link createTestStep} accepts: any member of `FunctionStep`,
229
+ * with its declared type. A `do` override must handle both call forms,
230
+ * `do(name, body)` and `do(name, config, body)`, as the declaration does.
231
+ *
232
+ * @beta
233
+ */
234
+ export type TestStepOverrides = Partial<FunctionStep>;
235
+
236
+ /**
237
+ * Build a `FunctionContext` for a unit test.
238
+ *
239
+ * Every member the overrides do not set is still present: a function
240
+ * (`reauthorize` among them) throws an `Error` named
241
+ * `TEST_MEMBER_NOT_PROVIDED`, whose `member` is the dotted path
242
+ * (`ctx.users.send`), when called; a required data member (`user`, `trigger`,
243
+ * `runtime`, `runId`, `sliceId`, and `auth`) throws the same error when read;
244
+ * `tool` reads `undefined`.
245
+ *
246
+ * With an `auth` or a `reauthorize` override, the result is typed
247
+ * `FunctionContext & FunctionAuthorizedContext`. With `auth` given, `auth`
248
+ * alone fixes the type of `ctx.auth`, and `reauthorize` must resolve that
249
+ * type; without it, the type is what `reauthorize` resolves.
250
+ *
251
+ * Throws a `TypeError` naming the path when an override key is not a member of
252
+ * `FunctionContext`, when a function member is given something other than a
253
+ * function, or when a namespace override is not a plain object.
254
+ *
255
+ * @typeParam TAuth - The type of `ctx.auth`, inferred from the `auth` override.
256
+ * @typeParam TReauthorize - The `reauthorize` override's own type, inferred
257
+ * from it. Left at its default `never` (no override, or explicit type
258
+ * arguments), it means no override was given, so a call with explicit type
259
+ * arguments and a `reauthorize` override resolves to the next signature.
260
+ * @typeParam TFresh - What the `reauthorize` override resolves, inferred from
261
+ * it: the type of `ctx.auth` when there is no `auth` override.
262
+ * @param overrides - The members the test provides.
263
+ * @returns A fresh context; with an `auth` or `reauthorize` override (or an
264
+ * explicit `TAuth`), typed `FunctionContext & FunctionAuthorizedContext`.
265
+ * @beta
266
+ */
267
+ export declare function createTestContext<TAuth = never, TReauthorize = never, TFresh = never>(
268
+ overrides?: Omit<TestNamespaceOverrides<FunctionContext>, "db3"> & {
269
+ db3?: TestDb3Override;
270
+ auth?: TAuth;
271
+ reauthorize?: TReauthorize & (() => Promise<[TAuth] extends [never] ? TFresh : NoInfer<TAuth>>);
272
+ }
273
+ ): [TAuth] extends [never]
274
+ ? [TReauthorize] extends [never]
275
+ ? FunctionContext
276
+ : // A spy's `any` result infers nothing for `TFresh`; keep it `any`.
277
+ FunctionContext &
278
+ FunctionAuthorizedContext<
279
+ TReauthorize extends (...args: any) => infer R ? (0 extends 1 & R ? any : TFresh) : TFresh
280
+ >
281
+ : FunctionContext & FunctionAuthorizedContext<TAuth>;
282
+ /**
283
+ * {@link createTestContext} with an explicit `TAuth` and a `reauthorize`
284
+ * override: the override resolves `TAuth`, and the result is always typed
285
+ * `FunctionContext & FunctionAuthorizedContext<TAuth>`, `TAuth` of `never`
286
+ * (a deny fake) included.
287
+ *
288
+ * @beta
289
+ */
290
+ export declare function createTestContext<TAuth>(
291
+ overrides: Omit<TestContextOverrides<TAuth>, "reauthorize"> & {
292
+ reauthorize: FunctionAuthorizedContext<NoInfer<TAuth>>["reauthorize"];
293
+ }
294
+ ): FunctionContext & FunctionAuthorizedContext<TAuth>;
295
+ /**
296
+ * {@link createTestContext} for overrides typed {@link TestContextOverrides},
297
+ * as a generic helper passes them on: `createTestContext<A>(overrides)`.
298
+ *
299
+ * @beta
300
+ */
301
+ export declare function createTestContext<TAuth = never>(
302
+ overrides?: TestContextOverrides<TAuth>
303
+ ): [TAuth] extends [never] ? FunctionContext : FunctionContext & FunctionAuthorizedContext<TAuth>;
304
+
305
+ /**
306
+ * Build a `FunctionStep` for a unit test.
307
+ *
308
+ * `step.do(name, body)` and `step.do(name, config, body)` run the body once
309
+ * and resolve to its value, or reject with what it threw, as a request-runtime
310
+ * step does. `sleep`, `sleepUntil` and `waitForEvent` throw
311
+ * `TEST_MEMBER_NOT_PROVIDED` unless overridden.
312
+ *
313
+ * Throws a `TypeError` naming the path when an override key is not a member of
314
+ * `FunctionStep` or is not a function.
315
+ *
316
+ * @param overrides - The members the test provides.
317
+ * @returns A fresh step.
318
+ * @beta
319
+ */
320
+ export declare function createTestStep(overrides?: TestStepOverrides): FunctionStep;
321
+
322
+ // Keeps the declarations above without an `export` keyword private to this module.
323
+ export {};
package/testing.js ADDED
@@ -0,0 +1,150 @@
1
+ // Test doubles for a server function's `ctx` and `step`. See testing.d.ts.
2
+ //
3
+ // Unlike the package's main entry, which the platform replaces at invoke
4
+ // time, this module is real code: it runs under Node with no platform, for
5
+ // unit tests only. Each double is a plain object built from the member tree
6
+ // `pnpm functions:profile` generates from the declaration, so every declared
7
+ // member is present — not a Proxy, which would answer `then`, `toJSON` and
8
+ // every other probe a test runner makes.
9
+
10
+ import { TEST_MEMBERS } from "./testing-members.generated.js";
11
+
12
+ const NOT_PROVIDED = "TEST_MEMBER_NOT_PROVIDED";
13
+
14
+ const hasOwn = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
15
+
16
+ function isPlainObject(value) {
17
+ if (value === null || typeof value !== "object") return false;
18
+ const prototype = Object.getPrototypeOf(value);
19
+ return prototype === Object.prototype || prototype === null;
20
+ }
21
+
22
+ // `ctx.users.send` → `{ users: { send: … } }`: the override that provides it.
23
+ function overrideFor(member) {
24
+ return member
25
+ .split(".")
26
+ .slice(1)
27
+ .reduceRight((inner, key) => `{ ${key}: ${inner} }`, "…");
28
+ }
29
+
30
+ function notProvided(member, factory) {
31
+ const error = new Error(
32
+ `${member} was not provided to the test double: pass it to ${factory}() as ${overrideFor(member)}`
33
+ );
34
+ error.name = NOT_PROVIDED;
35
+ error.member = member;
36
+ return error;
37
+ }
38
+
39
+ function refused(member, problem) {
40
+ const error = new TypeError(`${member} ${problem}`);
41
+ error.member = member;
42
+ return error;
43
+ }
44
+
45
+ // Refuse what the double cannot honour, before anything is built.
46
+ function validate(tree, overrides, path, extraKeys) {
47
+ if (!isPlainObject(overrides)) {
48
+ throw refused(path, "must be a plain object of overrides (an object literal), not a class instance, array, function or primitive");
49
+ }
50
+ for (const key of Reflect.ownKeys(overrides)) {
51
+ const member = `${path}.${String(key)}`;
52
+ if (typeof key === "symbol" || !hasOwn(tree, key)) {
53
+ if (typeof key === "string" && extraKeys.includes(key)) continue;
54
+ throw refused(member, "is not a declared member, so it cannot be overridden");
55
+ }
56
+ const kind = tree[key];
57
+ const value = overrides[key];
58
+ if (kind === "fn") {
59
+ if (typeof value !== "function") throw refused(member, "is a function: its override must be a function");
60
+ } else if (typeof kind === "object") {
61
+ validate(kind, value, member, []);
62
+ }
63
+ }
64
+ }
65
+
66
+ function throwingMember(member, factory) {
67
+ return function notProvidedMember() {
68
+ throw notProvided(member, factory);
69
+ };
70
+ }
71
+
72
+ // A data member the test did not set: throws on read, and a test may still
73
+ // assign it later. Non-enumerable, so spreading or printing the double never
74
+ // reads it.
75
+ function defineThrowingData(target, key, member, factory) {
76
+ Object.defineProperty(target, key, {
77
+ configurable: true,
78
+ enumerable: false,
79
+ get() {
80
+ throw notProvided(member, factory);
81
+ },
82
+ set(value) {
83
+ Object.defineProperty(this, key, { value, writable: true, enumerable: true, configurable: true });
84
+ },
85
+ });
86
+ }
87
+
88
+ function build(tree, overrides, path, factory) {
89
+ const built = {};
90
+ for (const [key, kind] of Object.entries(tree)) {
91
+ const member = `${path}.${key}`;
92
+ const given = hasOwn(overrides, key);
93
+ if (typeof kind === "object") {
94
+ // A namespace is always the double's own object, so every member the
95
+ // test left out is present and throws by name.
96
+ built[key] = build(kind, given ? overrides[key] : {}, member, factory);
97
+ } else if (given) {
98
+ built[key] = overrides[key];
99
+ } else if (kind === "fn") {
100
+ built[key] = throwingMember(member, factory);
101
+ } else if (kind === "data") {
102
+ defineThrowingData(built, key, member, factory);
103
+ }
104
+ // "data?" not given: absent, so it reads `undefined`.
105
+ }
106
+ return built;
107
+ }
108
+
109
+ /**
110
+ * Build a `FunctionContext` for a unit test. See testing.d.ts.
111
+ *
112
+ * @param {object} [overrides] The members the test provides.
113
+ * @returns {object} A fresh context.
114
+ */
115
+ export function createTestContext(overrides = {}) {
116
+ // `auth` and `reauthorize` are `FunctionAuthorizedContext`'s members, which
117
+ // the generated tree (rendered from `FunctionContext`) does not hold.
118
+ validate(TEST_MEMBERS.ctx, overrides, "ctx", ["auth", "reauthorize"]);
119
+ if (hasOwn(overrides, "reauthorize") && typeof overrides.reauthorize !== "function") {
120
+ throw refused("ctx.reauthorize", "is a function: its override must be a function");
121
+ }
122
+ const ctx = build(TEST_MEMBERS.ctx, overrides, "ctx", "createTestContext");
123
+ if (hasOwn(overrides, "auth")) ctx.auth = overrides.auth;
124
+ else defineThrowingData(ctx, "auth", "ctx.auth", "createTestContext");
125
+ ctx.reauthorize = hasOwn(overrides, "reauthorize")
126
+ ? overrides.reauthorize
127
+ : throwingMember("ctx.reauthorize", "createTestContext");
128
+ return ctx;
129
+ }
130
+
131
+ /**
132
+ * Build a `FunctionStep` for a unit test. See testing.d.ts.
133
+ *
134
+ * @param {object} [overrides] The members the test provides.
135
+ * @returns {object} A fresh step.
136
+ */
137
+ export function createTestStep(overrides = {}) {
138
+ validate(TEST_MEMBERS.step, overrides, "step", []);
139
+ const step = build(TEST_MEMBERS.step, overrides, "step", "createTestStep");
140
+ if (!hasOwn(overrides, "do")) {
141
+ // The request runtime's rule: the body is the second argument, or the
142
+ // third after a config; it runs once and its result is the step's.
143
+ step.do = async (name, configOrBody, maybeBody) => {
144
+ const body = typeof configOrBody === "function" ? configOrBody : maybeBody;
145
+ if (typeof body !== "function") throw new TypeError(`step.do("${name}") requires a function body`);
146
+ return body();
147
+ };
148
+ }
149
+ return step;
150
+ }