@veriforms/webapp-sdk 0.0.0-stage → 0.1.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/LICENSE +8 -0
- package/README.md +233 -2
- package/config.schema.json +564 -0
- package/dist/index.d.ts +419 -0
- package/dist/index.js +203 -0
- package/dist/server.d.ts +190 -0
- package/dist/server.js +49 -0
- package/dist/serverClient.d.ts +111 -0
- package/dist/serverClient.js +201 -0
- package/dist/serverRoute.d.ts +19 -0
- package/dist/serverRoute.js +31 -0
- package/package.json +49 -4
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @veriforms/webapp-sdk/server — server functions of a web app built in code (R7 batch 3b;
|
|
3
|
+
* docs/webapp-builder/CWA-CODE-BACKEND-CONCEPT.md §5.2).
|
|
4
|
+
*
|
|
5
|
+
* PILOT, PLATFORM ADMINISTRATORS ONLY: the gateway runs server functions only for a platform administrator's
|
|
6
|
+
* own web app, pushed and released by a platform administrator, and only while the platform setting
|
|
7
|
+
* (`CwaCode:ServerFunctions`) is not `off` — it is `off` in production. Everyone else's upload of a build
|
|
8
|
+
* with `server/` is refused (`bundle_server_code_not_enabled`).
|
|
9
|
+
*
|
|
10
|
+
* Files under `src/server/` import {@link defineServerFunction} BY NAME from this module and export each
|
|
11
|
+
* definition as a top-level `const`:
|
|
12
|
+
*
|
|
13
|
+
* ```ts
|
|
14
|
+
* import { defineServerFunction } from '@veriforms/webapp-sdk/server';
|
|
15
|
+
*
|
|
16
|
+
* export const placeOrder = defineServerFunction({
|
|
17
|
+
* access: 'signedIn', // or 'anyone' / { signedIn: true }
|
|
18
|
+
* sources: ['orders'], // every config source it calls, written out
|
|
19
|
+
* input: { type: 'object', properties: { note: { type: 'string', maxLength: 200 } }, required: ['note'] },
|
|
20
|
+
* async handler(input, ctx) {
|
|
21
|
+
* const row = await ctx.source('orders').insert({ note: input.note });
|
|
22
|
+
* return { ok: true, row };
|
|
23
|
+
* },
|
|
24
|
+
* });
|
|
25
|
+
* ```
|
|
26
|
+
*
|
|
27
|
+
* The gateway READS the definition statically (`VeriForms.Ai.ServerFunctions.ServerManifestReader`): the
|
|
28
|
+
* object must be a literal, `sources` an array of quoted names, `input` a literal JSON-Schema subset
|
|
29
|
+
* (`type`, `properties`, `required`, `items`, `maxLength`, `maximum`, `enum`), and every `ctx.source('…')`,
|
|
30
|
+
* `ctx.automation.run('…')` / `.start('…')` in it must name a declared source in quotes. The export name in
|
|
31
|
+
* camelCase is served in kebab-case: `placeOrder` → `POST /a/{app}/fn/place-order`.
|
|
32
|
+
*
|
|
33
|
+
* At run time the gateway provides this module itself (the build keeps the import), and it exports
|
|
34
|
+
* `defineServerFunction` and nothing else — so this entry exports nothing else at run time either (types
|
|
35
|
+
* aside); the Vite plugin refuses any other name imported from it. The implementation here only matters for
|
|
36
|
+
* local tests, and marks a definition exactly as the runtime does.
|
|
37
|
+
*/
|
|
38
|
+
import type { FieldsOf, ParamsOf, ResultOf, RowOf, SendResultOf, SourceKey, TablePage, SubmissionsPage, WriteResult } from './index.js';
|
|
39
|
+
/** The types a schema may name (`ServerManifestReader.SchemaTypes`; the list is `INPUT_SCHEMA_TYPES` of the main entry). */
|
|
40
|
+
export type InputSchemaType = 'object' | 'array' | 'string' | 'number' | 'integer' | 'boolean' | 'null';
|
|
41
|
+
/** A function's input contract, checked by the gateway before the function starts. */
|
|
42
|
+
export interface InputSchema {
|
|
43
|
+
readonly type?: InputSchemaType;
|
|
44
|
+
readonly properties?: {
|
|
45
|
+
readonly [name: string]: InputSchema;
|
|
46
|
+
};
|
|
47
|
+
readonly required?: readonly string[];
|
|
48
|
+
readonly items?: InputSchema;
|
|
49
|
+
readonly maxLength?: number;
|
|
50
|
+
readonly maximum?: number;
|
|
51
|
+
readonly enum?: readonly (string | number | boolean | null)[];
|
|
52
|
+
}
|
|
53
|
+
type Expand<T> = T extends object ? {
|
|
54
|
+
[K in keyof T]: T[K];
|
|
55
|
+
} : T;
|
|
56
|
+
type ObjectFromSchema<P, R> = Expand<{
|
|
57
|
+
-readonly [K in keyof P as K extends R ? K : never]-?: FromSchema<P[K]>;
|
|
58
|
+
} & {
|
|
59
|
+
-readonly [K in keyof P as K extends R ? never : K]?: FromSchema<P[K]>;
|
|
60
|
+
}>;
|
|
61
|
+
/** The TypeScript type of the values a schema accepts. Without a schema: `unknown`. */
|
|
62
|
+
export type FromSchema<S> = S extends {
|
|
63
|
+
readonly enum: readonly (infer E)[];
|
|
64
|
+
} ? E : S extends {
|
|
65
|
+
readonly type: 'string';
|
|
66
|
+
} ? string : S extends {
|
|
67
|
+
readonly type: 'number' | 'integer';
|
|
68
|
+
} ? number : S extends {
|
|
69
|
+
readonly type: 'boolean';
|
|
70
|
+
} ? boolean : S extends {
|
|
71
|
+
readonly type: 'null';
|
|
72
|
+
} ? null : S extends {
|
|
73
|
+
readonly type: 'array';
|
|
74
|
+
readonly items: infer I;
|
|
75
|
+
} ? FromSchema<I>[] : S extends {
|
|
76
|
+
readonly type: 'array';
|
|
77
|
+
} ? unknown[] : S extends {
|
|
78
|
+
readonly type: 'object';
|
|
79
|
+
readonly properties: infer P;
|
|
80
|
+
} ? ObjectFromSchema<P, S extends {
|
|
81
|
+
readonly required: readonly (infer R)[];
|
|
82
|
+
} ? R : never> : S extends {
|
|
83
|
+
readonly type: 'object';
|
|
84
|
+
} ? Record<string, unknown> : unknown;
|
|
85
|
+
/** What a read of one source answers: the same body the page's call of that source gets. */
|
|
86
|
+
export type ServerReadOf<K> = K extends SourceKey<'customdb'> ? TablePage<RowOf<K>> : K extends SourceKey<'veriforms-data'> ? SubmissionsPage<FieldsOf<K>> : K extends SourceKey<'veriflow' | 'http' | 'demo'> ? ResultOf<K> : unknown;
|
|
87
|
+
/** What a write to one source answers. */
|
|
88
|
+
export type ServerWriteOf<K> = K extends SourceKey<'veriflow'> ? SendResultOf<K> : WriteResult;
|
|
89
|
+
/**
|
|
90
|
+
* One declared source, as `ctx.source(key)` gives it. Every call goes through the SAME pipeline as the page's
|
|
91
|
+
* call of that source — row rules, `minLevel`, roles, `allowClientParams`, the visitor limit — under the
|
|
92
|
+
* visitor who called the function. Data calls are synchronous in the pilot runtime (the gateway waits off
|
|
93
|
+
* the sandbox thread); `await` on their answer works as on any value, and a failure throws where the call is.
|
|
94
|
+
*/
|
|
95
|
+
export interface ServerSource<K> {
|
|
96
|
+
read(params?: Partial<ParamsOf<K>>): ServerReadOf<K>;
|
|
97
|
+
/** The same as {@link read}. */
|
|
98
|
+
list(params?: Partial<ParamsOf<K>>): ServerReadOf<K>;
|
|
99
|
+
/** The same as {@link read}. */
|
|
100
|
+
get(params?: Partial<ParamsOf<K>>): ServerReadOf<K>;
|
|
101
|
+
write(body: FieldsOf<K> | Array<FieldsOf<K>> | Record<string, unknown>): ServerWriteOf<K>;
|
|
102
|
+
/** The same as {@link write}. */
|
|
103
|
+
insert(body: FieldsOf<K> | Array<FieldsOf<K>> | Record<string, unknown>): ServerWriteOf<K>;
|
|
104
|
+
/** The same as {@link write}. */
|
|
105
|
+
send(body: FieldsOf<K> | Array<FieldsOf<K>> | Record<string, unknown>): ServerWriteOf<K>;
|
|
106
|
+
}
|
|
107
|
+
/** The visitor who called the function, read-only (no other identity is reachable). */
|
|
108
|
+
export interface ServerVisitor {
|
|
109
|
+
readonly signedIn: boolean;
|
|
110
|
+
readonly email: string | null;
|
|
111
|
+
readonly name: string | null;
|
|
112
|
+
readonly level: string | null;
|
|
113
|
+
readonly roles: readonly string[];
|
|
114
|
+
}
|
|
115
|
+
/** The error {@link ServerContext.refuse} makes: thrown, the page receives a 422 with the author's code and both texts. */
|
|
116
|
+
export interface ServerFunctionRefusal extends Error {
|
|
117
|
+
readonly name: 'ServerFunctionRefusal';
|
|
118
|
+
readonly code: string;
|
|
119
|
+
readonly de: string | null;
|
|
120
|
+
readonly en: string | null;
|
|
121
|
+
}
|
|
122
|
+
/** `ctx`: the only way a handler reaches anything. No `fetch`, no secrets, no database, no environment. */
|
|
123
|
+
export interface ServerContext {
|
|
124
|
+
/** A source the definition lists in `sources`; any other is refused (`server_function_source_undeclared`). */
|
|
125
|
+
source<K extends SourceKey>(key: K): ServerSource<K>;
|
|
126
|
+
/** Definitions values the app's config exposes — settings, fees, thresholds stay values, never constants. */
|
|
127
|
+
values: {
|
|
128
|
+
get(key: string): unknown;
|
|
129
|
+
getMany(keys: string[]): Record<string, unknown>;
|
|
130
|
+
};
|
|
131
|
+
/** The app's `veriflow` sources: `run` waits for the Automation's answer, `start` does not. */
|
|
132
|
+
automation: {
|
|
133
|
+
run<K extends SourceKey<'veriflow'>>(key: K, input?: Record<string, unknown>): SendResultOf<K>;
|
|
134
|
+
start<K extends SourceKey<'veriflow'>>(key: K, input?: Record<string, unknown>): unknown;
|
|
135
|
+
};
|
|
136
|
+
/** The visitor who called (the runtime's `user`). */
|
|
137
|
+
user: ServerVisitor;
|
|
138
|
+
/** The visitor's language. */
|
|
139
|
+
language: 'de' | 'en';
|
|
140
|
+
/** The instance the page was opened for, or null. */
|
|
141
|
+
instance: string | null;
|
|
142
|
+
/** This function's route name (kebab-case). */
|
|
143
|
+
functionName: string;
|
|
144
|
+
/** A refusal the page shows: `throw ctx.refuse('out_of_stock', 'Nicht mehr vorrätig.', 'Out of stock.')`. */
|
|
145
|
+
refuse(code: string, de: string, en: string): ServerFunctionRefusal;
|
|
146
|
+
/** Lines for the debug log (draft and test plane; R7 batch 4). */
|
|
147
|
+
log: {
|
|
148
|
+
info(text: unknown): void;
|
|
149
|
+
warn(text: unknown): void;
|
|
150
|
+
error(text: unknown): void;
|
|
151
|
+
};
|
|
152
|
+
/** The current time as an ISO string. */
|
|
153
|
+
now(): string;
|
|
154
|
+
/** A fresh random id. */
|
|
155
|
+
uuid(): string;
|
|
156
|
+
}
|
|
157
|
+
/** Who may call a function: a signed-in visitor (the pilot default) or anyone. */
|
|
158
|
+
export type ServerFunctionAccess = 'signedIn' | 'anyone' | {
|
|
159
|
+
readonly signedIn: boolean;
|
|
160
|
+
};
|
|
161
|
+
/** A definition as the author writes it. */
|
|
162
|
+
export interface ServerFunctionDefinition<S extends InputSchema | undefined, O> {
|
|
163
|
+
access?: ServerFunctionAccess;
|
|
164
|
+
sources?: readonly SourceKey[];
|
|
165
|
+
input?: S;
|
|
166
|
+
handler(input: FromSchema<S>, ctx: ServerContext): O | Promise<O>;
|
|
167
|
+
}
|
|
168
|
+
/** A defined server function. The phantom `__types` carries its input and output to the page's client stub. */
|
|
169
|
+
export interface ServerFunction<I, O> {
|
|
170
|
+
readonly access?: ServerFunctionAccess;
|
|
171
|
+
readonly sources?: readonly string[];
|
|
172
|
+
readonly input?: InputSchema;
|
|
173
|
+
readonly handler: (input: I, ctx: ServerContext) => O | Promise<O>;
|
|
174
|
+
readonly __vfServerFunction: true;
|
|
175
|
+
/** Types only; never present at run time. */
|
|
176
|
+
readonly __types?: {
|
|
177
|
+
input: I;
|
|
178
|
+
output: O;
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
/** The input a server function takes. */
|
|
182
|
+
export type ServerFunctionInput<F> = F extends ServerFunction<infer I, infer _O> ? I : never;
|
|
183
|
+
/** What a server function answers (its handler's value, awaited). */
|
|
184
|
+
export type ServerFunctionOutput<F> = F extends ServerFunction<infer _I, infer O> ? Awaited<O> : never;
|
|
185
|
+
/**
|
|
186
|
+
* Defines a server function. Export the result as a top-level `const` of a file under `src/server/`
|
|
187
|
+
* (a file or folder starting with `_` holds shared code, not functions).
|
|
188
|
+
*/
|
|
189
|
+
export declare function defineServerFunction<const S extends InputSchema | undefined = undefined, O = unknown>(definition: ServerFunctionDefinition<S, O>): ServerFunction<FromSchema<S>, O>;
|
|
190
|
+
export {};
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @veriforms/webapp-sdk/server — server functions of a web app built in code (R7 batch 3b;
|
|
3
|
+
* docs/webapp-builder/CWA-CODE-BACKEND-CONCEPT.md §5.2).
|
|
4
|
+
*
|
|
5
|
+
* PILOT, PLATFORM ADMINISTRATORS ONLY: the gateway runs server functions only for a platform administrator's
|
|
6
|
+
* own web app, pushed and released by a platform administrator, and only while the platform setting
|
|
7
|
+
* (`CwaCode:ServerFunctions`) is not `off` — it is `off` in production. Everyone else's upload of a build
|
|
8
|
+
* with `server/` is refused (`bundle_server_code_not_enabled`).
|
|
9
|
+
*
|
|
10
|
+
* Files under `src/server/` import {@link defineServerFunction} BY NAME from this module and export each
|
|
11
|
+
* definition as a top-level `const`:
|
|
12
|
+
*
|
|
13
|
+
* ```ts
|
|
14
|
+
* import { defineServerFunction } from '@veriforms/webapp-sdk/server';
|
|
15
|
+
*
|
|
16
|
+
* export const placeOrder = defineServerFunction({
|
|
17
|
+
* access: 'signedIn', // or 'anyone' / { signedIn: true }
|
|
18
|
+
* sources: ['orders'], // every config source it calls, written out
|
|
19
|
+
* input: { type: 'object', properties: { note: { type: 'string', maxLength: 200 } }, required: ['note'] },
|
|
20
|
+
* async handler(input, ctx) {
|
|
21
|
+
* const row = await ctx.source('orders').insert({ note: input.note });
|
|
22
|
+
* return { ok: true, row };
|
|
23
|
+
* },
|
|
24
|
+
* });
|
|
25
|
+
* ```
|
|
26
|
+
*
|
|
27
|
+
* The gateway READS the definition statically (`VeriForms.Ai.ServerFunctions.ServerManifestReader`): the
|
|
28
|
+
* object must be a literal, `sources` an array of quoted names, `input` a literal JSON-Schema subset
|
|
29
|
+
* (`type`, `properties`, `required`, `items`, `maxLength`, `maximum`, `enum`), and every `ctx.source('…')`,
|
|
30
|
+
* `ctx.automation.run('…')` / `.start('…')` in it must name a declared source in quotes. The export name in
|
|
31
|
+
* camelCase is served in kebab-case: `placeOrder` → `POST /a/{app}/fn/place-order`.
|
|
32
|
+
*
|
|
33
|
+
* At run time the gateway provides this module itself (the build keeps the import), and it exports
|
|
34
|
+
* `defineServerFunction` and nothing else — so this entry exports nothing else at run time either (types
|
|
35
|
+
* aside); the Vite plugin refuses any other name imported from it. The implementation here only matters for
|
|
36
|
+
* local tests, and marks a definition exactly as the runtime does.
|
|
37
|
+
*/
|
|
38
|
+
/**
|
|
39
|
+
* Defines a server function. Export the result as a top-level `const` of a file under `src/server/`
|
|
40
|
+
* (a file or folder starting with `_` holds shared code, not functions).
|
|
41
|
+
*/
|
|
42
|
+
export function defineServerFunction(definition) {
|
|
43
|
+
if (definition === null || typeof definition !== 'object' || typeof definition.handler !== 'function') {
|
|
44
|
+
throw new TypeError('defineServerFunction(...) needs an object with a handler function.');
|
|
45
|
+
}
|
|
46
|
+
const out = Object.assign({}, definition);
|
|
47
|
+
Object.defineProperty(out, '__vfServerFunction', { value: true });
|
|
48
|
+
return Object.freeze(out);
|
|
49
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The page side of server functions (R7 batch 3b; CWA-CODE-BACKEND-CONCEPT §5.2): the client stub that
|
|
3
|
+
* calls `POST {app}/fn/{route}` with the bundle hash the page was served with, and turns every refusal into a
|
|
4
|
+
* typed {@link ServerFunctionError}. PILOT, PLATFORM ADMINISTRATORS ONLY (see `@veriforms/webapp-sdk/server`).
|
|
5
|
+
*
|
|
6
|
+
* ```ts
|
|
7
|
+
* import { server, callServerFunction, isServerFunctionError } from '@veriforms/webapp-sdk';
|
|
8
|
+
*
|
|
9
|
+
* const { orderId } = await server.placeOrder({ note: 'Bitte schnell' }); // typed from src/server/
|
|
10
|
+
* await callServerFunction('placeOrder', { note: '…' }); // the same call, by name
|
|
11
|
+
* ```
|
|
12
|
+
*
|
|
13
|
+
* Version skew (X9): every call sends the hash of the build the page was served with (`X-VF-Bundle`). When
|
|
14
|
+
* the app has been released again since, the gateway answers `409 server_function_version_changed` and never
|
|
15
|
+
* runs the old code — the stub then RELOADS the page (once per build, so a page served stale twice does not
|
|
16
|
+
* reload in a loop) and rejects with {@link ServerFunctionVersionChangedError}.
|
|
17
|
+
*/
|
|
18
|
+
import type { ServerFunctionInput, ServerFunctionOutput } from './server.js';
|
|
19
|
+
/** The header the stub sends the bundle hash in (`CwaServerFunctions.BundleHeader`; pinned by a test). */
|
|
20
|
+
export declare const SERVER_FUNCTION_BUNDLE_HEADER = "X-VF-Bundle";
|
|
21
|
+
/** The header every answer names its run in (`CwaServerFunctions.RunHeader`). */
|
|
22
|
+
export declare const SERVER_FUNCTION_RUN_HEADER = "X-VF-Run";
|
|
23
|
+
/** The repeat key of one call (`WriteOutcome.KeyHeader`): the same key replays the call's writes (X6). */
|
|
24
|
+
export declare const SERVER_FUNCTION_IDEMPOTENCY_HEADER = "Idempotency-Key";
|
|
25
|
+
/** The module server code imports `defineServerFunction` from (`CwaServerFunctions.SdkModule`). */
|
|
26
|
+
export declare const SERVER_SDK_MODULE = "@veriforms/webapp-sdk/server";
|
|
27
|
+
/** The JSON-Schema keywords an input contract may use (`ServerManifestReader.SchemaKeywords`). */
|
|
28
|
+
export declare const INPUT_SCHEMA_KEYWORDS: readonly ["type", "properties", "required", "items", "maxLength", "maximum", "enum"];
|
|
29
|
+
/** The types an input contract may name (`ServerManifestReader.SchemaTypes`). */
|
|
30
|
+
export declare const INPUT_SCHEMA_TYPES: readonly ["object", "array", "string", "number", "integer", "boolean", "null"];
|
|
31
|
+
/**
|
|
32
|
+
* Every refusal a server-function call can answer with, by name (`CwaServerFunctions.Codes`; a test pins
|
|
33
|
+
* the two lists equal). An author's own refusal (`ctx.refuse`) keeps the author's code and has
|
|
34
|
+
* `kind === 'server_function_refused'`.
|
|
35
|
+
*/
|
|
36
|
+
export declare const SERVER_FUNCTION_CODES: readonly ["server_functions_off", "server_functions_not_enabled", "server_function_unavailable", "server_function_not_found", "server_function_version_changed", "server_function_sign_in_required", "server_function_input_too_large", "server_function_input_invalid", "server_function_nesting_limit", "server_function_budget_exhausted", "server_function_busy", "server_function_breaker_open", "server_function_time_limit", "server_function_statement_limit", "server_function_allocation_limit", "server_function_stack_limit", "server_function_regex_limit", "server_function_forbidden", "server_function_too_many_data_calls", "server_function_source_undeclared", "server_function_source_unsupported", "server_function_source_timeout", "server_function_source_refused", "server_function_module_unknown", "server_function_output_too_large", "server_function_output_invalid", "server_function_failed", "server_function_refused", "server_function_partial", "server_manifest_mismatch"];
|
|
37
|
+
export type ServerFunctionCode = typeof SERVER_FUNCTION_CODES[number];
|
|
38
|
+
/** The stub's own codes: the request never got an answer (`network`), or one that is not the gateway's JSON (`http_error`). */
|
|
39
|
+
export type ServerFunctionClientCode = 'network' | 'http_error';
|
|
40
|
+
/**
|
|
41
|
+
* A refused or failed server-function call. `message` is the gateway's sentence in the visitor's language;
|
|
42
|
+
* `messageDe` / `messageEn` both. `outcome === 'unknown'`: the request may have run — resend with the same
|
|
43
|
+
* `idempotencyKey` (its writes are replayed, never repeated), never "failed, try again".
|
|
44
|
+
*/
|
|
45
|
+
export declare class ServerFunctionError extends Error {
|
|
46
|
+
readonly code: ServerFunctionCode | ServerFunctionClientCode | string;
|
|
47
|
+
readonly status: number | undefined;
|
|
48
|
+
/** The function's route name. */
|
|
49
|
+
readonly functionName: string;
|
|
50
|
+
/** The gateway's reference of this run (`X-VF-Run`). */
|
|
51
|
+
readonly runId: string | undefined;
|
|
52
|
+
readonly messageDe: string | undefined;
|
|
53
|
+
readonly messageEn: string | undefined;
|
|
54
|
+
/** `server_function_refused` for an author's `ctx.refuse(…)` (then `code` is the author's). */
|
|
55
|
+
readonly kind: string | undefined;
|
|
56
|
+
readonly outcome: 'unknown' | undefined;
|
|
57
|
+
readonly idempotencyKey: string;
|
|
58
|
+
/** The whole answer body (e.g. `completed` / `pending` of `server_function_partial`). */
|
|
59
|
+
readonly data: Record<string, unknown> | undefined;
|
|
60
|
+
constructor(init: {
|
|
61
|
+
code: string;
|
|
62
|
+
message: string;
|
|
63
|
+
status?: number;
|
|
64
|
+
functionName: string;
|
|
65
|
+
runId?: string;
|
|
66
|
+
messageDe?: string;
|
|
67
|
+
messageEn?: string;
|
|
68
|
+
kind?: string;
|
|
69
|
+
outcome?: 'unknown';
|
|
70
|
+
idempotencyKey: string;
|
|
71
|
+
data?: Record<string, unknown>;
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
/** 409 `server_function_version_changed`: the page is out of date; the stub has started a reload (unless it already did for this build). */
|
|
75
|
+
export declare class ServerFunctionVersionChangedError extends ServerFunctionError {
|
|
76
|
+
/** True when the stub started a reload; false when it had already reloaded for this build once. */
|
|
77
|
+
readonly reloading: boolean;
|
|
78
|
+
constructor(init: ConstructorParameters<typeof ServerFunctionError>[0], reloading: boolean);
|
|
79
|
+
}
|
|
80
|
+
/** True for a {@link ServerFunctionError}, optionally of one code. */
|
|
81
|
+
export declare function isServerFunctionError(e: unknown, code?: ServerFunctionCode | ServerFunctionClientCode | string): e is ServerFunctionError;
|
|
82
|
+
/**
|
|
83
|
+
* The page's server functions by export name — filled in by the `vf-server.d.ts` the Vite plugin writes
|
|
84
|
+
* (`placeOrder: typeof import('./src/server/placeOrder').placeOrder`). Without it every name is a string
|
|
85
|
+
* and every input and answer unknown.
|
|
86
|
+
*/
|
|
87
|
+
export interface ServerFunctionRegistry {
|
|
88
|
+
}
|
|
89
|
+
type Registered = keyof ServerFunctionRegistry extends never ? false : true;
|
|
90
|
+
/** A server function's name as the page calls it (the export name). */
|
|
91
|
+
export type ServerFunctionName = Registered extends true ? keyof ServerFunctionRegistry & string : string;
|
|
92
|
+
type InputOf<N> = N extends keyof ServerFunctionRegistry ? ServerFunctionInput<ServerFunctionRegistry[N]> : unknown;
|
|
93
|
+
type OutputOf<N> = N extends keyof ServerFunctionRegistry ? ServerFunctionOutput<ServerFunctionRegistry[N]> : unknown;
|
|
94
|
+
export interface CallOptions {
|
|
95
|
+
/** The call's repeat key (default: a fresh one). Resend with the key of an `outcome: 'unknown'` error. */
|
|
96
|
+
idempotencyKey?: string;
|
|
97
|
+
/** Reload the page on `server_function_version_changed` (default true, decision X9). */
|
|
98
|
+
reloadOnVersionChange?: boolean;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Calls a server function by its export name (`placeOrder`) or its route name (`place-order`) and resolves
|
|
102
|
+
* with its answer. Rejects with a {@link ServerFunctionError} for every refusal — never resolves with an
|
|
103
|
+
* error body.
|
|
104
|
+
*/
|
|
105
|
+
export declare function callServerFunction<N extends ServerFunctionName>(name: N, input?: InputOf<N>, opts?: CallOptions): Promise<OutputOf<N>>;
|
|
106
|
+
/** The typed stub: `server.placeOrder(input)` is `callServerFunction('placeOrder', input)`. */
|
|
107
|
+
export type ServerStub = {
|
|
108
|
+
[N in keyof ServerFunctionRegistry & string]: (input: InputOf<N>, opts?: CallOptions) => Promise<OutputOf<N>>;
|
|
109
|
+
} & (Registered extends true ? unknown : Record<string, (input?: unknown, opts?: CallOptions) => Promise<unknown>>);
|
|
110
|
+
export declare const server: ServerStub;
|
|
111
|
+
export {};
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The page side of server functions (R7 batch 3b; CWA-CODE-BACKEND-CONCEPT §5.2): the client stub that
|
|
3
|
+
* calls `POST {app}/fn/{route}` with the bundle hash the page was served with, and turns every refusal into a
|
|
4
|
+
* typed {@link ServerFunctionError}. PILOT, PLATFORM ADMINISTRATORS ONLY (see `@veriforms/webapp-sdk/server`).
|
|
5
|
+
*
|
|
6
|
+
* ```ts
|
|
7
|
+
* import { server, callServerFunction, isServerFunctionError } from '@veriforms/webapp-sdk';
|
|
8
|
+
*
|
|
9
|
+
* const { orderId } = await server.placeOrder({ note: 'Bitte schnell' }); // typed from src/server/
|
|
10
|
+
* await callServerFunction('placeOrder', { note: '…' }); // the same call, by name
|
|
11
|
+
* ```
|
|
12
|
+
*
|
|
13
|
+
* Version skew (X9): every call sends the hash of the build the page was served with (`X-VF-Bundle`). When
|
|
14
|
+
* the app has been released again since, the gateway answers `409 server_function_version_changed` and never
|
|
15
|
+
* runs the old code — the stub then RELOADS the page (once per build, so a page served stale twice does not
|
|
16
|
+
* reload in a loop) and rejects with {@link ServerFunctionVersionChangedError}.
|
|
17
|
+
*/
|
|
18
|
+
import { SdkRuntimeMismatchError } from './index.js';
|
|
19
|
+
import { serverFunctionRoute } from './serverRoute.js';
|
|
20
|
+
/** The header the stub sends the bundle hash in (`CwaServerFunctions.BundleHeader`; pinned by a test). */
|
|
21
|
+
export const SERVER_FUNCTION_BUNDLE_HEADER = 'X-VF-Bundle';
|
|
22
|
+
/** The header every answer names its run in (`CwaServerFunctions.RunHeader`). */
|
|
23
|
+
export const SERVER_FUNCTION_RUN_HEADER = 'X-VF-Run';
|
|
24
|
+
/** The repeat key of one call (`WriteOutcome.KeyHeader`): the same key replays the call's writes (X6). */
|
|
25
|
+
export const SERVER_FUNCTION_IDEMPOTENCY_HEADER = 'Idempotency-Key';
|
|
26
|
+
/** The module server code imports `defineServerFunction` from (`CwaServerFunctions.SdkModule`). */
|
|
27
|
+
export const SERVER_SDK_MODULE = '@veriforms/webapp-sdk/server';
|
|
28
|
+
/** The JSON-Schema keywords an input contract may use (`ServerManifestReader.SchemaKeywords`). */
|
|
29
|
+
export const INPUT_SCHEMA_KEYWORDS = ['type', 'properties', 'required', 'items', 'maxLength', 'maximum', 'enum'];
|
|
30
|
+
/** The types an input contract may name (`ServerManifestReader.SchemaTypes`). */
|
|
31
|
+
export const INPUT_SCHEMA_TYPES = ['object', 'array', 'string', 'number', 'integer', 'boolean', 'null'];
|
|
32
|
+
/**
|
|
33
|
+
* Every refusal a server-function call can answer with, by name (`CwaServerFunctions.Codes`; a test pins
|
|
34
|
+
* the two lists equal). An author's own refusal (`ctx.refuse`) keeps the author's code and has
|
|
35
|
+
* `kind === 'server_function_refused'`.
|
|
36
|
+
*/
|
|
37
|
+
export const SERVER_FUNCTION_CODES = [
|
|
38
|
+
'server_functions_off',
|
|
39
|
+
'server_functions_not_enabled',
|
|
40
|
+
'server_function_unavailable',
|
|
41
|
+
'server_function_not_found',
|
|
42
|
+
'server_function_version_changed',
|
|
43
|
+
'server_function_sign_in_required',
|
|
44
|
+
'server_function_input_too_large',
|
|
45
|
+
'server_function_input_invalid',
|
|
46
|
+
'server_function_nesting_limit',
|
|
47
|
+
'server_function_budget_exhausted',
|
|
48
|
+
'server_function_busy',
|
|
49
|
+
'server_function_breaker_open',
|
|
50
|
+
'server_function_time_limit',
|
|
51
|
+
'server_function_statement_limit',
|
|
52
|
+
'server_function_allocation_limit',
|
|
53
|
+
'server_function_stack_limit',
|
|
54
|
+
'server_function_regex_limit',
|
|
55
|
+
'server_function_forbidden',
|
|
56
|
+
'server_function_too_many_data_calls',
|
|
57
|
+
'server_function_source_undeclared',
|
|
58
|
+
'server_function_source_unsupported',
|
|
59
|
+
'server_function_source_timeout',
|
|
60
|
+
'server_function_source_refused',
|
|
61
|
+
'server_function_module_unknown',
|
|
62
|
+
'server_function_output_too_large',
|
|
63
|
+
'server_function_output_invalid',
|
|
64
|
+
'server_function_failed',
|
|
65
|
+
'server_function_refused',
|
|
66
|
+
'server_function_partial',
|
|
67
|
+
'server_manifest_mismatch',
|
|
68
|
+
];
|
|
69
|
+
/**
|
|
70
|
+
* A refused or failed server-function call. `message` is the gateway's sentence in the visitor's language;
|
|
71
|
+
* `messageDe` / `messageEn` both. `outcome === 'unknown'`: the request may have run — resend with the same
|
|
72
|
+
* `idempotencyKey` (its writes are replayed, never repeated), never "failed, try again".
|
|
73
|
+
*/
|
|
74
|
+
export class ServerFunctionError extends Error {
|
|
75
|
+
constructor(init) {
|
|
76
|
+
super(init.message);
|
|
77
|
+
this.name = 'ServerFunctionError';
|
|
78
|
+
this.code = init.code;
|
|
79
|
+
this.status = init.status;
|
|
80
|
+
this.functionName = init.functionName;
|
|
81
|
+
this.runId = init.runId;
|
|
82
|
+
this.messageDe = init.messageDe;
|
|
83
|
+
this.messageEn = init.messageEn;
|
|
84
|
+
this.kind = init.kind;
|
|
85
|
+
this.outcome = init.outcome;
|
|
86
|
+
this.idempotencyKey = init.idempotencyKey;
|
|
87
|
+
this.data = init.data;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/** 409 `server_function_version_changed`: the page is out of date; the stub has started a reload (unless it already did for this build). */
|
|
91
|
+
export class ServerFunctionVersionChangedError extends ServerFunctionError {
|
|
92
|
+
constructor(init, reloading) {
|
|
93
|
+
super(init);
|
|
94
|
+
this.name = 'ServerFunctionVersionChangedError';
|
|
95
|
+
this.reloading = reloading;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
/** True for a {@link ServerFunctionError}, optionally of one code. */
|
|
99
|
+
export function isServerFunctionError(e, code) {
|
|
100
|
+
return e instanceof ServerFunctionError && (code === undefined || e.code === code);
|
|
101
|
+
}
|
|
102
|
+
function bridge() {
|
|
103
|
+
const g = globalThis;
|
|
104
|
+
const b = g.window?.__VF__ ?? g.__VF__;
|
|
105
|
+
if (!b || typeof b !== 'object')
|
|
106
|
+
throw new SdkRuntimeMismatchError('window.__VF__');
|
|
107
|
+
return b;
|
|
108
|
+
}
|
|
109
|
+
function newKey() {
|
|
110
|
+
const c = globalThis.crypto;
|
|
111
|
+
if (c?.randomUUID)
|
|
112
|
+
return c.randomUUID();
|
|
113
|
+
return 'k' + Date.now().toString(36) + Math.random().toString(36).slice(2) + Math.random().toString(36).slice(2);
|
|
114
|
+
}
|
|
115
|
+
const RELOAD_MARK = 'vf-fn-reloaded:';
|
|
116
|
+
/** Starts one reload per served build; false when this build already reloaded once (a stale page twice is not a loop). */
|
|
117
|
+
function reloadOnce(bundle) {
|
|
118
|
+
const w = globalThis.window;
|
|
119
|
+
try {
|
|
120
|
+
if (w?.sessionStorage?.getItem(RELOAD_MARK + bundle))
|
|
121
|
+
return false;
|
|
122
|
+
w?.sessionStorage?.setItem(RELOAD_MARK + bundle, String(Date.now()));
|
|
123
|
+
}
|
|
124
|
+
catch { /* storage refused: still reload once in this page's life */ }
|
|
125
|
+
if (typeof w?.location?.reload !== 'function')
|
|
126
|
+
return false;
|
|
127
|
+
w.location.reload();
|
|
128
|
+
return true;
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Calls a server function by its export name (`placeOrder`) or its route name (`place-order`) and resolves
|
|
132
|
+
* with its answer. Rejects with a {@link ServerFunctionError} for every refusal — never resolves with an
|
|
133
|
+
* error body.
|
|
134
|
+
*/
|
|
135
|
+
export async function callServerFunction(name, input, opts = {}) {
|
|
136
|
+
const route = serverFunctionRoute(name);
|
|
137
|
+
const b = bridge();
|
|
138
|
+
if (typeof b.base !== 'string' || !b.base)
|
|
139
|
+
throw new SdkRuntimeMismatchError('__VF__.base');
|
|
140
|
+
// No build hash: the page was not served from an uploaded build (or by a gateway without server functions).
|
|
141
|
+
if (typeof b.bundle !== 'string' || !b.bundle)
|
|
142
|
+
throw new SdkRuntimeMismatchError('__VF__.bundle');
|
|
143
|
+
const key = opts.idempotencyKey ?? newKey();
|
|
144
|
+
const url = `${b.base}/fn/${route}${b.preview && b.fileQuery ? b.fileQuery : ''}`;
|
|
145
|
+
const fail = (init) => new ServerFunctionError({ ...init, functionName: route, idempotencyKey: key });
|
|
146
|
+
let res;
|
|
147
|
+
try {
|
|
148
|
+
res = await fetch(url, {
|
|
149
|
+
method: 'POST',
|
|
150
|
+
credentials: 'same-origin',
|
|
151
|
+
cache: 'no-store',
|
|
152
|
+
headers: {
|
|
153
|
+
'Content-Type': 'application/json',
|
|
154
|
+
[SERVER_FUNCTION_BUNDLE_HEADER]: b.bundle,
|
|
155
|
+
[SERVER_FUNCTION_IDEMPOTENCY_HEADER]: key,
|
|
156
|
+
},
|
|
157
|
+
body: JSON.stringify(input === undefined ? null : input),
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
catch (e) {
|
|
161
|
+
// The request may or may not have reached the gateway: say so, never "failed".
|
|
162
|
+
throw fail({ code: 'network', message: `The server function "${route}" could not be reached (${e?.message ?? e}). It may have run: resend with the same idempotencyKey.`, outcome: 'unknown' });
|
|
163
|
+
}
|
|
164
|
+
const text = await res.text();
|
|
165
|
+
let body;
|
|
166
|
+
try {
|
|
167
|
+
body = text ? JSON.parse(text) : null;
|
|
168
|
+
}
|
|
169
|
+
catch {
|
|
170
|
+
body = undefined;
|
|
171
|
+
}
|
|
172
|
+
if (res.ok) {
|
|
173
|
+
if (body === undefined)
|
|
174
|
+
throw fail({ code: 'http_error', status: res.status, message: `The server function "${route}" answered something that is not JSON.` });
|
|
175
|
+
return body;
|
|
176
|
+
}
|
|
177
|
+
const data = body && typeof body === 'object' ? body : undefined;
|
|
178
|
+
const str = (k) => (data && typeof data[k] === 'string' ? data[k] : undefined);
|
|
179
|
+
const init = {
|
|
180
|
+
code: str('code') ?? 'http_error',
|
|
181
|
+
status: res.status,
|
|
182
|
+
message: str('message') ?? `The server function "${route}" answered ${res.status}.`,
|
|
183
|
+
runId: str('runId') ?? res.headers.get(SERVER_FUNCTION_RUN_HEADER) ?? undefined,
|
|
184
|
+
messageDe: str('messageDe'),
|
|
185
|
+
messageEn: str('messageEn'),
|
|
186
|
+
kind: str('kind'),
|
|
187
|
+
data,
|
|
188
|
+
};
|
|
189
|
+
if (init.code === 'server_function_version_changed') {
|
|
190
|
+
const reloading = opts.reloadOnVersionChange === false ? false : reloadOnce(b.bundle);
|
|
191
|
+
throw new ServerFunctionVersionChangedError({ ...init, functionName: route, idempotencyKey: key }, reloading);
|
|
192
|
+
}
|
|
193
|
+
throw fail(init);
|
|
194
|
+
}
|
|
195
|
+
export const server = new Proxy({}, {
|
|
196
|
+
get(_target, prop) {
|
|
197
|
+
if (typeof prop !== 'string' || prop === 'then')
|
|
198
|
+
return undefined; // not a thenable
|
|
199
|
+
return (input, opts) => callServerFunction(prop, input, opts);
|
|
200
|
+
},
|
|
201
|
+
});
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The route name of a server function (R7 batch 3b): the export name in camelCase as the author writes it,
|
|
3
|
+
* the route name in kebab-case as the gateway serves it — `placeOrder` → `place-order`
|
|
4
|
+
* (`POST /a/{app}/fn/place-order`). One rule for the SDK's client stub, the Vite plugin's build and the
|
|
5
|
+
* manifest it writes; the plugin's tests pin that both packages map the same table the same way.
|
|
6
|
+
*
|
|
7
|
+
* The result must match the gateway's name rule (`VeriForms.Ai.CwaServerFunctions.NamePattern`,
|
|
8
|
+
* {@link SERVER_FUNCTION_NAME}); a name it cannot map to one is refused by {@link serverFunctionRoute}.
|
|
9
|
+
*/
|
|
10
|
+
/** The gateway's route-name rule (`CwaServerFunctions.NamePattern`; pinned by a test). */
|
|
11
|
+
export declare const SERVER_FUNCTION_NAME: RegExp;
|
|
12
|
+
/**
|
|
13
|
+
* camelCase → kebab-case: an upper-case letter starts a new word (`placeOrder` → `place-order`), a run of
|
|
14
|
+
* capitals is one word (`getHTTPStatus` → `get-http-status`), digits and `_` stay. A name that is already a
|
|
15
|
+
* route name (`place-order`, `place_order`, `quote`) maps to itself.
|
|
16
|
+
*/
|
|
17
|
+
export declare function kebabOf(name: string): string;
|
|
18
|
+
/** The route name of `name`; throws, naming the rule, when it cannot be one. */
|
|
19
|
+
export declare function serverFunctionRoute(name: string): string;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The route name of a server function (R7 batch 3b): the export name in camelCase as the author writes it,
|
|
3
|
+
* the route name in kebab-case as the gateway serves it — `placeOrder` → `place-order`
|
|
4
|
+
* (`POST /a/{app}/fn/place-order`). One rule for the SDK's client stub, the Vite plugin's build and the
|
|
5
|
+
* manifest it writes; the plugin's tests pin that both packages map the same table the same way.
|
|
6
|
+
*
|
|
7
|
+
* The result must match the gateway's name rule (`VeriForms.Ai.CwaServerFunctions.NamePattern`,
|
|
8
|
+
* {@link SERVER_FUNCTION_NAME}); a name it cannot map to one is refused by {@link serverFunctionRoute}.
|
|
9
|
+
*/
|
|
10
|
+
/** The gateway's route-name rule (`CwaServerFunctions.NamePattern`; pinned by a test). */
|
|
11
|
+
export const SERVER_FUNCTION_NAME = /^[a-z][a-z0-9_-]{0,63}$/;
|
|
12
|
+
/**
|
|
13
|
+
* camelCase → kebab-case: an upper-case letter starts a new word (`placeOrder` → `place-order`), a run of
|
|
14
|
+
* capitals is one word (`getHTTPStatus` → `get-http-status`), digits and `_` stay. A name that is already a
|
|
15
|
+
* route name (`place-order`, `place_order`, `quote`) maps to itself.
|
|
16
|
+
*/
|
|
17
|
+
export function kebabOf(name) {
|
|
18
|
+
return name
|
|
19
|
+
.replace(/([a-z0-9])([A-Z])/g, '$1-$2')
|
|
20
|
+
.replace(/([A-Z])([A-Z][a-z])/g, '$1-$2')
|
|
21
|
+
.toLowerCase();
|
|
22
|
+
}
|
|
23
|
+
/** The route name of `name`; throws, naming the rule, when it cannot be one. */
|
|
24
|
+
export function serverFunctionRoute(name) {
|
|
25
|
+
const route = kebabOf(String(name ?? ''));
|
|
26
|
+
if (!SERVER_FUNCTION_NAME.test(route)) {
|
|
27
|
+
throw new TypeError(`"${name}" is not a server function name: a letter first, then letters, digits, "_" or "-" `
|
|
28
|
+
+ `(camelCase becomes kebab-case: placeOrder → place-order), at most 64 characters.`);
|
|
29
|
+
}
|
|
30
|
+
return route;
|
|
31
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,51 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@veriforms/webapp-sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
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
|
+
"keywords": [
|
|
6
|
+
"veriforms",
|
|
7
|
+
"web app",
|
|
8
|
+
"sdk"
|
|
9
|
+
],
|
|
10
|
+
"homepage": "https://www.veriforms.net",
|
|
11
|
+
"repository": {
|
|
12
|
+
"type": "git",
|
|
13
|
+
"url": "git+https://github.com/In-Data-Veritas-GmbH/VeriForms.git",
|
|
14
|
+
"directory": "tools/webapp-sdk"
|
|
15
|
+
},
|
|
16
|
+
"type": "module",
|
|
17
|
+
"license": "UNLICENSED",
|
|
18
|
+
"sideEffects": false,
|
|
19
|
+
"exports": {
|
|
20
|
+
".": {
|
|
21
|
+
"types": "./dist/index.d.ts",
|
|
22
|
+
"import": "./dist/index.js"
|
|
23
|
+
},
|
|
24
|
+
"./server": {
|
|
25
|
+
"types": "./dist/server.d.ts",
|
|
26
|
+
"import": "./dist/server.js"
|
|
27
|
+
},
|
|
28
|
+
"./config.schema.json": "./config.schema.json"
|
|
29
|
+
},
|
|
30
|
+
"types": "./dist/index.d.ts",
|
|
31
|
+
"files": [
|
|
32
|
+
"dist",
|
|
33
|
+
"config.schema.json",
|
|
34
|
+
"README.md",
|
|
35
|
+
"LICENSE"
|
|
36
|
+
],
|
|
37
|
+
"scripts": {
|
|
38
|
+
"build": "tsc -p tsconfig.build.json",
|
|
39
|
+
"typecheck": "tsc --noEmit",
|
|
40
|
+
"test": "vitest run",
|
|
41
|
+
"prepublishOnly": "npm run build"
|
|
42
|
+
},
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"@types/node": "22.10.2",
|
|
45
|
+
"typescript": "5.6.3",
|
|
46
|
+
"vitest": "2.1.8"
|
|
47
|
+
},
|
|
48
|
+
"publishConfig": {
|
|
49
|
+
"access": "public"
|
|
50
|
+
}
|
|
51
|
+
}
|