@veriforms/webapp-sdk 0.1.3 → 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
@@ -5,9 +5,27 @@ Typed access to the VeriForms web app runtime, for web apps built in code
5
5
 
6
6
  ## Install
7
7
 
8
+ The VeriForms CLI writes the project (batch 236c): `vf app init <appId>` for a web app created with
9
+ "Build in code" — or `vf app convert <appId> --to-code`, which switches an existing one first — writes
10
+ `package.json` (this package, `@veriforms/webapp-react` and `@veriforms/webapp-vite` at one version,
11
+ React 18.3.1, date-fns, clsx, TypeScript and Vite 6), `vite.config.ts`, `tsconfig.json`,
12
+ `src/pages/main.tsx`, the app's `config.json` and `veriforms.webapp.json` into `./<appId>`. Then:
13
+
14
+ ```sh
15
+ cd <appId>
16
+ npm install
17
+ vf app types # vf-app.d.ts from config.json
18
+ vf app dev # your code against the draft, preview data only
19
+ vf app build # tsc --noEmit, then vite build into vf-build/
20
+ vf app push # the build becomes the DRAFT
21
+ ```
22
+
23
+ By hand, in a project of your own: the three packages at the same version, React and React DOM at
24
+ exactly 18.3.1, and a Vite the plugin accepts (6.x):
25
+
8
26
  ```sh
9
27
  npm i @veriforms/webapp-sdk @veriforms/webapp-react react@18.3.1 react-dom@18.3.1
10
- npm i -D @veriforms/webapp-vite vite
28
+ npm i -D @veriforms/webapp-vite vite@6
11
29
  ```
12
30
 
13
31
  The packages are public on npm (owner decision 2026-12-03). Web apps built in code are open to
@@ -63,7 +81,8 @@ location.href = pageLink('admin'); // every area is its own page, gated by the
63
81
  | `db.update(source, id, patch, version?, {clientToken}?)` | `customdb-write` | `VF.db.update` (version → 409 row_changed when someone changed the row) |
64
82
  | `data.list(source, params?)` | `veriforms-data` | `VF.data.list` → `{Rows, Count, Truncated}` |
65
83
  | `fetchSource(source, params?)` | `veriflow`, `http`, `demo` | `VF.fetch` |
66
- | `knowledge.search(source, question)` (0.1.3) | `knowledge` | `VF.fetch` with `?q=` → `{status, message, passages, sourceLine}` |
84
+ | `knowledge.search(source, question)` (0.1.3) | `knowledge` | `VF.fetch` with `?q=` → `{status, message, passages, sourceLine}` (`sourceLine` always text with `ok`, 0.1.4) |
85
+ | `values.get(keys?)` (0.1.4) | `"values"` in config.json | `GET {base}/values?keys=…` → `{key: text}`; refusals are a `ValuesError` (`value_not_declared`, `value_not_found`) |
67
86
  | `send(source, body, {clientToken}?)` | submission, webhook, workflow, veriflow, customdb-write | `VF.send` (repeat-safe) |
68
87
  | `runAction(source, opts?)` | `workflow`, `veriflow`, `webhook` | `VF.runAction` |
69
88
  | `form.render(target, source, opts?)`, `form.submitPartial` | submission, customdb-write | `VF.form.*` |
@@ -98,12 +117,15 @@ there is no key for "anyone who is signed in". So the pattern is three things:
98
117
  "dataSources": {
99
118
  "myBookings": { "type": "customdb", "table": "bookings", "select": ["_id", "item", "day"],
100
119
  "rowRules": { "member": { "column": "booked_by", "equals": "$visitor.email" } } },
101
- "book": { "type": "customdb-write", "table": "bookings",
120
+ "book": { "type": "customdb-write", "table": "bookings", "mode": "insert",
102
121
  "fields": { "item": { "type": "string", "required": true }, "booked_by": { "type": "server-user" } },
103
122
  "rowRules": { "member": { "column": "booked_by", "equals": "$visitor.email" } } }
104
123
  }
105
124
  ```
106
125
 
126
+ A `customdb-write` source always names its `"mode"` — `"insert"`, `"upsert"` or `"update"`: there is
127
+ no default, the server refuses a config without it, and so does `vf app types` (it never assumes one).
128
+
107
129
  1. the role is declared under `"roles"` (a `rowRules` key that is not a
108
130
  declared role is refused when the config is saved);
109
131
  2. the rule compares a column with `"$visitor.email"`, the signed-in address —
@@ -249,7 +271,28 @@ try {
249
271
  - **A newer release (X9):** `409 server_function_version_changed` reloads the page (once per build) and
250
272
  rejects with `ServerFunctionVersionChangedError`; the old code never runs.
251
273
  - **Types:** the plugin writes `vf-server.d.ts` (input and answer of every function, from its
252
- 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).
253
296
 
254
297
  ## config.json in your editor
255
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.3";
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
  *
@@ -71,6 +71,8 @@ export interface AppShape {
71
71
  sources: Record<string, SourceShape>;
72
72
  pages: string;
73
73
  roles: string;
74
+ /** The Definitions values config.json declares in "values" (since 0.1.4). */
75
+ values: string;
74
76
  }
75
77
  /** What an app without generated types looks like: anything goes, nothing is checked. */
76
78
  interface UntypedSource {
@@ -86,6 +88,7 @@ interface UntypedApp {
86
88
  sources: Record<string, UntypedSource>;
87
89
  pages: string;
88
90
  roles: string;
91
+ values: string;
89
92
  }
90
93
  /** The app this code is typed against: the generated one, or {@link UntypedApp}. */
91
94
  export type App = Register extends {
@@ -129,6 +132,10 @@ export type PageName = (App extends {
129
132
  export type RoleName = App extends {
130
133
  roles: infer R;
131
134
  } ? R : string;
135
+ /** A value the app's config.json declares in "values" (a Definitions key such as company.iban), since 0.1.4. */
136
+ export type ValueKey = App extends {
137
+ values: infer V;
138
+ } ? V : string;
132
139
  export type RowOf<K> = SourceOf<K> extends {
133
140
  row: infer R;
134
141
  } ? R : Record<string, unknown>;
@@ -321,6 +328,11 @@ export interface VfRuntime {
321
328
  };
322
329
  t(key: string, vars?: Record<string, unknown>): string;
323
330
  newClientToken(): string;
331
+ /** The page's addresses: base (the app's path on this plane) and fileQuery (the draft preview's token). */
332
+ bridge?: {
333
+ base?: string;
334
+ fileQuery?: string;
335
+ };
324
336
  }
325
337
  /**
326
338
  * Thrown when the page has no VeriForms runtime, or the runtime lacks a
@@ -386,13 +398,14 @@ export interface KnowledgePassage {
386
398
  export declare const KNOWLEDGE_PASSAGE_FIELDS: readonly ["document", "url", "table", "rowId", "position", "score", "text"];
387
399
  /**
388
400
  * What {@link knowledge.search} resolves with. `sourceLine` is the server-built citation ("Quelle: …" /
389
- * "Source: …"): show it under any answer built from the passages — never write a citation yourself.
401
+ * "Source: …"), always there with `ok` (since 0.1.4 typed so): show it under any answer built from the
402
+ * passages — never write a citation yourself.
390
403
  */
391
404
  export type KnowledgeAnswer = {
392
405
  status: 'ok';
393
406
  message: string | null;
394
407
  passages: KnowledgePassage[];
395
- sourceLine: string | null;
408
+ sourceLine: string;
396
409
  } | {
397
410
  status: 'no_match' | 'empty';
398
411
  message: string | null;
@@ -444,6 +457,35 @@ export declare const knowledge: {
444
457
  */
445
458
  search<K extends KnowledgeKey>(source: K, question: string): Promise<KnowledgeAnswer>;
446
459
  };
460
+ /**
461
+ * The codes a values read is refused with (the gateway's GET {base}/values, ServeController.Values):
462
+ * a key config.json does not declare in "values" (`value_not_declared`, 403), a declared value the
463
+ * space does not serve — missing, not marked "may be shown in web apps", another application's
464
+ * (`value_not_found` and the resolver's codes, 502). Pinned against the gateway by test/pins.test.ts.
465
+ */
466
+ export declare const VALUE_REFUSAL_CODES: readonly ["value_not_declared", "value_not_found", "values_unavailable"];
467
+ /** A values read that did not answer every key: refused, unreadable or unreachable. Never an empty text. */
468
+ export declare class ValuesError extends Error {
469
+ readonly code: string;
470
+ readonly keys: string[];
471
+ readonly status?: number | undefined;
472
+ constructor(code: string, keys: string[], message: string, status?: number | undefined, options?: {
473
+ cause?: unknown;
474
+ });
475
+ }
476
+ /** Definitions values: settings, fees, an IBAN — the same for every visitor, edited in VeriForms, never in the page. */
477
+ export declare const values: {
478
+ /**
479
+ * The values of `keys` (or every value config.json declares), each as TEXT exactly as
480
+ * `{{value:<key>}}` puts it in the config — formatted; parse a number yourself. Resolves with every
481
+ * key asked for, or rejects with a {@link ValuesError} naming the code and the keys: a key that is
482
+ * not declared, a value that cannot be served, or an answer without one of the keys. Works on the
483
+ * served planes and on the draft (the builder's preview, `vf app dev`).
484
+ */
485
+ get<K extends ValueKey>(keys?: readonly K[]): Promise<Record<K, string>>;
486
+ };
487
+ /** True for a values read the server refused (an undeclared key, a value it does not serve). */
488
+ export declare function isValuesError(e: unknown): e is ValuesError;
447
489
  /**
448
490
  * Posts to a source with one clientToken for the visitor's one action, and asks
449
491
  * again with the same token when the answer did not settle anything. A rejection
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.3';
18
+ export const SDK_VERSION = '0.1.5';
19
19
  export function isVfRequestError(e) {
20
20
  return e instanceof Error;
21
21
  }
@@ -160,9 +160,11 @@ function readKnowledgeAnswer(source, raw) {
160
160
  throw unreadable();
161
161
  const message = typeof a.message === 'string' ? a.message : null;
162
162
  if (a.status === 'ok') {
163
- if (a.passages.length === 0)
163
+ // An ok answer always carries the server-built line (KnowledgeCitations.SourceLineOf over its passages):
164
+ // without it the page would show an answer with no source, so it is unreadable, never null (batch 236c).
165
+ if (a.passages.length === 0 || typeof a.sourceLine !== 'string' || !a.sourceLine)
164
166
  throw unreadable();
165
- return { status: 'ok', message, passages: a.passages, sourceLine: typeof a.sourceLine === 'string' ? a.sourceLine : null };
167
+ return { status: 'ok', message, passages: a.passages, sourceLine: a.sourceLine };
166
168
  }
167
169
  if (a.passages.length > 0)
168
170
  throw unreadable();
@@ -195,6 +197,83 @@ export const knowledge = {
195
197
  return readKnowledgeAnswer(source, raw);
196
198
  },
197
199
  };
200
+ // ─────────────────────────────────────────────────────────────────────────────
201
+ // Values (Definitions), since 0.1.4
202
+ // ─────────────────────────────────────────────────────────────────────────────
203
+ /**
204
+ * The codes a values read is refused with (the gateway's GET {base}/values, ServeController.Values):
205
+ * a key config.json does not declare in "values" (`value_not_declared`, 403), a declared value the
206
+ * space does not serve — missing, not marked "may be shown in web apps", another application's
207
+ * (`value_not_found` and the resolver's codes, 502). Pinned against the gateway by test/pins.test.ts.
208
+ */
209
+ export const VALUE_REFUSAL_CODES = ['value_not_declared', 'value_not_found', 'values_unavailable'];
210
+ /** A values read that did not answer every key: refused, unreadable or unreachable. Never an empty text. */
211
+ export class ValuesError extends Error {
212
+ constructor(code, keys, message, status, options) {
213
+ super(message, options);
214
+ this.code = code;
215
+ this.keys = keys;
216
+ this.status = status;
217
+ this.name = 'ValuesError';
218
+ }
219
+ }
220
+ /** Definitions values: settings, fees, an IBAN — the same for every visitor, edited in VeriForms, never in the page. */
221
+ export const values = {
222
+ /**
223
+ * The values of `keys` (or every value config.json declares), each as TEXT exactly as
224
+ * `{{value:<key>}}` puts it in the config — formatted; parse a number yourself. Resolves with every
225
+ * key asked for, or rejects with a {@link ValuesError} naming the code and the keys: a key that is
226
+ * not declared, a value that cannot be served, or an answer without one of the keys. Works on the
227
+ * served planes and on the draft (the builder's preview, `vf app dev`).
228
+ */
229
+ async get(keys) {
230
+ const bridge = runtime().bridge;
231
+ if (!bridge || typeof bridge.base !== 'string')
232
+ throw new SdkRuntimeMismatchError('bridge.base');
233
+ const asked = [...new Set((keys ?? []).map(k => String(k).trim()).filter(Boolean))];
234
+ const query = bridge.fileQuery ?? '';
235
+ const url = `${bridge.base}/values${query}${asked.length ? `${query.includes('?') ? '&' : '?'}keys=${asked.map(encodeURIComponent).join(',')}` : ''}`;
236
+ let res;
237
+ try {
238
+ res = await fetch(url, { credentials: 'same-origin', headers: { Accept: 'application/json' } });
239
+ }
240
+ catch (e) {
241
+ throw new ValuesError('values_unavailable', asked, `@veriforms/webapp-sdk ${SDK_VERSION}: the values could not be read (${e.message}).`, undefined, { cause: e });
242
+ }
243
+ let body;
244
+ try {
245
+ body = await res.json();
246
+ }
247
+ catch {
248
+ body = undefined;
249
+ }
250
+ const b = (body && typeof body === 'object' ? body : {});
251
+ if (!res.ok) {
252
+ const code = typeof b.code === 'string' ? b.code : 'values_unavailable';
253
+ const named = Array.isArray(b.keys) ? b.keys.filter((k) => typeof k === 'string') : asked;
254
+ throw new ValuesError(code, named, typeof b.message === 'string' ? b.message : `The values could not be read (${res.status}).`, res.status);
255
+ }
256
+ const got = b.values;
257
+ if (!got || typeof got !== 'object' || Array.isArray(got)) {
258
+ throw new ValuesError('values_unreadable', asked, `@veriforms/webapp-sdk ${SDK_VERSION}: the values answer could not be read.`, res.status);
259
+ }
260
+ const map = got;
261
+ // Every key asked for is in the answer as text — a missing one is a fault, never "".
262
+ const missing = asked.filter(k => typeof map[k] !== 'string');
263
+ if (missing.length) {
264
+ throw new ValuesError('value_not_found', missing, `The values answer has no text for ${missing.join(', ')}.`, res.status);
265
+ }
266
+ const out = {};
267
+ for (const [k, v] of Object.entries(map))
268
+ if (typeof v === 'string')
269
+ out[k] = v;
270
+ return out;
271
+ },
272
+ };
273
+ /** True for a values read the server refused (an undeclared key, a value it does not serve). */
274
+ export function isValuesError(e) {
275
+ return e instanceof ValuesError;
276
+ }
198
277
  /**
199
278
  * Posts to a source with one clientToken for the visitor's one action, and asks
200
279
  * again with the same token when the answer did not settle anything. A rejection
@@ -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.3",
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",