@xeplr/ui-jobs 1.0.3 → 1.2.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
@@ -84,11 +84,11 @@ There is no embedded / standalone switch: `registerJobsUI()` returns `<Route>` e
84
84
  | `optionSources` | `{}` | where a kind of thing is listed, for action inputs with `optionsFrom` — see below |
85
85
  | `breadcrumb` | — | a component, rendered as `<Breadcrumb items={[{ label: 'Jobs' }]} />` above the page |
86
86
  | `uploadLink` | — | element or string, shown in the page footnote ("Loading a file into a table is recorded separately — see …"); without it the footnote says "the upload screen" |
87
- | `connectLink` | — | element shown in the header before **+ New job** — a link to a workflow canvas for chaining jobs. Passed in rather than imported, so this package does not depend on workflow (which already calls jobs over HTTP) |
87
+ | `chainsApiBase` | `null` | where the **workflow** API is mounted (e.g. `'/workflow'`). It keeps each job's "After this job" rules (`/job-chains/:jobId`), because jobs never start each other: the workflow engine does every hand-off. `null` (no workflow on the install) leaves the editor's **After this job** step out. HTTP only; this package does not import workflow |
88
88
 
89
89
  Returns `{ routes, path }`: one `<Route>` at `path`, and the path itself so your navigation does not retype it.
90
90
 
91
- `apiBase` and `optionSources` are module-level settings — the last `registerJobsUI()` call wins.
91
+ `apiBase`, `optionSources` and `chainsApiBase` are module-level settings — the last `registerJobsUI()` call wins.
92
92
 
93
93
  ## Requests
94
94
 
@@ -107,6 +107,7 @@ Every call goes through `authFetch`, which prefixes the base URL `@xeplr/ui-acco
107
107
  | pause / resume | `POST /jobs/:id/pause`, `POST /jobs/:id/resume` |
108
108
  | a run's log lines | `GET /logs?referenceId=<occurrenceId>` — **not** under `apiBase` |
109
109
  | an option list | `GET <source.url>?limit=0` — under `apiBase` |
110
+ | a job's "After this job" rules | `GET` / `PUT <chainsApiBase>/job-chains/:jobId` with `{ rules, jobName }` — **not** under `apiBase` |
110
111
 
111
112
  `/logs` is the platform's generic log route, not part of `@xeplr/jobs`. A host without it answers 404 and the panel shows an error in place of the log. Log lines are keyed by occurrence id because an action writes under the `referenceId` it is handed.
112
113
 
@@ -121,11 +122,21 @@ State shows **Running** over **Paused**: a pause takes effect at the next pick,
121
122
 
122
123
  ### The editor
123
124
 
124
- Three steps, all reachable at any time, with **Save job** on each:
125
+ Three steps (four with `chainsApiBase`), all reachable at any time, with **Save job** on each:
125
126
 
126
127
  1. **Job** — name, description, action.
127
128
  2. **Inputs** — a control per field of the action's `inputSchema`: a select for `options`, true/false for `boolean`, a number input, a JSON textarea for `object` / `array` (invalid JSON blocks the save), text otherwise. Fields marked `system: true` are never shown — the server fills them, and rendering them would ask for a credential. Optional fields with a `default` are under **Advanced**, whose summary lists their values. Values are converted to the declared types on save, since `@xeplr/schema-handler` rejects `"1000"` for a number.
128
129
  3. **Schedule** — cron (`CronScheduleField`), status, **Start from** (`startAt`), **Retry on failure** (0–3, default 0), **Give up after** (`timeoutMinutes`, blank = server default of 30).
130
+ 4. **After this job** (`JobChainSection`, `useJobChainController`, `lib/jobChainModel.js`) — "Run another job when this one finishes", then rules checked top to bottom, first match wins. Each rule has:
131
+ - **If**: a JSON condition, e.g. `{ "field": "status", "op": "=", "value": "success" }`, or `{ "all": [ … ] }` / `{ "any": [ … ] }`. Empty means "otherwise" and must come last.
132
+ - **Run**: another job.
133
+ - Optional **inputs** for the next job and **carry** for later ones, binding `{output.x}`, `{carry.x}`, `{window.to}`.
134
+
135
+ The period this job ran for passes to the next job by itself. Text that is not JSON, a missing job, or an "otherwise" that is not last is refused before anything is saved; the server checks the meaning and names the rule. An existing job's rules are saved before the job, and a new job's right after it (it needs its id).
136
+
137
+ An input the action marks `control: 'parameters'` (a procedure's parameters) is shown as rows, not JSON (`ParametersField`, `lib/parametersModel.js`): a parameter's name, and where its value comes from: **Start of the window**, **End of the window** (saved as `{window.from}` / `{window.to}`, which `@xeplr/jobs` fills in with the run's dates) or a **Fixed value**. The choices are the jobs package's run contract (`GET /jobs/run-contract`, `useRunContract`). A job with no parameters yet starts with the two window rows, and one whose name is left empty is not saved. An input marked `hidden` (the procedure's old **Window**) is shown only when a job already holds one.
138
+
139
+ With `chainsApiBase`, **Inputs** also has **From the job before**: tickboxes for the inputs another job may fill when it runs this one (the job's `acceptsInputs`). No field is ticked by default, and a field naming a connection is never offered.
129
140
 
130
141
  A new job with a schedule defaults to **Paused**, so it can be written now and started later. A job with no schedule is saved as `ready` and runs only when triggered.
131
142
 
@@ -181,7 +192,7 @@ Styles read `--accent`, `--surface`, `--ink`, `--muted`, `--hair`, `--plane` and
181
192
  npm test
182
193
  ```
183
194
 
184
- Plain Node scripts, no framework (`test/run.mjs` runs each `*.test.*` file): job state, `describeCron`, next-run and duration labels, latest run per job, search and sort.
195
+ Plain Node scripts, no framework (`test/run.mjs` runs each `*.test.*` file): job state, `describeCron`, next-run and duration labels, latest run per job, search and sort; and the "After this job" form's rules: text to rules and back, what is refused, what the job before may fill (`jobChainModel.test.mjs`).
185
196
 
186
197
  ## License
187
198
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xeplr/ui-jobs",
3
- "version": "1.0.3",
3
+ "version": "1.2.0",
4
4
  "description": "The screens for @xeplr/jobs — schedule, run, pause and watch jobs — as routes a host app registers, or a standalone app",
5
5
  "type": "module",
6
6
  "main": "src/index.jsx",
@@ -0,0 +1,36 @@
1
+ import { authFetch } from '@xeplr/ui-account'
2
+
3
+ // "AFTER THIS JOB" RULES — served by the WORKFLOW API, not by jobs.
4
+ //
5
+ // Jobs never start each other; the workflow engine does every hand-off, and a
6
+ // job's rules are a workflow it keeps (GET/PUT <workflow>/job-chains/:jobId).
7
+ // So this is where that API is mounted, set by the host — and null when there
8
+ // is no workflow on the install, which hides the section rather than showing
9
+ // one that cannot save.
10
+ //
11
+ // Over HTTP only: this package does not import workflow's code, so each can be
12
+ // installed on its own.
13
+ let CHAINS_BASE = null
14
+
15
+ export function configureChainsApi(base) {
16
+ CHAINS_BASE = typeof base === 'string' ? base.replace(/\/+$/, '') : null
17
+ }
18
+
19
+ export function chainsEnabled() {
20
+ return CHAINS_BASE !== null
21
+ }
22
+
23
+ const url = (jobId) => `${CHAINS_BASE}/job-chains/${encodeURIComponent(jobId)}`
24
+
25
+ /** { jobId, workflowId, rules } — an empty list for a job with none. */
26
+ export async function getChain(jobId) {
27
+ return authFetch(url(jobId))
28
+ }
29
+
30
+ /** Replace a job's rules. An empty list removes them. */
31
+ export async function putChain(jobId, rules, jobName) {
32
+ return authFetch(url(jobId), {
33
+ method: 'PUT',
34
+ body: JSON.stringify({ rules: rules, jobName: jobName })
35
+ })
36
+ }
package/src/api/jobs.js CHANGED
@@ -185,3 +185,13 @@ export async function fetchOccurrenceLogs(occurrenceId) {
185
185
  const res = await authFetch(`/logs?referenceId=${encodeURIComponent(occurrenceId)}`)
186
186
  return res.dataArray || []
187
187
  }
188
+
189
+ /**
190
+ * What every run of a job receives — its window's start and end — as the
191
+ * names an input binds to: [{ key, label, description }]. From @xeplr/jobs'
192
+ * GET /jobs/run-contract, so the dropdowns offer exactly what the server fills.
193
+ */
194
+ export async function getRunContract() {
195
+ const res = await authFetch(url('/jobs/run-contract'))
196
+ return res.dataArray || []
197
+ }
@@ -0,0 +1,19 @@
1
+ /* "After this job" — the rules list in the job editor. */
2
+ .jb-chain { display: grid; gap: 10px; }
3
+ .jb-chain-toggle { display: flex; align-items: center; gap: 8px; font-size: 14px; color: var(--ink, #1a1a19); cursor: pointer; }
4
+ .jb-chain-rules { list-style: none; margin: 0; padding: 0; display: grid; gap: 12px; }
5
+ .jb-chain-rule {
6
+ padding: 12px 14px; background: var(--plane, #f7f7f5);
7
+ border: 1px solid var(--hair, #e2e1d9); border-radius: 11px;
8
+ }
9
+ .jb-chain-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px; }
10
+ .jb-chain-n { font-size: 12px; font-weight: 600; letter-spacing: .04em; text-transform: uppercase; color: var(--muted, #6b6a63); }
11
+ .jb-chain-tools { display: flex; gap: 6px; }
12
+ .jb-chain-tools button, .jb-chain-add {
13
+ padding: 4px 10px; font: inherit; font-size: 12px; color: var(--ink, #1a1a19);
14
+ background: var(--surface, #ffffff); border: 1px solid var(--hair, #e2e1d9); border-radius: 7px; cursor: pointer;
15
+ }
16
+ .jb-chain-tools button:disabled { opacity: .45; cursor: default; }
17
+ .jb-chain-add { justify-self: start; font-size: 13px; padding: 6px 12px; }
18
+ .jb-chain-json { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12.5px; resize: vertical; }
19
+ .jb-chain-fields { margin: 6px 0 8px; padding-left: 18px; font-size: 13px; color: var(--muted, #6b6a63); display: grid; gap: 3px; }
@@ -0,0 +1,115 @@
1
+ import { CHAIN_FIELDS, EXAMPLE_WHEN } from '../lib/jobChainModel.js'
2
+ import './JobChainSection.css'
3
+
4
+ /**
5
+ * "After this job" — which job runs next, depending on how this one ended.
6
+ *
7
+ * Presentation only: everything comes from useJobChainController. Conditions
8
+ * and values are JSON on purpose (the free product has no workflow designer);
9
+ * the server checks what they mean and names the rule when one is wrong.
10
+ *
11
+ * @param {object} props.chain useJobChainController()
12
+ * @param {object[]} props.jobs every job, for the "run" picker
13
+ * @param {string} [props.jobId] this job, left out of the picker
14
+ */
15
+ export default function JobChainSection({ chain, jobs, jobId }) {
16
+ if (chain.loading) return <p className="muted">Loading the rules…</p>
17
+ if (chain.loadError) {
18
+ return <p className="jb-help jb-warn">Could not load this job's rules, so they cannot be changed here: {chain.loadError}</p>
19
+ }
20
+
21
+ const others = (jobs || []).filter((j) => j.id !== jobId)
22
+
23
+ return (
24
+ <div className="jb-chain">
25
+ <label className="jb-chain-toggle">
26
+ <input type="checkbox" checked={chain.on} onChange={(e) => chain.setOn(e.target.checked)} />
27
+ Run another job when this one finishes
28
+ </label>
29
+
30
+ {!chain.on && (
31
+ <p className="jb-help">Nothing runs after this job. Tick the box to choose what should, and when.</p>
32
+ )}
33
+
34
+ {chain.on && (
35
+ <>
36
+ <p className="jb-help">
37
+ Rules are checked top to bottom and the first that matches runs its job. A rule with no
38
+ condition means “otherwise”. The period this job ran for passes to the next job by itself.
39
+ </p>
40
+
41
+ <ol className="jb-chain-rules">
42
+ {chain.rows.map((row, i) => (
43
+ <li key={i} className="jb-chain-rule">
44
+ <div className="jb-chain-head">
45
+ <span className="jb-chain-n">Rule {i + 1}</span>
46
+ <span className="jb-chain-tools">
47
+ <button type="button" onClick={() => chain.moveUp(i)} disabled={i === 0} title="Check this rule earlier">↑</button>
48
+ <button type="button" className="jb-danger" onClick={() => chain.removeRow(i)}>Remove</button>
49
+ </span>
50
+ </div>
51
+
52
+ <div className="jb-field">
53
+ <label htmlFor={`jb-chain-when-${i}`}>If <span className="jb-type">· JSON, empty = otherwise</span></label>
54
+ <textarea id={`jb-chain-when-${i}`} className="jb-chain-json" rows={3}
55
+ placeholder={EXAMPLE_WHEN} value={row.when}
56
+ onChange={(e) => chain.updateRow(i, { when: e.target.value })} />
57
+ </div>
58
+
59
+ <div className="jb-field">
60
+ <label htmlFor={`jb-chain-run-${i}`}>Run</label>
61
+ <select id={`jb-chain-run-${i}`} value={row.run}
62
+ onChange={(e) => chain.updateRow(i, { run: e.target.value })}>
63
+ <option value="">Choose a job…</option>
64
+ {others.map((j) => <option key={j.id} value={j.id}>{j.name}</option>)}
65
+ </select>
66
+ </div>
67
+
68
+ <details className="jb-advanced" open={Boolean(row.inputs || row.carry)}>
69
+ <summary>Pass values on <span className="jb-dim">— optional</span></summary>
70
+ <div className="jb-field">
71
+ <label htmlFor={`jb-chain-inputs-${i}`}>Inputs of the next job <span className="jb-type">· JSON</span></label>
72
+ <textarea id={`jb-chain-inputs-${i}`} className="jb-chain-json" rows={3}
73
+ placeholder={'{ "region": "{output.region}" }'} value={row.inputs}
74
+ onChange={(e) => chain.updateRow(i, { inputs: e.target.value })} />
75
+ <span className="jb-help">
76
+ Only inputs the next job accepts (its Inputs step lists them). Leave out
77
+ <code className="jb-code">window</code> to pass this job's period on unchanged.
78
+ </span>
79
+ </div>
80
+ <div className="jb-field">
81
+ <label htmlFor={`jb-chain-carry-${i}`}>Carry for later jobs <span className="jb-type">· JSON</span></label>
82
+ <textarea id={`jb-chain-carry-${i}`} className="jb-chain-json" rows={3}
83
+ placeholder={'{ "loadedRows": "{output.totalRows}" }'} value={row.carry}
84
+ onChange={(e) => chain.updateRow(i, { carry: e.target.value })} />
85
+ <span className="jb-help">Read later as <code className="jb-code">carry.loadedRows</code>, in a condition or a value.</span>
86
+ </div>
87
+ </details>
88
+ </li>
89
+ ))}
90
+ </ol>
91
+
92
+ <button type="button" className="jb-chain-add" onClick={chain.addRow}>+ Add rule</button>
93
+
94
+ <details className="jb-advanced">
95
+ <summary>What a condition can read</summary>
96
+ <ul className="jb-chain-fields">
97
+ {CHAIN_FIELDS.map((f) => (
98
+ <li key={f.field}><code className="jb-code">{f.field}</code> — {f.about}</li>
99
+ ))}
100
+ </ul>
101
+ <p className="jb-help">
102
+ Comparisons: <code className="jb-code">=</code> <code className="jb-code">!=</code>{' '}
103
+ <code className="jb-code">&gt;</code> <code className="jb-code">&gt;=</code>{' '}
104
+ <code className="jb-code">&lt;</code> <code className="jb-code">&lt;=</code>{' '}
105
+ <code className="jb-code">in</code> <code className="jb-code">contains</code>{' '}
106
+ <code className="jb-code">isEmpty</code> and more. Combine with
107
+ <code className="jb-code">{'{ "all": [ … ] }'}</code> or <code className="jb-code">{'{ "any": [ … ] }'}</code>.
108
+ Values bind with <code className="jb-code">{'{output.name}'}</code>, <code className="jb-code">{'{carry.name}'}</code>, <code className="jb-code">{'{window.to}'}</code>.
109
+ </p>
110
+ </details>
111
+ </>
112
+ )}
113
+ </div>
114
+ )
115
+ }
@@ -0,0 +1,20 @@
1
+ /* Parameters as rows — name ← where its value comes from. Widths set here
2
+ because the editor gives every input full width. */
3
+ .jb-params { display: grid; gap: 8px; margin: 6px 0 8px; }
4
+ .jb-param {
5
+ display: grid; align-items: center; gap: 8px;
6
+ grid-template-columns: minmax(140px, 220px) auto minmax(180px, 240px) minmax(0, 1fr) auto;
7
+ }
8
+ .jb-editor .jb-param input, .jb-editor .jb-param select { width: 100%; min-width: 0; }
9
+ .jb-param-name { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 13px; }
10
+ .jb-param-arrow { color: var(--muted, #6b6a63); }
11
+ .jb-param-gap { min-width: 0; }
12
+ .jb-param-remove, .jb-param-add {
13
+ padding: 5px 10px; font: inherit; font-size: 12px; color: var(--ink, #1a1a19);
14
+ background: var(--surface, #ffffff); border: 1px solid var(--hair, #e2e1d9); border-radius: 7px; cursor: pointer;
15
+ }
16
+ .jb-param-add { justify-self: start; font-size: 13px; }
17
+ @media (max-width: 640px) {
18
+ .jb-param { grid-template-columns: 1fr auto; }
19
+ .jb-param-arrow { display: none; }
20
+ }
@@ -0,0 +1,80 @@
1
+ import { useState } from 'react'
2
+ import { FIXED, rowsFromText, rowsToText, sourceOf, valueForSource } from '../lib/parametersModel.js'
3
+ import './ParametersField.css'
4
+
5
+ /**
6
+ * Parameters as rows: a name, and where its value comes from — the start or
7
+ * end of the run's window, or a fixed value. Presentation and row editing only;
8
+ * the conversion is lib/parametersModel.js.
9
+ *
10
+ * `value` / `onChange` carry the saved text ([{ name, value }] as JSON), so
11
+ * the editor saves this field like any other list.
12
+ *
13
+ * @param {object} props.field the action's input ({ name, label, description })
14
+ * @param {string} props.value saved JSON text
15
+ * @param {Function} props.onChange
16
+ * @param {object[]} props.contract what every run receives (useRunContract)
17
+ */
18
+ export default function ParametersField({ field, value, onChange, contract }) {
19
+ const [rows, setRows] = useState(() => rowsFromText(value, contract))
20
+ const id = `jb-in-${field.name}`
21
+
22
+ // Saved text that is not a list (typed by hand before this control
23
+ // existed) is shown as it is rather than guessed at.
24
+ if (rows === null) {
25
+ return (
26
+ <div className="jb-field jb-field--wide">
27
+ <label htmlFor={id}>{field.label || field.name}</label>
28
+ <textarea id={id} rows={4} spellCheck="false" value={value} onChange={(e) => onChange(e.target.value)} />
29
+ <span className="jb-help jb-warn">This is not a list of parameters, so it is shown as it was saved.</span>
30
+ </div>
31
+ )
32
+ }
33
+
34
+ function update(next) {
35
+ setRows(next)
36
+ onChange(rowsToText(next))
37
+ }
38
+ const patchRow = (i, p) => update(rows.map((r, j) => (j === i ? { ...r, ...p } : r)))
39
+
40
+ return (
41
+ <div className="jb-field jb-field--wide">
42
+ <label>{field.label || field.name}</label>
43
+ {contract.length > 0 && (
44
+ <span className="jb-help">
45
+ Every run receives a window, from this job's schedule or from the job before it:{' '}
46
+ {contract.map((c) => c.label.toLowerCase()).join(' and ')}. Pick it as a parameter's value.
47
+ </span>
48
+ )}
49
+ <div className="jb-params">
50
+ {rows.map((r, i) => {
51
+ const source = sourceOf(r.value, contract)
52
+ return (
53
+ <div key={i} className="jb-param">
54
+ <input aria-label={`Parameter ${i + 1} name`} className="jb-param-name" value={r.name}
55
+ placeholder={source === FIXED ? 'name' : 'e.g. startDate'}
56
+ onChange={(e) => patchRow(i, { name: e.target.value })} />
57
+ <span className="jb-param-arrow" aria-hidden="true">←</span>
58
+ <select aria-label={`Parameter ${i + 1} value`} value={source}
59
+ onChange={(e) => patchRow(i, { value: valueForSource(e.target.value, r.value, contract) })}>
60
+ {contract.map((c) => <option key={c.key} value={c.key}>{c.label}</option>)}
61
+ <option value={FIXED}>Fixed value</option>
62
+ </select>
63
+ {source === FIXED ? (
64
+ <input aria-label={`Parameter ${i + 1} fixed value`} className="jb-param-value" value={r.value == null ? '' : String(r.value)}
65
+ placeholder="value" onChange={(e) => patchRow(i, { value: e.target.value })} />
66
+ ) : <span className="jb-param-gap" />}
67
+ <button type="button" className="jb-param-remove" title="Remove this parameter"
68
+ onClick={() => update(rows.filter((_, j) => j !== i))}>✕</button>
69
+ </div>
70
+ )
71
+ })}
72
+ </div>
73
+ <button type="button" className="jb-param-add" onClick={() => update([...rows, { name: '', value: '' }])}>+ Add parameter</button>
74
+ <span className="jb-help">
75
+ The name is the procedure's own parameter name. On MySQL, parameters go by position, so keep
76
+ them in the order the procedure declares them.
77
+ </span>
78
+ </div>
79
+ )
80
+ }
package/src/index.jsx CHANGED
@@ -1,6 +1,7 @@
1
1
  import { Route } from 'react-router-dom';
2
2
  import JobsPage from './pages/Jobs.jsx';
3
3
  import { configureJobsApi, configureOptionSources } from './api/jobs.js';
4
+ import { configureChainsApi } from './api/jobChains.js';
4
5
  import { ROUTES } from './routes.js';
5
6
 
6
7
  /**
@@ -57,18 +58,18 @@ import { ROUTES } from './routes.js';
57
58
  * navigate back up to.
58
59
  * @param {JSX.Element|string} [config.uploadLink] - a link to wherever the host
59
60
  * loads files, named in the empty state.
60
- * @param {JSX.Element} [config.connectLink] - a link to the workflow canvas,
61
- * for connecting jobs so one starts when another finishes. Supplied by the
62
- * host because this package must not import @xeplr/workflow — workflow
63
- * already calls jobs over HTTP at run time, and importing its UI here would
64
- * close that into a circular dependency between two packages that are
65
- * deliberately installable on their own.
61
+ * @param {string|null} [config.chainsApiBase=null] - where the WORKFLOW API
62
+ * is mounted (e.g. '/workflow'), which keeps each job's "After this job"
63
+ * rules. Jobs never start each other — the workflow engine does every
64
+ * hand-off — so without it the editor shows no "After this job" step.
65
+ * Talked to over HTTP only: this package does not import workflow.
66
66
  * @returns {{ routes: JSX.Element[], path: string }}
67
67
  */
68
68
  export function registerJobsUI(config) {
69
69
  config = config || {};
70
70
  if (config.apiBase !== undefined) configureJobsApi({ base: config.apiBase });
71
71
  configureOptionSources(config.optionSources);
72
+ configureChainsApi(config.chainsApiBase);
72
73
 
73
74
  var path = ROUTES.jobs(config.basePath);
74
75
 
@@ -0,0 +1,122 @@
1
+ // "AFTER THIS JOB" — the rules a job's screen writes, as pure logic.
2
+ //
3
+ // The rules are kept by the workflow engine, not by jobs: each becomes a branch
4
+ // of one hidden workflow that runs when the job finishes (see
5
+ // @xeplr-workflow/engine's lib/jobChains.js). This file is only the form's
6
+ // half — the text a person types, turned into the rules the server takes,
7
+ // and back — so it can be tested with plain node.
8
+ //
9
+ // A rule as the server takes it:
10
+ //
11
+ // { when: { field, op, value } | { all: [...] } | { any: [...] } | null,
12
+ // run: '<jobId>', inputs: { … }, carry: { … } }
13
+ //
14
+ // `when` null is "otherwise". The window the job ran for passes to the next
15
+ // job by itself; `inputs` and `carry` are only for anything more.
16
+
17
+ /** The fields a condition can read, for the help text. */
18
+ export const CHAIN_FIELDS = [
19
+ { field: 'status', about: '"success" or "failed" — did this job\'s work happen' },
20
+ { field: 'output.<name>', about: 'what this job\'s action returned, e.g. output.totalRows' },
21
+ { field: 'window.from / window.to', about: 'the period this job ran for' },
22
+ { field: 'carry.<name>', about: 'values carried from earlier jobs in the chain' },
23
+ { field: 'error.message', about: 'why it failed' }
24
+ ]
25
+
26
+ export const EXAMPLE_WHEN = '{ "field": "status", "op": "=", "value": "success" }'
27
+
28
+ function pretty(value) {
29
+ if (value === null || value === undefined) return ''
30
+ if (typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) return ''
31
+ return JSON.stringify(value, null, 2)
32
+ }
33
+
34
+ /** Server rules → the rows the form edits (JSON as text). */
35
+ export function rulesToRows(rules) {
36
+ return (Array.isArray(rules) ? rules : []).map((r) => ({
37
+ when: pretty(r.when),
38
+ run: r.run || '',
39
+ inputs: pretty(r.inputs),
40
+ carry: pretty(r.carry)
41
+ }))
42
+ }
43
+
44
+ export function blankRow() {
45
+ return { when: '', run: '', inputs: '', carry: '' }
46
+ }
47
+
48
+ function parseObject(text, label, problems) {
49
+ const raw = String(text || '').trim()
50
+ if (!raw) return null
51
+ try {
52
+ const value = JSON.parse(raw)
53
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
54
+ problems.push(`${label} must be a JSON object, in { }.`)
55
+ return null
56
+ }
57
+ return value
58
+ } catch (err) {
59
+ problems.push(`${label} is not valid JSON: ${err.message}`)
60
+ return null
61
+ }
62
+ }
63
+
64
+ /**
65
+ * The form's rows → { rules, problems }. Every problem names its rule, so the
66
+ * form can say all of them at once rather than one per save.
67
+ *
68
+ * The meaning of a condition (which fields, which comparisons) is the
69
+ * server's to check — it answers with the rule and the reason. This only
70
+ * catches what would never reach it: text that is not JSON, a rule with no job.
71
+ */
72
+ export function rowsToRules(rows, ownJobId) {
73
+ const problems = []
74
+ const rules = (rows || []).map((row, i) => {
75
+ const n = i + 1
76
+ if (!row.run) problems.push(`Rule ${n}: choose the job to run.`)
77
+ else if (ownJobId && row.run === ownJobId) problems.push(`Rule ${n}: a job cannot run itself when it finishes.`)
78
+ const when = parseObject(row.when, `Rule ${n}'s condition`, problems)
79
+ const inputs = parseObject(row.inputs, `Rule ${n}'s inputs`, problems)
80
+ const carry = parseObject(row.carry, `Rule ${n}'s carry`, problems)
81
+ return { when: when, run: row.run, inputs: inputs || {}, carry: carry || {} }
82
+ })
83
+ // First match wins, so nothing can follow an "otherwise".
84
+ const otherwiseAt = rules.findIndex((r) => !r.when)
85
+ if (otherwiseAt > -1 && otherwiseAt < rules.length - 1) {
86
+ problems.push(`Rule ${otherwiseAt + 1} has no condition, so it always matches — move it last, or give it one.`)
87
+ }
88
+ return { rules: rules, problems: problems }
89
+ }
90
+
91
+ /** Whether two sets of server rules say the same thing. */
92
+ export function sameRules(a, b) {
93
+ return JSON.stringify(a || []) === JSON.stringify(b || [])
94
+ }
95
+
96
+ /** One line describing a rule, for a summary. */
97
+ export function describeRule(rule, jobName) {
98
+ const target = jobName(rule.run) || rule.run || 'a job'
99
+ const w = rule.when
100
+ if (!w) return `Otherwise, run ${target}`
101
+ if (w.field) return `If ${w.field} ${w.op} ${JSON.stringify(w.value ?? '')}, run ${target}`
102
+ return `If ${w.all ? 'all' : 'any'} of ${(w.all || w.any || []).length} conditions match, run ${target}`
103
+ }
104
+
105
+ // ── what a job accepts from the job before it ───────────────────────────
106
+ //
107
+ // @xeplr/jobs lets a trigger fill only `window` and the inputs a job lists in
108
+ // acceptsInputs. A connection is never offered: it decides where the job
109
+ // reads and writes, and only whoever saves the job chooses that.
110
+ const NEVER_ACCEPTED = /connection/i
111
+
112
+ /** The action's fields another job could fill, by name. */
113
+ export function acceptableFields(fields) {
114
+ return (fields || []).filter((f) => f && f.name && f.name !== 'window' && !NEVER_ACCEPTED.test(f.name))
115
+ }
116
+
117
+ export function toggleAccepted(list, name, on) {
118
+ const set = new Set(Array.isArray(list) ? list : [])
119
+ if (on) set.add(name)
120
+ else set.delete(name)
121
+ return Array.from(set)
122
+ }
@@ -0,0 +1,55 @@
1
+ // A PROCEDURE'S PARAMETERS AS ROWS — the form's half, as pure logic.
2
+ //
3
+ // What a job saves is the list the procedure step takes, [{ name, value }]
4
+ // (or bare values, positional). A value is either fixed text or BOUND to the
5
+ // run's window: "{window.from}" / "{window.to}", which @xeplr/jobs fills in
6
+ // with this run's dates (its run contract, GET /jobs/run-contract). This file
7
+ // turns that list into rows a person edits — a name, and where its value
8
+ // comes from — and back.
9
+
10
+ export const FIXED = 'fixed'
11
+
12
+ export function bindingFor(key) {
13
+ return '{' + key + '}'
14
+ }
15
+
16
+ /** The contract key a value is bound to, or FIXED. */
17
+ export function sourceOf(value, contract) {
18
+ const hit = (contract || []).find((c) => value === bindingFor(c.key))
19
+ return hit ? hit.key : FIXED
20
+ }
21
+
22
+ /**
23
+ * Saved text → rows. A job with no parameters yet starts with one row per
24
+ * contract value (the window's start and end), named by the person — the
25
+ * period is what nearly every scheduled procedure takes.
26
+ */
27
+ export function rowsFromText(text, contract) {
28
+ let list = []
29
+ try { list = text ? JSON.parse(text) : [] } catch (e) { list = null }
30
+ if (!Array.isArray(list)) return null
31
+ if (!list.length) {
32
+ return (contract || []).map((c) => ({ name: '', value: bindingFor(c.key), starter: true }))
33
+ }
34
+ return list.map((p) => (p && typeof p === 'object' && !Array.isArray(p)
35
+ ? { name: p.name == null ? '' : String(p.name), value: p.value == null ? '' : p.value }
36
+ : { name: '', value: p == null ? '' : p, bare: true }))
37
+ }
38
+
39
+ /**
40
+ * Rows → the text the form saves. A starter row nobody named is left out, so
41
+ * a procedure with no date parameters gets none. A row with no name is kept
42
+ * as a bare (positional) value.
43
+ */
44
+ export function rowsToText(rows) {
45
+ const list = (rows || [])
46
+ .filter((r) => !(r.starter && !String(r.name || '').trim()))
47
+ .map((r) => (String(r.name || '').trim() ? { name: String(r.name).trim(), value: r.value } : r.value))
48
+ return list.length ? JSON.stringify(list, null, 2) : ''
49
+ }
50
+
51
+ /** A row's value when its source changes: a binding, or empty fixed text. */
52
+ export function valueForSource(source, current, contract) {
53
+ if (source === FIXED) return sourceOf(current, contract) === FIXED ? current : ''
54
+ return bindingFor(source)
55
+ }
@@ -11,6 +11,11 @@ import {
11
11
  latestByJob, prepareJobs, progressLabel, progressStale, lastSeenLabel
12
12
  } from './jobsList.js'
13
13
  import CronScheduleField from '../components/CronScheduleField.jsx'
14
+ import JobChainSection from '../components/JobChainSection.jsx'
15
+ import ParametersField from '../components/ParametersField.jsx'
16
+ import { useRunContract } from '../useRunContract.js'
17
+ import { useJobChainController } from '../useJobChainController.js'
18
+ import { acceptableFields, toggleAccepted } from '../lib/jobChainModel.js'
14
19
  import './Jobs.css'
15
20
 
16
21
  // SCHEDULED JOBS — @xeplr/jobs, in this product's chrome.
@@ -254,12 +259,15 @@ function JobRuns({ jobId, refreshKey }) {
254
259
  // always available — someone editing a live job to change its cron should not
255
260
  // have to walk past its name and its inputs to get there. The steps are for
256
261
  // grouping, not for gatekeeping.
257
- const STEPS = [
262
+ const BASE_STEPS = [
258
263
  { key: 'job', label: 'Job', hint: 'What it is, and what it runs' },
259
264
  { key: 'inputs', label: 'Inputs', hint: 'What that action needs' },
260
265
  { key: 'schedule', label: 'Schedule', hint: 'When, and what if it goes wrong' }
261
266
  ]
262
267
 
268
+ // Shown only when the host has a workflow API — the rules are kept there.
269
+ const AFTER_STEP = { key: 'after', label: 'After this job', hint: 'What runs when this one finishes' }
270
+
263
271
  /**
264
272
  * Fields a PERSON fills in.
265
273
  *
@@ -268,8 +276,14 @@ const STEPS = [
268
276
  * would be asking somebody to type a password into a form, which is exactly
269
277
  * what storing an id instead was for.
270
278
  */
271
- function visibleFields(action) {
272
- return (action?.inputSchema || []).filter((f) => !f.system)
279
+ function visibleFields(action, inputs) {
280
+ // `hidden` (an action's hint): left out unless this job already holds one,
281
+ // so nothing saved is ever invisible.
282
+ const held = (f) => {
283
+ const v = inputs?.[f.name]
284
+ return v !== undefined && v !== '' && v !== '{}' && v !== '[]'
285
+ }
286
+ return (action?.inputSchema || []).filter((f) => !f.system && (!f.hidden || held(f)))
273
287
  }
274
288
 
275
289
  // ── labels ────────────────────────────────────────────────────────────────
@@ -429,8 +443,13 @@ function RemoteSelect({ field, value, onChange, dependsOnValue }) {
429
443
  }
430
444
 
431
445
  /** One input, rendered as whatever its declared type actually is. */
432
- function ActionInput({ field, value, onChange, inputs }) {
446
+ function ActionInput({ field, value, onChange, inputs, contract }) {
433
447
  const id = `jb-in-${field.name}`
448
+
449
+ // Rows rather than JSON, for an input the action marks as parameters.
450
+ if (field.control === 'parameters') {
451
+ return <ParametersField field={field} value={value} onChange={onChange} contract={contract || []} />
452
+ }
434
453
  const common = { id, value, onChange: (e) => onChange(e.target.value) }
435
454
 
436
455
  // A host-provided list, when the host has one. Without a source configured
@@ -489,7 +508,7 @@ function ActionInput({ field, value, onChange, inputs }) {
489
508
 
490
509
  // The editor. A panel rather than a route: a job is a handful of fields, and a
491
510
  // page you navigate to and back from for those is three navigations too many.
492
- function JobEditor({ job, actions, onCancel, onSaved }) {
511
+ function JobEditor({ job, jobs, actions, onCancel, onSaved }) {
493
512
  const [draft, setDraft] = useState(() => ({
494
513
  name: job?.name || '',
495
514
  description: job?.description || '',
@@ -515,10 +534,16 @@ function JobEditor({ job, actions, onCancel, onSaved }) {
515
534
  // at save — see fromFieldValues.
516
535
  inputs: Object.fromEntries(
517
536
  Object.entries(job?.inputs || {}).map(([k, v]) => [k, toFieldValue(v)])
518
- )
537
+ ),
538
+ // Inputs the job BEFORE this one in a chain may fill (@xeplr/jobs'
539
+ // acceptsInputs). `window` always may, so it is not listed.
540
+ acceptsInputs: Array.isArray(job?.acceptsInputs) ? job.acceptsInputs : []
519
541
  }))
520
542
  const [saving, setSaving] = useState(false)
521
543
  const [step, setStep] = useState(0)
544
+ const chain = useJobChainController(job?.id || null)
545
+ const contract = useRunContract()
546
+ const STEPS = chain.enabled ? [...BASE_STEPS, AFTER_STEP] : BASE_STEPS
522
547
 
523
548
  const action = actions.find((a) => a.name === draft.actionName) || null
524
549
  const patch = (p) => setDraft((d) => ({ ...d, ...p }))
@@ -534,12 +559,26 @@ function JobEditor({ job, actions, onCancel, onSaved }) {
534
559
  raiseSnackbar(`Not valid JSON: ${broken.join(', ')}`, { design: 'error' })
535
560
  return
536
561
  }
562
+ // The rules are checked BEFORE anything is saved, so a typo in one does
563
+ // not leave a job saved and its chain not.
564
+ const chainCheck = chain.check(job?.id)
565
+ if (chainCheck.problems.length) {
566
+ setStep(STEPS.length - 1)
567
+ raiseSnackbar(chainCheck.problems.join(' '), { design: 'error' })
568
+ return
569
+ }
537
570
 
538
571
  setSaving(true)
539
572
  try {
540
- await saveJob({
573
+ const name = draft.name.trim() || 'Untitled job'
574
+ // AN EXISTING JOB'S RULES GO FIRST: the server is the one that checks
575
+ // what a condition means, and a refusal there should leave the job as
576
+ // it was rather than half-saved. A new job has no id to hang rules on
577
+ // until it is saved, so its rules follow it.
578
+ if (job?.id) await chain.save(job.id, name)
579
+ const res = await saveJob({
541
580
  ...(job?.id ? { id: job.id } : {}),
542
- name: draft.name.trim() || 'Untitled job',
581
+ name: name,
543
582
  description: draft.description || '',
544
583
  actionName: draft.actionName,
545
584
  // Trimmed to null rather than '': the model treats an absent schedule
@@ -558,8 +597,19 @@ function JobEditor({ job, actions, onCancel, onSaved }) {
558
597
  timeoutMinutes: draft.timeoutMinutes === '' ? null : Number(draft.timeoutMinutes),
559
598
  // Converted back to the types the action declared. Sending the raw
560
599
  // strings is what made every number/boolean field fail validation.
561
- inputs: fromFieldValues(action, draft.inputs)
600
+ inputs: fromFieldValues(action, draft.inputs),
601
+ // Only names that are still fields of the chosen action.
602
+ acceptsInputs: draft.acceptsInputs.filter((n) => acceptableFields(fields).some((f) => f.name === n))
562
603
  })
604
+ if (!job?.id) {
605
+ const newId = res && Array.isArray(res.updatedIds) ? res.updatedIds[0] : null
606
+ try {
607
+ await chain.save(newId, name)
608
+ } catch (err) {
609
+ // The job exists now; reopening it shows the rules to fix.
610
+ raiseSnackbar(`The job was saved, but its "After this job" rules were not: ${err.message}`, { design: 'error' })
611
+ }
612
+ }
563
613
  onSaved()
564
614
  } catch (err) {
565
615
  raiseSnackbar(err.message || 'Could not save the job', { design: 'error' })
@@ -568,7 +618,7 @@ function JobEditor({ job, actions, onCancel, onSaved }) {
568
618
  }
569
619
  }
570
620
 
571
- const fields = visibleFields(action)
621
+ const fields = visibleFields(action, draft.inputs)
572
622
 
573
623
  return (
574
624
  <form className="jb-editor" onSubmit={submit}>
@@ -642,13 +692,40 @@ function JobEditor({ job, actions, onCancel, onSaved }) {
642
692
  key={f.name}
643
693
  field={f}
644
694
  inputs={draft.inputs}
695
+ contract={contract}
645
696
  value={draft.inputs?.[f.name] ?? ''}
646
697
  onChange={(v) => patch({ inputs: { ...draft.inputs, [f.name]: v } })}
647
698
  />
648
699
  )
700
+ const acceptable = acceptableFields(fields)
649
701
  return (
650
702
  <>
651
703
  <div className="jb-grid">{primary.map(render)}</div>
704
+ {chain.enabled && acceptable.length > 0 && (
705
+ /* WHAT THE JOB BEFORE THIS ONE MAY FILL. Off for every
706
+ field until ticked: a chain may otherwise only pass the
707
+ period (window), never this job's SQL or connection. */
708
+ <details className="jb-advanced" open={draft.acceptsInputs.length > 0}>
709
+ <summary>
710
+ From the job before
711
+ <span className="jb-dim">
712
+ {' — '}
713
+ {draft.acceptsInputs.length ? draft.acceptsInputs.map((n) => fieldLabel(acceptable.find((f) => f.name === n) || { name: n })).join(' · ') : 'only the period'}
714
+ </span>
715
+ </summary>
716
+ <p className="jb-help">
717
+ When another job runs this one, it always passes the period it ran for. Tick the inputs
718
+ it may also fill; everything else stays as saved here.
719
+ </p>
720
+ {acceptable.map((f) => (
721
+ <label key={f.name} className="jb-chain-toggle">
722
+ <input type="checkbox" checked={draft.acceptsInputs.includes(f.name)}
723
+ onChange={(e) => patch({ acceptsInputs: toggleAccepted(draft.acceptsInputs, f.name, e.target.checked) })} />
724
+ {fieldLabel(f)}
725
+ </label>
726
+ ))}
727
+ </details>
728
+ )}
652
729
  {advanced.length > 0 && (
653
730
  /* COLLAPSED, NOT HIDDEN. The summary names every field in
654
731
  here and its current value, so closing it never conceals
@@ -770,6 +847,11 @@ function JobEditor({ job, actions, onCancel, onSaved }) {
770
847
  </>
771
848
  )}
772
849
 
850
+ {/* ── 4. What runs next ────────────────────────────────────────────── */}
851
+ {chain.enabled && step === STEPS.length - 1 && STEPS[step].key === 'after' && (
852
+ <JobChainSection chain={chain} jobs={jobs} jobId={job?.id} />
853
+ )}
854
+
773
855
  <div className="jb-editor-actions">
774
856
  <button type="button" onClick={onCancel}>Cancel</button>
775
857
  <span className="jb-editor-nav">
@@ -802,8 +884,6 @@ function JobEditor({ job, actions, onCancel, onSaved }) {
802
884
  * @param {Function} [props.breadcrumb] - the host's breadcrumb component
803
885
  * @param {JSX.Element|string} [props.uploadLink] - a link to wherever the host
804
886
  * loads files, if it has such a screen
805
- * @param {JSX.Element} [props.connectLink] - a link to the workflow canvas,
806
- * for connecting jobs to each other so one starts when another finishes.
807
887
  *
808
888
  * SUPPLIED BY THE HOST, not imported. This package must not depend on
809
889
  * @xeplr/workflow: workflow already calls jobs — over HTTP, at run time, to
@@ -817,7 +897,7 @@ function JobEditor({ job, actions, onCancel, onSaved }) {
817
897
  * the link. Omitted, nothing is rendered — the screen is complete without
818
898
  * it, exactly as uploadLink is.
819
899
  */
820
- export default function Jobs({ breadcrumb: Breadcrumb, uploadLink, connectLink } = {}) {
900
+ export default function Jobs({ breadcrumb: Breadcrumb, uploadLink } = {}) {
821
901
  const [jobs, setJobs] = useState(null)
822
902
  const [runs, setRuns] = useState([])
823
903
  const [actions, setActions] = useState([])
@@ -988,10 +1068,6 @@ export default function Jobs({ breadcrumb: Breadcrumb, uploadLink, connectLink }
988
1068
  <span className="jb-live-count">{active.length} running</span>
989
1069
  )}
990
1070
  </label>
991
- {/* Before "+ New job", because connecting jobs is something you do
992
- to the ones already listed — a secondary action ON this screen's
993
- content, where the primary one creates more of it. */}
994
- {connectLink}
995
1071
  <button type="button" className="jb-primary" onClick={() => setEditing({})}>+ New job</button>
996
1072
  </div>
997
1073
  </header>
@@ -1002,6 +1078,7 @@ export default function Jobs({ breadcrumb: Breadcrumb, uploadLink, connectLink }
1002
1078
  {editing && (
1003
1079
  <JobEditor
1004
1080
  job={editing.id ? editing : null}
1081
+ jobs={jobs || []}
1005
1082
  actions={actions}
1006
1083
  onCancel={() => setEditing(null)}
1007
1084
  onSaved={() => { setEditing(null); load() }}
@@ -0,0 +1,83 @@
1
+ import { useEffect, useState } from 'react'
2
+ import { chainsEnabled, getChain, putChain } from './api/jobChains.js'
3
+ import { blankRow, rowsToRules, rulesToRows, sameRules } from './lib/jobChainModel.js'
4
+
5
+ /**
6
+ * State and handlers for a job's "After this job" rules — no JSX.
7
+ *
8
+ * Loaded when an existing job is opened; saved by the editor's own Save,
9
+ * after the job itself (a new job has no id to hang rules on until then).
10
+ * `enabled` is false when the host has no workflow API, and the section is
11
+ * then not shown at all.
12
+ */
13
+ export function useJobChainController(jobId) {
14
+ const enabled = chainsEnabled()
15
+ const [rows, setRows] = useState([])
16
+ const [saved, setSaved] = useState([])
17
+ const [on, setOn] = useState(false)
18
+ const [loading, setLoading] = useState(Boolean(enabled && jobId))
19
+ const [loadError, setLoadError] = useState(null)
20
+
21
+ useEffect(() => {
22
+ if (!enabled || !jobId) return
23
+ let live = true
24
+ setLoading(true)
25
+ getChain(jobId)
26
+ .then((res) => {
27
+ if (!live) return
28
+ const rules = (res && res.rules) || []
29
+ setSaved(rules)
30
+ setRows(rulesToRows(rules))
31
+ setOn(rules.length > 0)
32
+ setLoadError(null)
33
+ })
34
+ .catch((err) => { if (live) setLoadError(err.message || 'Could not load the rules') })
35
+ .finally(() => { if (live) setLoading(false) })
36
+ return () => { live = false }
37
+ }, [enabled, jobId])
38
+
39
+ function setTurnedOn(value) {
40
+ setOn(value)
41
+ if (value && !rows.length) setRows([blankRow()])
42
+ }
43
+
44
+ function updateRow(index, patch) {
45
+ setRows((rs) => rs.map((r, i) => (i === index ? { ...r, ...patch } : r)))
46
+ }
47
+
48
+ function addRow() { setRows((rs) => [...rs, blankRow()]) }
49
+
50
+ function removeRow(index) { setRows((rs) => rs.filter((_, i) => i !== index)) }
51
+
52
+ // First match wins, so order is meaning.
53
+ function moveUp(index) {
54
+ if (index < 1) return
55
+ setRows((rs) => {
56
+ const next = rs.slice()
57
+ const [row] = next.splice(index, 1)
58
+ next.splice(index - 1, 0, row)
59
+ return next
60
+ })
61
+ }
62
+
63
+ /** The rules this form would save, and anything wrong with them. */
64
+ function check(ownJobId) {
65
+ if (!on) return { rules: [], problems: [] }
66
+ return rowsToRules(rows, ownJobId)
67
+ }
68
+
69
+ /**
70
+ * Save the rules for a job that now has an id. Skipped when nothing
71
+ * changed, so saving a job's schedule does not rewrite its chain.
72
+ */
73
+ async function save(savedJobId, jobName) {
74
+ if (!enabled || !savedJobId || loadError) return
75
+ const { rules, problems } = check(savedJobId)
76
+ if (problems.length) throw new Error(problems.join(' '))
77
+ if (sameRules(rules, saved)) return
78
+ const res = await putChain(savedJobId, rules, jobName)
79
+ setSaved((res && res.rules) || rules)
80
+ }
81
+
82
+ return { enabled, on, setOn: setTurnedOn, rows, updateRow, addRow, removeRow, moveUp, loading, loadError, check, save }
83
+ }
@@ -0,0 +1,23 @@
1
+ import { useEffect, useState } from 'react'
2
+ import { getRunContract } from './api/jobs.js'
3
+
4
+ // Fetched once per page load: it is a fact about the server, not about a job.
5
+ let cached = null
6
+
7
+ /**
8
+ * The run contract (what every run receives), for the parameter dropdowns.
9
+ * Empty until it arrives, and empty when the server has none to give — the
10
+ * rows then offer only a fixed value.
11
+ */
12
+ export function useRunContract() {
13
+ const [contract, setContract] = useState(cached || [])
14
+ useEffect(() => {
15
+ if (cached) return
16
+ let live = true
17
+ getRunContract()
18
+ .then((c) => { cached = c; if (live) setContract(c) })
19
+ .catch(() => { if (live) setContract([]) })
20
+ return () => { live = false }
21
+ }, [])
22
+ return contract
23
+ }