@veriforms/webapp-sdk 0.1.4 → 0.1.5

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/README.md CHANGED
@@ -271,7 +271,28 @@ try {
271
271
  - **A newer release (X9):** `409 server_function_version_changed` reloads the page (once per build) and
272
272
  rejects with `ServerFunctionVersionChangedError`; the old code never runs.
273
273
  - **Types:** the plugin writes `vf-server.d.ts` (input and answer of every function, from its
274
- definition); keep it next to `vf-app.d.ts`.
274
+ definition); keep it next to `vf-app.d.ts` and list it in `tsconfig.json`'s `include`. `vf app types`
275
+ (CLI 0.1.51) and `vf app build` write it too, with the plugin's own generator — one source, so the
276
+ file is the same whichever wrote it.
277
+ - **Unit tests (since 0.1.5):** `@veriforms/webapp-sdk/server/testing` gives a fake `ctx`. It is **not
278
+ the gateway** — no row rules, levels, roles, limits or sandbox; those are proven on the draft plane
279
+ (`vf app dev`) and the test version. It keeps what would make a test pass for a function the gateway
280
+ refuses: an undeclared source fails the run even when caught, a read, value or Automation without a
281
+ test answer throws by name (never `undefined`), input and answer go through JSON, and a function for
282
+ signed-in visitors refuses an anonymous user.
283
+
284
+ ```ts
285
+ import { runServerFunction, createTestContext } from '@veriforms/webapp-sdk/server/testing';
286
+ import { placeOrder } from '../src/server/placeOrder';
287
+
288
+ const { output, ctx } = await runServerFunction(placeOrder, { items: [{ id: 'p1' }] }, {
289
+ sources: { products: [{ id: 'p1', price: 10 }] }, // an array reads as a table page
290
+ values: { vat_rate: 0.19 },
291
+ });
292
+ expect(ctx.writes.orders).toHaveLength(1); // what it would have saved
293
+ ```
294
+
295
+ A `*.test.ts` / `*.spec.ts` file in `src/server/` is never built or uploaded (the plugin skips it).
275
296
 
276
297
  ## config.json in your editor
277
298
 
package/dist/index.d.ts CHANGED
@@ -15,7 +15,7 @@
15
15
  *
16
16
  * Concept: docs/webapp-builder/CWA-CODE-APPS-CONCEPT.md (§4.2).
17
17
  */
18
- export declare const SDK_VERSION = "0.1.4";
18
+ export declare const SDK_VERSION = "0.1.5";
19
19
  /**
20
20
  * Augmented by the `vf-app.d.ts` that `vf app types` generates:
21
21
  *
package/dist/index.js CHANGED
@@ -15,7 +15,7 @@
15
15
  *
16
16
  * Concept: docs/webapp-builder/CWA-CODE-APPS-CONCEPT.md (§4.2).
17
17
  */
18
- export const SDK_VERSION = '0.1.4';
18
+ export const SDK_VERSION = '0.1.5';
19
19
  export function isVfRequestError(e) {
20
20
  return e instanceof Error;
21
21
  }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * @veriforms/webapp-sdk/server/testing — a fake `ctx` for unit tests of server functions (R7 batch 4;
3
+ * CWA-CODE-BACKEND-CONCEPT §5.3). PILOT, PLATFORM ADMINISTRATORS ONLY, like server functions themselves.
4
+ *
5
+ * ```ts
6
+ * import { describe, expect, it } from 'vitest';
7
+ * import { createTestContext, runServerFunction } from '@veriforms/webapp-sdk/server/testing';
8
+ * import { placeOrder } from '../src/server/placeOrder';
9
+ *
10
+ * it('stores the order', async () => {
11
+ * const ctx = createTestContext({ sources: { products: [{ id: 'p1', price: 10 }] }, values: { vat_rate: 0.19 } });
12
+ * const { output } = await runServerFunction(placeOrder, { items: [{ id: 'p1' }] }, ctx);
13
+ * expect(ctx.writes.orders).toHaveLength(1);
14
+ * });
15
+ * ```
16
+ *
17
+ * **This is NOT the gateway.** It runs your handler in Node with the data you give it. It does not apply row
18
+ * rules, levels, roles, `allowClientParams`, visitor limits, the input schema's exact checks, the statement or
19
+ * time limits, or the sandbox — those are proven only on the draft plane (`vf app dev`) and the test version.
20
+ * What it does keep from the gateway, so a test cannot pass for a function the gateway would refuse:
21
+ *
22
+ * - `ctx` has exactly the runtime's members (`source`, `values`, `automation`, `user`, `language`, `instance`,
23
+ * `functionName`, `refuse`, `log`, `now`, `uuid`) and is frozen;
24
+ * - a source the definition does not list in `sources` is refused (`server_function_source_undeclared`) and
25
+ * fails the run even when the function catches it — the gateway's rule;
26
+ * - a read, a value or an Automation the test gave no answer for THROWS, naming it — never `undefined` a
27
+ * function could compute with (an unresolvable reference is a fault, not an empty value);
28
+ * - the input and the answer go through JSON, as they do over the wire; an answer that is not JSON fails;
29
+ * - a function for signed-in visitors refuses an anonymous `user` (`server_function_sign_in_required`).
30
+ */
31
+ import type { ServerContext, ServerFunction, ServerVisitor } from './server.js';
32
+ /** What a read of one source answers in a test: rows (wrapped like a table page), a whole answer, or a function of the params. */
33
+ export type TestSourceData = unknown[] | Record<string, unknown> | ((params: Record<string, unknown> | null) => unknown);
34
+ /** What a write to one source answers in a test (default `{ written: n }`), or a function of the body. */
35
+ export type TestWriteAnswer = unknown | ((body: unknown) => unknown);
36
+ export interface TestContextOptions {
37
+ /** Read answers by source key. An array is answered as a table page (`rows`, `rowCount`, …). */
38
+ sources?: Record<string, TestSourceData>;
39
+ /** Write answers by source key (default `{ written: <rows> }`). */
40
+ writeAnswers?: Record<string, TestWriteAnswer>;
41
+ /** Definitions values by key (`ctx.values.get`). */
42
+ values?: Record<string, unknown>;
43
+ /** Automation answers by source key (`ctx.automation.run`); a function gets the input. */
44
+ automations?: Record<string, unknown | ((input: unknown) => unknown)>;
45
+ /** The visitor. Default: signed in (`visitor@example.test`, level `write`, no roles). `null` = anonymous. */
46
+ user?: Partial<ServerVisitor> | null;
47
+ language?: 'de' | 'en';
48
+ instance?: string | null;
49
+ /** The function's route name (default: the definition's name when run with {@link runServerFunction}, else `test`). */
50
+ functionName?: string;
51
+ /**
52
+ * The sources the function may call. {@link runServerFunction} takes them from the definition's `sources`;
53
+ * set them here when you call a handler yourself. Absent = every source (the test then cannot see an
54
+ * undeclared call — use runServerFunction).
55
+ */
56
+ declaredSources?: readonly string[];
57
+ /** A fixed clock for `ctx.now()` (default: the real time). */
58
+ now?: () => string;
59
+ /** Fixed ids for `ctx.uuid()` (default: random). */
60
+ uuid?: () => string;
61
+ }
62
+ /** One data call the function made, in order. */
63
+ export interface TestCall {
64
+ kind: 'read' | 'write' | 'automation.run' | 'automation.start' | 'values';
65
+ key: string;
66
+ data: unknown;
67
+ }
68
+ /** The fake `ctx` plus what the function did with it. */
69
+ export interface TestContext extends ServerContext {
70
+ /** Every data call, in order. */
71
+ readonly calls: TestCall[];
72
+ /** The bodies written, by source key (what the function would have saved). */
73
+ readonly writes: Record<string, unknown[]>;
74
+ /** The Automations started (`automation.start`), by source key, with their input. */
75
+ readonly started: Record<string, unknown[]>;
76
+ /** `ctx.log.*` lines. */
77
+ readonly logs: Array<{
78
+ level: 'info' | 'warn' | 'error';
79
+ text: string;
80
+ }>;
81
+ /** Set when the function broke a gateway rule (an undeclared source): the run fails by it even if caught. */
82
+ readonly violation: TestRunError | null;
83
+ }
84
+ /** A run the gateway would refuse or fail: `code` is the gateway's (`server_function_*`) or the author's (`ctx.refuse`). */
85
+ export declare class TestRunError extends Error {
86
+ readonly code: string;
87
+ constructor(code: string, message: string);
88
+ }
89
+ /** A fake `ctx` for a server function's handler. See the module comment for what it does and does not check. */
90
+ export declare function createTestContext(options?: TestContextOptions): TestContext;
91
+ /** What {@link runServerFunction} answers: the function's output (after the JSON round trip) and the context it ran with. */
92
+ export interface TestRun<O> {
93
+ output: O;
94
+ ctx: TestContext;
95
+ }
96
+ /**
97
+ * Runs a defined server function with a fake context: the access rule, the declared sources (an undeclared
98
+ * call fails the run even if caught), the JSON round trip of input and answer. Rejects with the author's
99
+ * refusal (`ctx.refuse`, an Error named `ServerFunctionRefusal`) or a {@link TestRunError}.
100
+ *
101
+ * Pass the options directly (the definition's `sources` become the declared list), or a context from
102
+ * {@link createTestContext} — give that one `declaredSources: fn.sources` yourself, or it cannot see an
103
+ * undeclared call.
104
+ */
105
+ export declare function runServerFunction<I, O>(fn: ServerFunction<I, O>, input?: I, context?: TestContext | TestContextOptions, name?: string): Promise<TestRun<Awaited<O>>>;
@@ -0,0 +1,204 @@
1
+ /**
2
+ * @veriforms/webapp-sdk/server/testing — a fake `ctx` for unit tests of server functions (R7 batch 4;
3
+ * CWA-CODE-BACKEND-CONCEPT §5.3). PILOT, PLATFORM ADMINISTRATORS ONLY, like server functions themselves.
4
+ *
5
+ * ```ts
6
+ * import { describe, expect, it } from 'vitest';
7
+ * import { createTestContext, runServerFunction } from '@veriforms/webapp-sdk/server/testing';
8
+ * import { placeOrder } from '../src/server/placeOrder';
9
+ *
10
+ * it('stores the order', async () => {
11
+ * const ctx = createTestContext({ sources: { products: [{ id: 'p1', price: 10 }] }, values: { vat_rate: 0.19 } });
12
+ * const { output } = await runServerFunction(placeOrder, { items: [{ id: 'p1' }] }, ctx);
13
+ * expect(ctx.writes.orders).toHaveLength(1);
14
+ * });
15
+ * ```
16
+ *
17
+ * **This is NOT the gateway.** It runs your handler in Node with the data you give it. It does not apply row
18
+ * rules, levels, roles, `allowClientParams`, visitor limits, the input schema's exact checks, the statement or
19
+ * time limits, or the sandbox — those are proven only on the draft plane (`vf app dev`) and the test version.
20
+ * What it does keep from the gateway, so a test cannot pass for a function the gateway would refuse:
21
+ *
22
+ * - `ctx` has exactly the runtime's members (`source`, `values`, `automation`, `user`, `language`, `instance`,
23
+ * `functionName`, `refuse`, `log`, `now`, `uuid`) and is frozen;
24
+ * - a source the definition does not list in `sources` is refused (`server_function_source_undeclared`) and
25
+ * fails the run even when the function catches it — the gateway's rule;
26
+ * - a read, a value or an Automation the test gave no answer for THROWS, naming it — never `undefined` a
27
+ * function could compute with (an unresolvable reference is a fault, not an empty value);
28
+ * - the input and the answer go through JSON, as they do over the wire; an answer that is not JSON fails;
29
+ * - a function for signed-in visitors refuses an anonymous `user` (`server_function_sign_in_required`).
30
+ */
31
+ /** A run the gateway would refuse or fail: `code` is the gateway's (`server_function_*`) or the author's (`ctx.refuse`). */
32
+ export class TestRunError extends Error {
33
+ constructor(code, message) {
34
+ super(message);
35
+ this.name = 'TestRunError';
36
+ this.code = code;
37
+ }
38
+ }
39
+ const clone = (v) => (v === undefined ? null : JSON.parse(JSON.stringify(v)));
40
+ function tablePage(rows) {
41
+ return { rows: clone(rows), rowCount: rows.length, limit: rows.length, offset: 0, hasMore: false, nextOffset: null };
42
+ }
43
+ function randomId() {
44
+ const c = globalThis.crypto;
45
+ if (c?.randomUUID)
46
+ return c.randomUUID();
47
+ return 'xxxxxxxx-xxxx-4xxx-8xxx-xxxxxxxxxxxx'.replace(/x/g, () => Math.floor(Math.random() * 16).toString(16));
48
+ }
49
+ /** A fake `ctx` for a server function's handler. See the module comment for what it does and does not check. */
50
+ export function createTestContext(options = {}) {
51
+ const calls = [];
52
+ const writes = {};
53
+ const started = {};
54
+ const logs = [];
55
+ const state = { violation: null };
56
+ const declared = options.declaredSources ? new Set(options.declaredSources) : null;
57
+ const check = (key) => {
58
+ if (typeof key !== 'string')
59
+ throw new TypeError('ctx.source(key) needs the source key as a string.');
60
+ if (declared && !declared.has(key)) {
61
+ const e = new TestRunError('server_function_source_undeclared', `The function called source "${key}", which its definition does not list in "sources" — the gateway refuses the call and fails the run.`);
62
+ state.violation ?? (state.violation = e);
63
+ throw e;
64
+ }
65
+ return key;
66
+ };
67
+ const source = (key) => {
68
+ const k = check(key);
69
+ const read = (params) => {
70
+ calls.push({ kind: 'read', key: k, data: clone(params ?? null) });
71
+ const data = options.sources?.[k];
72
+ if (data === undefined) {
73
+ throw new TestRunError('test_source_missing', `createTestContext has no read answer for source "${k}": give it in options.sources.`);
74
+ }
75
+ if (typeof data === 'function')
76
+ return clone(data(clone((params ?? null))));
77
+ return Array.isArray(data) ? tablePage(data) : clone(data);
78
+ };
79
+ const write = (body) => {
80
+ const sent = clone(body);
81
+ calls.push({ kind: 'write', key: k, data: sent });
82
+ (writes[k] ?? (writes[k] = [])).push(sent);
83
+ const answer = options.writeAnswers?.[k];
84
+ if (answer === undefined)
85
+ return { written: Array.isArray(sent) ? sent.length : 1 };
86
+ return clone(typeof answer === 'function' ? answer(sent) : answer);
87
+ };
88
+ return Object.freeze({ read, list: read, get: read, write, insert: write, send: write });
89
+ };
90
+ const valueOf = (key) => {
91
+ const k = String(key);
92
+ if (!options.values || !(k in options.values)) {
93
+ throw new TestRunError('value_not_found', `createTestContext has no value "${k}": give it in options.values (the gateway fails an unresolved value, never answers empty).`);
94
+ }
95
+ return clone(options.values[k]);
96
+ };
97
+ const user = options.user === null
98
+ ? Object.freeze({ signedIn: false, email: null, name: null, level: null, roles: Object.freeze([]) })
99
+ : Object.freeze({
100
+ signedIn: options.user?.signedIn ?? true,
101
+ email: options.user?.email ?? 'visitor@example.test',
102
+ name: options.user?.name ?? null,
103
+ level: options.user?.level ?? 'write',
104
+ roles: Object.freeze([...(options.user?.roles ?? [])]),
105
+ });
106
+ const line = (level) => (text) => { logs.push({ level, text: String(text) }); };
107
+ const ctx = {
108
+ source,
109
+ values: Object.freeze({
110
+ get: (key) => { calls.push({ kind: 'values', key: String(key), data: null }); return valueOf(key); },
111
+ getMany: (keys) => {
112
+ if (!Array.isArray(keys))
113
+ throw new TypeError('ctx.values.getMany(keys) needs a list of keys.');
114
+ calls.push({ kind: 'values', key: keys.map(String).join(','), data: null });
115
+ return Object.fromEntries(keys.map((k) => [String(k), valueOf(k)]));
116
+ },
117
+ }),
118
+ automation: Object.freeze({
119
+ run: (key, input) => {
120
+ const k = check(key);
121
+ calls.push({ kind: 'automation.run', key: k, data: clone(input ?? null) });
122
+ const answer = options.automations?.[k];
123
+ if (answer === undefined)
124
+ throw new TestRunError('test_automation_missing', `createTestContext has no answer for Automation source "${k}": give it in options.automations.`);
125
+ return clone(typeof answer === 'function' ? answer(clone(input ?? null)) : answer);
126
+ },
127
+ start: (key, input) => {
128
+ const k = check(key);
129
+ calls.push({ kind: 'automation.start', key: k, data: clone(input ?? null) });
130
+ (started[k] ?? (started[k] = [])).push(clone(input ?? null));
131
+ return { started: true, replayed: false };
132
+ },
133
+ }),
134
+ user: user,
135
+ language: options.language ?? 'de',
136
+ instance: options.instance ?? null,
137
+ functionName: options.functionName ?? 'test',
138
+ refuse: (code, de, en) => {
139
+ const e = new Error(String(en || de || code));
140
+ e.name = 'ServerFunctionRefusal';
141
+ e.code = String(code);
142
+ e.de = de == null ? null : String(de);
143
+ e.en = en == null ? null : String(en);
144
+ return e;
145
+ },
146
+ log: Object.freeze({ info: line('info'), warn: line('warn'), error: line('error') }),
147
+ now: options.now ?? (() => new Date().toISOString()),
148
+ uuid: options.uuid ?? randomId,
149
+ };
150
+ // What the test reads afterwards is not part of the runtime's ctx: non-enumerable, so Object.keys(ctx) is the runtime's list.
151
+ Object.defineProperties(ctx, {
152
+ calls: { value: calls },
153
+ writes: { value: writes },
154
+ started: { value: started },
155
+ logs: { value: logs },
156
+ violation: { get: () => state.violation },
157
+ });
158
+ return Object.freeze(ctx);
159
+ }
160
+ function kebab(name) {
161
+ return name.replace(/([a-z0-9])([A-Z])/g, '$1-$2').replace(/([A-Z])([A-Z][a-z])/g, '$1-$2').toLowerCase();
162
+ }
163
+ /**
164
+ * Runs a defined server function with a fake context: the access rule, the declared sources (an undeclared
165
+ * call fails the run even if caught), the JSON round trip of input and answer. Rejects with the author's
166
+ * refusal (`ctx.refuse`, an Error named `ServerFunctionRefusal`) or a {@link TestRunError}.
167
+ *
168
+ * Pass the options directly (the definition's `sources` become the declared list), or a context from
169
+ * {@link createTestContext} — give that one `declaredSources: fn.sources` yourself, or it cannot see an
170
+ * undeclared call.
171
+ */
172
+ export async function runServerFunction(fn, input, context, name) {
173
+ if (!fn || fn.__vfServerFunction !== true || typeof fn.handler !== 'function') {
174
+ throw new TypeError('runServerFunction(fn) needs a definition made by defineServerFunction(...).');
175
+ }
176
+ const ctx = context && 'calls' in context && 'writes' in context
177
+ ? context
178
+ : createTestContext({ declaredSources: fn.sources ?? [], functionName: name ? kebab(name) : undefined, ...context });
179
+ const access = fn.access ?? 'signedIn';
180
+ const signedInOnly = access === 'signedIn' || (typeof access === 'object' && access.signedIn === true);
181
+ if (signedInOnly && !ctx.user.signedIn) {
182
+ throw new TestRunError('server_function_sign_in_required', 'The function is for signed-in visitors; the test\'s user is anonymous.');
183
+ }
184
+ let output;
185
+ try {
186
+ output = await fn.handler(clone(input ?? null), ctx);
187
+ }
188
+ catch (e) {
189
+ if (ctx.violation)
190
+ throw ctx.violation;
191
+ throw e;
192
+ }
193
+ // The gateway's rule: a broken rule fails the run even when the function caught the refusal.
194
+ if (ctx.violation)
195
+ throw ctx.violation;
196
+ let json;
197
+ try {
198
+ json = JSON.stringify(output);
199
+ }
200
+ catch (e) {
201
+ throw new TestRunError('server_function_output_invalid', `The function's answer is not JSON: ${e.message}`);
202
+ }
203
+ return { output: (json === undefined ? null : JSON.parse(json)), ctx };
204
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@veriforms/webapp-sdk",
3
- "version": "0.1.4",
3
+ "version": "0.1.5",
4
4
  "description": "Typed access to the VeriForms web app runtime (window.VF) for web apps built in code: data sources, tables, submissions, actions, payments, sign-in and pages.",
5
5
  "keywords": [
6
6
  "veriforms",
@@ -25,6 +25,10 @@
25
25
  "types": "./dist/server.d.ts",
26
26
  "import": "./dist/server.js"
27
27
  },
28
+ "./server/testing": {
29
+ "types": "./dist/serverTesting.d.ts",
30
+ "import": "./dist/serverTesting.js"
31
+ },
28
32
  "./config.schema.json": "./config.schema.json"
29
33
  },
30
34
  "types": "./dist/index.d.ts",