@nanobpm/urban 0.96.3 → 0.98.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/README.md +60 -0
- package/dist/runtime/connector-worker-sdk.d.ts +2 -0
- package/dist/runtime/connector-worker-sdk.js +6 -1
- package/dist/runtime/core/host.d.ts +15 -5
- package/dist/runtime/core/manifest.d.ts +23 -0
- package/dist/runtime/core/manifest.js +8 -0
- package/dist/runtime/core/modules/connectors.d.ts +3 -0
- package/dist/runtime/core/modules/connectors.js +32 -1
- package/dist/runtime/core/modules/formjs.gen.js +1 -1
- package/dist/runtime/core/modules/forms.d.ts +20 -0
- package/dist/runtime/core/modules/forms.js +47 -0
- package/dist/runtime/core/modules/pages.js +12 -1
- package/dist/runtime/core/modules/runtime.gen.js +1 -1
- package/dist/runtime/core/modules/surfaces.js +57 -4
- package/dist/runtime/core/modules/workers.js +5 -1
- package/dist/runtime/core/validate.js +12 -0
- package/dist/runtime/engine/nanosdk.d.ts +1 -0
- package/dist/runtime/engine/nanosdk.js +3 -0
- package/dist/runtime/index.d.ts +3 -3
- package/dist/runtime/index.js +1 -1
- package/package.json +2 -2
- package/src/runtime/browser/fake-dom.test-utils.ts +16 -1
- package/src/runtime/browser/formjs.browser.js +258 -7
- package/src/runtime/browser/formjs.browser.test.ts +690 -0
- package/src/runtime/browser/runtime.browser.js +25 -3
- package/src/runtime/browser/runtime.engineform.test.ts +203 -0
- package/src/runtime/connector-worker-sdk.test.ts +9 -0
- package/src/runtime/connector-worker-sdk.ts +8 -1
- package/src/runtime/core/host.ts +16 -1
- package/src/runtime/core/manifest.ts +28 -0
- package/src/runtime/core/modules/connectors.test.ts +158 -1
- package/src/runtime/core/modules/connectors.ts +44 -1
- package/src/runtime/core/modules/formjs.gen.ts +1 -1
- package/src/runtime/core/modules/forms.ts +47 -0
- package/src/runtime/core/modules/pages.test.ts +21 -0
- package/src/runtime/core/modules/pages.ts +13 -1
- package/src/runtime/core/modules/runtime.gen.ts +1 -1
- package/src/runtime/core/modules/surfaces.test.ts +308 -0
- package/src/runtime/core/modules/surfaces.ts +58 -4
- package/src/runtime/core/modules/workers.test.ts +45 -1
- package/src/runtime/core/modules/workers.ts +5 -1
- package/src/runtime/core/validate.test.ts +19 -0
- package/src/runtime/core/validate.ts +12 -0
- package/src/runtime/engine/nanosdk.test.ts +17 -0
- package/src/runtime/engine/nanosdk.ts +4 -1
- package/src/runtime/index.ts +3 -0
package/README.md
CHANGED
|
@@ -210,6 +210,38 @@ wiring; `WorkflowClient` deploys and starts, `Worker` hosts your `run` steps.
|
|
|
210
210
|
inspectable in a modeller/Operate — `@nanobpm/urban` bundles `bpmn-auto-layout`
|
|
211
211
|
so this works out of the box.
|
|
212
212
|
|
|
213
|
+
For a long-running step (transcription, an agent call, a multi-GB upload),
|
|
214
|
+
declare a job lock timeout so the engine's lease cannot expire mid-handler and
|
|
215
|
+
the job run twice — per step with `w.run(name, handler, { timeoutMs })`, or
|
|
216
|
+
worker-wide with `new Worker({ jobTimeoutMs })`:
|
|
217
|
+
|
|
218
|
+
```ts
|
|
219
|
+
const flow = defineFlow("uploads", (w) => {
|
|
220
|
+
w.run("transcode", transcode, { timeoutMs: 3_600_000 }); // 1h lock for this step
|
|
221
|
+
w.run("notify", notify); // worker-wide default (30s) applies
|
|
222
|
+
});
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
Manifest-declared workers get the same knob as `timeoutMs` on the `workers[]`
|
|
226
|
+
entry (validated as a positive integer of ms):
|
|
227
|
+
|
|
228
|
+
```jsonc
|
|
229
|
+
// nano.app.json
|
|
230
|
+
{
|
|
231
|
+
"workers": [
|
|
232
|
+
{ "taskType": "media.transcode", "handler": "workers/transcode.ts", "timeoutMs": 3600000 }
|
|
233
|
+
]
|
|
234
|
+
}
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
Connector-backed workers resolve the lock timeout from three sources, first
|
|
238
|
+
declared wins: the pack's `defineWorker({ timeoutMs })` (authoritative runtime
|
|
239
|
+
value), then the pack's `nano-ide.ext.json` worker `timeoutMs` (design-time
|
|
240
|
+
default), then the app manifest's `workers[].timeoutMs`. Pack-supplied values
|
|
241
|
+
are validated at registration (a non-positive-integer fails the mount, naming
|
|
242
|
+
the source); the manifest value is validated at author time like any other
|
|
243
|
+
worker.
|
|
244
|
+
|
|
213
245
|
### Deploy by convention (`resources/`)
|
|
214
246
|
|
|
215
247
|
Deployables are discovered by convention: with **no `models`** block in the
|
|
@@ -299,6 +331,34 @@ deploy-time string substitution (`{{name}}` templating has been removed).
|
|
|
299
331
|
> model per environment. Pass the value as a process variable and reference it
|
|
300
332
|
> with FEEL instead.
|
|
301
333
|
|
|
334
|
+
### Task forms — what the `taskInbox` (and pages `engineForm`) renders
|
|
335
|
+
|
|
336
|
+
A user task linked to a deployed `.form` is rendered by the ONE shared form-js
|
|
337
|
+
renderer (`NanoFormJs`) in both human surfaces — the `taskInbox` page and a
|
|
338
|
+
pages `dataGrid` `detail.engineForm` drawer. When a task is opened, the surface
|
|
339
|
+
also loads the task's **variables** (the engine's variables search by the task's
|
|
340
|
+
process instance) and passes them to the renderer as its **context**, so a
|
|
341
|
+
reviewer sees what they are reviewing.
|
|
342
|
+
|
|
343
|
+
The context holds only **process-level** variables (task-local variables of
|
|
344
|
+
other element instances are excluded, so a sibling task's value can never leak
|
|
345
|
+
in) and omits **truncated** previews (so a clipped value is never prefilled and
|
|
346
|
+
resubmitted over the original). Lookups use the context's own properties only.
|
|
347
|
+
|
|
348
|
+
Supported form-js components:
|
|
349
|
+
|
|
350
|
+
| Component | Behaviour |
|
|
351
|
+
| --- | --- |
|
|
352
|
+
| `text` | Static paragraph; `{{name}}` placeholders interpolate from the context (objects as JSON, unknown names empty). Rendered as **text only** — a variable holding markup renders literally, never as HTML. |
|
|
353
|
+
| `image` | `<img class="njf-image">` (max-width 100%). `source` is a literal URL or `=varName` (a plain variable reference — full FEEL is not evaluated). Only `http(s):` URLs, app-relative paths, and `data:image/(png|jpeg|gif|webp)` URLs are allowed (the data-URL mediatype may be followed directly by `,` — parameters and `;base64` are optional); anything else (`javascript:`, other schemes, protocol-relative, or any URL containing whitespace, control characters, or backslashes) renders nothing. A root-relative source (`/app/…`) is rebased onto the app's mount root, so it resolves correctly behind the console's path-prefixed proxy; the allowlist is re-checked on the **rebased** URL, and only an `http(s)`/same-origin result is ever set — a resolver output that comes back as a forbidden or non-fetchable scheme renders nothing. `alt` sets the alt text. |
|
|
354
|
+
| `textfield` / `textarea` / `number` / `datetime` | Keyed inputs; submitted as the completion `variables[key]`. A key present in the context **prefills** the input; clearing a prefilled input submits an empty string (an explicit clear), while a never-prefilled blank input is omitted. A prefill the control cannot hold (e.g. a timezone-bearing timestamp in a `datetime` field) counts as **no prefill** — an untouched submit omits the key rather than overwriting the variable with `""`. |
|
|
355
|
+
| `select` / `radio` | Keyed choice inputs from `values[]`; prefilled when the context value matches an option. Choosing a select's blank option after a prefill submits an empty string. A context value matching **no** option counts as no prefill — an untouched submit omits the key. |
|
|
356
|
+
| `checkbox` | Keyed boolean; pre-checked when the context value is `true`. |
|
|
357
|
+
| other / keyless layout components | Skipped. |
|
|
358
|
+
|
|
359
|
+
Forms with no templating, images, or matching context keys render exactly as
|
|
360
|
+
before — the context is additive.
|
|
361
|
+
|
|
302
362
|
### Triggers — the inbound I/O edge
|
|
303
363
|
|
|
304
364
|
Declare `triggers[]` in the app manifest to turn outside events into engine
|
|
@@ -28,6 +28,8 @@ export interface ConnectorWorkerOptions {
|
|
|
28
28
|
export interface DefinedConnectorWorker {
|
|
29
29
|
type: string;
|
|
30
30
|
maxParallelJobs?: number;
|
|
31
|
+
/** Job lock timeout, ms (issue #596) — carried from `defineWorker({ timeoutMs })`. */
|
|
32
|
+
timeoutMs?: number;
|
|
31
33
|
handle: ConnectorWorkerOptions["handle"];
|
|
32
34
|
}
|
|
33
35
|
/** The `@nanobpm/worker` entrypoint the pack calls. Records the handler; does not
|
|
@@ -29,7 +29,12 @@ export function defineWorker(opts) {
|
|
|
29
29
|
if (typeof opts.handle !== "function") {
|
|
30
30
|
throw new Error(`defineWorker("${opts.type}"): handle must be a function`);
|
|
31
31
|
}
|
|
32
|
-
registered.push({
|
|
32
|
+
registered.push({
|
|
33
|
+
type: opts.type,
|
|
34
|
+
maxParallelJobs: opts.maxParallelJobs,
|
|
35
|
+
timeoutMs: opts.timeoutMs,
|
|
36
|
+
handle: opts.handle,
|
|
37
|
+
});
|
|
33
38
|
}
|
|
34
39
|
/** Return every worker registered since the last drain, and clear the registry.
|
|
35
40
|
* The runtime calls this immediately after importing one pack entry, so the
|
|
@@ -201,6 +201,20 @@ export interface WorkerSubscription {
|
|
|
201
201
|
readonly jobType: string;
|
|
202
202
|
unsubscribe(): Promise<void>;
|
|
203
203
|
}
|
|
204
|
+
/** Options for {@link EngineClient.registerWorker}. */
|
|
205
|
+
export interface RegisterWorkerOptions {
|
|
206
|
+
/** Worker name reported to the engine. The adapter supplies a default. */
|
|
207
|
+
workerName?: string;
|
|
208
|
+
/** Max jobs the worker handles in parallel. The adapter supplies a default. */
|
|
209
|
+
maxParallelJobs?: number;
|
|
210
|
+
/** Job lock timeout, ms (issue #596): how long the engine leases an activated job to
|
|
211
|
+
* this worker before re-activating it elsewhere. Set it above the handler's worst-case
|
|
212
|
+
* runtime for long steps (transcription, an agent call, a multi-GB upload) so the lock
|
|
213
|
+
* cannot expire mid-handler and the job run twice. Absent ⇒ the engine/SDK default. */
|
|
214
|
+
timeoutMs?: number;
|
|
215
|
+
/** Restrict the variables surfaced to the handler to this subset (engine-side projection). */
|
|
216
|
+
fetchVariables?: string[];
|
|
217
|
+
}
|
|
204
218
|
/**
|
|
205
219
|
* A process instance's terminal-relevant lifecycle state, as the engine reports it.
|
|
206
220
|
* `ACTIVE` (still running), `COMPLETED` (ended normally at an end event), or
|
|
@@ -910,11 +924,7 @@ export interface EngineClient {
|
|
|
910
924
|
local?: boolean;
|
|
911
925
|
}): Promise<void>;
|
|
912
926
|
/** Register a push worker for a job type. Draining is handled by the adapter. */
|
|
913
|
-
registerWorker(jobType: string, handler: JobHandler, options?:
|
|
914
|
-
workerName?: string;
|
|
915
|
-
maxParallelJobs?: number;
|
|
916
|
-
fetchVariables?: string[];
|
|
917
|
-
}): Promise<WorkerSubscription>;
|
|
927
|
+
registerWorker(jobType: string, handler: JobHandler, options?: RegisterWorkerOptions): Promise<WorkerSubscription>;
|
|
918
928
|
/** Tear down all connections. */
|
|
919
929
|
close(): Promise<void>;
|
|
920
930
|
}
|
|
@@ -84,8 +84,31 @@ export type InstanceTracking = SchemaInstanceTracking & {
|
|
|
84
84
|
* characters, or `activeStatuses.map(...)` crash on a non-array).
|
|
85
85
|
*/
|
|
86
86
|
export declare function isConfiguredStatusSelector(v: unknown): v is readonly string[];
|
|
87
|
+
/**
|
|
88
|
+
* A worker declaration (`workers[]`) as the runtime consumes it: the schema-owned
|
|
89
|
+
* {@link Worker} plus the pending-schema `timeoutMs` field (issue #596) — the job lock
|
|
90
|
+
* timeout in ms, passed through `registerWorker` to `createJobWorker({ jobTimeoutMs })`.
|
|
91
|
+
* For a long-running step (transcription, an agent call, a multi-GB upload) the SDK's
|
|
92
|
+
* default lock expires mid-handler: the engine re-activates the job and a second worker
|
|
93
|
+
* runs it again, and the first worker's completion is rejected. Set `timeoutMs` above the
|
|
94
|
+
* handler's worst-case runtime to keep the lock for the whole step.
|
|
95
|
+
*
|
|
96
|
+
* Bridged locally — like {@link NetworkConfig} — until `@nanobpm/nano-app-schema` folds
|
|
97
|
+
* `timeoutMs` into the `worker` definition (the schema shape is owned by that package,
|
|
98
|
+
* ADR 0027, and CI bans `declare module` augmentation). Drop this augmentation and
|
|
99
|
+
* re-export `Worker` plainly once the dep bump lands (No Drift Surfaces).
|
|
100
|
+
*/
|
|
101
|
+
export type WorkerDecl = Worker & {
|
|
102
|
+
/** Job lock timeout, ms. Must be a positive integer (the manifest validator enforces it). */
|
|
103
|
+
readonly timeoutMs?: number;
|
|
104
|
+
};
|
|
87
105
|
/** The job type a worker subscribes to (schema key: `taskType`). */
|
|
88
106
|
export declare function workerJobType(w: Worker): string | undefined;
|
|
107
|
+
/** A worker declaration's job lock timeout, or `undefined` when absent/invalid — the
|
|
108
|
+
* validator flags an invalid value, so a consumer treats it as unset rather than
|
|
109
|
+
* propagating a malformed lock to the engine. Read reflectively (like `network.bind`)
|
|
110
|
+
* because `timeoutMs` is pending-schema and not on the static {@link Worker} type. */
|
|
111
|
+
export declare function workerTimeoutMs(w: Worker): number | undefined;
|
|
89
112
|
/**
|
|
90
113
|
* The valid HTTP bind modes, in declaration order. This is the single runtime source of
|
|
91
114
|
* truth for the set: {@link BindMode}, {@link isBindMode}, and the manifest validator
|
|
@@ -25,6 +25,14 @@ export function isConfiguredStatusSelector(v) {
|
|
|
25
25
|
export function workerJobType(w) {
|
|
26
26
|
return w.taskType;
|
|
27
27
|
}
|
|
28
|
+
/** A worker declaration's job lock timeout, or `undefined` when absent/invalid — the
|
|
29
|
+
* validator flags an invalid value, so a consumer treats it as unset rather than
|
|
30
|
+
* propagating a malformed lock to the engine. Read reflectively (like `network.bind`)
|
|
31
|
+
* because `timeoutMs` is pending-schema and not on the static {@link Worker} type. */
|
|
32
|
+
export function workerTimeoutMs(w) {
|
|
33
|
+
const v = Reflect.get(w, "timeoutMs");
|
|
34
|
+
return typeof v === "number" && Number.isInteger(v) && v > 0 ? v : undefined;
|
|
35
|
+
}
|
|
28
36
|
/**
|
|
29
37
|
* The valid HTTP bind modes, in declaration order. This is the single runtime source of
|
|
30
38
|
* truth for the set: {@link BindMode}, {@link isBindMode}, and the manifest validator
|
|
@@ -13,6 +13,9 @@ interface PackWorkerSpec {
|
|
|
13
13
|
type: string;
|
|
14
14
|
entry: string;
|
|
15
15
|
maxParallelJobs?: number;
|
|
16
|
+
/** Job lock timeout, ms (issue #596) — a design-time default the pack's
|
|
17
|
+
* `defineWorker({ timeoutMs })` overrides when both are set. */
|
|
18
|
+
timeoutMs?: number;
|
|
16
19
|
configFields?: PackConfigField[];
|
|
17
20
|
}
|
|
18
21
|
/** The pack manifest (`nano-ide.ext.json`) fields the runtime reads. */
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
// the pack's `@nanobpm/worker` import live behind `host.importConnectorModule`.
|
|
17
17
|
import { errorMessage, isRecord } from "../guards.js";
|
|
18
18
|
import { BpmnError } from "../host.js";
|
|
19
|
-
import { workerJobType } from "../manifest.js";
|
|
19
|
+
import { workerJobType, workerTimeoutMs } from "../manifest.js";
|
|
20
20
|
import { drainDefinedWorkers, } from "../../connector-worker-sdk.js";
|
|
21
21
|
import { runInJobContext } from "../execContext.js";
|
|
22
22
|
function joinRoot(root, p) {
|
|
@@ -121,6 +121,24 @@ export function adaptConnectorHandler(worker) {
|
|
|
121
121
|
return isRecord(ret) ? ret : {};
|
|
122
122
|
};
|
|
123
123
|
}
|
|
124
|
+
/**
|
|
125
|
+
* Validate a connector worker's job lock timeout (issue #596) before it reaches the
|
|
126
|
+
* engine. Unlike a manifest `workers[].timeoutMs` (author-time validated by
|
|
127
|
+
* `collectManifestIssues`) or a `w.run({ timeoutMs })` (validated at flow build), a
|
|
128
|
+
* connector timeout arrives from a THIRD-PARTY pack — `defineWorker({ timeoutMs })`
|
|
129
|
+
* in pack code or the `timeoutMs` field of its `nano-ide.ext.json` — with no
|
|
130
|
+
* validating gate in between. A zero/negative lock would expire instantly (the job
|
|
131
|
+
* re-activated mid-handler ⇒ duplicate execution) and a non-integer is a pack typo;
|
|
132
|
+
* fail closed at registration, naming the source, rather than propagate either to
|
|
133
|
+
* the engine.
|
|
134
|
+
*/
|
|
135
|
+
function validateConnectorTimeout(value, source, jobType, packId) {
|
|
136
|
+
if (!Number.isInteger(value) || value <= 0) {
|
|
137
|
+
throw new Error(`connector worker "${jobType}" (pack "${packId}"): ${source} timeoutMs must be a ` +
|
|
138
|
+
`positive integer (ms), got ${JSON.stringify(value)}`);
|
|
139
|
+
}
|
|
140
|
+
return value;
|
|
141
|
+
}
|
|
124
142
|
/**
|
|
125
143
|
* Mount every enabled connector worker (`workers[]` entries carrying a
|
|
126
144
|
* `connector` field). Fails closed on a seam mismatch (an enabled connector whose
|
|
@@ -192,11 +210,24 @@ export async function mountConnectors(ctx, app) {
|
|
|
192
210
|
}
|
|
193
211
|
const inner = adaptConnectorHandler(worker);
|
|
194
212
|
const wrapped = (job) => runInJobContext({ instanceKey: job.processInstanceKey, elementId: job.elementId, jobType }, () => inner(job));
|
|
213
|
+
// Job lock timeout (issue #596) precedence, first declared wins:
|
|
214
|
+
// 1. the pack's `defineWorker({ timeoutMs })` — the authoritative runtime value
|
|
215
|
+
// 2. the pack's `nano-ide.ext.json` spec — the pack's design-time default
|
|
216
|
+
// 3. the app manifest's `workers[].timeoutMs` — the app author's declaration
|
|
217
|
+
// (mirrors the maxParallelJobs precedence below). The manifest value is already
|
|
218
|
+
// author-time validated (`collectManifestIssues`); the two pack-supplied values
|
|
219
|
+
// are validated here before either reaches the engine as a lock horizon.
|
|
220
|
+
const timeoutMs = worker.timeoutMs !== undefined
|
|
221
|
+
? validateConnectorTimeout(worker.timeoutMs, "defineWorker", jobType, packId)
|
|
222
|
+
: spec.timeoutMs !== undefined
|
|
223
|
+
? validateConnectorTimeout(spec.timeoutMs, "nano-ide.ext.json", jobType, packId)
|
|
224
|
+
: workerTimeoutMs(decl);
|
|
195
225
|
const sub = await ctx.engine.registerWorker(jobType, wrapped, {
|
|
196
226
|
workerName: `${ctx.manifest.id}:${jobType}`,
|
|
197
227
|
// The pack's `defineWorker({ maxParallelJobs })` is the authoritative runtime
|
|
198
228
|
// value; the ext.json spec is a design-time default when the code omits it.
|
|
199
229
|
maxParallelJobs: worker.maxParallelJobs ?? spec.maxParallelJobs,
|
|
230
|
+
timeoutMs,
|
|
200
231
|
});
|
|
201
232
|
subs.push(sub);
|
|
202
233
|
jobTypes.push(jobType);
|
|
@@ -2,4 +2,4 @@
|
|
|
2
2
|
// Source: src/runtime/browser/formjs.browser.js (the shared, type-checked/linted/tested
|
|
3
3
|
// form-js renderer). Regenerate with `npm run gen:runtime`; CI enforces this file
|
|
4
4
|
// is byte-identical to a fresh generation via `git diff --exit-code` (npm run check:runtime).
|
|
5
|
-
export const FORMJS_JS = "// @ts-check\n// ── Shared, XSS-safe form-js schema renderer (ADR 0026, extended by #457) ─────\n// This is the ONE client implementation of \"render a deployed `.form`'s form-js\n// schema and collect its field values\", shared verbatim by BOTH:\n// • the `taskInbox` surface (surfaces.ts `inboxPage`), and\n// • the pages `dataGrid` engine-form detail (runtime.browser.js).\n// It used to live inline in surfaces.ts; factoring it here means the two surfaces\n// can never fork the renderer or drift on how a form-js component maps to an input\n// and its submitted value.\n//\n// Like the rest of the browser runtime it is authored/type-checked/linted/tested\n// as real source and served as a generated string artifact (formjs.gen.ts, emitted\n// by scripts/gen-runtime.mjs). It performs NO DOM access at load — every DOM touch\n// is inside a function — so it is import-safe under Node/Deno for unit testing.\n//\n// SECURITY: every value the engine returns is placed via textContent / setAttribute\n// (never innerHTML), so nothing in the form schema can inject markup. The submitted\n// `variables` bag is null-prototype so an engine-supplied component key of\n// `__proto__`/`constructor` lands as a plain own property and can never mutate a\n// prototype (prototype-pollution class).\n\n/** Create an element, setting attributes via setAttribute and text via textContent only.\n * @param {string} tag\n * @param {Record<string, string>} [attrs]\n * @param {string} [text]\n * @returns {any}\n */\nfunction fjEl(tag, attrs, text) {\n const e = document.createElement(tag);\n if (attrs) for (const k in attrs) e.setAttribute(k, attrs[k]);\n if (text != null) e.textContent = text;\n return e;\n}\n\n/** A plain type=\"button\" with an optional click handler.\n * @param {string} label\n * @param {(() => void) | null} [onClick]\n * @returns {any}\n */\nfunction fjBtn(label, onClick) {\n const b = document.createElement(\"button\");\n b.type = \"button\";\n b.textContent = label;\n if (onClick) b.addEventListener(\"click\", onClick);\n return b;\n}\n\n/** Build one form-js component into its field element and (for keyed inputs) a reader\n * that returns the entered `{ key, value }` or null when blank. Static (keyless)\n * components render as inert text; layout-only components are skipped (null).\n * @param {any} c\n * @returns {{ field: any, read?: () => ({ key: string, value: any } | null) } | null}\n */\nfunction buildField(c) {\n const type = c && c.type;\n // Static (keyless) components: show text as a paragraph, ignore layout-only ones.\n if (type === \"text\") {\n return { field: fjEl(\"p\", { class: \"njf-text\" }, typeof c.text === \"string\" ? c.text : \"\") };\n }\n const key = c && c.key;\n if (!key) return null;\n const wrap = fjEl(\"div\", { class: \"njf-field\" });\n const label = typeof c.label === \"string\" && c.label ? c.label : key;\n if (type === \"checkbox\") {\n const input = document.createElement(\"input\");\n input.type = \"checkbox\";\n const lab = fjEl(\"label\", {});\n lab.appendChild(input);\n lab.appendChild(document.createTextNode(\" \" + label));\n wrap.appendChild(lab);\n return { field: wrap, read: () => ({ key, value: input.checked }) };\n }\n const labelEl = fjEl(\"label\", {}, label);\n wrap.appendChild(labelEl);\n let input;\n if (type === \"textarea\") {\n input = document.createElement(\"textarea\");\n } else if (type === \"select\") {\n input = document.createElement(\"select\");\n input.appendChild(fjEl(\"option\", { value: \"\" }, \"\\u2014\"));\n for (const o of Array.isArray(c.values) ? c.values : []) {\n input.appendChild(fjEl(\"option\", { value: String(o.value) }, String(o.label != null ? o.label : o.value)));\n }\n } else if (type === \"radio\") {\n const name = \"r\" + Math.random().toString(36).slice(2);\n const group = fjEl(\"div\", {});\n for (const o of Array.isArray(c.values) ? c.values : []) {\n const rlab = fjEl(\"label\", {});\n const r = document.createElement(\"input\");\n r.type = \"radio\";\n r.name = name;\n r.value = String(o.value);\n rlab.appendChild(r);\n rlab.appendChild(document.createTextNode(\" \" + String(o.label != null ? o.label : o.value)));\n group.appendChild(rlab);\n }\n wrap.appendChild(group);\n return {\n field: wrap,\n read: () => {\n const sel = group.querySelector(\"input:checked\");\n return sel ? { key, value: sel.value } : null;\n },\n };\n } else {\n input = document.createElement(\"input\");\n input.type = type === \"number\" ? \"number\" : type === \"datetime\" ? \"datetime-local\" : \"text\";\n }\n // Associate the label with the input (for/id) so screen readers announce it on focus.\n const fieldId = \"f\" + Math.random().toString(36).slice(2);\n input.id = fieldId;\n labelEl.setAttribute(\"for\", fieldId);\n wrap.appendChild(input);\n const isNumber = type === \"number\";\n return {\n field: wrap,\n read: () => {\n const raw = input.value;\n if (raw === \"\" || raw == null) return null;\n if (isNumber) {\n const n = Number(raw);\n // A non-numeric value in a number field is only reachable via tampering (the browser\n // blanks invalid type=number input). Treat it as absent rather than silently submitting\n // NaN, which JSON.stringify serializes as null — quietly changing the submitted value.\n return Number.isFinite(n) ? { key, value: n } : null;\n }\n return { key, value: raw };\n },\n };\n}\n\n/**\n * Render a form-js schema into a `<form>` element with a submit + optional cancel.\n * On submit it assembles every keyed field's value into one null-prototype\n * `variables` bag and calls `opts.onSubmit(variables)`; a rejected submit re-enables\n * the button so the operator can retry. `opts.onCancel`, when supplied, wires a\n * cancel button.\n * @param {any} schema the parsed form-js document (`{ components: [...] }`)\n * @param {{ heading?: string, submitLabel?: string, cancelLabel?: string,\n * onSubmit: (variables: Record<string, any>) => (void | Promise<void>),\n * onCancel?: () => void }} opts\n * @returns {any} the built <form> element\n */\nfunction renderForm(schema, opts) {\n const form = document.createElement(\"form\");\n form.className = \"njf-form\";\n if (opts.heading) form.appendChild(fjEl(\"h2\", { class: \"njf-heading\" }, opts.heading));\n const components = schema && Array.isArray(schema.components) ? schema.components : [];\n /** @type {Array<() => ({ key: string, value: any } | null)>} */\n const inputs = [];\n for (const c of components) {\n const built = buildField(c);\n if (!built) continue;\n form.appendChild(built.field);\n if (built.read) inputs.push(built.read);\n }\n const submit = fjBtn(opts.submitLabel || \"Submit\", null);\n submit.type = \"submit\";\n const bar = fjEl(\"div\", { class: \"njf-actions\" });\n bar.appendChild(submit);\n if (opts.onCancel) bar.appendChild(fjBtn(opts.cancelLabel || \"Cancel\", opts.onCancel));\n form.appendChild(bar);\n form.addEventListener(\"submit\", (e) => {\n e.preventDefault();\n // Null-prototype: field keys come from the engine-supplied form schema. A component\n // keyed '__proto__'/'constructor' must land as a plain own property (and round-trip\n // through JSON), never mutate a prototype — no prototype pollution in the page runtime.\n const variables = Object.create(null);\n for (const read of inputs) {\n const kv = read();\n if (kv) variables[kv.key] = kv.value;\n }\n submit.disabled = true;\n Promise.resolve()\n .then(() => opts.onSubmit(variables))\n .catch(() => {\n submit.disabled = false;\n });\n });\n return form;\n}\n\n\n// Expose the renderer as a browser global so both self-contained page bundles can\n// reach the ONE implementation without importing it: the taskInbox page embeds this\n// module inline and the pages shell does the same before loading the ES-module\n// runtime, which reads `globalThis.NanoFormJs` lazily when it renders an engine form.\n// Guarded so importing under Node/Deno for tests is a harmless no-op-ish assignment.\nif (typeof globalThis !== \"undefined\") {\n /** @type {any} */ (globalThis).NanoFormJs = { buildField, renderForm };\n}\n";
|
|
5
|
+
export const FORMJS_JS = "// @ts-check\n// ── Shared, XSS-safe form-js schema renderer (ADR 0026, extended by #457) ─────\n// This is the ONE client implementation of \"render a deployed `.form`'s form-js\n// schema and collect its field values\", shared verbatim by BOTH:\n// • the `taskInbox` surface (surfaces.ts `inboxPage`), and\n// • the pages `dataGrid` engine-form detail (runtime.browser.js).\n// It used to live inline in surfaces.ts; factoring it here means the two surfaces\n// can never fork the renderer or drift on how a form-js component maps to an input\n// and its submitted value.\n//\n// Like the rest of the browser runtime it is authored/type-checked/linted/tested\n// as real source and served as a generated string artifact (formjs.gen.ts, emitted\n// by scripts/gen-runtime.mjs). It performs NO DOM access at load — every DOM touch\n// is inside a function — so it is import-safe under Node/Deno for unit testing.\n//\n// SECURITY: every value the engine returns is placed via textContent / setAttribute\n// (never innerHTML), so nothing in the form schema can inject markup. The submitted\n// `variables` bag is null-prototype so an engine-supplied component key of\n// `__proto__`/`constructor` lands as a plain own property and can never mutate a\n// prototype (prototype-pollution class).\n//\n// VARIABLES CONTEXT (#603): both surfaces pass the task's variables as the render\n// `context`. `text` components interpolate `{{name}}` against it (textContent-only,\n// never markup), `image` components resolve a `=varName` source from it, and a\n// keyed input whose key is present is prefilled — the form-js/Camunda Tasklist\n// behaviour, so a reviewer sees what they are reviewing.\n\n/** Create an element, setting attributes via setAttribute and text via textContent only.\n * @param {string} tag\n * @param {Record<string, string>} [attrs]\n * @param {string} [text]\n * @returns {any}\n */\nfunction fjEl(tag, attrs, text) {\n const e = document.createElement(tag);\n if (attrs) for (const k in attrs) e.setAttribute(k, attrs[k]);\n if (text != null) e.textContent = text;\n return e;\n}\n\n/** A plain type=\"button\" with an optional click handler.\n * @param {string} label\n * @param {(() => void) | null} [onClick]\n * @returns {any}\n */\nfunction fjBtn(label, onClick) {\n const b = document.createElement(\"button\");\n b.type = \"button\";\n b.textContent = label;\n if (onClick) b.addEventListener(\"click\", onClick);\n return b;\n}\n\n/** Interpolate `{{name}}` placeholders in a `text` component against the render\n * context (the task's variables), following form-js/Camunda Tasklist. A present\n * value is stringified (objects/arrays as JSON); an unknown name becomes the empty\n * string. The result is placed via textContent only — a variable holding markup\n * (`<img onerror=…>`) renders as literal text, never as HTML (the XSS rule holds\n * for templated text exactly as for static text).\n * @param {string} text\n * @param {Record<string, any>} context\n * @returns {string}\n */\nfunction fjTemplate(text, context) {\n return text.replace(/\\{\\{\\s*([^{}\\s]+)\\s*\\}\\}/g, (_m, name) => {\n const v = context[name];\n if (v == null) return \"\";\n return typeof v === \"string\" ? v : JSON.stringify(v);\n });\n}\n\n/** Copy only the context's OWN enumerable properties into a null-prototype\n * dictionary, so lookups like `ctx[\"constructor\"]` or `ctx[\"__proto__\"]` never\n * resolve to inherited members (which would template/prefill bogus values), while\n * an explicitly supplied own value with such a name is still honoured.\n * @param {any} context\n * @returns {Record<string, any>}\n */\nfunction fjOwnContext(context) {\n /** @type {Record<string, any>} */\n const out = Object.create(null);\n if (context == null || typeof context !== \"object\") return out;\n for (const k of Object.keys(context)) {\n Object.defineProperty(out, k, { value: context[k], enumerable: true, writable: true, configurable: true });\n }\n return out;\n}\n\n/** The image-source allowlist, applied to BOTH the raw source and — when a\n * `resolveUrl` rewrote it — the RESOLVED URL. A resolver is same-origin trusted\n * code, but it TRANSFORMS the string (the pages runtime's `apiUrl` strips the\n * leading slash before `new URL(...)`), and a transformation can mint a forbidden\n * shape from an accepted one: a root-prefixed script-scheme path passes below as\n * an app-relative path (the leading slash defeats the scheme check), then\n * resolves to the bare forbidden-scheme URL. Re-running the allowlist on the\n * resolver's result closes that laundering class at the single choke point every\n * surface flows through, so no resolver — present or future — can widen the\n * accepted set.\n * @param {string} url\n * @returns {string | null} the URL when allowed, null when rejected\n */\nfunction fjAllowImageUrl(url) {\n // Browsers strip/normalise whitespace and control characters and treat `\\` as\n // `/` before interpreting a URL, so `java\\tscript:` or ` data:image/svg+xml` or\n // `/\\\\host` could slip past the allowlist below. Fail closed on any of them.\n if (/[\\s\\u0000-\\u001f\\u007f\\\\]/.test(url)) return null;\n // data:image — RFC 2397 lets the mediatype be followed directly by `,`\n // (parameters and `;base64` are both optional), so accept `;` OR `,` after the\n // subtype or a percent-encoded payload silently never renders.\n if (/^data:image\\/(png|jpeg|gif|webp)[;,]/i.test(url)) return url;\n if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(url)) {\n // A scheme: only http(s) is allowed (javascript:/data-text-html/etc. rejected).\n return /^https?:\\/\\//i.test(url) ? url : null;\n }\n if (url.startsWith(\"//\")) return null; // protocol-relative → off-origin, reject\n return url; // app-relative path\n}\n\n/** Resolve an `image` component's `source` to a URL the renderer will put on the\n * <img>, or null to reject it. `source` is either a literal URL or `=varName` — a\n * PLAIN variable reference into the render context (full FEEL is intentionally not\n * supported: anything after `=` that is not a bare identifier is rejected). Only\n * `http(s):` URLs, app-relative paths (no scheme, no `//host` protocol-relative),\n * and `data:image/(png|jpeg|gif|webp)` URLs are allowed — never `javascript:` or\n * any other scheme. The URL is set with setAttribute (never innerHTML).\n * `resolveUrl`, when supplied, rewrites an ACCEPTED URL just before it is set —\n * both surfaces pass their app-mount-aware resolver (the pages runtime's `apiUrl`,\n * the inbox page's mount prefix) so a root-relative `/app/…` source requests the\n * app's own path even behind the console's path-prefixed proxy. The allowlist runs\n * on the raw source AND again on the resolver's result (see fjAllowImageUrl), so a\n * resolver can never launder a rejected URL — including one it minted itself by\n * rebasing a disguised path.\n * @param {any} source\n * @param {Record<string, any>} context\n * @param {(url: string) => string} [resolveUrl]\n * @returns {string | null}\n */\nfunction fjImageSrc(source, context, resolveUrl) {\n let url = source;\n if (typeof url === \"string\" && url.startsWith(\"=\")) {\n const name = url.slice(1).trim();\n // A plain variable reference only — reject anything that isn't a bare\n // identifier (a FEEL expression, a call, a path) rather than evaluating it.\n if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name)) return null;\n url = context[name];\n }\n if (typeof url !== \"string\" || url === \"\") return null;\n const allowed = fjAllowImageUrl(url);\n if (allowed == null) return null;\n // App-relative path. A root-relative one (\"/app/…\") is only correct when the app\n // is served at the origin root; behind the console's path-prefixed proxy it must\n // be rebased onto the app mount (the resolver both surfaces pass). Absolute\n // http(s)/data: URLs pass through untouched (the resolvers only rewrite\n // single-leading-slash paths), but revalidate the result regardless — a resolver\n // that strips the leading slash (the pages `apiUrl`) turns \"/javascript:…\" into\n // a forbidden-scheme URL, which must not reach the <img>.\n if (!resolveUrl) return allowed;\n // A resolver can THROW on an allowlist-accepted source: the pages `apiUrl`\n // strips the leading slash and calls `new URL(...)`, which throws `Invalid URL`\n // on a path that is not URL-path-shaped (e.g. \"/http://\"). Uncaught, that\n // exception escapes buildField and the WHOLE task form fails to render. A\n // failed resolution rejects just this image (null), exactly like a resolver\n // that returned a rejected URL.\n let resolved;\n try {\n resolved = resolveUrl(allowed);\n } catch {\n return null;\n }\n if (typeof resolved !== \"string\" || resolved === \"\") return null;\n // Re-run the SAME allowlist on the resolver's output (one source of truth):\n // app-relative paths, http(s) and data:image survive; a forbidden scheme the\n // resolver minted (e.g. \"/javascript:…\" stripped to \"javascript:…\"), a file:\n // URL, or a protocol-relative URL is rejected.\n return fjAllowImageUrl(resolved);\n}\n\n/** The value a keyed input is prefilled with when its key is present in the render\n * context (form-js prefill semantics): strings as-is, other scalars stringified,\n * objects/arrays as JSON. `undefined`/`null` mean \"no prefill\".\n * @param {Record<string, any>} context\n * @param {string} key\n * @returns {string | undefined}\n */\nfunction fjPrefill(context, key) {\n const v = context[key];\n if (v == null) return undefined;\n return typeof v === \"string\" ? v : typeof v === \"object\" ? JSON.stringify(v) : String(v);\n}\n\n/** The prefill pair for a keyed input: `display` is the string the control shows\n * (fjPrefill's rendering); `original` is the context value itself, captured at\n * prefill time. An UNTOUCHED control — one that still shows exactly `display` —\n * submits `original`, never `display`: the completion endpoint forwards submitted\n * values verbatim, so forwarding the stringified rendering would retype the\n * variable (a prefilled `{ approved: true }` textarea would overwrite the object\n * with the STRING '{\"approved\":true}'; a numeric select/radio prefill would\n * overwrite the number with \"1\"). Once the operator changes the control away\n * from `display` the edited string (or its number coercion) submits instead.\n * @param {Record<string, any>} context\n * @param {string} key\n * @returns {{ display: string, original: any } | undefined}\n */\nfunction fjPrefillPair(context, key) {\n const display = fjPrefill(context, key);\n return display === undefined ? undefined : { display, original: context[key] };\n}\n\n/** Build one form-js component into its field element and (for keyed inputs) a reader\n * that returns the entered `{ key, value }` or null when blank. Static (keyless)\n * components render as inert text; layout-only components are skipped (null).\n * `context` carries the task's variables: `text` components interpolate `{{name}}`\n * against it, `image` components resolve a `=varName` source from it, and a keyed\n * input whose key is present is prefilled with its value.\n * @param {any} c\n * @param {Record<string, any>} [context]\n * @param {{ resolveUrl?: (url: string) => string }} [opts]\n * @returns {{ field: any, read?: () => ({ key: string, value: any } | null) } | null}\n */\nfunction buildField(c, context, opts) {\n const ctx = fjOwnContext(context);\n const type = c && c.type;\n // Static (keyless) components: show text as a paragraph, ignore layout-only ones.\n if (type === \"text\") {\n const raw = typeof c.text === \"string\" ? c.text : \"\";\n return { field: fjEl(\"p\", { class: \"njf-text\" }, fjTemplate(raw, ctx)) };\n }\n // An image component (form-js `{ type: \"image\", source, alt }`) — keyless, renders\n // an <img> whose src is resolved + scheme-gated by fjImageSrc. A rejected/absent\n // source renders nothing (null) rather than a broken or unsafe <img>.\n if (type === \"image\") {\n const src = fjImageSrc(c.source, ctx, opts && opts.resolveUrl);\n if (src == null) return null;\n const attrs = { class: \"njf-image\", src, alt: typeof c.alt === \"string\" ? c.alt : \"\" };\n return { field: fjEl(\"img\", attrs) };\n }\n const key = c && c.key;\n if (!key) return null;\n const wrap = fjEl(\"div\", { class: \"njf-field\" });\n const label = typeof c.label === \"string\" && c.label ? c.label : key;\n if (type === \"checkbox\") {\n const input = document.createElement(\"input\");\n input.type = \"checkbox\";\n // Prefill: a boolean context value checks the box.\n if (ctx[key] === true) input.checked = true;\n const lab = fjEl(\"label\", {});\n lab.appendChild(input);\n lab.appendChild(document.createTextNode(\" \" + label));\n wrap.appendChild(lab);\n return { field: wrap, read: () => ({ key, value: input.checked }) };\n }\n const labelEl = fjEl(\"label\", {}, label);\n wrap.appendChild(labelEl);\n let input;\n // Was this field prefilled from the context — AND did the control ACCEPT the\n // value? Only a successful prefill counts: a prefilled field the operator CLEARS\n // (empties the text input, picks the blank select option) must submit an empty\n // string — returning null would omit the key and silently leave the original\n // variable unchanged. But a REJECTED prefill (a select value matching no option,\n // a timezone-bearing timestamp a datetime-local control blanks) leaves the\n // control empty through no operator action; treating that as prefilled would\n // submit \"\" from an untouched form and overwrite the original variable. A\n // rejected prefill behaves like no prefill: blank means \"not entered\", so the\n // key is omitted.\n let prefilled = false;\n /** @type {{ display: string, original: any } | undefined} */\n let prefillPair;\n if (type === \"textarea\") {\n input = document.createElement(\"textarea\");\n prefillPair = fjPrefillPair(ctx, key);\n if (prefillPair !== undefined) {\n input.value = prefillPair.display;\n prefilled = true;\n }\n } else if (type === \"select\") {\n input = document.createElement(\"select\");\n input.appendChild(fjEl(\"option\", { value: \"\" }, \"\\u2014\"));\n prefillPair = fjPrefillPair(ctx, key);\n const pre = prefillPair === undefined ? undefined : prefillPair.display;\n for (const o of Array.isArray(c.values) ? c.values : []) {\n const opt = fjEl(\"option\", { value: String(o.value) }, String(o.label != null ? o.label : o.value));\n // Prefill: mark the option matching the context value as selected.\n if (pre !== undefined && String(o.value) === pre) opt.setAttribute(\"selected\", \"\");\n input.appendChild(opt);\n }\n if (pre !== undefined) {\n input.value = pre;\n // The select ACCEPTS the prefill only when it matches a declared option —\n // otherwise the DOM snaps the value back to \"\" and the control sits blank.\n // Check acceptance structurally (against the option list), not by reading\n // the value back: the control must not be treated as prefilled when it\n // could not take the value, or an untouched submit would overwrite the\n // original variable with \"\".\n const accepted = (Array.isArray(c.values) ? c.values : []).some((/** @type {any} */ o) => String(o.value) === pre);\n prefilled = pre !== \"\" && accepted;\n if (!prefilled) prefillPair = undefined; // a rejected prefill is not a prefill\n }\n } else if (type === \"radio\") {\n const name = \"r\" + Math.random().toString(36).slice(2);\n const prefillRadio = fjPrefillPair(ctx, key);\n const pre = prefillRadio === undefined ? undefined : prefillRadio.display;\n const group = fjEl(\"div\", {});\n for (const o of Array.isArray(c.values) ? c.values : []) {\n const rlab = fjEl(\"label\", {});\n const r = document.createElement(\"input\");\n r.type = \"radio\";\n r.name = name;\n r.value = String(o.value);\n // Prefill: check the option matching the context value.\n if (pre !== undefined && r.value === pre) r.checked = true;\n rlab.appendChild(r);\n rlab.appendChild(document.createTextNode(\" \" + String(o.label != null ? o.label : o.value)));\n group.appendChild(rlab);\n }\n wrap.appendChild(group);\n return {\n field: wrap,\n read: () => {\n const sel = group.querySelector(\"input:checked\");\n if (!sel) return null;\n // Untouched (the checked option is still the prefill's): submit the\n // ORIGINAL value so a numeric prefill stays a number — the completion\n // endpoint forwards submitted values verbatim, and a radio option's\n // value is always a string.\n if (prefillRadio !== undefined && sel.value === prefillRadio.display) return { key, value: prefillRadio.original };\n return { key, value: sel.value };\n },\n };\n } else {\n input = document.createElement(\"input\");\n input.type = type === \"number\" ? \"number\" : type === \"datetime\" ? \"datetime-local\" : \"text\";\n prefillPair = fjPrefillPair(ctx, key);\n if (prefillPair !== undefined) {\n input.value = prefillPair.display;\n // A typed control (number/datetime-local) sanitizes a value it cannot hold\n // to \"\" — e.g. a timezone-bearing timestamp assigned to datetime-local. Only\n // a value that survived counts as a successful prefill.\n prefilled = input.value !== \"\";\n if (!prefilled) prefillPair = undefined; // a rejected prefill is not a prefill\n }\n }\n // Associate the label with the input (for/id) so screen readers announce it on focus.\n const fieldId = \"f\" + Math.random().toString(36).slice(2);\n input.id = fieldId;\n labelEl.setAttribute(\"for\", fieldId);\n wrap.appendChild(input);\n const isNumber = type === \"number\";\n return {\n field: wrap,\n read: () => {\n const raw = input.value;\n // A prefilled field the operator cleared submits an empty string (an explicit\n // \"set this variable to empty\"), never an omission that would leave the\n // original value in place. A never-prefilled blank field is still omitted.\n if (raw === \"\" || raw == null) return prefilled ? { key, value: \"\" } : null;\n // Untouched (the control still shows exactly the prefill's rendering):\n // submit the ORIGINAL context value, never the stringified display — the\n // completion endpoint forwards submitted values verbatim, so the string\n // would retype the variable (an object prefill would become its JSON\n // string; a numeric prefill would become \"3\"). Once the operator changes\n // the control away from the prefill, the edited value submits below.\n if (prefillPair !== undefined && raw === prefillPair.display) return { key, value: prefillPair.original };\n if (isNumber) {\n const n = Number(raw);\n // A non-numeric value in a number field is only reachable via tampering (the browser\n // blanks invalid type=number input). Treat it as absent rather than silently submitting\n // NaN, which JSON.stringify serializes as null — quietly changing the submitted value.\n return Number.isFinite(n) ? { key, value: n } : null;\n }\n return { key, value: raw };\n },\n };\n}\n\n/**\n * Render a form-js schema into a `<form>` element with a submit + optional cancel.\n * On submit it assembles every keyed field's value into one null-prototype\n * `variables` bag and calls `opts.onSubmit(variables)`; a rejected submit re-enables\n * the button so the operator can retry. `opts.onCancel`, when supplied, wires a\n * cancel button. `opts.context` carries the task's variables — `{{name}}` text\n * templating, `=varName` image sources, and keyed-input prefill all resolve\n * against it (see buildField). `opts.resolveUrl`, when supplied, rewrites each\n * ACCEPTED image source before it is set — both surfaces pass their app-mount-aware\n * resolver so a root-relative `/app/…` image survives the console's path-prefixed\n * proxy (see fjImageSrc).\n * @param {any} schema the parsed form-js document (`{ components: [...] }`)\n * @param {{ heading?: string, submitLabel?: string, cancelLabel?: string,\n * context?: Record<string, any>,\n * resolveUrl?: (url: string) => string,\n * onSubmit: (variables: Record<string, any>) => (void | Promise<void>),\n * onCancel?: () => void }} opts\n * @returns {any} the built <form> element\n */\nfunction renderForm(schema, opts) {\n const form = document.createElement(\"form\");\n form.className = \"njf-form\";\n if (opts.heading) form.appendChild(fjEl(\"h2\", { class: \"njf-heading\" }, opts.heading));\n const context = fjOwnContext(opts.context);\n const components = schema && Array.isArray(schema.components) ? schema.components : [];\n /** @type {Array<() => ({ key: string, value: any } | null)>} */\n const inputs = [];\n for (const c of components) {\n const built = buildField(c, context, { resolveUrl: opts.resolveUrl });\n if (!built) continue;\n form.appendChild(built.field);\n if (built.read) inputs.push(built.read);\n }\n const submit = fjBtn(opts.submitLabel || \"Submit\", null);\n submit.type = \"submit\";\n const bar = fjEl(\"div\", { class: \"njf-actions\" });\n bar.appendChild(submit);\n if (opts.onCancel) bar.appendChild(fjBtn(opts.cancelLabel || \"Cancel\", opts.onCancel));\n form.appendChild(bar);\n form.addEventListener(\"submit\", (e) => {\n e.preventDefault();\n // Null-prototype: field keys come from the engine-supplied form schema. A component\n // keyed '__proto__'/'constructor' must land as a plain own property (and round-trip\n // through JSON), never mutate a prototype — no prototype pollution in the page runtime.\n const variables = Object.create(null);\n for (const read of inputs) {\n const kv = read();\n if (kv) variables[kv.key] = kv.value;\n }\n submit.disabled = true;\n Promise.resolve()\n .then(() => opts.onSubmit(variables))\n .catch(() => {\n submit.disabled = false;\n });\n });\n return form;\n}\n\n\n// Expose the renderer as a browser global so both self-contained page bundles can\n// reach the ONE implementation without importing it: the taskInbox page embeds this\n// module inline and the pages shell does the same before loading the ES-module\n// runtime, which reads `globalThis.NanoFormJs` lazily when it renders an engine form.\n// Guarded so importing under Node/Deno for tests is a harmless no-op-ish assignment.\nif (typeof globalThis !== \"undefined\") {\n /** @type {any} */ (globalThis).NanoFormJs = { buildField, renderForm };\n}\n";
|
|
@@ -20,3 +20,23 @@ export declare function resolveFormResponse(engine: Pick<EngineClient, "getForm"
|
|
|
20
20
|
* contract can't drift between them.
|
|
21
21
|
*/
|
|
22
22
|
export declare function completeUserTaskResponse(engine: Pick<EngineClient, "completeUserTask">, bodyText: string): Promise<HttpResponse>;
|
|
23
|
+
/**
|
|
24
|
+
* The shared task-variables endpoint (#603). Responds with the variables of one
|
|
25
|
+
* process instance as a plain `{ name: value }` object — the render context both
|
|
26
|
+
* form surfaces (taskInbox, pages `dataGrid` engine-form detail) pass to the
|
|
27
|
+
* shared form-js renderer for `{{name}}` text templating, `=varName` image
|
|
28
|
+
* sources, and keyed-input prefill. Sourced from `EngineClient.searchVariables`
|
|
29
|
+
* (the engine's user-task/process variables search), so the two surfaces can
|
|
30
|
+
* never drift on where the context comes from.
|
|
31
|
+
*
|
|
32
|
+
* Each `VariableSummary.value` is the variable's serialized JSON (a string); it
|
|
33
|
+
* is `JSON.parse`d here so the client receives real values (numbers, objects),
|
|
34
|
+
* not double-encoded strings. A value that fails to parse is passed through as
|
|
35
|
+
* the raw string rather than failing the whole read. Only PROCESS-level variables
|
|
36
|
+
* (`scopeKey === processInstanceKey`) are included — task-local variables of other
|
|
37
|
+
* element instances never leak into the context — and truncated previews
|
|
38
|
+
* (`isTruncated`) are omitted so they can never be prefilled and resubmitted over
|
|
39
|
+
* the full value. A missing/blank
|
|
40
|
+
* `processInstanceKey` 400s — without it there is no well-defined scope to read.
|
|
41
|
+
*/
|
|
42
|
+
export declare function taskVariablesResponse(engine: Pick<EngineClient, "searchVariables">, processInstanceKey: string | undefined): Promise<HttpResponse>;
|
|
@@ -57,3 +57,50 @@ export async function completeUserTaskResponse(engine, bodyText) {
|
|
|
57
57
|
await engine.completeUserTask(userTaskKey, variables);
|
|
58
58
|
return json({ ok: true });
|
|
59
59
|
}
|
|
60
|
+
/**
|
|
61
|
+
* The shared task-variables endpoint (#603). Responds with the variables of one
|
|
62
|
+
* process instance as a plain `{ name: value }` object — the render context both
|
|
63
|
+
* form surfaces (taskInbox, pages `dataGrid` engine-form detail) pass to the
|
|
64
|
+
* shared form-js renderer for `{{name}}` text templating, `=varName` image
|
|
65
|
+
* sources, and keyed-input prefill. Sourced from `EngineClient.searchVariables`
|
|
66
|
+
* (the engine's user-task/process variables search), so the two surfaces can
|
|
67
|
+
* never drift on where the context comes from.
|
|
68
|
+
*
|
|
69
|
+
* Each `VariableSummary.value` is the variable's serialized JSON (a string); it
|
|
70
|
+
* is `JSON.parse`d here so the client receives real values (numbers, objects),
|
|
71
|
+
* not double-encoded strings. A value that fails to parse is passed through as
|
|
72
|
+
* the raw string rather than failing the whole read. Only PROCESS-level variables
|
|
73
|
+
* (`scopeKey === processInstanceKey`) are included — task-local variables of other
|
|
74
|
+
* element instances never leak into the context — and truncated previews
|
|
75
|
+
* (`isTruncated`) are omitted so they can never be prefilled and resubmitted over
|
|
76
|
+
* the full value. A missing/blank
|
|
77
|
+
* `processInstanceKey` 400s — without it there is no well-defined scope to read.
|
|
78
|
+
*/
|
|
79
|
+
export async function taskVariablesResponse(engine, processInstanceKey) {
|
|
80
|
+
const key = processInstanceKey?.trim();
|
|
81
|
+
if (!key)
|
|
82
|
+
return json({ error: "processInstanceKey required" }, 400);
|
|
83
|
+
const rows = await engine.searchVariables({ processInstanceKey: key });
|
|
84
|
+
// A null-prototype bag: a variable named `__proto__` (or `constructor`) is stored
|
|
85
|
+
// as an own data property instead of invoking an inherited setter, so every
|
|
86
|
+
// variable name round-trips through `json()` as data.
|
|
87
|
+
const variables = Object.create(null);
|
|
88
|
+
for (const row of rows) {
|
|
89
|
+
// Process-level scope only: a row whose scopeKey is an element instance is a
|
|
90
|
+
// task-LOCAL variable of some (possibly sibling) task. Flattening those by name
|
|
91
|
+
// would let another task's value win, so they are excluded outright.
|
|
92
|
+
if (row.scopeKey !== key)
|
|
93
|
+
continue;
|
|
94
|
+
// A truncated row's `value` is a preview, not the variable. Prefilling it would
|
|
95
|
+
// let an untouched form submit clipped text over the original — omit it.
|
|
96
|
+
if (row.isTruncated)
|
|
97
|
+
continue;
|
|
98
|
+
try {
|
|
99
|
+
variables[row.name] = JSON.parse(row.value);
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
variables[row.name] = row.value;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return json(variables);
|
|
106
|
+
}
|
|
@@ -29,7 +29,7 @@ import { html, json } from "../router.js";
|
|
|
29
29
|
import { cancelInstanceReconciling } from "./cancel.js";
|
|
30
30
|
import { apiDocsPath } from "./api.js";
|
|
31
31
|
import { FORMJS_JS } from "./formjs.gen.js";
|
|
32
|
-
import { completeUserTaskResponse, resolveFormResponse } from "./forms.js";
|
|
32
|
+
import { completeUserTaskResponse, resolveFormResponse, taskVariablesResponse } from "./forms.js";
|
|
33
33
|
import { quoteIdent } from "./gateway.js";
|
|
34
34
|
import { RENDERER_JS } from "./runtime.gen.js";
|
|
35
35
|
import { isSqlIdentifier } from "../read-model.js";
|
|
@@ -546,6 +546,16 @@ export function createPagesRoutes(opts, deps) {
|
|
|
546
546
|
source: "surface:pages",
|
|
547
547
|
handler: async (req) => completeUserTaskResponse(engine, await req.text()),
|
|
548
548
|
});
|
|
549
|
+
// The selected row's task variables (#603) — the render context the engineForm
|
|
550
|
+
// drawer passes to the shared form-js renderer (text `{{name}}` templating,
|
|
551
|
+
// `=varName` image sources, keyed-input prefill). The SAME seam the taskInbox
|
|
552
|
+
// surface uses, reused via forms.ts so the context source can't drift.
|
|
553
|
+
routes.push({
|
|
554
|
+
method: "GET",
|
|
555
|
+
path: "/app/actions/variables",
|
|
556
|
+
source: "surface:pages",
|
|
557
|
+
handler: async (req) => taskVariablesResponse(engine, req.query.get("processInstanceKey") ?? undefined),
|
|
558
|
+
});
|
|
549
559
|
// ── nested (multi-appView) sidecars (#442) ──────────────────────────────
|
|
550
560
|
// An app with more than one `appView` cannot share the four FLAT sidecar names above:
|
|
551
561
|
// each view ships its own SUBDIR sidecar — e.g. `pages/cockpit.page.json` →
|
|
@@ -813,6 +823,7 @@ body { margin:0; font:15px/1.5 system-ui,sans-serif; padding:2rem; max-width:64r
|
|
|
813
823
|
.njf-form { display:flex; flex-direction:column; gap:.4rem; margin-top:.5rem; }
|
|
814
824
|
.njf-heading { font-size:1rem; margin:0 0 .25rem; }
|
|
815
825
|
.njf-text { color:var(--nano-text-muted); margin:.25rem 0; }
|
|
826
|
+
.njf-image { display:block; max-width:100%; height:auto; margin:.4rem 0; }
|
|
816
827
|
.njf-field { display:flex; flex-direction:column; gap:.25rem; }
|
|
817
828
|
.njf-field label { font-size:.8rem; color:var(--nano-text-muted); }
|
|
818
829
|
.njf-field input:not([type=checkbox]):not([type=radio]), .njf-field textarea, .njf-field select { padding:.5rem .6rem; border:1px solid var(--nano-edge); border-radius:.4rem; font:inherit; background:var(--nano-inset); color:var(--nano-text); max-width:24rem; }
|