@veriforms/webapp-vite 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/dist/server.js ADDED
@@ -0,0 +1,721 @@
1
+ // Server functions in the Vite plugin (R7 batch 3b; docs/webapp-builder/CWA-CODE-BACKEND-CONCEPT.md §5.1–§5.3).
2
+ // PILOT, PLATFORM ADMINISTRATORS ONLY — the gateway accepts a build's server/ folder only from a platform
3
+ // administrator, for their own app, while the platform setting is not off (it is off in production).
4
+ //
5
+ // What the plugin does with src/server/ when the project opts in (veriformsWebApp({ serverFunctions: true })):
6
+ // - every file in src/server/ is a function file unless it (or a folder above it) starts with "_" — that is
7
+ // shared server code; each function file is built on its own to vf-build/server/<path>.js, shared code goes
8
+ // into vf-build/server/_shared/;
9
+ // - the import of `defineServerFunction` from @veriforms/webapp-sdk/server stays an import (the gateway's
10
+ // runtime provides that module); any other bare import, an import of page code and an import of another
11
+ // function file fail the build;
12
+ // - each exported function is served under its kebab-case route name (placeOrder → place-order): the
13
+ // build writes `export { placeOrder as "place-order" }`;
14
+ // - vf-build/server-manifest.json is the manifest the gateway derives itself
15
+ // (VeriForms.Ai.ServerFunctions.ServerManifestReader) — read from the BUILT code with the same rules, so
16
+ // the two agree; `vf app push` sends it with the build (the gateway refuses one that disagrees);
17
+ // - vf-server.d.ts registers the functions' types for the pages' client stub (`server.placeOrder(…)`).
18
+ import fs from 'node:fs';
19
+ import path from 'node:path';
20
+ import { build, parseAst } from 'vite';
21
+ /** The module server code imports `defineServerFunction` from (VeriForms.Ai.CwaServerFunctions.SdkModule). */
22
+ export const SERVER_SDK_MODULE = '@veriforms/webapp-sdk/server';
23
+ export const DEFINE_NAME = 'defineServerFunction';
24
+ /** Where the build writes the manifest (beside server/, never uploaded as a file: `vf app push` sends it as the manifest). */
25
+ export const SERVER_MANIFEST_FILE = 'server-manifest.json';
26
+ /** The types file that registers the functions for the pages (project root, next to vf-app.d.ts). */
27
+ export const SERVER_TYPES_FILE = 'vf-server.d.ts';
28
+ /** Where shared server code goes in the build. */
29
+ export const SERVER_SHARED_DIR = '_shared';
30
+ /** The route-name rule (VeriForms.Ai.CwaServerFunctions.NamePattern). */
31
+ export const SERVER_FUNCTION_NAME = /^[a-z][a-z0-9_-]{0,63}$/;
32
+ /** The keys a definition may have (ServerManifestReader.DefinitionKeys). */
33
+ export const DEFINITION_KEYS = ['access', 'sources', 'input', 'handler'];
34
+ /** The JSON-Schema subset of the input contract (ServerManifestReader.SchemaKeywords). */
35
+ export const SCHEMA_KEYWORDS = ['type', 'properties', 'required', 'items', 'maxLength', 'maximum', 'enum'];
36
+ export const SCHEMA_TYPES = ['object', 'array', 'string', 'number', 'integer', 'boolean', 'null'];
37
+ /** Globals server code may not name (ServerManifestReader.ForbiddenGlobals). */
38
+ export const FORBIDDEN_GLOBALS = ['eval', 'Function', 'WebAssembly', 'SharedArrayBuffer', 'Atomics'];
39
+ /** At most this many functions (CwaServerFunctions.MaxFunctions). */
40
+ export const MAX_FUNCTIONS = 50;
41
+ /**
42
+ * camelCase → kebab-case route name — the SDK's `kebabOf` (tools/webapp-sdk/src/serverRoute.ts), the same
43
+ * rule; test/serverBuild.test.ts maps one table through both.
44
+ */
45
+ export function kebabOf(name) {
46
+ return name
47
+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
48
+ .replace(/([A-Z])([A-Z][a-z])/g, '$1-$2')
49
+ .toLowerCase();
50
+ }
51
+ const CODE_FILE = /\.(ts|tsx|js|mjs)$/;
52
+ /** The function files of src/server/: entry name (path below server/ without extension) → file. Shared code (a "_" file or folder) is not one. */
53
+ export function findServerFunctionFiles(serverDir) {
54
+ const entries = {};
55
+ const walk = (dir, rel) => {
56
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
57
+ if (entry.name.startsWith('_') || entry.name.startsWith('.'))
58
+ continue;
59
+ const full = path.join(dir, entry.name);
60
+ if (entry.isDirectory()) {
61
+ walk(full, rel ? `${rel}/${entry.name}` : entry.name);
62
+ continue;
63
+ }
64
+ if (!CODE_FILE.test(entry.name) || entry.name.endsWith('.d.ts') || /\.(test|spec)\./.test(entry.name))
65
+ continue;
66
+ const name = (rel ? `${rel}/` : '') + entry.name.replace(CODE_FILE, '');
67
+ entries[name] = full;
68
+ }
69
+ };
70
+ if (fs.existsSync(serverDir))
71
+ walk(serverDir, '');
72
+ return entries;
73
+ }
74
+ /** True when `file` is inside `dir`. */
75
+ export function isInside(dir, file) {
76
+ const rel = path.relative(dir, file);
77
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
78
+ }
79
+ /** True for a function file of src/server/ (not shared code): no "_" segment below server/. */
80
+ export function isFunctionFile(serverDir, file) {
81
+ if (!isInside(serverDir, file))
82
+ return false;
83
+ return !path.relative(serverDir, file).split(/[\\/]/).some((seg) => seg.startsWith('_'));
84
+ }
85
+ /** The data-source keys of a config.json ("dataSources", without "_" notes); null when it does not parse (then not checked). */
86
+ export function configSourceKeys(configJson) {
87
+ if (configJson === undefined)
88
+ return null;
89
+ try {
90
+ const doc = JSON.parse(configJson.trim() ? configJson : '{}');
91
+ if (!doc || typeof doc !== 'object' || Array.isArray(doc))
92
+ return null;
93
+ const sources = doc.dataSources;
94
+ if (!sources || typeof sources !== 'object' || Array.isArray(sources))
95
+ return [];
96
+ return Object.keys(sources).filter((k) => !k.startsWith('_'));
97
+ }
98
+ catch {
99
+ return null;
100
+ }
101
+ }
102
+ const isNode = (v) => !!v && typeof v === 'object' && typeof v.type === 'string';
103
+ function children(node) {
104
+ const out = [];
105
+ for (const [key, value] of Object.entries(node)) {
106
+ if (key === 'type' || key === 'start' || key === 'end' || key === 'loc' || key === 'range')
107
+ continue;
108
+ if (Array.isArray(value)) {
109
+ for (const v of value)
110
+ if (isNode(v))
111
+ out.push(v);
112
+ }
113
+ else if (isNode(value))
114
+ out.push(value);
115
+ }
116
+ return out;
117
+ }
118
+ function descendants(root) {
119
+ const out = [];
120
+ const stack = [root];
121
+ while (stack.length) {
122
+ const n = stack.pop();
123
+ out.push(n);
124
+ for (const c of children(n))
125
+ stack.push(c);
126
+ }
127
+ return out;
128
+ }
129
+ const nameOf = (n) => {
130
+ if (!isNode(n))
131
+ return undefined;
132
+ if (n.type === 'Identifier')
133
+ return n.name;
134
+ if (n.type === 'Literal' && typeof n.value === 'string')
135
+ return n.value;
136
+ return undefined;
137
+ };
138
+ const isString = (n) => isNode(n) && n.type === 'Literal' && typeof n.value === 'string';
139
+ /** A literal expression as JSON (objects with keys written out, arrays, strings, numbers, booleans, null); undefined otherwise. */
140
+ function literal(node) {
141
+ switch (node.type) {
142
+ case 'ObjectExpression': {
143
+ const obj = {};
144
+ for (const p of node.properties) {
145
+ if (p.type !== 'Property' || p.computed || p.kind !== 'init' || p.method || p.shorthand)
146
+ return undefined;
147
+ const key = nameOf(p.key);
148
+ if (key === undefined || Object.prototype.hasOwnProperty.call(obj, key))
149
+ return undefined;
150
+ const value = literal(p.value);
151
+ if (value === undefined)
152
+ return undefined;
153
+ obj[key] = value;
154
+ }
155
+ return obj;
156
+ }
157
+ case 'ArrayExpression': {
158
+ const arr = [];
159
+ for (const e of node.elements) {
160
+ if (!e || e.type === 'SpreadElement')
161
+ return undefined;
162
+ const value = literal(e);
163
+ if (value === undefined)
164
+ return undefined;
165
+ arr.push(value);
166
+ }
167
+ return arr;
168
+ }
169
+ case 'Literal':
170
+ if (node.regex || node.bigint)
171
+ return undefined;
172
+ return typeof node.value === 'string' || typeof node.value === 'number' || typeof node.value === 'boolean' || node.value === null ? node.value : undefined;
173
+ case 'UnaryExpression':
174
+ if (node.operator === '-' && isNode(node.argument) && node.argument.type === 'Literal' && typeof node.argument.value === 'number')
175
+ return -node.argument.value;
176
+ return undefined;
177
+ default:
178
+ return undefined;
179
+ }
180
+ }
181
+ /** Sorted keys, compact (ServerManifestReader.Canonical) — so two writings of one schema compare equal. */
182
+ export function canonical(value) {
183
+ if (value === null || typeof value !== 'object')
184
+ return JSON.stringify(value);
185
+ if (Array.isArray(value))
186
+ return '[' + value.map(canonical).join(',') + ']';
187
+ const keys = Object.keys(value).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
188
+ return '{' + keys.map((k) => JSON.stringify(k) + ':' + canonical(value[k])).join(',') + '}';
189
+ }
190
+ function schemaProblems(node, where, problems) {
191
+ if (!node || typeof node !== 'object' || Array.isArray(node)) {
192
+ problems.push(`${where} must be a schema object`);
193
+ return;
194
+ }
195
+ const obj = node;
196
+ for (const [key, value] of Object.entries(obj)) {
197
+ switch (key) {
198
+ case 'type':
199
+ if (typeof value !== 'string' || !SCHEMA_TYPES.includes(value))
200
+ problems.push(`${where}.type must be one of ${SCHEMA_TYPES.join(', ')}`);
201
+ break;
202
+ case 'properties':
203
+ if (!value || typeof value !== 'object' || Array.isArray(value))
204
+ problems.push(`${where}.properties must be an object of schemas`);
205
+ else
206
+ for (const [prop, schema] of Object.entries(value))
207
+ schemaProblems(schema, `${where}.properties.${prop}`, problems);
208
+ break;
209
+ case 'items':
210
+ schemaProblems(value, `${where}.items`, problems);
211
+ break;
212
+ case 'required':
213
+ if (!Array.isArray(value) || value.some((r) => typeof r !== 'string'))
214
+ problems.push(`${where}.required must be an array of property names`);
215
+ else if (obj.properties && typeof obj.properties === 'object' && !Array.isArray(obj.properties))
216
+ for (const r of value)
217
+ if (!Object.prototype.hasOwnProperty.call(obj.properties, r))
218
+ problems.push(`${where}.required names '${r}', which is not in properties`);
219
+ break;
220
+ case 'maxLength':
221
+ if (typeof value !== 'number' || value < 0 || !Number.isInteger(value))
222
+ problems.push(`${where}.maxLength must be a whole number of 0 or more`);
223
+ break;
224
+ case 'maximum':
225
+ if (typeof value !== 'number')
226
+ problems.push(`${where}.maximum must be a number`);
227
+ break;
228
+ case 'enum':
229
+ if (!Array.isArray(value) || value.length === 0 || value.some((e) => e !== null && typeof e === 'object'))
230
+ problems.push(`${where}.enum must be a non-empty array of plain values`);
231
+ break;
232
+ default:
233
+ problems.push(`${where}: the schema keyword '${key}' is not supported (allowed: ${SCHEMA_KEYWORDS.join(', ')})`);
234
+ }
235
+ }
236
+ }
237
+ /**
238
+ * The manifest of the built server files (path under the build → code), read with the gateway's rules
239
+ * (ServerManifestReader.Derive). `configSources`: the config's source keys; null = not checked.
240
+ */
241
+ export function deriveServerManifest(files, configSources) {
242
+ const errors = [];
243
+ const functions = [];
244
+ for (const f of [...files].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)))
245
+ readFile(f.path, f.code, configSources, errors, functions);
246
+ const byName = new Map();
247
+ for (const f of functions)
248
+ byName.set(f.name, [...(byName.get(f.name) ?? []), f]);
249
+ for (const [name, list] of byName) {
250
+ if (list.length > 1)
251
+ errors.push(`${list[0].file}: the server function '${name}' is defined more than once (${list.map((d) => d.file).join(', ')}); every function needs its own name`);
252
+ }
253
+ if (functions.length > MAX_FUNCTIONS)
254
+ errors.push(`The build defines ${functions.length} server functions; a web app may have at most ${MAX_FUNCTIONS}.`);
255
+ functions.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
256
+ return { manifest: { version: 1, functions }, errors };
257
+ }
258
+ function readFile(file, code, configSources, errors, out) {
259
+ const lineOf = (n) => code.slice(0, n.start).split('\n').length;
260
+ const unreadable = (line, en) => errors.push(`${file}:${line} — ${en}. The server reads server code statically and refuses what it cannot read.`);
261
+ const definition = (line, en) => errors.push(`${file}:${line} — ${en}.`);
262
+ const forbidden = (line, what) => errors.push(`${file}:${line} — server code may not use ${what} (eval, the Function constructor, WebAssembly, SharedArrayBuffer, Atomics, a computed import() and writes to globalThis are refused).`);
263
+ let program;
264
+ try {
265
+ program = parseAst(code);
266
+ }
267
+ catch (e) {
268
+ unreadable(1, `it does not parse as a JavaScript module (${e.message})`);
269
+ return;
270
+ }
271
+ const body = program.body;
272
+ const aliases = new Set();
273
+ const definitionCalls = new Set();
274
+ // 1. The SDK import: defineServerFunction by name (an alias is fine).
275
+ for (const st of body) {
276
+ if (st.type !== 'ImportDeclaration' || !isString(st.source) || st.source.value !== SERVER_SDK_MODULE)
277
+ continue;
278
+ for (const spec of st.specifiers) {
279
+ if (spec.type === 'ImportSpecifier' && nameOf(spec.imported) === DEFINE_NAME)
280
+ aliases.add(nameOf(spec.local));
281
+ else if (spec.type === 'ImportNamespaceSpecifier' || spec.type === 'ImportDefaultSpecifier')
282
+ unreadable(lineOf(spec), `'${SERVER_SDK_MODULE}' is imported as a whole; import ${DEFINE_NAME} by name so the server can read the functions`);
283
+ }
284
+ }
285
+ const isDefineCallee = (n) => isNode(n) && n.type === 'Identifier' && aliases.has(n.name);
286
+ // 2. Top-level definitions: const <local> = defineServerFunction({…}).
287
+ const locals = new Map();
288
+ const exportedDirect = [];
289
+ for (const st of body) {
290
+ const [decl, exported] = st.type === 'VariableDeclaration' ? [st, false]
291
+ : st.type === 'ExportNamedDeclaration' && isNode(st.declaration) && st.declaration.type === 'VariableDeclaration' ? [st.declaration, true]
292
+ : [undefined, false];
293
+ if (!decl)
294
+ continue;
295
+ for (const d of decl.declarations) {
296
+ const init = d.init;
297
+ if (!init || init.type !== 'CallExpression' || !isDefineCallee(init.callee))
298
+ continue;
299
+ if (decl.kind !== 'const' || !isNode(d.id) || d.id.type !== 'Identifier') {
300
+ unreadable(lineOf(d), `a server function is defined with '${decl.kind}' or a destructuring pattern; write 'export const name = ${DEFINE_NAME}({…})'`);
301
+ continue;
302
+ }
303
+ definitionCalls.add(init);
304
+ locals.set(d.id.name, { call: init, line: lineOf(d) });
305
+ if (exported)
306
+ exportedDirect.push(d.id.name);
307
+ }
308
+ }
309
+ // 3. Exports: the direct ones and export { local as name }.
310
+ const exports = exportedDirect.map((l) => ({ name: l, local: l, line: locals.get(l).line }));
311
+ const mentions = (n) => descendants(n).some((x) => x.type === 'Identifier' && aliases.has(x.name));
312
+ for (const st of body) {
313
+ if (st.type === 'ExportNamedDeclaration' && !st.source && !st.declaration) {
314
+ for (const spec of st.specifiers) {
315
+ const local = nameOf(spec.local);
316
+ if (!local || !locals.has(local))
317
+ continue;
318
+ exports.push({ name: nameOf(spec.exported) ?? '', local, line: lineOf(spec) });
319
+ }
320
+ }
321
+ else if (st.type === 'ExportDefaultDeclaration' && mentions(st)) {
322
+ unreadable(lineOf(st), `a server function is the default export; a function needs a name — write 'export const name = ${DEFINE_NAME}({…})'`);
323
+ }
324
+ }
325
+ for (const [local, { line }] of locals) {
326
+ const names = exports.filter((e) => e.local === local);
327
+ if (names.length === 0)
328
+ unreadable(line, `'${local}' is defined with ${DEFINE_NAME} but not exported; only an exported function can be called`);
329
+ else if (names.length > 1)
330
+ unreadable(line, `'${local}' is exported under more than one name (${names.map((n) => n.name).join(', ')}); export each function once`);
331
+ }
332
+ // 4. Everything else: forbidden constructs, and defineServerFunction anywhere else.
333
+ const stack = [{ node: program, parent: null }];
334
+ while (stack.length) {
335
+ const { node, parent } = stack.pop();
336
+ if (node.type === 'ImportDeclaration')
337
+ continue;
338
+ if (node.type === 'Identifier' && isReference(node, parent)) {
339
+ const name = node.name;
340
+ if (aliases.has(name) && !(parent && parent.type === 'CallExpression' && parent.callee === node && definitionCalls.has(parent)))
341
+ unreadable(lineOf(node), `${DEFINE_NAME} is used at line ${lineOf(node)} where the server cannot read it; only 'export const name = ${DEFINE_NAME}({…})' at the top of a file defines a function`);
342
+ else if (FORBIDDEN_GLOBALS.includes(name))
343
+ forbidden(lineOf(node), `'${name}'`);
344
+ }
345
+ else if (node.type === 'ImportExpression' && !isString(node.source)) {
346
+ forbidden(lineOf(node), 'import() with a computed module name');
347
+ }
348
+ else if (node.type === 'AssignmentExpression' && isNode(node.left) && node.left.type === 'MemberExpression'
349
+ && isNode(node.left.object) && node.left.object.type === 'Identifier' && node.left.object.name === 'globalThis') {
350
+ forbidden(lineOf(node), 'a write to globalThis');
351
+ }
352
+ for (const c of children(node))
353
+ stack.push({ node: c, parent: node });
354
+ }
355
+ // 5. Each exported definition.
356
+ for (const { name, local, line } of exports) {
357
+ if (!SERVER_FUNCTION_NAME.test(name)) {
358
+ definition(line, `'${name}' is not a server function name: lower case letters, digits, '_' and '-', starting with a letter, at most 64 characters (e.g. place_order)`);
359
+ continue;
360
+ }
361
+ const entry = readDefinition(name, locals.get(local).call);
362
+ if (entry)
363
+ out.push(entry);
364
+ }
365
+ function readDefinition(name, call) {
366
+ const before = errors.length;
367
+ const args = call.arguments;
368
+ if (args.length !== 1 || args[0].type !== 'ObjectExpression') {
369
+ unreadable(lineOf(call), `'${name}': ${DEFINE_NAME} takes one object literal; the server cannot read anything else`);
370
+ return undefined;
371
+ }
372
+ const def = args[0];
373
+ let access = 'signedIn';
374
+ let sources = [];
375
+ let schema = null;
376
+ let hasHandler = false;
377
+ for (const p of def.properties) {
378
+ const key = p.type === 'Property' && !p.computed ? nameOf(p.key) : undefined;
379
+ if (key === undefined) {
380
+ unreadable(lineOf(p), `'${name}': the definition has a spread or a computed key; write each key out`);
381
+ continue;
382
+ }
383
+ switch (key) {
384
+ case 'handler':
385
+ hasHandler = true;
386
+ break;
387
+ case 'access':
388
+ access = readAccess(name, p.value) ?? access;
389
+ break;
390
+ case 'sources':
391
+ sources = readSources(name, p.value);
392
+ break;
393
+ case 'input':
394
+ schema = readInput(name, p.value);
395
+ break;
396
+ default: definition(lineOf(p), `'${name}': '${key}' is not a key of a server function definition (allowed: ${DEFINITION_KEYS.join(', ')})`);
397
+ }
398
+ }
399
+ if (!hasHandler)
400
+ definition(lineOf(call), `'${name}' has no handler`);
401
+ for (const c of descendants(def)) {
402
+ if (c.type !== 'CallExpression')
403
+ continue;
404
+ const kind = dataCallKind(c);
405
+ if (!kind)
406
+ continue;
407
+ const first = c.arguments[0];
408
+ if (!isString(first)) {
409
+ unreadable(lineOf(c), `'${name}': ${kind}(…) names its source with a computed key; write the source name in quotes`);
410
+ continue;
411
+ }
412
+ if (!sources.includes(first.value))
413
+ errors.push(`${file}:${lineOf(c)} — the server function '${name}' calls the source '${first.value}' (line ${lineOf(c)}) but does not list it in 'sources'. Add it to 'sources'.`);
414
+ }
415
+ if (configSources)
416
+ for (const s of sources.filter((x) => !configSources.includes(x)))
417
+ errors.push(`${file}:${lineOf(call)} — the server function '${name}' declares the source '${s}', which config.json does not have. Add the source to config.json or remove it from 'sources'.`);
418
+ if (errors.length !== before)
419
+ return undefined;
420
+ return { name, file, sources, access, inputSchemaJson: schema };
421
+ }
422
+ function readAccess(name, value) {
423
+ if (isString(value)) {
424
+ if (value.value === 'signedIn' || value.value === 'anyone')
425
+ return value.value;
426
+ }
427
+ else if (value.type === 'ObjectExpression') {
428
+ let result;
429
+ let bad = false;
430
+ for (const p of value.properties) {
431
+ if (p.type === 'Property' && !p.computed && nameOf(p.key) === 'signedIn' && isNode(p.value) && p.value.type === 'Literal' && typeof p.value.value === 'boolean')
432
+ result = p.value.value ? 'signedIn' : 'anyone';
433
+ else
434
+ bad = true;
435
+ }
436
+ if (!bad && result)
437
+ return result;
438
+ }
439
+ definition(lineOf(value), `'${name}': access is "signedIn", "anyone" or { signedIn: true|false } written out (minLevel and roles are not supported for server functions yet — put them on the sources it calls)`);
440
+ return undefined;
441
+ }
442
+ function readSources(name, value) {
443
+ const list = [];
444
+ if (value.type !== 'ArrayExpression') {
445
+ unreadable(lineOf(value), `'${name}': sources is an array of source names written out`);
446
+ return list;
447
+ }
448
+ for (const e of value.elements) {
449
+ if (isString(e) && e.value.length > 0) {
450
+ if (list.includes(e.value))
451
+ definition(lineOf(e), `'${name}': the source '${e.value}' is listed twice`);
452
+ else
453
+ list.push(e.value);
454
+ }
455
+ else
456
+ unreadable(e ? lineOf(e) : lineOf(value), `'${name}': every entry of sources is a source name in quotes`);
457
+ }
458
+ return list;
459
+ }
460
+ function readInput(name, value) {
461
+ if (value.type === 'Literal' && value.value === null)
462
+ return null;
463
+ const json = literal(value);
464
+ if (json === undefined) {
465
+ unreadable(lineOf(value), `'${name}': input is a JSON schema written as a literal (no variables, calls or spreads)`);
466
+ return null;
467
+ }
468
+ const problems = [];
469
+ schemaProblems(json, 'input', problems);
470
+ for (const p of problems.slice(0, 5))
471
+ definition(lineOf(value), `'${name}': ${p}`);
472
+ return problems.length === 0 ? canonical(json) : null;
473
+ }
474
+ }
475
+ /** "source", "automation.run" or "automation.start" for a data call, else undefined. */
476
+ function dataCallKind(call) {
477
+ const m = call.callee;
478
+ if (m.type !== 'MemberExpression' || m.computed || !isNode(m.property) || m.property.type !== 'Identifier')
479
+ return undefined;
480
+ const prop = m.property.name;
481
+ if (prop === 'source')
482
+ return 'source';
483
+ if ((prop === 'run' || prop === 'start') && isNode(m.object) && m.object.type === 'MemberExpression' && !m.object.computed
484
+ && isNode(m.object.property) && m.object.property.type === 'Identifier' && m.object.property.name === 'automation')
485
+ return 'automation.' + prop;
486
+ return undefined;
487
+ }
488
+ /** An identifier that names a binding (not a property name or an object key) — ServerManifestReader.IsReference. */
489
+ function isReference(id, parent) {
490
+ if (!parent)
491
+ return true;
492
+ switch (parent.type) {
493
+ case 'MemberExpression': return !!parent.computed || parent.property !== id;
494
+ case 'Property': return !!parent.computed || parent.key !== id || !!parent.shorthand;
495
+ case 'MethodDefinition':
496
+ case 'PropertyDefinition': return !!parent.computed || parent.key !== id;
497
+ case 'ExportSpecifier': return !(parent.exported === id && parent.local !== id);
498
+ case 'LabeledStatement':
499
+ case 'BreakStatement':
500
+ case 'ContinueStatement': return false;
501
+ default: return true;
502
+ }
503
+ }
504
+ // ── Renaming the exports to their routes ─────────────────────────────────────────────────────────────────
505
+ /**
506
+ * The built entry chunk with every export list naming its kebab-case route: `export { placeOrder }` →
507
+ * `export { placeOrder as "place-order" }`. Names already routes stay as they are. Returns the code and the
508
+ * renames (export name → route) for the types file and the errors (two exports on one route).
509
+ */
510
+ export function renameExportsToRoutes(code) {
511
+ const program = parseAst(code);
512
+ const edits = [];
513
+ const renamed = [];
514
+ const errors = [];
515
+ const routes = new Map();
516
+ for (const st of program.body) {
517
+ if (st.type !== 'ExportNamedDeclaration' || st.source || st.declaration)
518
+ continue;
519
+ for (const spec of st.specifiers) {
520
+ const exported = nameOf(spec.exported);
521
+ if (exported === undefined)
522
+ continue;
523
+ const route = kebabOf(exported);
524
+ const clash = routes.get(route);
525
+ if (clash !== undefined && clash !== exported)
526
+ errors.push(`the exports '${clash}' and '${exported}' are both served as '${route}'; rename one`);
527
+ routes.set(route, exported);
528
+ if (route === exported)
529
+ continue;
530
+ edits.push({ start: spec.exported.start, end: spec.exported.end, text: JSON.stringify(route) });
531
+ if (spec.local === spec.exported || spec.local.start === spec.exported.start) {
532
+ // `export { placeOrder }`: the local name has to be written out before the new one.
533
+ edits[edits.length - 1].text = `${nameOf(spec.local)} as ${JSON.stringify(route)}`;
534
+ }
535
+ renamed.push({ from: exported, to: route });
536
+ }
537
+ }
538
+ let out = code;
539
+ for (const e of edits.sort((a, b) => b.start - a.start))
540
+ out = out.slice(0, e.start) + e.text + out.slice(e.end);
541
+ return { code: out, renamed, errors };
542
+ }
543
+ // ── The pages' types ─────────────────────────────────────────────────────────────────────────────────────
544
+ /**
545
+ * The exported definitions of a function file's source, by export name — read with a pattern (types only:
546
+ * a definition it misses is a compile error in the page, never a wrong route; the route and the manifest
547
+ * come from the built code).
548
+ */
549
+ export function definedExports(source) {
550
+ const aliases = [...source.matchAll(/import\s*(?:type\s+)?\{([^}]*)\}\s*from\s*["']@veriforms\/webapp-sdk\/server["']/g)]
551
+ .flatMap((m) => m[1].split(',').map((s) => s.trim()).filter(Boolean))
552
+ .map((s) => s.match(/^defineServerFunction(?:\s+as\s+([\w$]+))?$/))
553
+ .filter((m) => !!m)
554
+ .map((m) => m[1] ?? DEFINE_NAME);
555
+ if (aliases.length === 0)
556
+ return [];
557
+ const names = [];
558
+ const alias = aliases.map((a) => a.replace(/\$/g, '\\$')).join('|');
559
+ for (const m of source.matchAll(new RegExp(`export\\s+const\\s+([\\w$]+)\\s*(?::[^=]+)?=\\s*(?:${alias})\\s*\\(`, 'g')))
560
+ names.push(m[1]);
561
+ const locals = [...source.matchAll(new RegExp(`(?:^|\\n)\\s*const\\s+([\\w$]+)\\s*(?::[^=]+)?=\\s*(?:${alias})\\s*\\(`, 'g'))].map((m) => m[1]);
562
+ for (const m of source.matchAll(/export\s*\{([^}]*)\}(?!\s*from)/g)) {
563
+ for (const part of m[1].split(',').map((s) => s.trim()).filter(Boolean)) {
564
+ const [local, exported] = part.split(/\s+as\s+/).map((s) => s.trim().replace(/^["']|["']$/g, ''));
565
+ if (locals.includes(local))
566
+ names.push(exported ?? local);
567
+ }
568
+ }
569
+ return [...new Set(names)];
570
+ }
571
+ /** The contents of vf-server.d.ts for the function files (entry name → file) of a project rooted at `root`. */
572
+ export function serverTypes(root, files) {
573
+ const lines = [];
574
+ for (const [entry, file] of Object.entries(files).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {
575
+ const spec = './' + path.relative(root, file).split(path.sep).join('/').replace(CODE_FILE, '');
576
+ for (const name of definedExports(fs.readFileSync(file, 'utf8'))) {
577
+ const key = /^[A-Za-z_$][\w$]*$/.test(name) ? name : JSON.stringify(name);
578
+ lines.push(` ${key}: typeof import(${JSON.stringify(spec)})[${JSON.stringify(name)}]; // ${entry}`);
579
+ }
580
+ }
581
+ return '// Generated by @veriforms/webapp-vite from src/server/ — do not edit. Types only: the pages\' client stub\n'
582
+ + '// (server.<name>(input), callServerFunction) is typed from the server functions\' definitions.\n'
583
+ + 'export {};\n\n'
584
+ + "declare module '@veriforms/webapp-sdk' {\n interface ServerFunctionRegistry {\n"
585
+ + lines.join('\n') + (lines.length ? '\n' : '')
586
+ + ' }\n}\n';
587
+ }
588
+ // ── The build ────────────────────────────────────────────────────────────────────────────────────────────
589
+ /** A refusal raised through Rollup: the sentence, no bundler frames (see index.ts `refusal`). */
590
+ function fail(message) {
591
+ return { message, stack: '' };
592
+ }
593
+ /** What in server source the gateway refuses outright and the build can say with the line. */
594
+ const SERVER_FORBIDDEN = [
595
+ { pattern: /\beval\s*\(/, what: 'eval()' },
596
+ { pattern: /\bnew\s+Function\s*\(/, what: 'new Function()' },
597
+ { pattern: /\b(?:WebAssembly|SharedArrayBuffer|Atomics)\b/, what: 'WebAssembly, SharedArrayBuffer or Atomics' },
598
+ ];
599
+ /**
600
+ * The plugin of the server build: SDK import external, the import rules, the routes. `serverDir` and
601
+ * `pagesDir` are absolute.
602
+ */
603
+ export function serverBuildPlugin(serverDir, pagesDir) {
604
+ const rel = (file) => path.relative(process.cwd(), file);
605
+ return {
606
+ name: 'veriforms-webapp-server',
607
+ enforce: 'pre',
608
+ async resolveId(id, importer) {
609
+ if (id === SERVER_SDK_MODULE)
610
+ return { id, external: true };
611
+ if (!importer || id.startsWith('\0'))
612
+ return null;
613
+ const bare = !id.startsWith('.') && !id.startsWith('/') && !/^[a-zA-Z]:[\\/]/.test(id) && !id.includes(':');
614
+ if (bare) {
615
+ this.error(fail(`[veriforms] ${rel(importer)} imports "${id}": server code imports only ${SERVER_SDK_MODULE} (for ${DEFINE_NAME}) `
616
+ + 'and its own files. Packages are not available to server functions yet; write the code under src/server/_lib/.'));
617
+ }
618
+ const resolved = await this.resolve(id, importer, { skipSelf: true });
619
+ if (!resolved || resolved.external)
620
+ return resolved;
621
+ const file = resolved.id.split('?')[0];
622
+ if (isInside(pagesDir, file)) {
623
+ this.error(fail(`[veriforms] ${rel(importer)} imports "${id}", which is page code: server code may not import from the pages.`));
624
+ }
625
+ if (isFunctionFile(serverDir, file)) {
626
+ this.error(fail(`[veriforms] ${rel(importer)} imports "${id}", which is another server function's file. `
627
+ + 'Put code two functions share into a file or folder starting with "_" (e.g. src/server/_lib/pricing.ts).'));
628
+ }
629
+ return resolved;
630
+ },
631
+ transform(code, id) {
632
+ const file = id.split('?')[0];
633
+ if (id.startsWith('\0') || !CODE_FILE.test(file)) {
634
+ if (!id.startsWith('\0') && !file.includes('/node_modules/'))
635
+ this.error(fail(`[veriforms] ${rel(file)}: server code is JavaScript or TypeScript only (no styles, images or other files).`));
636
+ return null;
637
+ }
638
+ code.split(/\r?\n/).forEach((text, i) => {
639
+ for (const f of SERVER_FORBIDDEN)
640
+ if (f.pattern.test(text))
641
+ this.error(fail(`[veriforms] ${rel(file)}:${i + 1} — server code may not use ${f.what}; the platform refuses it.`));
642
+ });
643
+ return null;
644
+ },
645
+ renderChunk(code, chunk) {
646
+ if (!chunk.isEntry)
647
+ return null;
648
+ const renamed = renameExportsToRoutes(code);
649
+ if (renamed.errors.length)
650
+ this.error(fail(`[veriforms] server/${chunk.fileName}: ${renamed.errors.join('; ')}`));
651
+ return { code: renamed.code, map: null };
652
+ },
653
+ generateBundle(_output, bundle) {
654
+ for (const item of Object.values(bundle)) {
655
+ if (item.type !== 'chunk') {
656
+ this.error(fail(`[veriforms] server code emitted ${item.fileName}: server functions are JavaScript only (no styles or assets).`));
657
+ continue;
658
+ }
659
+ const names = item.importedBindings[SERVER_SDK_MODULE] ?? [];
660
+ const other = names.filter((n) => n !== DEFINE_NAME);
661
+ if (other.length) {
662
+ this.error(fail(`[veriforms] server/${item.fileName} imports ${other.map((n) => `"${n}"`).join(', ')} from ${SERVER_SDK_MODULE}, `
663
+ + `which the platform's runtime does not provide: at run time that module exports ${DEFINE_NAME} only (types aside).`));
664
+ }
665
+ for (const dynamic of item.dynamicImports)
666
+ this.error(fail(`[veriforms] server/${item.fileName} loads ${dynamic} lazily; server code imports statically.`));
667
+ }
668
+ },
669
+ };
670
+ }
671
+ /**
672
+ * Builds the function files (entry name → file) of the project at `root` into <outDir>/server/ and writes
673
+ * <outDir>/server-manifest.json — the manifest read from the built code with the gateway's rules. Throws,
674
+ * naming every problem, when the gateway would refuse it.
675
+ */
676
+ export async function buildServerFunctions(root, outDir, files, mode, pagesDir = 'src/pages') {
677
+ const out = path.resolve(root, outDir);
678
+ const serverOut = path.join(out, 'server');
679
+ fs.rmSync(serverOut, { recursive: true, force: true });
680
+ fs.rmSync(path.join(out, SERVER_MANIFEST_FILE), { force: true });
681
+ const result = await build({
682
+ root,
683
+ mode,
684
+ configFile: false,
685
+ logLevel: 'warn',
686
+ publicDir: false,
687
+ plugins: [serverBuildPlugin(path.resolve(root, 'src', 'server'), path.resolve(root, pagesDir))],
688
+ esbuild: { legalComments: 'none' },
689
+ build: {
690
+ outDir: serverOut,
691
+ emptyOutDir: false,
692
+ copyPublicDir: false,
693
+ // ES2022: the routes are export names in quotes (`export { placeOrder as "place-order" }`), which the
694
+ // gateway's parser and runtime read; es2020 tooling refuses them.
695
+ target: 'es2022',
696
+ // Readable, as written (the release review reads it; the gateway reads the definitions).
697
+ minify: false,
698
+ sourcemap: false,
699
+ modulePreload: false,
700
+ reportCompressedSize: false,
701
+ lib: { entry: files, formats: ['es'], fileName: (_format, entry) => `${entry}.js` },
702
+ rollupOptions: {
703
+ external: [SERVER_SDK_MODULE],
704
+ output: { format: 'es', entryFileNames: '[name].js', chunkFileNames: `${SERVER_SHARED_DIR}/[name]-[hash].js` },
705
+ },
706
+ },
707
+ });
708
+ const outputs = Array.isArray(result) ? result : [result];
709
+ const chunks = outputs.flatMap((o) => o.output).filter((o) => o.type === 'chunk')
710
+ .map((c) => ({ path: `server/${c.fileName}`, code: c.code }));
711
+ const configPath = path.join(root, 'config.json');
712
+ const derived = deriveServerManifest(chunks, configSourceKeys(fs.existsSync(configPath) ? fs.readFileSync(configPath, 'utf8') : undefined));
713
+ if (derived.errors.length) {
714
+ const error = new Error('[veriforms] The server functions cannot be uploaded — the gateway reads them from the built code and would refuse:\n '
715
+ + derived.errors.join('\n '));
716
+ error.stack = error.message;
717
+ throw error;
718
+ }
719
+ fs.writeFileSync(path.join(out, SERVER_MANIFEST_FILE), JSON.stringify(derived.manifest, null, 2) + '\n');
720
+ return derived.manifest;
721
+ }