@pipelex/mthds-ui 0.56.0 → 0.58.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 CHANGED
@@ -319,6 +319,7 @@ See `graphConfig.ts` for the full default palette.
319
319
  | `@pipelex/mthds-ui/shiki` | MTHDS syntax highlighting with shiki |
320
320
  | `@pipelex/mthds-ui/tailwind.css` | Where the kernel's classes are, for a Tailwind 4 host |
321
321
  | `@pipelex/mthds-ui/form-kernel.css` | The kernel's prebuilt stylesheet, for a host without Tailwind |
322
+ | `@pipelex/mthds-ui/pdf-layers.css` | The layers of a PDF the result view draws, for a Tailwind 4 host |
322
323
 
323
324
  ## Pure TypeScript usage
324
325
 
@@ -388,13 +389,15 @@ The controls inside `RunPanel`, and inside the graph's detail panel, are the for
388
389
 
389
390
  `tailwind.css` points Tailwind at the copy of the kernel this package depends on, wherever pnpm or npm put it beside or under this package, so you write no path into `node_modules` and do not declare `@pipelex/mthds-form` yourself. One layout escapes it: when your tree holds two versions of this package, npm can nest one below a kernel hoisted further up, and the controls then render unstyled without a warning; [docs/run-form-panel.md](./docs/run-form-panel.md) gives the one-line remedy. The rest of the kernel's setup stays yours: `tw-animate-css` animates the select popover and the tooltip, without the token mapping a class such as `bg-background` compiles to nothing, and the `@custom-variant` line, which a shadcn/ui codebase already has, keys `dark:` to the `.dark` class the kernel follows rather than to the operating system's preference.
390
391
 
392
+ If you hand the result view a document's bytes, so that it draws a PDF it cannot frame (`loadBytes` and `pdfWorker` on `GraphViewer`, or on `RunPanel`'s `env` for the run form's file fields), also import the styles of the drawn pages' text and annotation layers, which are plain CSS for pdf.js's own elements and not utilities your build could compile: `@import "@pipelex/mthds-ui/pdf-layers.css";`. Without them a page's selectable text sits visibly out of place over it. Every rule but one is scoped under the renderer's frame; the exception sets two marker properties on `body` and styles nothing.
393
+
391
394
  **A host without Tailwind** imports the prebuilt stylesheet once, from its entry:
392
395
 
393
396
  ```ts
394
397
  import "@pipelex/mthds-ui/form-kernel.css";
395
398
  ```
396
399
 
397
- It carries Tailwind's preflight, which resets the browser's default styles across your whole page (heading sizes, list markers, margins), and a cascade layer that lets every rule you write yourself win a tie against it.
400
+ It carries Tailwind's preflight, which resets the browser's default styles across your whole page (heading sizes, list markers, margins), and a cascade layer that lets every rule you write yourself win a tie against it. It also carries the layer styles of a PDF the result view draws, so such a host imports nothing more for them.
398
401
 
399
402
  Tailwind 3 hosts and Tailwind 4 hosts that configure a prefix are not supported: their builds cannot generate the kernel's unprefixed Tailwind 4 classes, and the prebuilt sheet cannot sit in their cascade, because its preflight must rank below their base styles while its utilities must rank above them.
400
403
 
@@ -154,7 +154,11 @@ interface RunPanelProps {
154
154
  * the host's value wins PER KEY: the panel fills in only what the host left
155
155
  * undefined — `disabled` from `running`, `onDropFile` from its own upload
156
156
  * tracking when `uploadFile` is supplied, `fileSource` and `loadText` from
157
- * the props of those names.
157
+ * the props of those names. Every other key reaches the controls as the host
158
+ * gave it, the result view's file settings `loadBytes`, `pdfWorker` and
159
+ * `openExternal` among them: with `pdfWorker` a file field draws a PDF's
160
+ * pages, from the dropped file's bytes or, for a stored one, from
161
+ * `loadBytes`, and without it shows a compact card.
158
162
  *
159
163
  * `uploadingIds` is the exception, and deliberately so: it is the UNION of
160
164
  * your set and the panel's, never a replacement. Because the keys default
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/form/react/index.ts","../../../src/form/react/RunPanel.tsx","../../../src/form/runGate.ts","../../../src/form/react/panelUpload.ts"],"sourcesContent":["\"use client\";\n\n/**\n * The `./form/react` entry — the run-form panel over `@pipelex/mthds-form`.\n *\n * The kernel is a DEPENDENCY of this package, so this entry is no longer the\n * only one allowed to import it. It stayed an optional peer while it powered\n * only this run form; it stopped being optional the moment the graph's detail\n * panel began rendering results through it, because a viewer whose detail\n * panel cannot show data is not a viewer. See `docs/stuff-result-panel.md`.\n */\n\n/**\n * No form kernel stylesheet is imported here, on purpose: the host styles the\n * kernel's controls in the way its kind of host needs. A host with Tailwind 4\n * compiles the kernel's classes itself, with\n * `@import \"@pipelex/mthds-ui/tailwind.css\"` in place of the `@source` line of\n * the kernel's documented setup; a host without Tailwind imports\n * `@pipelex/mthds-ui/form-kernel.css` once. The README's \"Styling the form\n * controls\" section is the host's side of it.\n *\n * Do not put an import back. v0.20.0 made the kernel's sheet this entry's job,\n * because Tailwind 3 hosts kept forgetting a content glob into `node_modules`\n * and silently lost the classes only the kernel uses (the result grid's column\n * template was the one that showed). v0.21.0 wrapped the sheet in a cascade\n * layer after the raw copy beat the host's own responsive variants. Neither\n * arrangement works, because the sheet is a complete Tailwind build whose two\n * halves need different places in a Tailwind 4 host's cascade: appended, the\n * layer outranked every variant the host wrote; named first, the host's\n * preflight stripped the kernel's utilities. In a host without Tailwind, the\n * preflight reset every browser default on the page the moment a panel\n * mounted. `docs/run-form-panel.md` has the full account.\n */\n\n/**\n * The kernel's React surface, re-exported. A host imports its controls from\n * here rather than naming `@pipelex/mthds-form` itself — see `../index.ts` for\n * why that indirection is the point rather than ceremony, and why importing the\n * kernel directly beside this package is the one thing that can reintroduce the\n * two-context-identities bug.\n */\nexport * from \"@pipelex/mthds-form/react\";\n\nexport { RunPanel } from \"./RunPanel\";\n// No `UploadedFile` of the panel's own: `uploadFile` resolves to the kernel's,\n// which the line above carries, so `MethodForm` and `RunPanel` take one type.\nexport type { RunPanelProps } from \"./RunPanel\";\n\n// The submit path, React-free and re-exported for hosts that run the gate\n// outside a panel (a toolbar button, a keyboard shortcut).\nexport { runSubmitGate, summarizeVerdict, defaultValidationTranslate } from \"@form/runGate\";\nexport type { RunGateOutcome, RunPanelMessageKey, RunPanelTranslate } from \"@form/runGate\";\n","\"use client\";\n\nimport * as React from \"react\";\nimport {\n computeReadiness,\n fieldsForContract,\n isFilled,\n sameRunValues,\n setValueAtPath,\n type FormExample,\n type LoadText,\n type PipeInputFormDescriptor,\n type PipeIOContract,\n type RunField,\n} from \"@pipelex/mthds-form\";\nimport {\n FieldDomIdProvider,\n FieldRenderer,\n FillWithExample,\n OptionalToggle,\n type ExamplePickerSource,\n type FieldEnv,\n type FilePickerSource,\n type UploadedFile,\n} from \"@pipelex/mthds-form/react\";\nimport { getPaletteForTheme } from \"@graph/graphConfig\";\nimport { GRAPH_THEME, type GraphTheme } from \"@graph/types\";\nimport { runSubmitGate, type RunPanelTranslate } from \"@form/runGate\";\nimport { runPanelUpload, type StoredFile } from \"./panelUpload\";\nimport \"./RunPanel.css\";\n\nexport interface RunPanelProps {\n /**\n * The pipe's IO contract — the kernel's type, supplied by the host.\n *\n * Hosts that can actually run a method already hold `pipe_io_contracts` from\n * the same `/validate` call that produced their graph spec; look an entry up\n * with the kernel's `getPipeIOContract(contracts, domain, pipeCode)`. The\n * panel deliberately does NOT accept a `GraphSpec` and derive a contract from\n * it — deriving field meaning locally is precisely what this component exists\n * not to do.\n */\n contract: PipeIOContract;\n /**\n * The pipe's input-form descriptor — the contract's sibling artifact, and\n * what now decides how every field renders.\n *\n * Since kernel `0.5.0` the descriptor IS the derivation: `buildRunFields`\n * maps this tree structurally, and the concept-name and schema-shape\n * heuristics that used to guess a field's kind are deleted rather than left\n * unreached. The contract is still required beside it — the two are\n * co-walked for the facts the descriptor deliberately omits (a scalar's\n * wrapper property, a nested array's bounds) — so neither artifact renders a\n * form on its own.\n *\n * It arrives the same way the contract does: the `/validate` call that\n * produced the graph spec returns `input_form` beside `pipe_io_contracts`\n * when asked for both views (`views: [\"pipe_io_contracts\", \"input_form\"]`),\n * and the kernel's `getPipeInputForm(inputForm, domain, pipeCode)` is\n * `getPipeIOContract`'s twin for looking an entry up.\n *\n * Required rather than optional, because the alternative is silent: the\n * kernel's `fieldsForContract` returns `[]` unless both artifacts are\n * present, so a host that omitted this would render a panel with no fields\n * and no error — a working form and an empty one look identical from here.\n */\n descriptor: PipeInputFormDescriptor;\n /** Fully controlled field values, host-owned — the kernel's philosophy. */\n values: Record<string, unknown>;\n onValuesChange: (values: Record<string, unknown>) => void;\n /** Fires only after the kernel's run gate passes, with the wire-ready payload. */\n onRun: (apiInputs: Record<string, unknown>) => void;\n /**\n * A run is in flight: the fields and the Run button go inert.\n *\n * **Set it synchronously inside `onRun`, before any `await`.** Across anything\n * longer than one task it is the only thing standing between a second submit\n * and a duplicate execution, and the panel cannot supply that itself: it never\n * learns that a run finished, so a lock held for a run's lifetime would have\n * no release. A host that flips this only once the server answers leaves the\n * button live for the whole round trip, and a second click there starts a\n * second run that nothing undoes.\n *\n * Synchronous re-entry within a single task is the panel's own problem and is\n * handled — see `justSubmittedRef` beside `handleSubmit`. That guard does not\n * reduce what this prop is for; it closes a window this prop cannot reach,\n * because React has not re-rendered inside it.\n */\n running?: boolean;\n /**\n * Ambient field state, passed to every control.\n *\n * For `disabled`, `onDropFile`, `fileSource`, `loadText` and `resolveUrl`\n * the host's value wins PER KEY: the panel fills in only what the host left\n * undefined — `disabled` from `running`, `onDropFile` from its own upload\n * tracking when `uploadFile` is supplied, `fileSource` and `loadText` from\n * the props of those names.\n *\n * `uploadingIds` is the exception, and deliberately so: it is the UNION of\n * your set and the panel's, never a replacement. Because the keys default\n * independently, a host can supply `uploadFile` — leaving the panel to own\n * the drop and mark the field in its own set — while also passing a tracker\n * of its own; letting yours win outright there would hide an upload the\n * panel itself started and leave Run live through it. A host that owns the\n * whole loop supplies `onDropFile` too, so the panel's set is empty and the\n * union is exactly your set.\n *\n * `onPreparingFile` joins the same way. The panel always supplies its own,\n * so a file the kernel's camera is still making holds Run as an upload in\n * flight does, and calls yours beside it when you pass one: your report\n * starts with the panel's, and the release the field calls ends both.\n *\n * A host owning the whole loop answers the field as the panel does: its\n * `onDropFile` returns its upload, a promise of what it stored that resolves\n * to the file it wrote and rejects when it wrote nothing. One that returns\n * nothing must write the value in the same render as it takes the id out of\n * `uploadingIds`, because the kernel reads a value written a render earlier\n * as another writer's file, and one written a render later as an upload that\n * stopped with nothing, and either way the field lets go of the preview.\n */\n env?: FieldEnv;\n /**\n * Stores a dropped file and returns its URL, or its URL and a display name:\n * the kernel's `UploadedFile`, the type its own `MethodForm` takes. The host\n * performs the upload — this library never touches an API client — while\n * the panel owns the bookkeeping around it: marking the field busy, writing\n * the result back at the field's dotted path (named after the dropped file\n * when the host gave no name), and answering the field with the file it\n * wrote, so the dropped file's preview stays whichever render your values\n * reach the screen in.\n */\n uploadFile?: (file: File, fieldId: string) => Promise<UploadedFile>;\n /**\n * Where a file field can take a file the host already stores: the first of\n * the kernel's two host seams beside the upload, its shape the one the\n * kernel's controls take, `FilePickerSource`: a `FileSource`, so every file\n * source is one, with an optional `renderGlyph` drawing a row's glyph in\n * place of the kernel's outline. Given one, every empty file field offers\n * \"Choose from your team's files\", and a list of files offers it for several\n * at once; the host lists the files, one page per query, and the kernel's\n * sheet does the rest. A chosen file is written as `{ url, filename }`\n * through the field's own change, exactly as an upload's result is, so it is\n * the person's own work like anything else they enter.\n *\n * The panel hands it to every control as `FieldEnv.fileSource`, which is all\n * this prop does: an `env.fileSource` of the host's own wins over it, per\n * key, as `env.onDropFile` wins over `uploadFile`. Left unset, no file field\n * offers anything it did not offer before.\n */\n fileSource?: FilePickerSource;\n /**\n * Where the form can take a saved example of the method: the second of the\n * kernel's two host seams beside the upload, its shape the one the kernel's\n * control takes, `ExamplePickerSource`: an `ExampleSource`, so every example\n * source is one, with an optional `renderDetail` drawing a line under each\n * row's name. Given one, the panel offers \"Fill with an example\" above the\n * fields, which sets every value at once through `onValuesChange` and never\n * starts a run. The source's `open`, given, hands a row's example to the\n * host's own surface with a `fill` that fills exactly as choosing the row\n * does, through everything below.\n *\n * A form holding work of the person's own is asked \"Replace what you\n * entered?\" first. The panel counts as such work a value that would send a\n * different run from the one the form held before the person's first edit\n * in this panel (or since the last fill), and a file still arriving. A value\n * the host sets from outside before that first edit (a draft it restores, a\n * past run's inputs) is the form it was given, not the person's work.\n *\n * Filling is a reset to the example's values, as the kernel's own form does\n * it: a rejected submit's summary goes, every field is remounted so no\n * control keeps what it held for the values replaced, and an upload the\n * panel has in flight is abandoned, its result discarded when it lands, as\n * on a pipe switch. An upload the host runs itself through `env.onDropFile`\n * is the host's to abandon, from `onFill`. Left unset, nothing is offered.\n */\n exampleSource?: ExamplePickerSource;\n /**\n * Reads a stored text: the kernel's `LoadText`, the loader its own\n * `MethodForm` takes. A runtime stores a large text input when a run starts,\n * so a host that hands a past run's inputs back to the form hands back the\n * reference, `{url, size, mime_type, preview}`, in its place. The field\n * shows the text's start and size, and the reference is a value the runtime\n * takes, so it fills the input and goes back as it came. Given a loader, the\n * field also offers \"Edit the text\", which calls it with the reference's\n * `url` and puts the whole text in the field's own control, to be edited and\n * sent inline; a text it cannot read leaves the reference in place.\n *\n * The panel hands it to every control as `FieldEnv.loadText`, which is all\n * this prop does: an `env.loadText` of the host's own wins over it. Left\n * unset, a stored text can only be replaced.\n */\n loadText?: LoadText;\n /**\n * Called once an example has filled the form, after `onValuesChange` has\n * been handed the example's values, with those values and the example.\n *\n * A fill reaches the host's state as an ordinary `onValuesChange`, so this is\n * the host's one signal that the form was reset rather than edited. The panel\n * abandons the uploads it runs itself; a host running its own through\n * `env.onDropFile` abandons them here, and clears their ids from\n * `env.uploadingIds`, or the field stays marked busy and a late result lands\n * over the example's value. A host may also use it to remember which example\n * the form now holds.\n */\n onFill?: (values: Record<string, unknown>, example: FormExample) => void;\n /** Panel header. The host names the pipe; there is no default heading. */\n title?: string;\n /**\n * The resolved theme, which drives the kernel's `.dark` class on the panel\n * container alongside this library's own palette variables. Defaults to\n * `light`. Pair it with `GraphViewer`'s `onThemeChange`, whose second\n * argument is exactly this resolved value.\n */\n theme?: GraphTheme;\n /**\n * Renders the whole error summary in the host's language. English by default.\n *\n * It covers the panel's own lines (`runPanel.*`) as well as the kernel's\n * per-error ones, because which of them a rejected run produces is the\n * kernel's decision and not something a host can predict.\n */\n translate?: RunPanelTranslate;\n /**\n * Makes this panel's control DOM ids predictable: a control at value path\n * `cv` gets `id=\"<idPrefix>-cv\"`, and `\"\"` writes the path unprefixed.\n *\n * Ids are namespaced whether or not you pass this. A control's `id` must be\n * unique in the DOCUMENT while a value path is unique only within one form,\n * so two panels each declaring an input named `text` would otherwise emit two\n * `id=\"text\"` — and a `<label for>` binds the first match in tree order,\n * which hands the second panel's label to the first panel's control and\n * leaves the second input with no accessible name. Left unset, the prefix\n * comes from `useId`: unique per panel and hydration-stable, but opaque, so\n * nothing outside can predict it.\n *\n * Pass one when something must ADDRESS a control — `getElementById`, a\n * deep-link that focuses a field, an end-to-end selector. Doing so moves the\n * uniqueness obligation to you: the prefix scopes this whole panel, so it\n * must be unique in the document, and `\"\"` restores the ids this panel emitted\n * before the kernel's fix along with the collision they had.\n */\n idPrefix?: string;\n /** Appended to the panel container's class list. */\n className?: string;\n}\n\nconst EMPTY_IDS: ReadonlySet<string> = new Set<string>();\nconst NO_REPORTS: ReadonlySet<number> = new Set<number>();\nconst NOTHING_REVEALED: ReadonlySet<string> = new Set<string>();\n\n/**\n * A pipe's input form: fields, readiness, and the run gate, composed.\n *\n * Every question of meaning is the form kernel's — `fieldsForContract` decides\n * what each input IS, `computeReadiness` decides whether the form MAY run, and\n * `runSubmitGate` (over the kernel's four steps) decides what goes on the wire.\n * What lives here is layout: which fields are visible, where the toggle and the\n * button sit, and how a rejected verdict is shown. The panel never reads\n * `json_schema` to make a rendering decision and never sniffs a value's shape,\n * since meaning is the kernel's — which is what keeps a change to the kernel's\n * derivation invisible to this repo.\n */\nexport function RunPanel({\n contract,\n descriptor,\n values,\n onValuesChange,\n onRun,\n running = false,\n env,\n uploadFile,\n fileSource,\n exampleSource,\n loadText,\n onFill,\n title,\n theme = GRAPH_THEME.LIGHT,\n translate,\n idPrefix,\n className,\n}: RunPanelProps) {\n const [showOptional, setShowOptional] = React.useState(false);\n const [uploadingIds, setUploadingIds] = React.useState<ReadonlySet<string>>(EMPTY_IDS);\n // The files the kernel's camera is still making, one entry per report\n // (`handlePreparingFile` below).\n const [preparing, setPreparing] = React.useState<ReadonlySet<number>>(NO_REPORTS);\n const [submitError, setSubmitError] = React.useState<string | null>(null);\n // What the person's own work is measured against, for \"Fill with an example\":\n // the values the form held just before their first edit in this panel, or the\n // example's values after a fill. `null` until then, while the values are\n // still entirely the host's — a draft it restores after mounting, a past\n // run's inputs — and nothing on screen is the person's yet. It is the kernel's\n // `touched` rule (`useMethodForm`), which cannot be read off the host's state\n // here: the values are the host's, and only the panel sees which changes came\n // through its own controls.\n const [given, setGiven] = React.useState<Record<string, unknown> | null>(null);\n // How many times an example has filled the form. The fields are keyed by it,\n // so a fill remounts them, as the kernel's own form does on a reset.\n const [fills, setFills] = React.useState(0);\n const readinessHintId = React.useId();\n const fallbackPrefix = React.useId();\n\n const fields = React.useMemo(\n () => fieldsForContract(contract, descriptor),\n [contract, descriptor],\n );\n const readiness = React.useMemo(() => computeReadiness(fields, values), [fields, values]);\n\n /**\n * Writes an edit of the person's own: a control's change, or an upload the\n * panel ran landing. `before` is the values the edit was made over, which the\n * first edit fixes as the measure of the person's work (`given` above).\n */\n const commitValues = React.useCallback(\n (next: Record<string, unknown>, before: Record<string, unknown>) => {\n // A summary describes the values that produced it; the moment they move\n // it is stale, and a stale complaint about a field just corrected is\n // worse than none.\n setSubmitError(null);\n setGiven((previous) => previous ?? before);\n onValuesChange(next);\n },\n [onValuesChange],\n );\n\n // An upload resolves long after the render that started it, so the write-back\n // must not target the values THAT render captured — the user may well have\n // typed elsewhere while waiting. This mirror holds the latest ones. Every path\n // that writes values reads it and moves it forward (a control's change, the\n // upload write-back, a fill), because the write-back lands outside a React\n // event: a control's change dispatched before the host re-renders would\n // otherwise build on values that no longer hold the file. It assumes what the\n // panel's contract says, that the host keeps the values it is handed: a host\n // refusing an edit by keeping its old `values` leaves the mirror ahead until\n // its values next change.\n // Layout, not passive, for the reason spelled out on the contract marker\n // below: a mirror that lags the commit is read by continuations landing in\n // exactly that lag, and here the cost is the host's newer edits overwritten.\n const valuesRef = React.useRef(values);\n React.useLayoutEffect(() => {\n valuesRef.current = values;\n }, [values]);\n\n // Switching pipes makes an upload started under the old one irrelevant — and\n // worse than irrelevant when both pipes declare the same input name, which\n // happens within a single method: `recruitment.cv_screening` and\n // `recruitment.extract_cv` both take a required `cv` document. A file chosen\n // for one would land in the other looking like a deliberate answer, gating\n // satisfied, ready to run. So a drop remembers the generation it happened\n // under, and a result arriving under a later one is dropped. This makes\n // `contract` referentially significant — a host that rebuilds it every render\n // loses its uploads (and is already rebuilding every field, since `fields`\n // memoizes on it).\n //\n // The marker COUNTS rather than naming the contract, because identity answers\n // a subtly different question. A host can leave pipe A and come back to the\n // very same contract object while A's upload is still in flight, and an\n // identity check then says \"same pipe, accept it\" — ABA, and it is not the\n // same form: switching away emptied `uploadingIds`, so that upload stopped\n // gating Run and its dropzone re-opened. Accepting it lands a file in a form\n // that never marked it — Run was live throughout, and for a non-gating input\n // the run may already have gone out without it — and, if the user re-dropped\n // on the way back, overwrites the fresh result while un-marking an upload\n // still in progress. Counting makes the predicate \"has the form moved on\n // since this drop\", which is what the guard always meant.\n //\n // A LAYOUT effect, deliberately. The marker answers \"which form is on\n // screen\", and it has to answer that as of the last COMMIT. A passive effect\n // answers later: React schedules those on a task, while an upload settling is\n // a promise continuation — a microtask, which runs first. In that window the\n // switched form is already rendered and the marker still counts the pipe the\n // user left, so the guard compares the departed generation against itself and\n // lets through precisely the write it exists to reject. Bumping during render\n // would close the window too, and is worse: a concurrent render React\n // abandons would advance past a contract that never commits, and an upload\n // belonging to the pipe still on screen would be thrown away instead. Layout\n // effects run inside the commit, and only for renders that commit.\n //\n // The bump lives in the CLEANUP, which is the one place BOTH ways of leaving a\n // form pass through. Changing `contract` is only one of them: a host that\n // writes `<RunPanel key={pipeRef} …>` — the ordinary React idiom for \"reset\n // this child when the entity changes\" — never changes the prop at all, it\n // unmounts this instance and mounts another. The effect body would then never\n // re-run, the marker would still equal the departed upload's `startedAt`, and\n // that upload's continuation would call `onValuesChange`, which is the HOST's\n // setter and very much still alive. The abandoned file would land in the\n // replacement panel's `cv` exactly as if it had been chosen there. Bumping on\n // cleanup makes the predicate mean what it says — this form instance has\n // stopped being the one on screen — however it stopped.\n //\n // A fill from an example is the third way the form moves on, and it bumps the\n // marker in its own handler (`handleFill`): an upload started before it was\n // for values the example has replaced, and landing afterwards it would put\n // back a file the person no longer sees chosen.\n const generationRef = React.useRef(0);\n React.useLayoutEffect(() => {\n // Whatever was in flight belonged to the previous pipe; it must not go on\n // gating this form's Run button until it happens to settle.\n setUploadingIds(EMPTY_IDS);\n // Nor may a complaint about the previous pipe's inputs stand over this\n // pipe's form: it names fields that are no longer on screen.\n setSubmitError(null);\n // And the measure of the person's work was taken over the previous pipe's\n // fields: this form has not been edited yet.\n setGiven(null);\n return () => {\n generationRef.current += 1;\n };\n }, [contract]);\n\n // The field's `onDropFile`. It returns the upload, the answer the kernel's\n // field matches to the value so the dropped file keeps its preview whichever\n // render the host's values land in: resolved to the file written, rejected\n // when nothing was (`panelUpload.ts` says why, and how a write-back bug stays\n // visible now that the field handles the rejection).\n const handleDropFile = React.useCallback(\n (id: string, file: File): Promise<StoredFile> | undefined => {\n if (!uploadFile) return undefined;\n const startedAt = generationRef.current;\n setUploadingIds((previous) => new Set(previous).add(id));\n return runPanelUpload({\n id,\n start: () => uploadFile(file, id),\n isCurrent: () => generationRef.current === startedAt,\n write: (uploaded) => {\n const before = valuesRef.current;\n const written = { url: uploaded.url, filename: uploaded.filename ?? file.name };\n const next = setValueAtPath(before, id.split(\".\"), written);\n // Advance the mirror here rather than waiting for the effect. Two\n // uploads finishing in the same React batch both run before any\n // re-render, so both would otherwise read the same snapshot and the\n // second write would drop the first — a pipe with two file inputs is\n // ordinary (`candidate_screening.screen_candidate` takes a `cv` and a\n // `job_offer`), and the loss is silent: both fields look settled\n // while one value is gone. The effect still owns syncing FROM the\n // host, so the mirror converges on whatever the host actually kept.\n valuesRef.current = next;\n commitValues(next, before);\n return written;\n },\n endFlight: () =>\n setUploadingIds((previous) => {\n const next = new Set(previous);\n next.delete(id);\n return next;\n }),\n });\n },\n // `contract` is no longer a dependency: the generation is read off the ref\n // at drop time, so this callback does not need rebuilding per pipe.\n [uploadFile, commitValues],\n );\n\n // The field's `onPreparingFile`. Since kernel 0.38.0 a file field offers a\n // camera wherever the panel stores files, and makes a document's PDF in the\n // browser before it hands the file to `onDropFile`: until then the value is\n // about to change, and a run started meanwhile would send the file the field\n // held before the last photo, or none. So a file being made holds Run exactly\n // as an upload in flight does. Without this seam the kernel empties the value\n // instead, which a list of files or an optional file input does not gate on,\n // so the method would run with the photographed file simply absent.\n //\n // Each report is a token, never an id: the kernel ends a report by calling\n // the release it was handed, and a report outlives its id (a list's row moved\n // or removed while its file is made). Only the count matters to Run, so the\n // panel keeps the tokens alone. It never clears them on a pipe switch or a\n // fill, as it does its uploads: the field always ends its report, at the\n // hand-off, when it gives up, or when it unmounts, and a fill and a pipe\n // switch both remount every field (the fields' key, below). The switch has to\n // remount them for this seam's sake too: an upload belongs to the form\n // generation current when the field hands its file over, and a camera's file\n // is handed over only once it is made, possibly after the switch. A field of\n // the same name in both pipes that survived the switch would store a photo\n // taken for the pipe the person left as the new pipe's input.\n //\n // The host's own `env.onPreparingFile` is called beside it, the union rule\n // `uploadingIds` follows: a host that tracks the camera itself still has Run\n // held by the panel. Read off a ref so the seam keeps its identity when a\n // host builds `env` inline.\n const hostPreparingRef = React.useRef(env?.onPreparingFile);\n React.useLayoutEffect(() => {\n hostPreparingRef.current = env?.onPreparingFile;\n }, [env?.onPreparingFile]);\n const reportCounter = React.useRef(0);\n const handlePreparingFile = React.useCallback((id: string): (() => void) => {\n reportCounter.current += 1;\n const token = reportCounter.current;\n setPreparing((previous) => new Set(previous).add(token));\n const releaseHost = hostPreparingRef.current?.(id);\n let released = false;\n return () => {\n if (released) return;\n released = true;\n setPreparing((previous) => {\n if (!previous.has(token)) return previous;\n const next = new Set(previous);\n next.delete(token);\n return next;\n });\n releaseHost?.();\n };\n }, []);\n\n const fieldEnv = React.useMemo<FieldEnv>(\n () => ({\n ...env,\n disabled: env?.disabled ?? running,\n onDropFile: env?.onDropFile ?? (uploadFile ? handleDropFile : undefined),\n // Passed through and nothing more: the kernel's sheet asks the host for\n // pages and writes the chosen file through the field's own `onChange`,\n // which is `commitValues` like any other edit.\n fileSource: env?.fileSource ?? fileSource,\n // Passed through as well: the kernel's stored-text field calls it when\n // the person asks to edit the text, and writes what it loads through\n // the field's own `onChange`.\n loadText: env?.loadText ?? loadText,\n // The UNION, not the host's set winning outright: `onDropFile` and\n // `uploadingIds` default independently per key, so a host may hand us\n // `uploadFile` (leaving the panel to own the drop, and to mark the field\n // in its own set) while also passing a tracker of its own. Letting the\n // host's set replace ours would hide an upload the panel itself started,\n // and Run would stay live through it. A host that owns the whole loop\n // supplies `onDropFile` too, so our set is empty and the union is exactly\n // its set — \"yours win\" still holds where that clause applies.\n uploadingIds: new Set([...(env?.uploadingIds ?? EMPTY_IDS), ...uploadingIds]),\n // Always the panel's, which calls the host's beside it (above).\n onPreparingFile: handlePreparingFile,\n }),\n [\n env,\n running,\n uploadFile,\n handleDropFile,\n fileSource,\n loadText,\n uploadingIds,\n handlePreparingFile,\n ],\n );\n\n // Readiness alone would let a run go out while a file is still uploading: a\n // non-gating file input (optional, or plural — `mustBeFilled` excludes lists)\n // never counts toward readiness, so Run stays live through its upload and the\n // method would run with the file simply absent. Read off `fieldEnv` rather\n // than the raw state, so a host driving its own loop through\n // `env.uploadingIds` gets the same gate. A file the camera is still making\n // counts too: it is an upload that has not started yet.\n const uploading = (fieldEnv.uploadingIds?.size ?? 0) > 0 || preparing.size > 0;\n const notReady = readiness.missing.length > 0;\n\n // ONE expression, read by the button and by the submit path, because they are\n // the same question asked twice and any gap between them is reachable: the\n // panel puts a real `<form>` in the host's DOM under a class name the docs\n // offer as a hook, and `form.requestSubmit()` ignores the submitter entirely,\n // so a disabled button stops nothing there. (The keyboard it does stop: Run is\n // this form's only submit button — every control the kernel renders carries\n // `type=\"button\"` — hence the default button, and implicit submission on a\n // disabled default button does nothing. Measured, not assumed.)\n //\n // Each term has to be here on its own merit, and none is redundant with the\n // kernel gate that runs afterwards. `uploading`: a non-gating file input\n // (optional, or plural — `mustBeFilled` excludes lists) never counts toward\n // readiness, so without this the method runs with the file simply absent.\n // `notReady`: an empty REQUIRED text input reaches the schema validator as `{ text: \"\" }`, a\n // perfectly valid string, so the gate passes it and only readiness notices —\n // that is pinned in `runGate.test.ts` and is exactly why the button gates on\n // readiness at all. `running`: a second run started over the first is a\n // duplicate execution, which nothing downstream would undo — and this term is\n // only ever as timely as the host makes it, which is why the prop's own doc\n // asks for it synchronously. `env.disabled`: the panel already treats the\n // host's flag and `running` as ONE concept where the fields are concerned\n // (`fieldEnv.disabled` falls back from one to the other), so gating the\n // button on only one of the two sources was the same asymmetry rounds 4 and 9\n // turned up — a host freezing the form got every input inert and a live Run\n // button beside them, and a click there starts a run from a form the user\n // cannot edit. It is read off the prop rather than off `fieldEnv.disabled`\n // because those differ exactly when the host passes `disabled: false` while\n // `running` is true, and there the button must still be held.\n const blocked = running || notReady || uploading || (env?.disabled ?? false);\n\n // Optional inputs that are still empty stay folded, so the form opens at its\n // simplest shape and grows on demand. Required or already-filled always show.\n //\n // Which optionals are revealed is LATCHED rather than re-derived from the\n // current value, and that is the whole point. Deriving it live means an\n // optional the user empties disappears from under the cursor: clearing the\n // last character flips `isFilled`, the field drops out of `visibleFields`,\n // and React unmounts the very input being typed into — focus lost, every\n // keystroke after it going nowhere. It needs no host pre-fill to reach:\n // expand the fold, fill an optional, collapse it (it stays on screen because\n // it is filled), then clear it.\n //\n // So between fold transitions the form's shape only ever GROWS. The latch is\n // cleared by the toggle's own handler, by a contract change and by a fill from\n // an example, which are the moments nobody is mid-edit; each is followed by\n // the grow pass below re-adding every optional that still holds a value, so an\n // emptied one folds back. Nothing about readiness or the wire depends on this —\n // an emptied optional is omitted from the payload whether or not its input is\n // on screen.\n //\n // The latch is STATE adjusted during render, not a ref mutated during render,\n // and in a library component that distinction is load-bearing. A ref written\n // during render survives a render that never commits, so a host rendering the\n // panel inside a transition — which App Router navigation does by default —\n // can have an abandoned render for contract B wipe the set that the committed\n // contract A is still displaying from, and an optional the user revealed,\n // collapsed and emptied vanishes on A's next render. That is the very defect\n // this latch exists to prevent, re-entering by another door. React discards a\n // state update from an abandoned render, so the two-`useState` form below is\n // the one that actually holds. It is React's documented shape for adjusting\n // state when a prop changes, and it converges: after the update lands, the\n // reset branch and `newlyRevealed` are both empty on the following pass.\n const [revealed, setRevealed] = React.useState<ReadonlySet<string>>(NOTHING_REVEALED);\n const [latchedFor, setLatchedFor] = React.useState(contract);\n // How many contracts this panel has shown, moved in the same render-phase\n // adjustment as the latch and for the same reason. \"Fill with an example\" is\n // keyed by it: the kernel's control keeps what it learned about one method's\n // examples (whether there are any, under `hideWhenEmpty`, read once as it\n // mounts) and reads again only on a remount, as the kernel's own form expects\n // a new key for a new method. Without it, a pipe whose method has no example\n // would hide the control from the next pipe's examples for good. It counts\n // contracts rather than keying on the source object, which a host may build\n // inline on every render: that would remount the control on each one, read\n // the list each time and close a sheet the person has open. The fields are\n // keyed by it too, so a switch remounts every field even where both pipes\n // declare an input of the same name: a field's work for the pipe the person\n // left, a photo still being made into a file, is dropped with it rather than\n // handed over to the new pipe's upload.\n const [contractTurns, setContractTurns] = React.useState(0);\n // Read this render off the local value, never off `revealed`: a state update\n // made during render is not visible until the re-render it schedules, and the\n // output computed below has to already reflect it.\n let revealedNow = revealed;\n let contractTurnsNow = contractTurns;\n if (latchedFor !== contract) {\n revealedNow = NOTHING_REVEALED;\n contractTurnsNow = contractTurns + 1;\n setLatchedFor(contract);\n setRevealed(revealedNow);\n setContractTurns(contractTurnsNow);\n }\n const newlyRevealed = fields.filter(\n (field) => !field.required && isFilled(values[field.name]) && !revealedNow.has(field.name),\n );\n if (newlyRevealed.length > 0) {\n revealedNow = new Set([...revealedNow, ...newlyRevealed.map((field) => field.name)]);\n setRevealed(revealedNow);\n }\n const isFolded = React.useCallback(\n (field: RunField) => !field.required && !revealedNow.has(field.name),\n [revealedNow],\n );\n // What a collapse would hide — every EMPTY optional — rather than what is\n // hidden right now. The two differ only for an optional that was revealed and\n // then emptied, and that difference is the whole affordance: counting the\n // latched-visible ones leaves the count at zero there, the toggle unrendered,\n // and the empty input stuck on screen with no control that would fold it. The\n // latch keeps deciding what renders; it just stops deciding whether the user\n // is offered a way out of it.\n const foldableCount = fields.filter(\n (field) => !field.required && !isFilled(values[field.name]),\n ).length;\n const visibleFields = showOptional ? fields : fields.filter((field) => !isFolded(field));\n\n // Whether \"Fill with an example\" asks before it replaces the values: the\n // kernel's `touched`, measured against `given` by the run the values would\n // send (`sameRunValues`), so a value typed and erased again, which sends the\n // same run, does not count. A file still arriving does, the host's included.\n // Only read with an example source, so a panel given none does no extra work.\n const hasExampleSource = exampleSource !== undefined;\n const touched = React.useMemo(\n () =>\n hasExampleSource && (uploading || (given !== null && !sameRunValues(values, given, fields))),\n [hasExampleSource, uploading, given, values, fields],\n );\n\n // A fill is a reset to the example's values, the kernel's own form's answer\n // (`useMethodForm`'s `reset`), made here over values the host owns. It runs\n // from the examples' list, a click away from any field, so nobody is mid-edit.\n const handleFill = React.useCallback(\n (next: Record<string, unknown>, example: FormExample) => {\n // An upload started before the fill was for values the example replaced:\n // its result is discarded when it lands, and it no longer holds Run.\n generationRef.current += 1;\n setUploadingIds(EMPTY_IDS);\n setSubmitError(null);\n // The example's values are what the person's next edits are measured\n // against, so a fill followed by a second fill does not ask.\n setGiven(next);\n // The form takes the example's shape: the optionals it fills are revealed\n // by the grow pass, and while the fold is collapsed those it leaves empty\n // fold away. An expanded fold stays expanded, as the kernel's own form\n // leaves its disclosure alone on a reset: the person opened it.\n setRevealed(NOTHING_REVEALED);\n // Remounted, so no control keeps what it held for the replaced values:\n // the preview of a file still arriving, a refused drop.\n setFills((count) => count + 1);\n // Advanced at once for the reason the upload write-back advances it: a\n // continuation landing before the host's re-render reads the mirror.\n valuesRef.current = next;\n onValuesChange(next);\n // Last, so a host reading its own state here already has the example's\n // values on their way.\n onFill?.(next, example);\n },\n [onValuesChange, onFill],\n );\n\n // A submit that has passed the gate latches until the end of the current task.\n //\n // `blocked` is computed during render, so two `requestSubmit()` calls made in\n // ONE synchronous host callback both close over the same render and both pass\n // it — even when the host sets `running` synchronously inside `onRun`, exactly\n // as that prop's doc demands, because React has not re-rendered in between.\n // Two real clicks are two separate tasks with a commit between them and were\n // never affected; this closes the programmatic path, which is a surface this\n // component documents and pins a story against.\n //\n // The release is a microtask, and that is the whole reason this is safe rather\n // than the lock this component deliberately does NOT take. A lock held for the\n // lifetime of a run would have no release — the panel is told when a run\n // starts and never that one finished — so a host that never passes `running`\n // would be wedged after its first run. This latch outlives nothing: the\n // microtask is queued unconditionally and always runs, so it cannot wedge, and\n // it holds no run state a later render could disagree with.\n const justSubmittedRef = React.useRef(false);\n\n const handleSubmit = (event: React.FormEvent) => {\n event.preventDefault();\n // The submit PATH owns the gate, not the button's `disabled` attribute —\n // see `blocked` above for why each term is there and why none is covered by\n // the kernel gate that runs next.\n if (blocked || justSubmittedRef.current) return;\n const outcome = runSubmitGate(contract, fields, values, translate);\n if (!outcome.ok) {\n setSubmitError(outcome.summary);\n return;\n }\n setSubmitError(null);\n // Latched BEFORE `onRun`, so a host that re-enters synchronously from inside\n // its own handler is held by the same guard.\n justSubmittedRef.current = true;\n queueMicrotask(() => {\n justSubmittedRef.current = false;\n });\n onRun(outcome.apiInputs);\n };\n\n const paletteStyle = React.useMemo(\n () => getPaletteForTheme(theme) as React.CSSProperties,\n [theme],\n );\n\n // One provider around the whole panel, which is exactly one form — the scope\n // the kernel's contract asks for. `fallbackPrefix` is this panel's own\n // `useId`, so an unset `idPrefix` keeps the kernel's default behaviour (unique\n // per instance) rather than turning the namespacing off.\n return (\n <FieldDomIdProvider prefix={idPrefix ?? fallbackPrefix}>\n <form\n className={[\"mthds-run-panel\", theme === GRAPH_THEME.DARK && \"dark\", className]\n .filter(Boolean)\n .join(\" \")}\n style={paletteStyle}\n // The panel's gate is the authority on whether a run may go out, and the\n // browser's is not merely redundant beside it — it is WRONG. The kernel's\n // number control carries `step={integer ? 1 : 0.1}`, so any float with\n // more than one decimal is a `stepMismatch` even though `native.Number`\n // accepts it and the kernel's own schema validation does too. Interactive\n // validation then aborts submission before `onSubmit` runs at all: no\n // gate, no `onRun`, no error from the panel, and a native message that is\n // wrong about the domain (\"nearest valid values are 87.2 and 87.3\").\n // Turning it off is what makes the documented `requestSubmit()` promise\n // true, and costs nothing — every constraint that should hold is checked\n // by `runSubmitGate`.\n noValidate\n onSubmit={handleSubmit}\n >\n {title && <h2 className=\"mthds-run-panel-title\">{title}</h2>}\n\n {fields.length > 0 ? (\n <div className=\"mthds-run-panel-fields\">\n {exampleSource && (\n // Its own row, so the control keeps its width in the column, and\n // `:empty` takes the row out while the kernel holds the control\n // back (`hideWhenEmpty`, a method with no example yet).\n <div className=\"mthds-run-panel-examples\">\n <FillWithExample\n key={contractTurnsNow}\n source={exampleSource}\n fields={fields}\n touched={touched}\n onFill={handleFill}\n // Held exactly when the fields are: filling is an edit of them.\n disabled={fieldEnv.disabled}\n />\n </div>\n )}\n {visibleFields.map((field) => (\n <FieldRenderer\n key={`${field.name}:${fills}:${contractTurnsNow}`}\n field={field}\n value={values[field.name]}\n onChange={(value) => {\n // Built on the mirror, not on this render's `values`, for the\n // reason the upload write-back advances it: an upload landing\n // calls `onValuesChange` outside a React event, so a keystroke\n // or a file chosen from the host's files can arrive before the\n // host re-renders, and building on the render's values would\n // drop the file that just landed. The mirror moves forward\n // here too, so two changes in one tick each build on the other.\n const before = valuesRef.current;\n const next = { ...before, [field.name]: value };\n valuesRef.current = next;\n commitValues(next, before);\n }}\n id={field.name}\n env={fieldEnv}\n />\n ))}\n {foldableCount > 0 && (\n <OptionalToggle\n count={foldableCount}\n expanded={showOptional}\n onToggle={() => {\n setShowOptional((expanded) => !expanded);\n // Clearing the latch here is what makes \"the shape only grows\"\n // a temporary state rather than a permanent one. A fold\n // transition is a click on this button, so nobody is mid-edit\n // in a field, and the render below re-adds every optional that\n // still holds a value — leaving exactly the emptied ones to\n // fold away, which is what the user just asked for.\n setRevealed(NOTHING_REVEALED);\n }}\n noun=\"input\"\n />\n )}\n </div>\n ) : (\n <p className=\"mthds-run-panel-empty\">This pipe takes no inputs.</p>\n )}\n\n {submitError && (\n <p className=\"mthds-run-panel-error\" role=\"alert\">\n {submitError}\n </p>\n )}\n\n <div className=\"mthds-run-panel-footer\">\n {/*\n The readiness line is the only thing on screen that says WHY Run is\n disabled, so it has to be reachable by the people who cannot see it\n sitting next to the button — and a disabled button is out of the tab\n order, so they will not arrive at it by walking the controls either.\n `aria-describedby` is the association that makes a screen reader read\n the reason with the button instead of announcing a bare dimmed \"Run\".\n The id comes from `useId` because a host may put two panels on one\n page, and a hardcoded one would make the second panel describe the\n first panel's button.\n */}\n <button\n type=\"submit\"\n className=\"mthds-run-panel-run\"\n disabled={blocked}\n aria-describedby={notReady ? readinessHintId : undefined}\n >\n {running ? \"Running…\" : \"Run\"}\n </button>\n {notReady && (\n <span id={readinessHintId} className=\"mthds-run-panel-readiness\">\n {`${readiness.ready} of ${readiness.total} ready — still needed: ${readiness.missing.join(\", \")}`}\n </span>\n )}\n </div>\n </form>\n </FieldDomIdProvider>\n );\n}\n","/**\n * The panel's submit path, kept React-free.\n *\n * Everything between \"the user pressed Run\" and \"the payload goes on the wire\"\n * is the kernel's (`@pipelex/mthds-form`, `core/gate.ts`); this module bridges\n * the panel's values into the shape the gate takes, calls it, and turns the\n * verdict into one line a panel can show. Splitting it out of `RunPanel.tsx` is\n * what lets the node vitest project test that seam without mounting React — the\n * gate's own behavior is covered by the kernel's tests and is deliberately not\n * re-tested here.\n */\nimport {\n describeValidationError,\n gateRunInputs,\n rjsfDataFromRunValues,\n type PipeIOContract,\n type RunField,\n type RunInputError,\n type ValidationMessageKey,\n} from \"@pipelex/mthds-form\";\n\n/**\n * How many schema errors the summary quotes when the missing-input scan comes up\n * empty. A form with a deep mismatch can produce dozens; past a handful the\n * line stops being readable and the user acts on the first one anyway.\n */\nconst MAX_QUOTED_ERRORS = 3;\n\n/** The outcome of one submit attempt. */\nexport type RunGateOutcome =\n | { ok: true; apiInputs: Record<string, unknown> }\n | { ok: false; missingInputs: string[]; summary: string };\n\n/**\n * Every message key the error summary can render — the kernel's, plus the two\n * this panel owns.\n *\n * The kernel's keys describe one schema error each and are rendered by\n * `describeValidationError`. The `runPanel.` ones are lines the panel writes\n * itself, around those errors, and they carry the prefix precisely so the\n * ownership is legible at the call site and in a host's translation file.\n *\n * Nesting the kernel's union inside ours is deliberate: a key the kernel ADDS\n * lands here automatically and then fails `VALIDATION_STRINGS`'s exhaustiveness\n * until it is given a string, which is how a kernel bump is stopped from\n * silently rendering `undefined` at a user.\n */\nexport type RunPanelMessageKey =\n | ValidationMessageKey\n | \"runPanel.missingInputs\"\n | \"runPanel.fillRequired\";\n\n/**\n * The panel's i18n seam — the kernel's `Translate` widened to the panel's own\n * keys. It accepts a superset of what the kernel asks for, so it is still a\n * valid `Translate` wherever the kernel wants one.\n */\nexport type RunPanelTranslate = (\n key: RunPanelMessageKey,\n values?: Record<string, string>,\n) => string;\n\n/**\n * English defaults for every key above. The kernel deliberately ships no\n * defaults for its own (its `Translate` contract is host-supplied), so a panel\n * that wants to say anything at all has to name them — the wording matches the\n * canonical consumer's `en.json` so the two surfaces read alike.\n */\nconst VALIDATION_STRINGS: Record<RunPanelMessageKey, string> = {\n \"inputPanel.aDateField\": \"A date field\",\n \"inputPanel.pickValidDate\": \"{label}: “{value}” is not a valid date\",\n \"inputPanel.pickValidDateEmpty\": \"{label}: pick a valid date\",\n \"inputPanel.dateCarriesTime\":\n \"{label}: “{value}” carries a time, but a date field takes the day alone — use “{day}” and put the time in the “time” field\",\n \"inputPanel.invalidValue\": \"Invalid value\",\n \"inputPanel.invalidValueWithData\": \"{stack} (value: “{value}”)\",\n \"runPanel.missingInputs\": \"Missing required fields in: {inputs}\",\n \"runPanel.fillRequired\": \"Please fill in all required fields before running.\",\n};\n\n/**\n * The default translator: the English strings above with `{placeholder}`\n * interpolation. A host that localizes passes its own translator instead.\n */\nexport const defaultValidationTranslate: RunPanelTranslate = (key, values) => {\n const template = VALIDATION_STRINGS[key];\n if (!values) return template;\n return template.replace(/\\{(\\w+)\\}/g, (whole, name: string) => values[name] ?? whole);\n};\n\n/**\n * One human line for an invalid verdict.\n *\n * `missingInputs` is the good case: it names the VARIABLES at fault, which is\n * what the user clicks on. The scan can legitimately come up empty on an\n * invalid form (a wrong value shape, a nested mismatch), and that is exactly\n * when falling back to the raw schema errors keeps the failure diagnosable rather\n * than silent — see `validateRunInputs` in the kernel.\n *\n * All three routes go through `t`. Which one runs is decided by the kernel's\n * verdict, so a host that localizes cannot know in advance which line it will\n * be shown — leaving any of them in hardcoded English would surface as the\n * summary silently reverting to English on some inputs and not others.\n */\nexport function summarizeVerdict(\n missingInputs: string[],\n errors: RunInputError[],\n preparedData: unknown,\n t: RunPanelTranslate = defaultValidationTranslate,\n): string {\n if (missingInputs.length > 0) {\n return t(\"runPanel.missingInputs\", { inputs: missingInputs.join(\", \") });\n }\n const described = errors\n .slice(0, MAX_QUOTED_ERRORS)\n .map((error) => describeValidationError(error, t, preparedData))\n .join(\"; \");\n return described || t(\"runPanel.fillRequired\");\n}\n\n/**\n * Run the kernel's gate over the panel's current values.\n *\n * `gateRunInputs` IS the gate — the whole chain in one call — so all this\n * module does either side of it is bridge and phrase: the panel holds values\n * keyed by variable, the gate takes the schema-shaped data those become, and a\n * rejected verdict has to come back as one line rather than as a discriminated\n * union the panel would have to read.\n *\n * Assembling those steps here instead was the earlier shape and it was wrong in\n * a way nothing local could see. The chain's schema validation is not the whole\n * rule: JSON Schema's `required` only asserts a key is PRESENT, and a content model\n * carries no `minLength`, so a required input that arrived empty — `{text: \"\"}`\n * from an untouched text field, `{url: \"\"}` from an untouched file field —\n * satisfied the schema and the run went out. The Run button refuses exactly\n * those, through `computeReadiness`. The gate now re-applies that same\n * emptiness rule with `computeReadiness`'s own functions over the same derived\n * fields, which makes the button's verdict and this one a single invariant\n * rather than two things that resemble each other.\n */\nexport function runSubmitGate(\n contract: PipeIOContract,\n fields: RunField[],\n values: Record<string, unknown>,\n t: RunPanelTranslate = defaultValidationTranslate,\n): RunGateOutcome {\n const verdict = gateRunInputs(contract, rjsfDataFromRunValues(values, fields));\n if (!verdict.ok) {\n return {\n ok: false,\n missingInputs: verdict.missingInputs,\n summary: summarizeVerdict(verdict.missingInputs, verdict.errors, verdict.preparedData, t),\n };\n }\n return { ok: true, apiInputs: verdict.inputs };\n}\n","/**\n * One upload the run panel runs for a dropped file: from the host's\n * `uploadFile` to the value written at the field's path, and the promise of that\n * value the panel hands back to the kernel's field as `onDropFile`'s answer.\n *\n * It is React-free and kept out of the component so that what the panel\n * promises the field can be tested on its own. The promise goes to the kernel's\n * control and to nothing else, so no story can hold it; the stories prove what\n * the field does with it.\n *\n * Why the panel answers at all (kernel `0.22.0`, docs/upload-seam.md in the\n * kernel, \"The local preview belongs to the value it was made for\"): a dropped\n * file is shown from an object URL until its upload lands, and the field must\n * then tell its upload's result from a file someone else wrote there. Told\n * nothing, it goes by when the value lands, which asks the host to write the\n * value in the very render it ends the flight. The panel cannot promise that:\n * the values are the host's, and a host applying them through a store, a\n * transition or a store that renders on write puts them on screen a render\n * after or before the panel's own mark goes, and the field then drops the\n * preview. Answered with the file the upload wrote, the field matches its URL\n * whichever render it lands in.\n */\n\nimport type { UploadedFile } from \"@pipelex/mthds-form/react\";\n\n/**\n * What an upload stored, as the panel writes it: the URL, and the display name\n * when the host gave one. A host's upload may resolve to the URL alone, as the\n * kernel's `UploadedFile` allows, and the panel reads that as this with no name.\n */\nexport type StoredFile = Exclude<UploadedFile, string>;\n\n/** The steps of one upload, each supplied by the panel. */\nexport interface PanelUpload {\n /** The field's id, its dotted value path, named when the upload is abandoned. */\n id: string;\n /** Starts the host's upload. */\n start: () => Promise<UploadedFile>;\n /** Whether the form the file was dropped in is still the one on screen. */\n isCurrent: () => boolean;\n /** Writes what the upload stored at the field's path and returns the value written. */\n write: (stored: StoredFile) => StoredFile;\n /** Takes the field out of the panel's set of uploads in flight. */\n endFlight: () => void;\n /** Where a bug in `write` is reported: an unhandled rejection unless a test passes its own. */\n reportBug?: (bug: unknown) => void;\n}\n\n/**\n * Runs one upload and returns its answer for the field: a promise that resolves\n * to the value it wrote, and rejects when it wrote nothing, because the upload\n * failed, the form moved on before it landed, or the write-back threw. The\n * field matches the resolved URL to the value, and retires the dropped file's\n * preview on a rejection rather than waiting for a file that will never arrive.\n * It is the kernel's own `useMethodForm` `dropFile`, answered the same way.\n *\n * Every rejection is handled here as well as by the field, so a caller that\n * ignores the promise leaves no unhandled rejection behind, as the kernel's\n * `dropFile` does. A failed upload is the host's to announce, since it owns the\n * transport, and an abandoned one is nobody's. A write-back bug is the one\n * failure that must stay visible, and is reported apart (see `write` below).\n */\nexport function runPanelUpload({\n id,\n start,\n isCurrent,\n write,\n endFlight,\n reportBug = surfaceAsUnhandledRejection,\n}: PanelUpload): Promise<StoredFile> {\n // Called through an async wrapper rather than directly. `uploadFile` is the\n // HOST's function and is typed as a plain function returning a promise —\n // nothing obliges it to be `async`. One that validates before it starts the\n // request (no API key configured, a file over the size limit, a mime type it\n // will not take) throws SYNCHRONOUSLY, and a synchronous throw happens before\n // there is a promise to hang the cleanup below on. The id the panel marked\n // before calling this would then stay marked for good: `uploading` disables\n // the dropzone, so the field cannot even be retried, and Run stays gated\n // until the user leaves the form entirely. The wrapper turns that throw into\n // the rejection this chain already cleans up, which makes the SAME host logic\n // behave the same way whether it was written `async` or not — the only\n // difference between those two spellings being the keyword.\n const landed = (async () => await start())().then((uploaded) => {\n // The form this file was dropped in is gone: another pipe, an example's\n // fill, or the panel unmounting (see the generation marker in\n // `RunPanel.tsx`). Writing now would land the file in a form that never\n // asked for it, so nothing is written, and the answer says so.\n if (!isCurrent()) {\n throw new Error(\n `The form moved on before the upload dropped at \"${id}\" landed, so it wrote nothing.`,\n );\n }\n try {\n // The kernel's `UploadedFile` lets a host resolve to the URL alone, as\n // its own form's `uploadFile` does; anything else goes to `write` as it\n // came, so a host's `undefined` still reaches the bug report below.\n return write(typeof uploaded === \"string\" ? { url: uploaded } : uploaded);\n } catch (bug) {\n // A bug in the write-back, not a failed upload. `uploadFile` is typed\n // `Promise<UploadedFile>`, but a type is not a runtime guarantee: a host\n // branch that forgets its `return`, or unwraps a JSON response one level\n // too few, resolves to `undefined`, and `stored.url` then throws.\n //\n // It rejects the answer, because nothing was written and the field must\n // not wait for it. But the field handles that rejection, and so does the\n // cleanup below, so a bug that only rejected the answer would be\n // swallowed: the spinner clears, the field reads empty, nothing is\n // logged, and re-dropping repeats it forever, the one failure in this\n // lifecycle with no diagnostic surface anywhere. Before the panel\n // answered the field, the bug stayed visible because nothing handled the\n // write-back's own promise; now that something does, it is also raised\n // on a promise of its own that nothing handles, as an unhandled rejection\n // where the host's error reporting can see it.\n reportBug(bug);\n throw bug;\n }\n });\n // The same generation check as the write-back, for a sharper reason.\n // Switching contracts already emptied the panel's set, and the very same id\n // may since have been re-added by a NEW upload under the new generation —\n // nothing exotic, since that is what sharing the `cv` input name means, and a\n // host returning to the pipe it left reaches it with no rename at all.\n // Deleting it here would un-mark an upload that is still running: its\n // dropzone re-enables mid-flight, its progress indicator vanishes, and the\n // Run gate lets go of it.\n //\n // Given both arguments, so this chain handles every rejection of `landed`\n // and itself always resolves.\n const settle = () => {\n if (isCurrent()) endFlight();\n };\n void landed.then(settle, settle);\n return landed;\n}\n\n/** Raises `bug` on a promise nothing handles: the host's error reporting sees an unhandled rejection. */\nfunction surfaceAsUnhandledRejection(bug: unknown): void {\n void Promise.resolve().then(() => {\n throw bug;\n });\n}\n"],"mappings":";;;;;;;;;;;;;AAyCA,cAAc;;;ACvCd,YAAY,WAAW;AACvB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAMK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAKK;;;ACbP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAK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oBAAC,OAAE,WAAU,yBAAwB,MAAK,SACvC,uBACH;AAAA,QAGF,qBAAC,SAAI,WAAU,0BAYb;AAAA;AAAA,YAAC;AAAA;AAAA,cACC,MAAK;AAAA,cACL,WAAU;AAAA,cACV,UAAU;AAAA,cACV,oBAAkB,WAAW,kBAAkB;AAAA,cAE9C,oBAAU,kBAAa;AAAA;AAAA,UAC1B;AAAA,UACC,YACC,oBAAC,UAAK,IAAI,iBAAiB,WAAU,6BAClC,aAAG,UAAU,KAAK,OAAO,UAAU,KAAK,+BAA0B,UAAU,QAAQ,KAAK,IAAI,CAAC,IACjG;AAAA,WAEJ;AAAA;AAAA;AAAA,EACF,GACF;AAEJ;","names":["_a","_b","_c"]}
1
+ {"version":3,"sources":["../../../src/form/react/index.ts","../../../src/form/react/RunPanel.tsx","../../../src/form/runGate.ts","../../../src/form/react/panelUpload.ts"],"sourcesContent":["\"use client\";\n\n/**\n * The `./form/react` entry — the run-form panel over `@pipelex/mthds-form`.\n *\n * The kernel is a DEPENDENCY of this package, so this entry is no longer the\n * only one allowed to import it. It stayed an optional peer while it powered\n * only this run form; it stopped being optional the moment the graph's detail\n * panel began rendering results through it, because a viewer whose detail\n * panel cannot show data is not a viewer. See `docs/stuff-result-panel.md`.\n */\n\n/**\n * No form kernel stylesheet is imported here, on purpose: the host styles the\n * kernel's controls in the way its kind of host needs. A host with Tailwind 4\n * compiles the kernel's classes itself, with\n * `@import \"@pipelex/mthds-ui/tailwind.css\"` in place of the `@source` line of\n * the kernel's documented setup; a host without Tailwind imports\n * `@pipelex/mthds-ui/form-kernel.css` once. The README's \"Styling the form\n * controls\" section is the host's side of it.\n *\n * Do not put an import back. v0.20.0 made the kernel's sheet this entry's job,\n * because Tailwind 3 hosts kept forgetting a content glob into `node_modules`\n * and silently lost the classes only the kernel uses (the result grid's column\n * template was the one that showed). v0.21.0 wrapped the sheet in a cascade\n * layer after the raw copy beat the host's own responsive variants. Neither\n * arrangement works, because the sheet is a complete Tailwind build whose two\n * halves need different places in a Tailwind 4 host's cascade: appended, the\n * layer outranked every variant the host wrote; named first, the host's\n * preflight stripped the kernel's utilities. In a host without Tailwind, the\n * preflight reset every browser default on the page the moment a panel\n * mounted. `docs/run-form-panel.md` has the full account.\n */\n\n/**\n * The kernel's React surface, re-exported. A host imports its controls from\n * here rather than naming `@pipelex/mthds-form` itself — see `../index.ts` for\n * why that indirection is the point rather than ceremony, and why importing the\n * kernel directly beside this package is the one thing that can reintroduce the\n * two-context-identities bug.\n */\nexport * from \"@pipelex/mthds-form/react\";\n\nexport { RunPanel } from \"./RunPanel\";\n// No `UploadedFile` of the panel's own: `uploadFile` resolves to the kernel's,\n// which the line above carries, so `MethodForm` and `RunPanel` take one type.\nexport type { RunPanelProps } from \"./RunPanel\";\n\n// The submit path, React-free and re-exported for hosts that run the gate\n// outside a panel (a toolbar button, a keyboard shortcut).\nexport { runSubmitGate, summarizeVerdict, defaultValidationTranslate } from \"@form/runGate\";\nexport type { RunGateOutcome, RunPanelMessageKey, RunPanelTranslate } from \"@form/runGate\";\n","\"use client\";\n\nimport * as React from \"react\";\nimport {\n computeReadiness,\n fieldsForContract,\n isFilled,\n sameRunValues,\n setValueAtPath,\n type FormExample,\n type LoadText,\n type PipeInputFormDescriptor,\n type PipeIOContract,\n type RunField,\n} from \"@pipelex/mthds-form\";\nimport {\n FieldDomIdProvider,\n FieldRenderer,\n FillWithExample,\n OptionalToggle,\n type ExamplePickerSource,\n type FieldEnv,\n type FilePickerSource,\n type UploadedFile,\n} from \"@pipelex/mthds-form/react\";\nimport { getPaletteForTheme } from \"@graph/graphConfig\";\nimport { GRAPH_THEME, type GraphTheme } from \"@graph/types\";\nimport { runSubmitGate, type RunPanelTranslate } from \"@form/runGate\";\nimport { runPanelUpload, type StoredFile } from \"./panelUpload\";\nimport \"./RunPanel.css\";\n\nexport interface RunPanelProps {\n /**\n * The pipe's IO contract — the kernel's type, supplied by the host.\n *\n * Hosts that can actually run a method already hold `pipe_io_contracts` from\n * the same `/validate` call that produced their graph spec; look an entry up\n * with the kernel's `getPipeIOContract(contracts, domain, pipeCode)`. The\n * panel deliberately does NOT accept a `GraphSpec` and derive a contract from\n * it — deriving field meaning locally is precisely what this component exists\n * not to do.\n */\n contract: PipeIOContract;\n /**\n * The pipe's input-form descriptor — the contract's sibling artifact, and\n * what now decides how every field renders.\n *\n * Since kernel `0.5.0` the descriptor IS the derivation: `buildRunFields`\n * maps this tree structurally, and the concept-name and schema-shape\n * heuristics that used to guess a field's kind are deleted rather than left\n * unreached. The contract is still required beside it — the two are\n * co-walked for the facts the descriptor deliberately omits (a scalar's\n * wrapper property, a nested array's bounds) — so neither artifact renders a\n * form on its own.\n *\n * It arrives the same way the contract does: the `/validate` call that\n * produced the graph spec returns `input_form` beside `pipe_io_contracts`\n * when asked for both views (`views: [\"pipe_io_contracts\", \"input_form\"]`),\n * and the kernel's `getPipeInputForm(inputForm, domain, pipeCode)` is\n * `getPipeIOContract`'s twin for looking an entry up.\n *\n * Required rather than optional, because the alternative is silent: the\n * kernel's `fieldsForContract` returns `[]` unless both artifacts are\n * present, so a host that omitted this would render a panel with no fields\n * and no error — a working form and an empty one look identical from here.\n */\n descriptor: PipeInputFormDescriptor;\n /** Fully controlled field values, host-owned — the kernel's philosophy. */\n values: Record<string, unknown>;\n onValuesChange: (values: Record<string, unknown>) => void;\n /** Fires only after the kernel's run gate passes, with the wire-ready payload. */\n onRun: (apiInputs: Record<string, unknown>) => void;\n /**\n * A run is in flight: the fields and the Run button go inert.\n *\n * **Set it synchronously inside `onRun`, before any `await`.** Across anything\n * longer than one task it is the only thing standing between a second submit\n * and a duplicate execution, and the panel cannot supply that itself: it never\n * learns that a run finished, so a lock held for a run's lifetime would have\n * no release. A host that flips this only once the server answers leaves the\n * button live for the whole round trip, and a second click there starts a\n * second run that nothing undoes.\n *\n * Synchronous re-entry within a single task is the panel's own problem and is\n * handled — see `justSubmittedRef` beside `handleSubmit`. That guard does not\n * reduce what this prop is for; it closes a window this prop cannot reach,\n * because React has not re-rendered inside it.\n */\n running?: boolean;\n /**\n * Ambient field state, passed to every control.\n *\n * For `disabled`, `onDropFile`, `fileSource`, `loadText` and `resolveUrl`\n * the host's value wins PER KEY: the panel fills in only what the host left\n * undefined — `disabled` from `running`, `onDropFile` from its own upload\n * tracking when `uploadFile` is supplied, `fileSource` and `loadText` from\n * the props of those names. Every other key reaches the controls as the host\n * gave it, the result view's file settings `loadBytes`, `pdfWorker` and\n * `openExternal` among them: with `pdfWorker` a file field draws a PDF's\n * pages, from the dropped file's bytes or, for a stored one, from\n * `loadBytes`, and without it shows a compact card.\n *\n * `uploadingIds` is the exception, and deliberately so: it is the UNION of\n * your set and the panel's, never a replacement. Because the keys default\n * independently, a host can supply `uploadFile` — leaving the panel to own\n * the drop and mark the field in its own set — while also passing a tracker\n * of its own; letting yours win outright there would hide an upload the\n * panel itself started and leave Run live through it. A host that owns the\n * whole loop supplies `onDropFile` too, so the panel's set is empty and the\n * union is exactly your set.\n *\n * `onPreparingFile` joins the same way. The panel always supplies its own,\n * so a file the kernel's camera is still making holds Run as an upload in\n * flight does, and calls yours beside it when you pass one: your report\n * starts with the panel's, and the release the field calls ends both.\n *\n * A host owning the whole loop answers the field as the panel does: its\n * `onDropFile` returns its upload, a promise of what it stored that resolves\n * to the file it wrote and rejects when it wrote nothing. One that returns\n * nothing must write the value in the same render as it takes the id out of\n * `uploadingIds`, because the kernel reads a value written a render earlier\n * as another writer's file, and one written a render later as an upload that\n * stopped with nothing, and either way the field lets go of the preview.\n */\n env?: FieldEnv;\n /**\n * Stores a dropped file and returns its URL, or its URL and a display name:\n * the kernel's `UploadedFile`, the type its own `MethodForm` takes. The host\n * performs the upload — this library never touches an API client — while\n * the panel owns the bookkeeping around it: marking the field busy, writing\n * the result back at the field's dotted path (named after the dropped file\n * when the host gave no name), and answering the field with the file it\n * wrote, so the dropped file's preview stays whichever render your values\n * reach the screen in.\n */\n uploadFile?: (file: File, fieldId: string) => Promise<UploadedFile>;\n /**\n * Where a file field can take a file the host already stores: the first of\n * the kernel's two host seams beside the upload, its shape the one the\n * kernel's controls take, `FilePickerSource`: a `FileSource`, so every file\n * source is one, with an optional `renderGlyph` drawing a row's glyph in\n * place of the kernel's outline. Given one, every empty file field offers\n * \"Choose from your team's files\", and a list of files offers it for several\n * at once; the host lists the files, one page per query, and the kernel's\n * sheet does the rest. A chosen file is written as `{ url, filename }`\n * through the field's own change, exactly as an upload's result is, so it is\n * the person's own work like anything else they enter.\n *\n * The panel hands it to every control as `FieldEnv.fileSource`, which is all\n * this prop does: an `env.fileSource` of the host's own wins over it, per\n * key, as `env.onDropFile` wins over `uploadFile`. Left unset, no file field\n * offers anything it did not offer before.\n */\n fileSource?: FilePickerSource;\n /**\n * Where the form can take a saved example of the method: the second of the\n * kernel's two host seams beside the upload, its shape the one the kernel's\n * control takes, `ExamplePickerSource`: an `ExampleSource`, so every example\n * source is one, with an optional `renderDetail` drawing a line under each\n * row's name. Given one, the panel offers \"Fill with an example\" above the\n * fields, which sets every value at once through `onValuesChange` and never\n * starts a run. The source's `open`, given, hands a row's example to the\n * host's own surface with a `fill` that fills exactly as choosing the row\n * does, through everything below.\n *\n * A form holding work of the person's own is asked \"Replace what you\n * entered?\" first. The panel counts as such work a value that would send a\n * different run from the one the form held before the person's first edit\n * in this panel (or since the last fill), and a file still arriving. A value\n * the host sets from outside before that first edit (a draft it restores, a\n * past run's inputs) is the form it was given, not the person's work.\n *\n * Filling is a reset to the example's values, as the kernel's own form does\n * it: a rejected submit's summary goes, every field is remounted so no\n * control keeps what it held for the values replaced, and an upload the\n * panel has in flight is abandoned, its result discarded when it lands, as\n * on a pipe switch. An upload the host runs itself through `env.onDropFile`\n * is the host's to abandon, from `onFill`. Left unset, nothing is offered.\n */\n exampleSource?: ExamplePickerSource;\n /**\n * Reads a stored text: the kernel's `LoadText`, the loader its own\n * `MethodForm` takes. A runtime stores a large text input when a run starts,\n * so a host that hands a past run's inputs back to the form hands back the\n * reference, `{url, size, mime_type, preview}`, in its place. The field\n * shows the text's start and size, and the reference is a value the runtime\n * takes, so it fills the input and goes back as it came. Given a loader, the\n * field also offers \"Edit the text\", which calls it with the reference's\n * `url` and puts the whole text in the field's own control, to be edited and\n * sent inline; a text it cannot read leaves the reference in place.\n *\n * The panel hands it to every control as `FieldEnv.loadText`, which is all\n * this prop does: an `env.loadText` of the host's own wins over it. Left\n * unset, a stored text can only be replaced.\n */\n loadText?: LoadText;\n /**\n * Called once an example has filled the form, after `onValuesChange` has\n * been handed the example's values, with those values and the example.\n *\n * A fill reaches the host's state as an ordinary `onValuesChange`, so this is\n * the host's one signal that the form was reset rather than edited. The panel\n * abandons the uploads it runs itself; a host running its own through\n * `env.onDropFile` abandons them here, and clears their ids from\n * `env.uploadingIds`, or the field stays marked busy and a late result lands\n * over the example's value. A host may also use it to remember which example\n * the form now holds.\n */\n onFill?: (values: Record<string, unknown>, example: FormExample) => void;\n /** Panel header. The host names the pipe; there is no default heading. */\n title?: string;\n /**\n * The resolved theme, which drives the kernel's `.dark` class on the panel\n * container alongside this library's own palette variables. Defaults to\n * `light`. Pair it with `GraphViewer`'s `onThemeChange`, whose second\n * argument is exactly this resolved value.\n */\n theme?: GraphTheme;\n /**\n * Renders the whole error summary in the host's language. English by default.\n *\n * It covers the panel's own lines (`runPanel.*`) as well as the kernel's\n * per-error ones, because which of them a rejected run produces is the\n * kernel's decision and not something a host can predict.\n */\n translate?: RunPanelTranslate;\n /**\n * Makes this panel's control DOM ids predictable: a control at value path\n * `cv` gets `id=\"<idPrefix>-cv\"`, and `\"\"` writes the path unprefixed.\n *\n * Ids are namespaced whether or not you pass this. A control's `id` must be\n * unique in the DOCUMENT while a value path is unique only within one form,\n * so two panels each declaring an input named `text` would otherwise emit two\n * `id=\"text\"` — and a `<label for>` binds the first match in tree order,\n * which hands the second panel's label to the first panel's control and\n * leaves the second input with no accessible name. Left unset, the prefix\n * comes from `useId`: unique per panel and hydration-stable, but opaque, so\n * nothing outside can predict it.\n *\n * Pass one when something must ADDRESS a control — `getElementById`, a\n * deep-link that focuses a field, an end-to-end selector. Doing so moves the\n * uniqueness obligation to you: the prefix scopes this whole panel, so it\n * must be unique in the document, and `\"\"` restores the ids this panel emitted\n * before the kernel's fix along with the collision they had.\n */\n idPrefix?: string;\n /** Appended to the panel container's class list. */\n className?: string;\n}\n\nconst EMPTY_IDS: ReadonlySet<string> = new Set<string>();\nconst NO_REPORTS: ReadonlySet<number> = new Set<number>();\nconst NOTHING_REVEALED: ReadonlySet<string> = new Set<string>();\n\n/**\n * A pipe's input form: fields, readiness, and the run gate, composed.\n *\n * Every question of meaning is the form kernel's — `fieldsForContract` decides\n * what each input IS, `computeReadiness` decides whether the form MAY run, and\n * `runSubmitGate` (over the kernel's four steps) decides what goes on the wire.\n * What lives here is layout: which fields are visible, where the toggle and the\n * button sit, and how a rejected verdict is shown. The panel never reads\n * `json_schema` to make a rendering decision and never sniffs a value's shape,\n * since meaning is the kernel's — which is what keeps a change to the kernel's\n * derivation invisible to this repo.\n */\nexport function RunPanel({\n contract,\n descriptor,\n values,\n onValuesChange,\n onRun,\n running = false,\n env,\n uploadFile,\n fileSource,\n exampleSource,\n loadText,\n onFill,\n title,\n theme = GRAPH_THEME.LIGHT,\n translate,\n idPrefix,\n className,\n}: RunPanelProps) {\n const [showOptional, setShowOptional] = React.useState(false);\n const [uploadingIds, setUploadingIds] = React.useState<ReadonlySet<string>>(EMPTY_IDS);\n // The files the kernel's camera is still making, one entry per report\n // (`handlePreparingFile` below).\n const [preparing, setPreparing] = React.useState<ReadonlySet<number>>(NO_REPORTS);\n const [submitError, setSubmitError] = React.useState<string | null>(null);\n // What the person's own work is measured against, for \"Fill with an example\":\n // the values the form held just before their first edit in this panel, or the\n // example's values after a fill. `null` until then, while the values are\n // still entirely the host's — a draft it restores after mounting, a past\n // run's inputs — and nothing on screen is the person's yet. It is the kernel's\n // `touched` rule (`useMethodForm`), which cannot be read off the host's state\n // here: the values are the host's, and only the panel sees which changes came\n // through its own controls.\n const [given, setGiven] = React.useState<Record<string, unknown> | null>(null);\n // How many times an example has filled the form. The fields are keyed by it,\n // so a fill remounts them, as the kernel's own form does on a reset.\n const [fills, setFills] = React.useState(0);\n const readinessHintId = React.useId();\n const fallbackPrefix = React.useId();\n\n const fields = React.useMemo(\n () => fieldsForContract(contract, descriptor),\n [contract, descriptor],\n );\n const readiness = React.useMemo(() => computeReadiness(fields, values), [fields, values]);\n\n /**\n * Writes an edit of the person's own: a control's change, or an upload the\n * panel ran landing. `before` is the values the edit was made over, which the\n * first edit fixes as the measure of the person's work (`given` above).\n */\n const commitValues = React.useCallback(\n (next: Record<string, unknown>, before: Record<string, unknown>) => {\n // A summary describes the values that produced it; the moment they move\n // it is stale, and a stale complaint about a field just corrected is\n // worse than none.\n setSubmitError(null);\n setGiven((previous) => previous ?? before);\n onValuesChange(next);\n },\n [onValuesChange],\n );\n\n // An upload resolves long after the render that started it, so the write-back\n // must not target the values THAT render captured — the user may well have\n // typed elsewhere while waiting. This mirror holds the latest ones. Every path\n // that writes values reads it and moves it forward (a control's change, the\n // upload write-back, a fill), because the write-back lands outside a React\n // event: a control's change dispatched before the host re-renders would\n // otherwise build on values that no longer hold the file. It assumes what the\n // panel's contract says, that the host keeps the values it is handed: a host\n // refusing an edit by keeping its old `values` leaves the mirror ahead until\n // its values next change.\n // Layout, not passive, for the reason spelled out on the contract marker\n // below: a mirror that lags the commit is read by continuations landing in\n // exactly that lag, and here the cost is the host's newer edits overwritten.\n const valuesRef = React.useRef(values);\n React.useLayoutEffect(() => {\n valuesRef.current = values;\n }, [values]);\n\n // Switching pipes makes an upload started under the old one irrelevant — and\n // worse than irrelevant when both pipes declare the same input name, which\n // happens within a single method: `recruitment.cv_screening` and\n // `recruitment.extract_cv` both take a required `cv` document. A file chosen\n // for one would land in the other looking like a deliberate answer, gating\n // satisfied, ready to run. So a drop remembers the generation it happened\n // under, and a result arriving under a later one is dropped. This makes\n // `contract` referentially significant — a host that rebuilds it every render\n // loses its uploads (and is already rebuilding every field, since `fields`\n // memoizes on it).\n //\n // The marker COUNTS rather than naming the contract, because identity answers\n // a subtly different question. A host can leave pipe A and come back to the\n // very same contract object while A's upload is still in flight, and an\n // identity check then says \"same pipe, accept it\" — ABA, and it is not the\n // same form: switching away emptied `uploadingIds`, so that upload stopped\n // gating Run and its dropzone re-opened. Accepting it lands a file in a form\n // that never marked it — Run was live throughout, and for a non-gating input\n // the run may already have gone out without it — and, if the user re-dropped\n // on the way back, overwrites the fresh result while un-marking an upload\n // still in progress. Counting makes the predicate \"has the form moved on\n // since this drop\", which is what the guard always meant.\n //\n // A LAYOUT effect, deliberately. The marker answers \"which form is on\n // screen\", and it has to answer that as of the last COMMIT. A passive effect\n // answers later: React schedules those on a task, while an upload settling is\n // a promise continuation — a microtask, which runs first. In that window the\n // switched form is already rendered and the marker still counts the pipe the\n // user left, so the guard compares the departed generation against itself and\n // lets through precisely the write it exists to reject. Bumping during render\n // would close the window too, and is worse: a concurrent render React\n // abandons would advance past a contract that never commits, and an upload\n // belonging to the pipe still on screen would be thrown away instead. Layout\n // effects run inside the commit, and only for renders that commit.\n //\n // The bump lives in the CLEANUP, which is the one place BOTH ways of leaving a\n // form pass through. Changing `contract` is only one of them: a host that\n // writes `<RunPanel key={pipeRef} …>` — the ordinary React idiom for \"reset\n // this child when the entity changes\" — never changes the prop at all, it\n // unmounts this instance and mounts another. The effect body would then never\n // re-run, the marker would still equal the departed upload's `startedAt`, and\n // that upload's continuation would call `onValuesChange`, which is the HOST's\n // setter and very much still alive. The abandoned file would land in the\n // replacement panel's `cv` exactly as if it had been chosen there. Bumping on\n // cleanup makes the predicate mean what it says — this form instance has\n // stopped being the one on screen — however it stopped.\n //\n // A fill from an example is the third way the form moves on, and it bumps the\n // marker in its own handler (`handleFill`): an upload started before it was\n // for values the example has replaced, and landing afterwards it would put\n // back a file the person no longer sees chosen.\n const generationRef = React.useRef(0);\n React.useLayoutEffect(() => {\n // Whatever was in flight belonged to the previous pipe; it must not go on\n // gating this form's Run button until it happens to settle.\n setUploadingIds(EMPTY_IDS);\n // Nor may a complaint about the previous pipe's inputs stand over this\n // pipe's form: it names fields that are no longer on screen.\n setSubmitError(null);\n // And the measure of the person's work was taken over the previous pipe's\n // fields: this form has not been edited yet.\n setGiven(null);\n return () => {\n generationRef.current += 1;\n };\n }, [contract]);\n\n // The field's `onDropFile`. It returns the upload, the answer the kernel's\n // field matches to the value so the dropped file keeps its preview whichever\n // render the host's values land in: resolved to the file written, rejected\n // when nothing was (`panelUpload.ts` says why, and how a write-back bug stays\n // visible now that the field handles the rejection).\n const handleDropFile = React.useCallback(\n (id: string, file: File): Promise<StoredFile> | undefined => {\n if (!uploadFile) return undefined;\n const startedAt = generationRef.current;\n setUploadingIds((previous) => new Set(previous).add(id));\n return runPanelUpload({\n id,\n start: () => uploadFile(file, id),\n isCurrent: () => generationRef.current === startedAt,\n write: (uploaded) => {\n const before = valuesRef.current;\n const written = { url: uploaded.url, filename: uploaded.filename ?? file.name };\n const next = setValueAtPath(before, id.split(\".\"), written);\n // Advance the mirror here rather than waiting for the effect. Two\n // uploads finishing in the same React batch both run before any\n // re-render, so both would otherwise read the same snapshot and the\n // second write would drop the first — a pipe with two file inputs is\n // ordinary (`candidate_screening.screen_candidate` takes a `cv` and a\n // `job_offer`), and the loss is silent: both fields look settled\n // while one value is gone. The effect still owns syncing FROM the\n // host, so the mirror converges on whatever the host actually kept.\n valuesRef.current = next;\n commitValues(next, before);\n return written;\n },\n endFlight: () =>\n setUploadingIds((previous) => {\n const next = new Set(previous);\n next.delete(id);\n return next;\n }),\n });\n },\n // `contract` is no longer a dependency: the generation is read off the ref\n // at drop time, so this callback does not need rebuilding per pipe.\n [uploadFile, commitValues],\n );\n\n // The field's `onPreparingFile`. Since kernel 0.38.0 a file field offers a\n // camera wherever the panel stores files, and makes a document's PDF in the\n // browser before it hands the file to `onDropFile`: until then the value is\n // about to change, and a run started meanwhile would send the file the field\n // held before the last photo, or none. So a file being made holds Run exactly\n // as an upload in flight does. Without this seam the kernel empties the value\n // instead, which a list of files or an optional file input does not gate on,\n // so the method would run with the photographed file simply absent.\n //\n // Each report is a token, never an id: the kernel ends a report by calling\n // the release it was handed, and a report outlives its id (a list's row moved\n // or removed while its file is made). Only the count matters to Run, so the\n // panel keeps the tokens alone. It never clears them on a pipe switch or a\n // fill, as it does its uploads: the field always ends its report, at the\n // hand-off, when it gives up, or when it unmounts, and a fill and a pipe\n // switch both remount every field (the fields' key, below). The switch has to\n // remount them for this seam's sake too: an upload belongs to the form\n // generation current when the field hands its file over, and a camera's file\n // is handed over only once it is made, possibly after the switch. A field of\n // the same name in both pipes that survived the switch would store a photo\n // taken for the pipe the person left as the new pipe's input.\n //\n // The host's own `env.onPreparingFile` is called beside it, the union rule\n // `uploadingIds` follows: a host that tracks the camera itself still has Run\n // held by the panel. Read off a ref so the seam keeps its identity when a\n // host builds `env` inline.\n const hostPreparingRef = React.useRef(env?.onPreparingFile);\n React.useLayoutEffect(() => {\n hostPreparingRef.current = env?.onPreparingFile;\n }, [env?.onPreparingFile]);\n const reportCounter = React.useRef(0);\n const handlePreparingFile = React.useCallback((id: string): (() => void) => {\n reportCounter.current += 1;\n const token = reportCounter.current;\n setPreparing((previous) => new Set(previous).add(token));\n const releaseHost = hostPreparingRef.current?.(id);\n let released = false;\n return () => {\n if (released) return;\n released = true;\n setPreparing((previous) => {\n if (!previous.has(token)) return previous;\n const next = new Set(previous);\n next.delete(token);\n return next;\n });\n releaseHost?.();\n };\n }, []);\n\n const fieldEnv = React.useMemo<FieldEnv>(\n () => ({\n ...env,\n disabled: env?.disabled ?? running,\n onDropFile: env?.onDropFile ?? (uploadFile ? handleDropFile : undefined),\n // Passed through and nothing more: the kernel's sheet asks the host for\n // pages and writes the chosen file through the field's own `onChange`,\n // which is `commitValues` like any other edit.\n fileSource: env?.fileSource ?? fileSource,\n // Passed through as well: the kernel's stored-text field calls it when\n // the person asks to edit the text, and writes what it loads through\n // the field's own `onChange`.\n loadText: env?.loadText ?? loadText,\n // The UNION, not the host's set winning outright: `onDropFile` and\n // `uploadingIds` default independently per key, so a host may hand us\n // `uploadFile` (leaving the panel to own the drop, and to mark the field\n // in its own set) while also passing a tracker of its own. Letting the\n // host's set replace ours would hide an upload the panel itself started,\n // and Run would stay live through it. A host that owns the whole loop\n // supplies `onDropFile` too, so our set is empty and the union is exactly\n // its set — \"yours win\" still holds where that clause applies.\n uploadingIds: new Set([...(env?.uploadingIds ?? EMPTY_IDS), ...uploadingIds]),\n // Always the panel's, which calls the host's beside it (above).\n onPreparingFile: handlePreparingFile,\n }),\n [\n env,\n running,\n uploadFile,\n handleDropFile,\n fileSource,\n loadText,\n uploadingIds,\n handlePreparingFile,\n ],\n );\n\n // Readiness alone would let a run go out while a file is still uploading: a\n // non-gating file input (optional, or plural — `mustBeFilled` excludes lists)\n // never counts toward readiness, so Run stays live through its upload and the\n // method would run with the file simply absent. Read off `fieldEnv` rather\n // than the raw state, so a host driving its own loop through\n // `env.uploadingIds` gets the same gate. A file the camera is still making\n // counts too: it is an upload that has not started yet.\n const uploading = (fieldEnv.uploadingIds?.size ?? 0) > 0 || preparing.size > 0;\n const notReady = readiness.missing.length > 0;\n\n // ONE expression, read by the button and by the submit path, because they are\n // the same question asked twice and any gap between them is reachable: the\n // panel puts a real `<form>` in the host's DOM under a class name the docs\n // offer as a hook, and `form.requestSubmit()` ignores the submitter entirely,\n // so a disabled button stops nothing there. (The keyboard it does stop: Run is\n // this form's only submit button — every control the kernel renders carries\n // `type=\"button\"` — hence the default button, and implicit submission on a\n // disabled default button does nothing. Measured, not assumed.)\n //\n // Each term has to be here on its own merit, and none is redundant with the\n // kernel gate that runs afterwards. `uploading`: a non-gating file input\n // (optional, or plural — `mustBeFilled` excludes lists) never counts toward\n // readiness, so without this the method runs with the file simply absent.\n // `notReady`: an empty REQUIRED text input reaches the schema validator as `{ text: \"\" }`, a\n // perfectly valid string, so the gate passes it and only readiness notices —\n // that is pinned in `runGate.test.ts` and is exactly why the button gates on\n // readiness at all. `running`: a second run started over the first is a\n // duplicate execution, which nothing downstream would undo — and this term is\n // only ever as timely as the host makes it, which is why the prop's own doc\n // asks for it synchronously. `env.disabled`: the panel already treats the\n // host's flag and `running` as ONE concept where the fields are concerned\n // (`fieldEnv.disabled` falls back from one to the other), so gating the\n // button on only one of the two sources was the same asymmetry rounds 4 and 9\n // turned up — a host freezing the form got every input inert and a live Run\n // button beside them, and a click there starts a run from a form the user\n // cannot edit. It is read off the prop rather than off `fieldEnv.disabled`\n // because those differ exactly when the host passes `disabled: false` while\n // `running` is true, and there the button must still be held.\n const blocked = running || notReady || uploading || (env?.disabled ?? false);\n\n // Optional inputs that are still empty stay folded, so the form opens at its\n // simplest shape and grows on demand. Required or already-filled always show.\n //\n // Which optionals are revealed is LATCHED rather than re-derived from the\n // current value, and that is the whole point. Deriving it live means an\n // optional the user empties disappears from under the cursor: clearing the\n // last character flips `isFilled`, the field drops out of `visibleFields`,\n // and React unmounts the very input being typed into — focus lost, every\n // keystroke after it going nowhere. It needs no host pre-fill to reach:\n // expand the fold, fill an optional, collapse it (it stays on screen because\n // it is filled), then clear it.\n //\n // So between fold transitions the form's shape only ever GROWS. The latch is\n // cleared by the toggle's own handler, by a contract change and by a fill from\n // an example, which are the moments nobody is mid-edit; each is followed by\n // the grow pass below re-adding every optional that still holds a value, so an\n // emptied one folds back. Nothing about readiness or the wire depends on this —\n // an emptied optional is omitted from the payload whether or not its input is\n // on screen.\n //\n // The latch is STATE adjusted during render, not a ref mutated during render,\n // and in a library component that distinction is load-bearing. A ref written\n // during render survives a render that never commits, so a host rendering the\n // panel inside a transition — which App Router navigation does by default —\n // can have an abandoned render for contract B wipe the set that the committed\n // contract A is still displaying from, and an optional the user revealed,\n // collapsed and emptied vanishes on A's next render. That is the very defect\n // this latch exists to prevent, re-entering by another door. React discards a\n // state update from an abandoned render, so the two-`useState` form below is\n // the one that actually holds. It is React's documented shape for adjusting\n // state when a prop changes, and it converges: after the update lands, the\n // reset branch and `newlyRevealed` are both empty on the following pass.\n const [revealed, setRevealed] = React.useState<ReadonlySet<string>>(NOTHING_REVEALED);\n const [latchedFor, setLatchedFor] = React.useState(contract);\n // How many contracts this panel has shown, moved in the same render-phase\n // adjustment as the latch and for the same reason. \"Fill with an example\" is\n // keyed by it: the kernel's control keeps what it learned about one method's\n // examples (whether there are any, under `hideWhenEmpty`, read once as it\n // mounts) and reads again only on a remount, as the kernel's own form expects\n // a new key for a new method. Without it, a pipe whose method has no example\n // would hide the control from the next pipe's examples for good. It counts\n // contracts rather than keying on the source object, which a host may build\n // inline on every render: that would remount the control on each one, read\n // the list each time and close a sheet the person has open. The fields are\n // keyed by it too, so a switch remounts every field even where both pipes\n // declare an input of the same name: a field's work for the pipe the person\n // left, a photo still being made into a file, is dropped with it rather than\n // handed over to the new pipe's upload.\n const [contractTurns, setContractTurns] = React.useState(0);\n // Read this render off the local value, never off `revealed`: a state update\n // made during render is not visible until the re-render it schedules, and the\n // output computed below has to already reflect it.\n let revealedNow = revealed;\n let contractTurnsNow = contractTurns;\n if (latchedFor !== contract) {\n revealedNow = NOTHING_REVEALED;\n contractTurnsNow = contractTurns + 1;\n setLatchedFor(contract);\n setRevealed(revealedNow);\n setContractTurns(contractTurnsNow);\n }\n const newlyRevealed = fields.filter(\n (field) => !field.required && isFilled(values[field.name]) && !revealedNow.has(field.name),\n );\n if (newlyRevealed.length > 0) {\n revealedNow = new Set([...revealedNow, ...newlyRevealed.map((field) => field.name)]);\n setRevealed(revealedNow);\n }\n const isFolded = React.useCallback(\n (field: RunField) => !field.required && !revealedNow.has(field.name),\n [revealedNow],\n );\n // What a collapse would hide — every EMPTY optional — rather than what is\n // hidden right now. The two differ only for an optional that was revealed and\n // then emptied, and that difference is the whole affordance: counting the\n // latched-visible ones leaves the count at zero there, the toggle unrendered,\n // and the empty input stuck on screen with no control that would fold it. The\n // latch keeps deciding what renders; it just stops deciding whether the user\n // is offered a way out of it.\n const foldableCount = fields.filter(\n (field) => !field.required && !isFilled(values[field.name]),\n ).length;\n const visibleFields = showOptional ? fields : fields.filter((field) => !isFolded(field));\n\n // Whether \"Fill with an example\" asks before it replaces the values: the\n // kernel's `touched`, measured against `given` by the run the values would\n // send (`sameRunValues`), so a value typed and erased again, which sends the\n // same run, does not count. A file still arriving does, the host's included.\n // Only read with an example source, so a panel given none does no extra work.\n const hasExampleSource = exampleSource !== undefined;\n const touched = React.useMemo(\n () =>\n hasExampleSource && (uploading || (given !== null && !sameRunValues(values, given, fields))),\n [hasExampleSource, uploading, given, values, fields],\n );\n\n // A fill is a reset to the example's values, the kernel's own form's answer\n // (`useMethodForm`'s `reset`), made here over values the host owns. It runs\n // from the examples' list, a click away from any field, so nobody is mid-edit.\n const handleFill = React.useCallback(\n (next: Record<string, unknown>, example: FormExample) => {\n // An upload started before the fill was for values the example replaced:\n // its result is discarded when it lands, and it no longer holds Run.\n generationRef.current += 1;\n setUploadingIds(EMPTY_IDS);\n setSubmitError(null);\n // The example's values are what the person's next edits are measured\n // against, so a fill followed by a second fill does not ask.\n setGiven(next);\n // The form takes the example's shape: the optionals it fills are revealed\n // by the grow pass, and while the fold is collapsed those it leaves empty\n // fold away. An expanded fold stays expanded, as the kernel's own form\n // leaves its disclosure alone on a reset: the person opened it.\n setRevealed(NOTHING_REVEALED);\n // Remounted, so no control keeps what it held for the replaced values:\n // the preview of a file still arriving, a refused drop.\n setFills((count) => count + 1);\n // Advanced at once for the reason the upload write-back advances it: a\n // continuation landing before the host's re-render reads the mirror.\n valuesRef.current = next;\n onValuesChange(next);\n // Last, so a host reading its own state here already has the example's\n // values on their way.\n onFill?.(next, example);\n },\n [onValuesChange, onFill],\n );\n\n // A submit that has passed the gate latches until the end of the current task.\n //\n // `blocked` is computed during render, so two `requestSubmit()` calls made in\n // ONE synchronous host callback both close over the same render and both pass\n // it — even when the host sets `running` synchronously inside `onRun`, exactly\n // as that prop's doc demands, because React has not re-rendered in between.\n // Two real clicks are two separate tasks with a commit between them and were\n // never affected; this closes the programmatic path, which is a surface this\n // component documents and pins a story against.\n //\n // The release is a microtask, and that is the whole reason this is safe rather\n // than the lock this component deliberately does NOT take. A lock held for the\n // lifetime of a run would have no release — the panel is told when a run\n // starts and never that one finished — so a host that never passes `running`\n // would be wedged after its first run. This latch outlives nothing: the\n // microtask is queued unconditionally and always runs, so it cannot wedge, and\n // it holds no run state a later render could disagree with.\n const justSubmittedRef = React.useRef(false);\n\n const handleSubmit = (event: React.FormEvent) => {\n event.preventDefault();\n // The submit PATH owns the gate, not the button's `disabled` attribute —\n // see `blocked` above for why each term is there and why none is covered by\n // the kernel gate that runs next.\n if (blocked || justSubmittedRef.current) return;\n const outcome = runSubmitGate(contract, fields, values, translate);\n if (!outcome.ok) {\n setSubmitError(outcome.summary);\n return;\n }\n setSubmitError(null);\n // Latched BEFORE `onRun`, so a host that re-enters synchronously from inside\n // its own handler is held by the same guard.\n justSubmittedRef.current = true;\n queueMicrotask(() => {\n justSubmittedRef.current = false;\n });\n onRun(outcome.apiInputs);\n };\n\n const paletteStyle = React.useMemo(\n () => getPaletteForTheme(theme) as React.CSSProperties,\n [theme],\n );\n\n // One provider around the whole panel, which is exactly one form — the scope\n // the kernel's contract asks for. `fallbackPrefix` is this panel's own\n // `useId`, so an unset `idPrefix` keeps the kernel's default behaviour (unique\n // per instance) rather than turning the namespacing off.\n return (\n <FieldDomIdProvider prefix={idPrefix ?? fallbackPrefix}>\n <form\n className={[\"mthds-run-panel\", theme === GRAPH_THEME.DARK && \"dark\", className]\n .filter(Boolean)\n .join(\" \")}\n style={paletteStyle}\n // The panel's gate is the authority on whether a run may go out, and the\n // browser's is not merely redundant beside it — it is WRONG. The kernel's\n // number control carries `step={integer ? 1 : 0.1}`, so any float with\n // more than one decimal is a `stepMismatch` even though `native.Number`\n // accepts it and the kernel's own schema validation does too. Interactive\n // validation then aborts submission before `onSubmit` runs at all: no\n // gate, no `onRun`, no error from the panel, and a native message that is\n // wrong about the domain (\"nearest valid values are 87.2 and 87.3\").\n // Turning it off is what makes the documented `requestSubmit()` promise\n // true, and costs nothing — every constraint that should hold is checked\n // by `runSubmitGate`.\n noValidate\n onSubmit={handleSubmit}\n >\n {title && <h2 className=\"mthds-run-panel-title\">{title}</h2>}\n\n {fields.length > 0 ? (\n <div className=\"mthds-run-panel-fields\">\n {exampleSource && (\n // Its own row, so the control keeps its width in the column, and\n // `:empty` takes the row out while the kernel holds the control\n // back (`hideWhenEmpty`, a method with no example yet).\n <div className=\"mthds-run-panel-examples\">\n <FillWithExample\n key={contractTurnsNow}\n source={exampleSource}\n fields={fields}\n touched={touched}\n onFill={handleFill}\n // Held exactly when the fields are: filling is an edit of them.\n disabled={fieldEnv.disabled}\n />\n </div>\n )}\n {visibleFields.map((field) => (\n <FieldRenderer\n key={`${field.name}:${fills}:${contractTurnsNow}`}\n field={field}\n value={values[field.name]}\n onChange={(value) => {\n // Built on the mirror, not on this render's `values`, for the\n // reason the upload write-back advances it: an upload landing\n // calls `onValuesChange` outside a React event, so a keystroke\n // or a file chosen from the host's files can arrive before the\n // host re-renders, and building on the render's values would\n // drop the file that just landed. The mirror moves forward\n // here too, so two changes in one tick each build on the other.\n const before = valuesRef.current;\n const next = { ...before, [field.name]: value };\n valuesRef.current = next;\n commitValues(next, before);\n }}\n id={field.name}\n env={fieldEnv}\n />\n ))}\n {foldableCount > 0 && (\n <OptionalToggle\n count={foldableCount}\n expanded={showOptional}\n onToggle={() => {\n setShowOptional((expanded) => !expanded);\n // Clearing the latch here is what makes \"the shape only grows\"\n // a temporary state rather than a permanent one. A fold\n // transition is a click on this button, so nobody is mid-edit\n // in a field, and the render below re-adds every optional that\n // still holds a value — leaving exactly the emptied ones to\n // fold away, which is what the user just asked for.\n setRevealed(NOTHING_REVEALED);\n }}\n noun=\"input\"\n />\n )}\n </div>\n ) : (\n <p className=\"mthds-run-panel-empty\">This pipe takes no inputs.</p>\n )}\n\n {submitError && (\n <p className=\"mthds-run-panel-error\" role=\"alert\">\n {submitError}\n </p>\n )}\n\n <div className=\"mthds-run-panel-footer\">\n {/*\n The readiness line is the only thing on screen that says WHY Run is\n disabled, so it has to be reachable by the people who cannot see it\n sitting next to the button — and a disabled button is out of the tab\n order, so they will not arrive at it by walking the controls either.\n `aria-describedby` is the association that makes a screen reader read\n the reason with the button instead of announcing a bare dimmed \"Run\".\n The id comes from `useId` because a host may put two panels on one\n page, and a hardcoded one would make the second panel describe the\n first panel's button.\n */}\n <button\n type=\"submit\"\n className=\"mthds-run-panel-run\"\n disabled={blocked}\n aria-describedby={notReady ? readinessHintId : undefined}\n >\n {running ? \"Running…\" : \"Run\"}\n </button>\n {notReady && (\n <span id={readinessHintId} className=\"mthds-run-panel-readiness\">\n {`${readiness.ready} of ${readiness.total} ready — still needed: ${readiness.missing.join(\", \")}`}\n </span>\n )}\n </div>\n </form>\n </FieldDomIdProvider>\n );\n}\n","/**\n * The panel's submit path, kept React-free.\n *\n * Everything between \"the user pressed Run\" and \"the payload goes on the wire\"\n * is the kernel's (`@pipelex/mthds-form`, `core/gate.ts`); this module bridges\n * the panel's values into the shape the gate takes, calls it, and turns the\n * verdict into one line a panel can show. Splitting it out of `RunPanel.tsx` is\n * what lets the node vitest project test that seam without mounting React — the\n * gate's own behavior is covered by the kernel's tests and is deliberately not\n * re-tested here.\n */\nimport {\n describeValidationError,\n gateRunInputs,\n rjsfDataFromRunValues,\n type PipeIOContract,\n type RunField,\n type RunInputError,\n type ValidationMessageKey,\n} from \"@pipelex/mthds-form\";\n\n/**\n * How many schema errors the summary quotes when the missing-input scan comes up\n * empty. A form with a deep mismatch can produce dozens; past a handful the\n * line stops being readable and the user acts on the first one anyway.\n */\nconst MAX_QUOTED_ERRORS = 3;\n\n/** The outcome of one submit attempt. */\nexport type RunGateOutcome =\n | { ok: true; apiInputs: Record<string, unknown> }\n | { ok: false; missingInputs: string[]; summary: string };\n\n/**\n * Every message key the error summary can render — the kernel's, plus the two\n * this panel owns.\n *\n * The kernel's keys describe one schema error each and are rendered by\n * `describeValidationError`. The `runPanel.` ones are lines the panel writes\n * itself, around those errors, and they carry the prefix precisely so the\n * ownership is legible at the call site and in a host's translation file.\n *\n * Nesting the kernel's union inside ours is deliberate: a key the kernel ADDS\n * lands here automatically and then fails `VALIDATION_STRINGS`'s exhaustiveness\n * until it is given a string, which is how a kernel bump is stopped from\n * silently rendering `undefined` at a user.\n */\nexport type RunPanelMessageKey =\n | ValidationMessageKey\n | \"runPanel.missingInputs\"\n | \"runPanel.fillRequired\";\n\n/**\n * The panel's i18n seam — the kernel's `Translate` widened to the panel's own\n * keys. It accepts a superset of what the kernel asks for, so it is still a\n * valid `Translate` wherever the kernel wants one.\n */\nexport type RunPanelTranslate = (\n key: RunPanelMessageKey,\n values?: Record<string, string>,\n) => string;\n\n/**\n * English defaults for every key above. The kernel deliberately ships no\n * defaults for its own (its `Translate` contract is host-supplied), so a panel\n * that wants to say anything at all has to name them — the wording matches the\n * canonical consumer's `en.json` so the two surfaces read alike.\n */\nconst VALIDATION_STRINGS: Record<RunPanelMessageKey, string> = {\n \"inputPanel.aDateField\": \"A date field\",\n \"inputPanel.pickValidDate\": \"{label}: “{value}” is not a valid date\",\n \"inputPanel.pickValidDateEmpty\": \"{label}: pick a valid date\",\n \"inputPanel.dateCarriesTime\":\n \"{label}: “{value}” carries a time, but a date field takes the day alone — use “{day}” and put the time in the “time” field\",\n \"inputPanel.invalidValue\": \"Invalid value\",\n \"inputPanel.invalidValueWithData\": \"{stack} (value: “{value}”)\",\n \"runPanel.missingInputs\": \"Missing required fields in: {inputs}\",\n \"runPanel.fillRequired\": \"Please fill in all required fields before running.\",\n};\n\n/**\n * The default translator: the English strings above with `{placeholder}`\n * interpolation. A host that localizes passes its own translator instead.\n */\nexport const defaultValidationTranslate: RunPanelTranslate = (key, values) => {\n const template = VALIDATION_STRINGS[key];\n if (!values) return template;\n return template.replace(/\\{(\\w+)\\}/g, (whole, name: string) => values[name] ?? whole);\n};\n\n/**\n * One human line for an invalid verdict.\n *\n * `missingInputs` is the good case: it names the VARIABLES at fault, which is\n * what the user clicks on. The scan can legitimately come up empty on an\n * invalid form (a wrong value shape, a nested mismatch), and that is exactly\n * when falling back to the raw schema errors keeps the failure diagnosable rather\n * than silent — see `validateRunInputs` in the kernel.\n *\n * All three routes go through `t`. Which one runs is decided by the kernel's\n * verdict, so a host that localizes cannot know in advance which line it will\n * be shown — leaving any of them in hardcoded English would surface as the\n * summary silently reverting to English on some inputs and not others.\n */\nexport function summarizeVerdict(\n missingInputs: string[],\n errors: RunInputError[],\n preparedData: unknown,\n t: RunPanelTranslate = defaultValidationTranslate,\n): string {\n if (missingInputs.length > 0) {\n return t(\"runPanel.missingInputs\", { inputs: missingInputs.join(\", \") });\n }\n const described = errors\n .slice(0, MAX_QUOTED_ERRORS)\n .map((error) => describeValidationError(error, t, preparedData))\n .join(\"; \");\n return described || t(\"runPanel.fillRequired\");\n}\n\n/**\n * Run the kernel's gate over the panel's current values.\n *\n * `gateRunInputs` IS the gate — the whole chain in one call — so all this\n * module does either side of it is bridge and phrase: the panel holds values\n * keyed by variable, the gate takes the schema-shaped data those become, and a\n * rejected verdict has to come back as one line rather than as a discriminated\n * union the panel would have to read.\n *\n * Assembling those steps here instead was the earlier shape and it was wrong in\n * a way nothing local could see. The chain's schema validation is not the whole\n * rule: JSON Schema's `required` only asserts a key is PRESENT, and a content model\n * carries no `minLength`, so a required input that arrived empty — `{text: \"\"}`\n * from an untouched text field, `{url: \"\"}` from an untouched file field —\n * satisfied the schema and the run went out. The Run button refuses exactly\n * those, through `computeReadiness`. The gate now re-applies that same\n * emptiness rule with `computeReadiness`'s own functions over the same derived\n * fields, which makes the button's verdict and this one a single invariant\n * rather than two things that resemble each other.\n */\nexport function runSubmitGate(\n contract: PipeIOContract,\n fields: RunField[],\n values: Record<string, unknown>,\n t: RunPanelTranslate = defaultValidationTranslate,\n): RunGateOutcome {\n const verdict = gateRunInputs(contract, rjsfDataFromRunValues(values, fields));\n if (!verdict.ok) {\n return {\n ok: false,\n missingInputs: verdict.missingInputs,\n summary: summarizeVerdict(verdict.missingInputs, verdict.errors, verdict.preparedData, t),\n };\n }\n return { ok: true, apiInputs: verdict.inputs };\n}\n","/**\n * One upload the run panel runs for a dropped file: from the host's\n * `uploadFile` to the value written at the field's path, and the promise of that\n * value the panel hands back to the kernel's field as `onDropFile`'s answer.\n *\n * It is React-free and kept out of the component so that what the panel\n * promises the field can be tested on its own. The promise goes to the kernel's\n * control and to nothing else, so no story can hold it; the stories prove what\n * the field does with it.\n *\n * Why the panel answers at all (kernel `0.22.0`, docs/upload-seam.md in the\n * kernel, \"The local preview belongs to the value it was made for\"): a dropped\n * file is shown from an object URL until its upload lands, and the field must\n * then tell its upload's result from a file someone else wrote there. Told\n * nothing, it goes by when the value lands, which asks the host to write the\n * value in the very render it ends the flight. The panel cannot promise that:\n * the values are the host's, and a host applying them through a store, a\n * transition or a store that renders on write puts them on screen a render\n * after or before the panel's own mark goes, and the field then drops the\n * preview. Answered with the file the upload wrote, the field matches its URL\n * whichever render it lands in.\n */\n\nimport type { UploadedFile } from \"@pipelex/mthds-form/react\";\n\n/**\n * What an upload stored, as the panel writes it: the URL, and the display name\n * when the host gave one. A host's upload may resolve to the URL alone, as the\n * kernel's `UploadedFile` allows, and the panel reads that as this with no name.\n */\nexport type StoredFile = Exclude<UploadedFile, string>;\n\n/** The steps of one upload, each supplied by the panel. */\nexport interface PanelUpload {\n /** The field's id, its dotted value path, named when the upload is abandoned. */\n id: string;\n /** Starts the host's upload. */\n start: () => Promise<UploadedFile>;\n /** Whether the form the file was dropped in is still the one on screen. */\n isCurrent: () => boolean;\n /** Writes what the upload stored at the field's path and returns the value written. */\n write: (stored: StoredFile) => StoredFile;\n /** Takes the field out of the panel's set of uploads in flight. */\n endFlight: () => void;\n /** Where a bug in `write` is reported: an unhandled rejection unless a test passes its own. */\n reportBug?: (bug: unknown) => void;\n}\n\n/**\n * Runs one upload and returns its answer for the field: a promise that resolves\n * to the value it wrote, and rejects when it wrote nothing, because the upload\n * failed, the form moved on before it landed, or the write-back threw. The\n * field matches the resolved URL to the value, and retires the dropped file's\n * preview on a rejection rather than waiting for a file that will never arrive.\n * It is the kernel's own `useMethodForm` `dropFile`, answered the same way.\n *\n * Every rejection is handled here as well as by the field, so a caller that\n * ignores the promise leaves no unhandled rejection behind, as the kernel's\n * `dropFile` does. A failed upload is the host's to announce, since it owns the\n * transport, and an abandoned one is nobody's. A write-back bug is the one\n * failure that must stay visible, and is reported apart (see `write` below).\n */\nexport function runPanelUpload({\n id,\n start,\n isCurrent,\n write,\n endFlight,\n reportBug = surfaceAsUnhandledRejection,\n}: PanelUpload): Promise<StoredFile> {\n // Called through an async wrapper rather than directly. `uploadFile` is the\n // HOST's function and is typed as a plain function returning a promise —\n // nothing obliges it to be `async`. One that validates before it starts the\n // request (no API key configured, a file over the size limit, a mime type it\n // will not take) throws SYNCHRONOUSLY, and a synchronous throw happens before\n // there is a promise to hang the cleanup below on. The id the panel marked\n // before calling this would then stay marked for good: `uploading` disables\n // the dropzone, so the field cannot even be retried, and Run stays gated\n // until the user leaves the form entirely. The wrapper turns that throw into\n // the rejection this chain already cleans up, which makes the SAME host logic\n // behave the same way whether it was written `async` or not — the only\n // difference between those two spellings being the keyword.\n const landed = (async () => await start())().then((uploaded) => {\n // The form this file was dropped in is gone: another pipe, an example's\n // fill, or the panel unmounting (see the generation marker in\n // `RunPanel.tsx`). Writing now would land the file in a form that never\n // asked for it, so nothing is written, and the answer says so.\n if (!isCurrent()) {\n throw new Error(\n `The form moved on before the upload dropped at \"${id}\" landed, so it wrote nothing.`,\n );\n }\n try {\n // The kernel's `UploadedFile` lets a host resolve to the URL alone, as\n // its own form's `uploadFile` does; anything else goes to `write` as it\n // came, so a host's `undefined` still reaches the bug report below.\n return write(typeof uploaded === \"string\" ? { url: uploaded } : uploaded);\n } catch (bug) {\n // A bug in the write-back, not a failed upload. `uploadFile` is typed\n // `Promise<UploadedFile>`, but a type is not a runtime guarantee: a host\n // branch that forgets its `return`, or unwraps a JSON response one level\n // too few, resolves to `undefined`, and `stored.url` then throws.\n //\n // It rejects the answer, because nothing was written and the field must\n // not wait for it. But the field handles that rejection, and so does the\n // cleanup below, so a bug that only rejected the answer would be\n // swallowed: the spinner clears, the field reads empty, nothing is\n // logged, and re-dropping repeats it forever, the one failure in this\n // lifecycle with no diagnostic surface anywhere. Before the panel\n // answered the field, the bug stayed visible because nothing handled the\n // write-back's own promise; now that something does, it is also raised\n // on a promise of its own that nothing handles, as an unhandled rejection\n // where the host's error reporting can see it.\n reportBug(bug);\n throw bug;\n }\n });\n // The same generation check as the write-back, for a sharper reason.\n // Switching contracts already emptied the panel's set, and the very same id\n // may since have been re-added by a NEW upload under the new generation —\n // nothing exotic, since that is what sharing the `cv` input name means, and a\n // host returning to the pipe it left reaches it with no rename at all.\n // Deleting it here would un-mark an upload that is still running: its\n // dropzone re-enables mid-flight, its progress indicator vanishes, and the\n // Run gate lets go of it.\n //\n // Given both arguments, so this chain handles every rejection of `landed`\n // and itself always resolves.\n const settle = () => {\n if (isCurrent()) endFlight();\n };\n void landed.then(settle, settle);\n return landed;\n}\n\n/** Raises `bug` on a promise nothing handles: the host's error reporting sees an unhandled rejection. */\nfunction surfaceAsUnhandledRejection(bug: unknown): void {\n void Promise.resolve().then(() => {\n throw bug;\n });\n}\n"],"mappings":";;;;;;;;;;;;;AAyCA,cAAc;;;ACvCd,YAAY,WAAW;AACvB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAMK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAKK;;;ACbP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAKK;AAOP,IAAM,oBAAoB;AA0C1B,IAAM,qBAAyD;AAAA,EAC7D,yBAAyB;AAAA,EACzB,4BAA4B;AAAA,EAC5B,iCAAiC;AAAA,EACjC,8BACE;AAAA,EACF,2BAA2B;AAAA,EAC3B,mCAAmC;AAAA,EACnC,0BAA0B;AAAA,EAC1B,yBAAyB;AAC3B;AAMO,IAAM,6BAAgD,CAAC,KAA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C,YACC,oBAAC,UAAK,IAAI,iBAAiB,WAAU,6BAClC,aAAG,UAAU,KAAK,OAAO,UAAU,KAAK,+BAA0B,UAAU,QAAQ,KAAK,IAAI,CAAC,IACjG;AAAA,WAEJ;AAAA;AAAA;AAAA,EACF,GACF;AAEJ;","names":["_a","_b","_c"]}
@@ -3,7 +3,7 @@ import React__default from 'react';
3
3
  import { d as GraphSpec, e as GraphNodeData, f as GraphEdge, g as GraphNode, h as GraphConfig, i as GraphDirection, F as FoldMode, G as GraphThemeMode, T as ToolbarPosition, j as GraphStyleId, a as GraphTheme, k as PipeStatus, l as GraphSpecNodeIoItem, m as ValidationState, V as ValidationIssue, L as LabelDescriptor, n as PipeControllerType, o as FoldToggleOptions, N as NodeValidationSummary, p as PipeCardPayload, C as ConceptInfo, q as GraphSpecNode } from '../../types-CnDJyLYo.js';
4
4
  export { r as PipeOperatorType } from '../../types-CnDJyLYo.js';
5
5
  import { PipeIOContracts, OutputForm, InputForm, LoadText, SaveFiles } from '@pipelex/mthds-form';
6
- import { ResolveUrl, ResolveRendition, ResolveDocumentPdf, ResolveShareUrl, DownloadDisplay } from '@pipelex/mthds-form/react';
6
+ import { ResolveUrl, ResolveRendition, ResolveDocumentPdf, LoadBytes, PdfWorkerConfig, OpenExternal, ResolveShareUrl, DownloadDisplay } from '@pipelex/mthds-form/react';
7
7
  import { Edge, Node, ReactFlowInstance } from '@xyflow/react';
8
8
  import 'mthds/errors';
9
9
 
@@ -305,6 +305,42 @@ interface GraphViewerProps {
305
305
  * reads as `unavailable`.
306
306
  */
307
307
  resolveDocumentPdf?: ResolveDocumentPdf;
308
+ /**
309
+ * Reads a document's bytes, so the result panel can draw a PDF it cannot
310
+ * frame (one `resolveUrl` answers on another origin, such as a presigned
311
+ * storage URL) page by page with pdf.js. It takes effect only with
312
+ * `pdfWorker`.
313
+ *
314
+ * Called with the document's own `url` member, as `resolveUrl` is, and a
315
+ * `{ maxBytes, signal }` request; resolve to the file's bytes as a
316
+ * `Uint8Array` or an `ArrayBuffer`, pass `signal` to your `fetch`, and reject
317
+ * for anything that is not a reference you store yourself: the method chose
318
+ * the URL, so never fetch an arbitrary one with credentials or through your
319
+ * own server. It goes on the panel's provider beside `resolveUrl`, which
320
+ * replaces an outer provider rather than merging with it, so a `loadBytes`
321
+ * set around the graph does not reach the panel.
322
+ */
323
+ loadBytes?: LoadBytes;
324
+ /**
325
+ * Names pdf.js's worker for the PDFs the result panel draws from `loadBytes`:
326
+ * a `workerSrc` URL of `pdf.worker.min.mjs` from the same `pdfjs-dist` the
327
+ * kernel's `react-pdf` resolves, or a `workerPort` the host started, with an
328
+ * optional `version` checked against pdf.js's and the optional data-file
329
+ * directories. Unset, no PDF is drawn and each keeps its link. Keep its
330
+ * identity stable (a constant or a memoized object). It goes on the panel's
331
+ * provider beside `resolveUrl`, so one set around the graph does not reach
332
+ * the panel.
333
+ */
334
+ pdfWorker?: PdfWorkerConfig;
335
+ /**
336
+ * Opens an external link in a PDF the result panel draws, for a host whose
337
+ * view cannot open a tab itself (a sandboxed frame). Called with the link's
338
+ * `http:`, `https:` or `mailto:` URL on a click or a middle click. Unset,
339
+ * such a link opens in a new tab with `noopener noreferrer`. It goes on the
340
+ * panel's provider beside `resolveUrl`, so one set around the graph does
341
+ * not reach the panel.
342
+ */
343
+ openExternal?: OpenExternal;
308
344
  /**
309
345
  * Mints a URL that works OUTSIDE this page, for the copy control.
310
346
  *
@@ -528,7 +564,11 @@ declare function PipeCardBase({ data, children }: PipeCardBaseProps): react_jsx_
528
564
  * other use of a picture keeps the whole one. A host that can make a PDF of a
529
565
  * document the browser cannot render, such as a Word, Excel or PowerPoint file,
530
566
  * passes `resolveDocumentPdf` there too, and that document's preview shows the
531
- * PDF's pages.
567
+ * PDF's pages. A host whose documents the panel cannot frame, because they are
568
+ * served from another origin such as a presigned storage URL, passes
569
+ * `loadBytes` and `pdfWorker` there as well, and the kernel draws such a PDF's
570
+ * pages itself with pdf.js; `openExternal` is how the links inside those pages
571
+ * leave a view that cannot open a tab.
532
572
  *
533
573
  * ## Stored texts
534
574
  *
@@ -635,6 +675,28 @@ interface StuffResultPanelProps extends StuffResultRendererOptions {
635
675
  * page's own origin; an answer on another origin reads as `unavailable`.
636
676
  */
637
677
  resolveDocumentPdf?: ResolveDocumentPdf;
678
+ /**
679
+ * Reads a document's bytes, for a PDF the panel cannot frame because the
680
+ * frame rule refused it (another origin, such as a presigned storage URL):
681
+ * called with the document's own `url` member and `{ maxBytes, signal }`, it
682
+ * resolves to the file as a `Uint8Array` or an `ArrayBuffer`, and the kernel
683
+ * draws its pages with pdf.js. It takes effect only with `pdfWorker`. The
684
+ * method chose the URL, so it reads only references the host stores itself
685
+ * and rejects every other.
686
+ */
687
+ loadBytes?: LoadBytes;
688
+ /**
689
+ * pdf.js's worker for the PDFs drawn from `loadBytes`: a `workerSrc` URL or a
690
+ * host-started `workerPort`, with an optional `version` and data-file
691
+ * directories. Unset, no PDF is drawn and each keeps its link.
692
+ */
693
+ pdfWorker?: PdfWorkerConfig;
694
+ /**
695
+ * Opens an external link inside a drawn PDF, for a view that cannot open a
696
+ * tab itself. Unset, such a link opens in a new tab with
697
+ * `noopener noreferrer`.
698
+ */
699
+ openExternal?: OpenExternal;
638
700
  /**
639
701
  * Reads a stored text: called with the reference's `url` when the panel
640
702
  * shows a `Text`, `Markdown`, `Html` or `JSON` value the runtime stored
@@ -663,7 +725,7 @@ interface StuffResultPanelProps extends StuffResultRendererOptions {
663
725
  */
664
726
  downloads?: DownloadDisplay;
665
727
  }
666
- declare function StuffResultPanel({ pipeIoContracts, outputForm, inputForm, stuff, producerPipeRef, consumer, resolveUrl, loadText, resolveRendition, resolveDocumentPdf, resolveShareUrl, saveFiles, downloads, }: StuffResultPanelProps): react_jsx_runtime.JSX.Element | null;
728
+ declare function StuffResultPanel({ pipeIoContracts, outputForm, inputForm, stuff, producerPipeRef, consumer, resolveUrl, loadText, resolveRendition, resolveDocumentPdf, loadBytes, pdfWorker, openExternal, resolveShareUrl, saveFiles, downloads, }: StuffResultPanelProps): react_jsx_runtime.JSX.Element | null;
667
729
 
668
730
  interface DetailPanelProps {
669
731
  isOpen: boolean;
@@ -450,6 +450,9 @@ function StuffResultPanel({
450
450
  loadText,
451
451
  resolveRendition,
452
452
  resolveDocumentPdf,
453
+ loadBytes,
454
+ pdfWorker,
455
+ openExternal,
453
456
  resolveShareUrl,
454
457
  saveFiles,
455
458
  downloads
@@ -477,13 +480,16 @@ function StuffResultPanel({
477
480
  ].join("\0");
478
481
  if (field) {
479
482
  const panel = /* @__PURE__ */ jsx3(LoadedStuffViewer, { field, nodeKey, value: stuff.data, name: stuff.name });
480
- return resolveUrl || loadText || resolveRendition || resolveDocumentPdf || resolveShareUrl || saveFiles || downloads ? /* @__PURE__ */ jsx3(
483
+ return resolveUrl || loadText || resolveRendition || resolveDocumentPdf || loadBytes || pdfWorker || openExternal || resolveShareUrl || saveFiles || downloads ? /* @__PURE__ */ jsx3(
481
484
  ResultEnvProvider,
482
485
  {
483
486
  resolveUrl,
484
487
  loadText,
485
488
  resolveRendition,
486
489
  resolveDocumentPdf,
490
+ loadBytes,
491
+ pdfWorker,
492
+ openExternal,
487
493
  resolveShareUrl,
488
494
  saveFiles,
489
495
  downloads,
@@ -2417,15 +2423,18 @@ function ResultView({
2417
2423
  loadText,
2418
2424
  resolveRendition,
2419
2425
  resolveDocumentPdf,
2426
+ loadBytes,
2427
+ pdfWorker,
2428
+ openExternal,
2420
2429
  resolveShareUrl,
2421
2430
  saveFiles,
2422
2431
  downloads
2423
2432
  } = valueOptions;
2424
2433
  return /* @__PURE__ */ jsx22(
2425
2434
  StuffResultPanel,
2426
- __spreadProps(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadProps(__spreadValues({}, descriptors), {
2435
+ __spreadProps(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadProps(__spreadValues({}, descriptors), {
2427
2436
  stuff
2428
- }), concept ? { concept } : {}), producerPipeRef ? { producerPipeRef } : {}), consumer ? { consumer } : {}), resolveUrl ? { resolveUrl } : {}), loadText ? { loadText } : {}), resolveRendition ? { resolveRendition } : {}), resolveDocumentPdf ? { resolveDocumentPdf } : {}), resolveShareUrl ? { resolveShareUrl } : {}), saveFiles ? { saveFiles } : {}), downloads ? { downloads } : {}), {
2437
+ }), concept ? { concept } : {}), producerPipeRef ? { producerPipeRef } : {}), consumer ? { consumer } : {}), resolveUrl ? { resolveUrl } : {}), loadText ? { loadText } : {}), resolveRendition ? { resolveRendition } : {}), resolveDocumentPdf ? { resolveDocumentPdf } : {}), loadBytes ? { loadBytes } : {}), pdfWorker ? { pdfWorker } : {}), openExternal ? { openExternal } : {}), resolveShareUrl ? { resolveShareUrl } : {}), saveFiles ? { saveFiles } : {}), downloads ? { downloads } : {}), {
2429
2438
  theme
2430
2439
  })
2431
2440
  );
@@ -4155,6 +4164,9 @@ function GraphViewerCanvas(props) {
4155
4164
  loadText,
4156
4165
  resolveRendition,
4157
4166
  resolveDocumentPdf,
4167
+ loadBytes,
4168
+ pdfWorker,
4169
+ openExternal,
4158
4170
  resolveShareUrl,
4159
4171
  saveFiles,
4160
4172
  downloads,
@@ -4886,6 +4898,9 @@ function GraphViewerCanvas(props) {
4886
4898
  loadText,
4887
4899
  resolveRendition,
4888
4900
  resolveDocumentPdf,
4901
+ loadBytes,
4902
+ pdfWorker,
4903
+ openExternal,
4889
4904
  resolveShareUrl,
4890
4905
  saveFiles,
4891
4906
  downloads
@@ -4895,6 +4910,9 @@ function GraphViewerCanvas(props) {
4895
4910
  loadText,
4896
4911
  resolveRendition,
4897
4912
  resolveDocumentPdf,
4913
+ loadBytes,
4914
+ pdfWorker,
4915
+ openExternal,
4898
4916
  resolveShareUrl,
4899
4917
  saveFiles,
4900
4918
  downloads