- Notifications
You must be signed in to change notification settings - Fork 1
✨ feat: loopback form server and browser protocol (#195)#243
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Uh oh!
There was an error while loading. Please reload this page.
Changes from all commits
859c49c7f42ba576678c6f07706d9f47e087d645afFile filter
Filter by extension
Conversations
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Uh oh!
There was an error while loading. Please reload this page.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Uh oh!
There was an error while loading. Please reload this page.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| /** | ||
| * The configuration the page fetches, validated before it is believed. | ||
| * | ||
| * The response comes from this WebForm's own server, but the page checks it | ||
| * anyway: the value flows into the DOM, and "the server sent it" is not a shape. | ||
| * A malformed or unexpected payload becomes a failure the page can report rather | ||
| * than an `undefined` rendered into the body. | ||
| * | ||
| * `bodyHtml` was sanitized on the server by `renderBody`, and it is the only | ||
| * field the page reads. Nothing widens that. | ||
| */ | ||
| export interface FormConfig { | ||
| bodyHtml: string; | ||
| } | ||
| export class ConfigError extends Error { | ||
| override name = "ConfigError"; | ||
| } | ||
| export function parseConfig(text: string): FormConfig { | ||
| let decoded: unknown; | ||
| try { | ||
| decoded = JSON.parse(text); | ||
| } catch { | ||
| throw new ConfigError("the form configuration is not JSON"); | ||
| } | ||
| if (typeof decoded !== "object" || decoded === null || Array.isArray(decoded)) { | ||
| throw new ConfigError("the form configuration is not an object"); | ||
| } | ||
| if (!("bodyHtml" in decoded)) { | ||
| throw new ConfigError("the form configuration has no bodyHtml"); | ||
| } | ||
| const { bodyHtml } = decoded; | ||
| if (typeof bodyHtml !== "string") { | ||
| throw new ConfigError("the form configuration's bodyHtml is not a string"); | ||
| } | ||
| return { bodyHtml }; | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,20 +1,60 @@ | ||
| /** | ||
| * The form page. | ||
| * | ||
| * Everything the page does happens inside one Effection scope, opened by `run()` | ||
| * at startup and closed when the tab goes away. That is not ceremony: an | ||
| * `XMLHttpRequest` started by a React callback outlives the callback, and without | ||
| * an owner it would keep pointing at a page that is being unloaded. The scope is | ||
| * the owner, and leaving it aborts whatever is still in flight. | ||
| * | ||
| * The scope stays open by waiting on `pagehide`. Returning from the root | ||
| * operation is what ends it — there is no `destroy()` to forget and no detached | ||
| * scope to leak. | ||
| * | ||
| * React callbacks run outside any operation, so they re-enter through the | ||
| * captured scope. Each re-entry contains its own failure: a task started with | ||
| * `scope.run()` that throws propagates into the scope and takes its siblings with | ||
| * it, which here would mean one failed submission killing the whole form. | ||
| * | ||
| * ## Order of appearance | ||
| * | ||
| * Nothing operable is shown until both halves are ready — the configuration and | ||
| * the precompiled validator. A form mounted before its validator would accept | ||
| * input it cannot check, and the person would find out only after submitting. | ||
| * Until then, and on any failure, the page shows fixed text: no author content, | ||
| * no server text, nothing executable. | ||
| */ | ||
| import { createElement } from "react"; | ||
| import { createRoot } from "react-dom/client"; | ||
| import type { RJSFSchema, UiSchema } from "@rjsf/utils"; | ||
| import withTheme from "@rjsf/core/lib/withTheme.js"; | ||
| import { generateTheme } from "@rjsf/shadcn/lib/Theme/index.js"; | ||
| import createPrecompiledValidator from "@rjsf/validator-ajv8/lib/createPrecompiledValidator.js"; | ||
| import type { ValidatorFunctions } from "@rjsf/validator-ajv8/lib/types.js"; | ||
| import { action, run, useScope, withResolvers } from "effection"; | ||
| import type { Operation, Scope } from "effection"; | ||
| import { resolveHelper } from "./helpers.ts"; | ||
| import { parseConfig } from "./config.ts"; | ||
| import type { FormConfig } from "./config.ts"; | ||
| import { outcomeFor, TRANSPORT_MESSAGE } from "./outcome.ts"; | ||
| import type { Outcome } from "./outcome.ts"; | ||
| import { get, postJson } from "./request.ts"; | ||
| interface Registration { | ||
| validateFns: ValidatorFunctions; | ||
| rootSchema: RJSFSchema; | ||
| uiSchema?: UiSchema; | ||
| } | ||
| /** | ||
| * The receiving side of the token-scoped external validator script. The server | ||
| * precompiles a WebForm's schema with RJSF/Ajv and serves the result as a | ||
| * same-origin script under the fixed `script-src 'self'` policy — no inline | ||
| * script, nonce, `unsafe-eval`, blob, or data script. This bridge is what that | ||
| * script resolves its helpers through and registers its validators with, so the | ||
| * browser bundle carries no `new Function` and no eval path of its | ||
| * own. | ||
| * browser bundle carries no `new Function` and no eval path of its own. | ||
| */ | ||
| interface WebFormBridge { | ||
| resolveHelper(id: string): { default: unknown }; | ||
| @@ -25,30 +65,136 @@ declare global { | ||
| var __WEBFORM__: WebFormBridge; | ||
| } | ||
| const STARTUP_FAILED = | ||
| "This form could not be prepared. Close this tab and run the workflow again."; | ||
| const Form = withTheme(generateTheme()); | ||
| function mount(validateFns: ValidatorFunctions, rootSchema: RJSFSchema, uiSchema?: UiSchema): void { | ||
| const validator = createPrecompiledValidator(validateFns, rootSchema); | ||
| const container = document.getElementById("root"); | ||
| if (!container) { | ||
| throw new Error("the form container element #root is missing from the page shell"); | ||
| } | ||
| createRoot(container).render( | ||
| createElement(Form, { schema: rootSchema, uiSchema: uiSchema ?? {}, validator }), | ||
| ); | ||
| } | ||
| function loadValidator(): void { | ||
| const script = document.createElement("script"); | ||
| script.src = "validator.js"; | ||
| document.head.appendChild(script); | ||
| } | ||
| const registered = withResolvers<Registration>(); | ||
| // Installed before the validator script is ever requested, so the script cannot | ||
| // arrive ahead of the bridge that receives it. | ||
| globalThis.__WEBFORM__ = { | ||
| resolveHelper, | ||
| register(validateFns: ValidatorFunctions, rootSchema: RJSFSchema, uiSchema?: UiSchema): void { | ||
| mount(validateFns, rootSchema, uiSchema); | ||
| registered.resolve({ validateFns, rootSchema, uiSchema }); | ||
| }, | ||
| }; | ||
| loadValidator(); | ||
| function element(id: string): HTMLElement { | ||
| const found = document.getElementById(id); | ||
| if (!found) { | ||
| throw new Error(`the page shell is missing #${id}`); | ||
| } | ||
| return found; | ||
| } | ||
| /** Fixed text only. Author content never reaches the status region. */ | ||
| function say(message: string): void { | ||
| element("status").textContent = message; | ||
| } | ||
| /** | ||
| * Load the validator script the server precompiled for this form. | ||
| * | ||
| * The page runs under `script-src 'self'` with no `unsafe-eval`, so a validator | ||
| * cannot be compiled here; it arrives as a same-origin script that calls back | ||
| * into the bridge. Loading it is an operation so a halt removes the element's | ||
| * listeners rather than leaving them attached to a page that is going away. | ||
| */ | ||
| function loadValidatorScript(): Operation<void> { | ||
| return action<void>((resolve, reject) => { | ||
| const script = document.createElement("script"); | ||
| const onLoad = (): void => resolve(); | ||
| const onError = (): void => reject(new Error("the validator script failed to load")); | ||
| script.addEventListener("load", onLoad); | ||
| script.addEventListener("error", onError); | ||
| script.src = "validator.js"; | ||
| document.head.appendChild(script); | ||
| return () => { | ||
| script.removeEventListener("load", onLoad); | ||
| script.removeEventListener("error", onError); | ||
| }; | ||
| }); | ||
| } | ||
| /** Resolves when the tab is going away, which is what ends the scope. */ | ||
| function untilPageHide(): Operation<void> { | ||
| return action<void>((resolve) => { | ||
| const onHide = (): void => resolve(); | ||
| globalThis.addEventListener("pagehide", onHide); | ||
| return () => globalThis.removeEventListener("pagehide", onHide); | ||
| }); | ||
| } | ||
| function* submit(formData: unknown): Operation<void> { | ||
| const result = yield* postJson("submit", JSON.stringify(formData ?? null)); | ||
| apply(outcomeFor(result.status)); | ||
| } | ||
| function apply(outcome: Outcome): void { | ||
| say(outcome.message); | ||
| if (!outcome.formUsable) { | ||
| element("root").setAttribute("hidden", "hidden"); | ||
| } | ||
| if (outcome.closable) { | ||
| // A script can only close a window it opened, so this may do nothing at | ||
| // all. The message above is the actual fallback. | ||
| globalThis.close(); | ||
| } | ||
| } | ||
| function mount(config: FormConfig, registration: Registration, scope: Scope): void { | ||
| // Sanitized on the server by `renderBody`. This is the only place author | ||
| // content enters the DOM. | ||
taras marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. taras marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| element("content").innerHTML = config.bodyHtml; | ||
| const validator = createPrecompiledValidator(registration.validateFns, registration.rootSchema); | ||
| createRoot(element("root")).render( | ||
| createElement(Form, { | ||
| schema: registration.rootSchema, | ||
| uiSchema: registration.uiSchema ?? {}, | ||
| validator, | ||
| onSubmit: (event: { formData?: unknown }) => { | ||
| // React calls this outside any operation. Re-entering through the | ||
| // captured scope gives the request an owner; catching inside keeps a | ||
| // failed submission from tearing the scope down with it. | ||
| scope.run(function* () { | ||
| try { | ||
| yield* submit(event.formData); | ||
| } catch { | ||
| say(TRANSPORT_MESSAGE); | ||
| } | ||
| }); | ||
| }, | ||
| }), | ||
| ); | ||
| } | ||
| function* start(): Operation<void> { | ||
| const scope = yield* useScope(); | ||
| const response = yield* get("config.json"); | ||
| if (response.status !== 200) { | ||
| throw new Error(`the form configuration could not be loaded (${response.status})`); | ||
| } | ||
| const config = parseConfig(response.body); | ||
| yield* loadValidatorScript(); | ||
| const registration = yield* registered.operation; | ||
| mount(config, registration, scope); | ||
| } | ||
| run(function* () { | ||
| try { | ||
| yield* start(); | ||
| } catch { | ||
| // Fixed text, never the failure's own message: nothing the server or the | ||
| // author wrote is rendered on a path that has already gone wrong. | ||
| say(STARTUP_FAILED); | ||
| return; | ||
| } | ||
| yield* untilPageHide(); | ||
| }); | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| /** | ||
| * What a person is told after submitting, and whether they can try again. | ||
| * | ||
| * Three of these are ordinary and one is not. A 204 means the workflow has the | ||
| * answer and this tab has no further purpose. A 409 means the form was already | ||
| * answered — by another tab, or by this one before a reload — and nothing the | ||
| * person does here will change that. A 422 or a transport failure is the only | ||
| * case where trying again makes sense, so it is the only case that leaves the | ||
| * form usable. | ||
| * | ||
| * Pure and free of the DOM, so the mapping is tested directly rather than | ||
| * inferred from what a page rendered. | ||
| */ | ||
| export type OutcomeKind = "accepted" | "already-submitted" | "retryable"; | ||
| export interface Outcome { | ||
| kind: OutcomeKind; | ||
| message: string; | ||
| /** Whether the person can correct their answer and submit again. */ | ||
| formUsable: boolean; | ||
| /** Whether this tab has finished its job and may close. */ | ||
| closable: boolean; | ||
| } | ||
| export const ACCEPTED_MESSAGE = "Submission received. You can safely close this tab."; | ||
| export const ALREADY_SUBMITTED_MESSAGE = | ||
| "This form was already submitted. You can safely close this tab."; | ||
| export const INVALID_MESSAGE = "The server rejected this submission. Correct it and try again."; | ||
| export const TRANSPORT_MESSAGE = "The submission could not be delivered. Try again."; | ||
| export function outcomeFor(status: number): Outcome { | ||
| if (status === 204) { | ||
| return { kind: "accepted", message: ACCEPTED_MESSAGE, formUsable: false, closable: true }; | ||
| } | ||
| if (status === 409) { | ||
| return { | ||
| kind: "already-submitted", | ||
| message: ALREADY_SUBMITTED_MESSAGE, | ||
| formUsable: false, | ||
| closable: true, | ||
| }; | ||
| } | ||
| if (status === 422) { | ||
| return { kind: "retryable", message: INVALID_MESSAGE, formUsable: true, closable: false }; | ||
| } | ||
| // Everything else — a refused origin, a media-type rejection, a size refusal, | ||
| // a dead connection reported as status 0 — is something the person may be able | ||
| // to get past, and none of it is a reason to take their answer away. | ||
| return { kind: "retryable", message: TRANSPORT_MESSAGE, formUsable: true, closable: false }; | ||
| } |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.