@veriforms/webapp-sdk 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,8 @@
1
+ Copyright (c) 2026 In Data Veritas GmbH. All rights reserved.
2
+
3
+ The VeriForms web app SDK (@veriforms/webapp-sdk) is proprietary software, published on npm as
4
+ a preview ("license": "UNLICENSED", like the VeriForms CLI). Until In Data Veritas GmbH
5
+ publishes it under a licence, no licence is granted to copy, modify or distribute it.
6
+
7
+ Using it to build web apps that run on VeriForms is governed by the VeriForms terms of
8
+ service (https://www.veriforms.net).
package/README.md CHANGED
@@ -1,3 +1,239 @@
1
- # Temporary Holding Version
1
+ # @veriforms/webapp-sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Typed access to the VeriForms web app runtime, for web apps built in code
4
+ ("Build in code"). Phase 1 of `docs/webapp-builder/CWA-CODE-APPS-CONCEPT.md`.
5
+
6
+ ## Install
7
+
8
+ ```sh
9
+ 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
11
+ ```
12
+
13
+ During the pilot the packages are on npm as **restricted**: only accounts the `@veriforms` scope
14
+ grants access can install them (run `npm login` with such an account, or put a read token into
15
+ `.npmrc`). Without access, use the pilot kit (`tools/webapp-starter/make-pilot-kit.mjs`). Public at
16
+ general availability. The three packages are released together at one version
17
+ (`webapp-react` names the SDK exactly). Install React at the version the platform serves (18.3.1) —
18
+ the upload compares your `package-lock.json`.
19
+
20
+ **Status:** pilot — published restricted (tag `webapp-v<version>`, `.github/workflows/webapp-release.yml`);
21
+ public at general availability.
22
+ **Availability:** web apps built in code are open only to platform administrators and
23
+ accounts an administrator enabled, until the owner confirms general availability
24
+ (concept §0.1). No public npm release and no public docs before then.
25
+ It becomes useful to customers with phase 2, when the gateway can serve a web app
26
+ built in code. Until then, VeriForms developers can already use it and its types.
27
+
28
+ ## What it is
29
+
30
+ The gateway injects `/vf-ui.js` into every page it serves; that script defines
31
+ `window.VF`. This package **does not re-implement any of it**. Every function
32
+ calls the injected runtime, so a web app built in code behaves exactly like one
33
+ built with Vera. It adds:
34
+
35
+ - **Types from the app's own config.** `vf app types` (the VeriForms CLI) reads
36
+ `config.json` and writes `vf-app.d.ts`, which fills in this package's
37
+ `Register` interface. A misspelt source key, a field a source does not
38
+ declare, a param it does not allow, a page the app does not have, or a role
39
+ it does not declare is then a **compile error**. The server still refuses
40
+ all of these; the compiler only catches them first.
41
+ - **A loud failure** when the page has no runtime or the runtime lacks a
42
+ function: `SdkRuntimeMismatchError` (`code: 'sdk_runtime_mismatch'`), naming
43
+ what is missing. Never a silent no-op.
44
+ - **`config.schema.json`**, a JSON Schema for `config.json`, for editor help.
45
+
46
+ ```ts
47
+ import { db, send, pageLink, isOutcomeUnknown } from '@veriforms/webapp-sdk';
48
+
49
+ const page = await db.list('orders', { status: 'open', limit: 25 }); // rows typed from the table
50
+ await db.insert('newOrder', { item: 'Pen', qty: 2 }); // fields typed from config.json
51
+ try {
52
+ await send('contact', { name: 'Ada', topic: 'sales' });
53
+ } catch (e) {
54
+ if (isOutcomeUnknown(e)) { /* "it may already have been received" — resend with e.clientToken */ }
55
+ }
56
+ location.href = pageLink('admin'); // every area is its own page, gated by the gateway
57
+ ```
58
+
59
+ ## The functions
60
+
61
+ | Function | Source kind | Runtime call |
62
+ |---|---|---|
63
+ | `db.list(source, params?)` | `customdb` | `VF.db.list` → `{rows, rowCount, limit, offset, hasMore, nextOffset}` |
64
+ | `db.insert / upsert(source, rows, {clientToken}?)` | `customdb-write` | `VF.db.insert / upsert` |
65
+ | `db.update(source, id, patch, version?, {clientToken}?)` | `customdb-write` | `VF.db.update` (version → 409 row_changed when someone changed the row) |
66
+ | `data.list(source, params?)` | `veriforms-data` | `VF.data.list` → `{Rows, Count, Truncated}` |
67
+ | `fetchSource(source, params?)` | `veriflow`, `http`, `demo` | `VF.fetch` |
68
+ | `send(source, body, {clientToken}?)` | submission, webhook, workflow, veriflow, customdb-write | `VF.send` (repeat-safe) |
69
+ | `runAction(source, opts?)` | `workflow`, `veriflow`, `webhook` | `VF.runAction` |
70
+ | `form.render(target, source, opts?)`, `form.submitPartial` | submission, customdb-write | `VF.form.*` |
71
+ | `pay.start / status / pendingId / receiptLink` | `veriforms-payment` | `VF.pay.*` |
72
+ | `user()`, `signIn()`, `signOut()` | — | `VF.user`, `VF.signIn`, `VF.signOut` |
73
+ | `access.has(role)`, `access.can(source)`, `access.level()`, `access.signedIn()` | — | `VF.access` |
74
+ | `pageLink(name, '?…' \| '#…')`, `currentPage()`, `appLink()`, `file()` | — | `VF.pageLink`, `VF.page`, `VF.appLink`, `VF.file` |
75
+ | `t()`, `theme()`, `newClientToken()`, `onDataChanged(listener)` | — | `VF.t`, `VF.theme.current`, `VF.newClientToken`, `vf:data-changed` |
76
+
77
+ Without a generated `vf-app.d.ts` every key is a plain string and every row a
78
+ plain record: the code compiles, nothing is checked.
79
+
80
+ ### Rows: what the type says
81
+
82
+ A `customdb` source with `"select"` returns exactly those columns, under those
83
+ names — and the row type has exactly them. `_id` (a React key, the id
84
+ `db.update` takes) is in the row when the source has no `"select"` or its
85
+ `"select"` lists `"_id"`; using it otherwise is a compile error, because the
86
+ row does not carry it. Every column of your own can be `null` in the row
87
+ type: the server's description of a table does not say which columns are
88
+ required, so none is assumed filled (`vf app types` drops the `null` for a
89
+ column the description reports as `Required`).
90
+
91
+ ### Own rows: "every signed-in visitor sees their own rows"
92
+
93
+ Rows only some people may see are narrowed on the server by the source's
94
+ `"rowRules"` — never by a filter the page sends. A rule belongs to a **role**:
95
+ there is no key for "anyone who is signed in". So the pattern is three things:
96
+
97
+ ```json
98
+ "roles": { "member": { "label": { "de": "Mitglied", "en": "Member" }, "level": "write" } },
99
+ "dataSources": {
100
+ "myBookings": { "type": "customdb", "table": "bookings", "select": ["_id", "item", "day"],
101
+ "rowRules": { "member": { "column": "booked_by", "equals": "$visitor.email" } } },
102
+ "book": { "type": "customdb-write", "table": "bookings",
103
+ "fields": { "item": { "type": "string", "required": true }, "booked_by": { "type": "server-user" } },
104
+ "rowRules": { "member": { "column": "booked_by", "equals": "$visitor.email" } } }
105
+ }
106
+ ```
107
+
108
+ 1. the role is declared under `"roles"` (a `rowRules` key that is not a
109
+ declared role is refused when the config is saved);
110
+ 2. the rule compares a column with `"$visitor.email"`, the signed-in address —
111
+ the page never supplies it; a write stamps the column with it;
112
+ 3. **the people hold the role.** Who holds a role is not in `config.json`: the
113
+ owner gives it on the app's Access tab (or with `assign_cwa_roles`), or binds
114
+ a permission table with `"roleSource"`. A tester of the test version needs
115
+ the role as well. A signed-in visitor who holds no role with a rule is
116
+ refused (`403 row_rule_missing`) — never shown every row.
117
+
118
+ The app must offer sign-in: restricted, or open to anyone with optional sign-in
119
+ (`set_cwa_access` with `methods`, e.g. `["code"]`) — otherwise the save refuses
120
+ the rule (`sign_in_not_offered`).
121
+
122
+ ### The draft shows preview data only
123
+
124
+ `vf app dev` and the builder's draft preview never read or change real rows. A
125
+ read source answers from its `"previewData"` in `config.json` (for a table
126
+ source: `{ "rows": [ … ], "rowCount": n }`); one without it answers
127
+ `this source has no preview data`. A write is refused (`This preview does not
128
+ save entries`). Real data and real writes are on the test version.
129
+
130
+ ## Server functions — PILOT, PLATFORM ADMINISTRATORS ONLY
131
+
132
+ > Only a **platform administrator** may push and release server functions — for a web app in any
133
+ > account, customer accounts included (owner decision 2026-12-03: VeriForms builds customer solutions
134
+ > as a consulting offer). A version runs its functions only when an administrator released it, and
135
+ > only while the platform has them switched on (it is **off in production**). For everyone else — the
136
+ > app's owner included — a build with `server/` is refused (`bundle_server_code_not_enabled`), and so
137
+ > is publishing, restoring or promoting a version that carries one (`server_functions_not_enabled`):
138
+ > push a build without `server/`, or ask the VeriForms team to release it. Not part of the public docs. Concept:
139
+ > `docs/webapp-builder/CWA-CODE-BACKEND-CONCEPT.md`; decisions: `CWA-DECISIONS.md`
140
+ > ("Server functions, the developer side").
141
+
142
+ The example lives here and not in the starter on purpose: the starter has to build and push for
143
+ everyone, and a project with `src/server/` builds only with the plugin's `serverFunctions: true`.
144
+
145
+ ```ts
146
+ // vite.config.ts — opt in
147
+ export default defineConfig({ plugins: [veriformsWebApp({ serverFunctions: true })] });
148
+ ```
149
+
150
+ ```ts
151
+ // src/server/placeOrder.ts — one file per function (a "_" file or folder is shared code: src/server/_lib/…)
152
+ import { defineServerFunction } from '@veriforms/webapp-sdk/server';
153
+
154
+ export const placeOrder = defineServerFunction({
155
+ access: 'signedIn', // or 'anyone' / { signedIn: true }
156
+ sources: ['orders', 'products'], // every config source it calls, written out
157
+ input: { // a literal JSON-Schema subset, checked by the gateway first
158
+ type: 'object',
159
+ properties: { note: { type: 'string', maxLength: 200 }, qty: { type: 'integer', maximum: 9 } },
160
+ required: ['note'],
161
+ },
162
+ async handler(input, ctx) { // input: { note: string; qty?: number }
163
+ const products = await ctx.source('products').read();
164
+ if (products.rowCount === 0) throw ctx.refuse('no_products', 'Es gibt keine Produkte.', 'There are no products.');
165
+ const saved = await ctx.source('orders').insert({ note: input.note, qty: input.qty ?? 1 });
166
+ return { saved, by: ctx.user.email };
167
+ },
168
+ });
169
+ ```
170
+
171
+ ```tsx
172
+ // src/pages/main.tsx — a page never imports src/server/; it calls the client stub
173
+ import { server, isServerFunctionError } from '@veriforms/webapp-sdk';
174
+
175
+ try {
176
+ const { saved } = await server.placeOrder({ note: 'Bitte schnell' }); // POST …/fn/place-order
177
+ } catch (e) {
178
+ if (isServerFunctionError(e, 'server_function_sign_in_required')) { /* … */ }
179
+ }
180
+ ```
181
+
182
+ - **No input:** a function defined without `input` is called with no argument — `await server.listMyQuotes()`
183
+ (sent as `null`; since 0.1.1). A function with an `input` schema still needs its input.
184
+ - **Routes:** the export name in camelCase is served in kebab-case — `placeOrder` → `/fn/place-order`
185
+ (the build writes `export { placeOrder as "place-order" }`).
186
+ - **The gateway reads the definition statically:** an object literal, `sources` as quoted names, `input`
187
+ as a literal, and every `ctx.source('…')` / `ctx.automation.run('…')` / `.start('…')` naming a
188
+ declared source in quotes. The plugin reads the BUILT code with the same rules and fails the build
189
+ with the file and line; it writes `vf-build/server-manifest.json`, which `vf app push` sends with the
190
+ build (the gateway derives its own and refuses one that disagrees).
191
+ - **`ctx`** is the runtime's, one to one: `source(key).read|list|get|write|insert|send`,
192
+ `values.get|getMany`, `automation.run|start`, `user`, `language`, `instance`, `functionName`,
193
+ `refuse(code, de, en)`, `log.info|warn|error`, `now()`, `uuid()`. No `fetch`, no secrets, no database,
194
+ no environment. Each data call goes through the source's own rules under the calling visitor.
195
+ - **Server code imports** only `defineServerFunction` from `@veriforms/webapp-sdk/server` and its own
196
+ files — no packages, no page code, no other function's file.
197
+ - **The client stub** (`server.<name>(input)` / `callServerFunction(name, input, { idempotencyKey })`)
198
+ sends the build hash the page was served with (`X-VF-Bundle`) and a repeat key (`Idempotency-Key`).
199
+ Every refusal rejects with `ServerFunctionError` (`code`, `status`, `message` / `messageDe` /
200
+ `messageEn`, `runId`; `kind === 'server_function_refused'` for `ctx.refuse`); no answer at all is
201
+ `code: 'network'` with `outcome: 'unknown'` — resend with the same `idempotencyKey`.
202
+ - **A newer release (X9):** `409 server_function_version_changed` reloads the page (once per build) and
203
+ rejects with `ServerFunctionVersionChangedError`; the old code never runs.
204
+ - **Types:** the plugin writes `vf-server.d.ts` (input and answer of every function, from its
205
+ definition); keep it next to `vf-app.d.ts`.
206
+
207
+ ## config.json in your editor
208
+
209
+ The gateway refuses unknown top-level keys, so `config.json` cannot carry a
210
+ `"$schema"` key. Map the schema in the editor instead (VS Code,
211
+ `.vscode/settings.json`):
212
+
213
+ ```json
214
+ { "json.schemas": [{ "fileMatch": ["**/config.json"], "url": "./node_modules/@veriforms/webapp-sdk/config.schema.json" }] }
215
+ ```
216
+
217
+ The schema is editor help only. The gateway validates `config.json` on every
218
+ save, and its answer is the one that counts.
219
+
220
+ ## Kept honest by tests
221
+
222
+ - `test/runtime.test.ts`: every function calls the runtime with the arguments it
223
+ takes, and a missing runtime or function fails loudly.
224
+ - `test/pins.test.ts` reads the gateway's own source and fails when the schema or
225
+ the SDK drift from it: the top-level keys (`AppConfigParser.TopLevelKeys`),
226
+ every `AppDataSource` property, the source types (`KnownTypes`), the field
227
+ rules (`CwaSourceRowRules`), `roleSource` and `legal`, and every `window.VF`
228
+ path the SDK calls (`VfUiLibrary.cs`).
229
+ - `test/types.ts` (run by `npm run typecheck`) pins the compile-time contract:
230
+ each `@ts-expect-error` line must fail to compile.
231
+ - The CLI's `test/appTypes.test.ts` compiles `vf app types` output against this
232
+ package's source.
233
+
234
+ CI runs them in the **CLI Tests** job whenever this package, the CLI or one of
235
+ the gateway files the pins read changes.
236
+
237
+ ```sh
238
+ npm ci && npm run typecheck && npm test && npm run build
239
+ ```