@sendproof/core 0.1.0-alpha.1 → 0.1.0-alpha.2
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/assets/api.js +2 -1
- package/assets/app.css +612 -1
- package/assets/app.js +89 -13
- package/assets/bar-fit.js +91 -0
- package/assets/commands.js +27 -4
- package/assets/dialog.css +125 -0
- package/assets/dialog.js +191 -0
- package/assets/fields/lookup-source.js +5 -2
- package/assets/fields/lookup.js +3 -2
- package/assets/i18n.js +13 -2
- package/assets/icons.js +18 -0
- package/assets/index.html +1 -0
- package/assets/journeys/compare.js +225 -0
- package/assets/journeys/expressions.js +89 -0
- package/assets/journeys/index.js +7 -0
- package/assets/journeys/run.js +152 -0
- package/assets/journeys/steps.js +163 -0
- package/assets/journeys-code.js +193 -0
- package/assets/journeys-dialog-model.js +172 -0
- package/assets/journeys-dialogs.js +301 -0
- package/assets/journeys-model.js +259 -0
- package/assets/journeys-runs.js +109 -0
- package/assets/journeys-session.js +135 -0
- package/assets/journeys-view.js +961 -0
- package/assets/journeys.js +962 -0
- package/assets/locales/ar-journeys.js +468 -0
- package/assets/locales/ar.js +2 -0
- package/assets/locales/cs-journeys.js +468 -0
- package/assets/locales/cs.js +2 -0
- package/assets/locales/da-journeys.js +465 -0
- package/assets/locales/da.js +2 -0
- package/assets/locales/de-journeys.js +465 -0
- package/assets/locales/de.js +2 -0
- package/assets/locales/el-journeys.js +465 -0
- package/assets/locales/el.js +2 -0
- package/assets/locales/en-journeys.js +467 -0
- package/assets/locales/en.js +2 -0
- package/assets/locales/es-journeys.js +467 -0
- package/assets/locales/es.js +2 -0
- package/assets/locales/fa-journeys.js +465 -0
- package/assets/locales/fa.js +2 -0
- package/assets/locales/fi-journeys.js +465 -0
- package/assets/locales/fi.js +2 -0
- package/assets/locales/fr-journeys.js +467 -0
- package/assets/locales/fr.js +2 -0
- package/assets/locales/he-journeys.js +468 -0
- package/assets/locales/he.js +2 -0
- package/assets/locales/hi-journeys.js +465 -0
- package/assets/locales/hi.js +2 -0
- package/assets/locales/id-journeys.js +466 -0
- package/assets/locales/id.js +2 -0
- package/assets/locales/it-journeys.js +467 -0
- package/assets/locales/it.js +2 -0
- package/assets/locales/ja-journeys.js +466 -0
- package/assets/locales/ja.js +2 -0
- package/assets/locales/ko-journeys.js +465 -0
- package/assets/locales/ko.js +2 -0
- package/assets/locales/nb-journeys.js +465 -0
- package/assets/locales/nb.js +2 -0
- package/assets/locales/nl-journeys.js +465 -0
- package/assets/locales/nl.js +2 -0
- package/assets/locales/pl-journeys.js +468 -0
- package/assets/locales/pl.js +2 -0
- package/assets/locales/pt-BR-journeys.js +467 -0
- package/assets/locales/pt-BR.js +2 -0
- package/assets/locales/pt-PT-journeys.js +467 -0
- package/assets/locales/pt-PT.js +2 -0
- package/assets/locales/ru-journeys.js +468 -0
- package/assets/locales/ru.js +2 -0
- package/assets/locales/sv-journeys.js +465 -0
- package/assets/locales/sv.js +2 -0
- package/assets/locales/th-journeys.js +466 -0
- package/assets/locales/th.js +2 -0
- package/assets/locales/tr-journeys.js +468 -0
- package/assets/locales/tr.js +2 -0
- package/assets/locales/uk-journeys.js +468 -0
- package/assets/locales/uk.js +2 -0
- package/assets/locales/vi-journeys.js +466 -0
- package/assets/locales/vi.js +2 -0
- package/assets/locales/zh-Hans-journeys.js +466 -0
- package/assets/locales/zh-Hans.js +2 -0
- package/assets/locales/zh-Hant-journeys.js +466 -0
- package/assets/locales/zh-Hant.js +2 -0
- package/assets/manifest.json +349 -104
- package/assets/markdown.js +27 -2
- package/assets/request-editor.js +7 -1
- package/assets/result-states.js +2 -2
- package/assets/results.js +41 -14
- package/assets/router.js +25 -1
- package/assets/seeded-menu.js +2 -1
- package/assets/shortcuts-sheet.js +3 -1
- package/assets/shortcuts.js +6 -0
- package/assets/sidebar.js +54 -5
- package/assets/signin.js +6 -3
- package/assets/styles.css +8 -2
- package/assets/toast.js +29 -0
- package/assets/vendor/arazzo-runtime-expression.js +136 -0
- package/assets/vendor/json-pointer.js +48 -0
- package/assets/vendor/jsonpath-rfc9535.js +15 -0
- package/assets/view.js +11 -3
- package/assets/views.css +7 -0
- package/dist/index.d.ts +7 -3
- package/dist/index.js +217 -26
- package/dist/journey-builder.d.ts +178 -0
- package/dist/journey-builder.js +169 -0
- package/dist/journeys.d.ts +24 -0
- package/dist/journeys.js +157 -0
- package/dist/node-http.d.ts +2 -0
- package/dist/node-http.js +17 -0
- package/dist/sessions.d.ts +43 -0
- package/dist/sessions.js +145 -0
- package/dist/statements.js +2 -2
- package/dist/stores/tables.d.ts +213 -0
- package/dist/stores/tables.js +213 -0
- package/dist/types.d.ts +34 -2
- package/package.json +1 -1
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
// Journeys mode's data (docs/plans/journeys.md, "Discovery"): the Arazzo documents and their
|
|
2
|
+
// expectations documents that capabilities list, read into journeys the workbench can show and
|
|
3
|
+
// run, plus the simple journeys inferred from OpenAPI `links` when an API publishes none. Pure:
|
|
4
|
+
// no DOM and no fetch (loading takes a `fetchJson`), so tests/ui and ui/*.test.mjs run it in Node.
|
|
5
|
+
import { bindStep } from './journeys/index.js';
|
|
6
|
+
import { opKey } from './operations.js';
|
|
7
|
+
import { dereference } from './api.js';
|
|
8
|
+
import { resolve } from './schema-model.js';
|
|
9
|
+
|
|
10
|
+
/** True when the workbench offers Journeys mode: the host lists journeys or holds Preview sessions. */
|
|
11
|
+
export const journeysEnabled = capabilities => (Array.isArray(capabilities?.journeys) && capabilities.journeys.length > 0) || capabilities?.previewSessions === true;
|
|
12
|
+
|
|
13
|
+
/** The operation an Arazzo step calls: an `operationId`, a `$sourceDescriptions.<name>.<id>` reference, or an `operationPath`. */
|
|
14
|
+
export function stepOperation(step, ops) {
|
|
15
|
+
const id = String(step.operationId ?? '');
|
|
16
|
+
if (id) {
|
|
17
|
+
const bare = id.startsWith('$sourceDescriptions.') ? id.split('.').slice(2).join('.') : id;
|
|
18
|
+
return ops.find(op => op.operation.operationId === bare) ?? null;
|
|
19
|
+
}
|
|
20
|
+
// operationPath: "{$sourceDescriptions.store.url}#/paths/~1orders~1{id}/get"
|
|
21
|
+
const pointer = /#\/paths\/([^/]+)\/(\w+)$/.exec(String(step.operationPath ?? ''));
|
|
22
|
+
if (pointer) {
|
|
23
|
+
const path = pointer[1].replace(/~1/g, '/').replace(/~0/g, '~');
|
|
24
|
+
return ops.find(op => op.path === path && op.method === pointer[2].toUpperCase()) ?? null;
|
|
25
|
+
}
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** "5 rows · 2 documents · 1 email": what a step's expectations say it writes, by kind. */
|
|
30
|
+
export function writeSummary(expected, sqlStore = 'sqlite') {
|
|
31
|
+
const counts = { rows: 0, documents: 0, keys: 0, emails: 0, effects: 0 };
|
|
32
|
+
for (const write of expected?.writes ?? []) {
|
|
33
|
+
if (typeof write.key === 'string' || write.store === 'redis') counts.keys++;
|
|
34
|
+
else if (write.collection !== undefined) counts.documents++;
|
|
35
|
+
else if ((write.store ?? sqlStore) === sqlStore || write.table !== undefined) counts.rows++;
|
|
36
|
+
else counts.documents++;
|
|
37
|
+
}
|
|
38
|
+
for (const effect of expected?.effects ?? []) {
|
|
39
|
+
if (effect.kind === 'email') counts.emails++;
|
|
40
|
+
else counts.effects++;
|
|
41
|
+
}
|
|
42
|
+
return counts;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Every value a step binds, classified without running it: `{ target, expression, from, stepId? }`. */
|
|
46
|
+
export function stepBindings(step) {
|
|
47
|
+
try { return bindStep(step, { inputs: {}, steps: {} }).bound; } catch { return []; }
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Fixed (literal) values a step sets in its body or parameters: targets with no expression. */
|
|
51
|
+
export function fixedValues(step) {
|
|
52
|
+
const fixed = [];
|
|
53
|
+
for (const parameter of step.parameters ?? []) {
|
|
54
|
+
if (!(typeof parameter.value === 'string' && parameter.value.startsWith('$'))) fixed.push({ target: `${parameter.in}.${parameter.name}`, value: parameter.value });
|
|
55
|
+
}
|
|
56
|
+
const walk = (value, pointer) => {
|
|
57
|
+
if (Array.isArray(value)) value.forEach((item, index) => walk(item, `${pointer}/${index}`));
|
|
58
|
+
else if (value !== null && typeof value === 'object') for (const [key, inner] of Object.entries(value)) walk(inner, `${pointer}/${key.replace(/~/g, '~0').replace(/\//g, '~1')}`);
|
|
59
|
+
else if (!(typeof value === 'string' && value.startsWith('$'))) fixed.push({ target: `body${pointer}`, value });
|
|
60
|
+
};
|
|
61
|
+
if (step.requestBody?.payload !== undefined) walk(step.requestBody.payload, '');
|
|
62
|
+
return fixed;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** For each journey input, the step numbers (from 1) that use it. */
|
|
66
|
+
export function inputUsage(journey) {
|
|
67
|
+
const usage = {};
|
|
68
|
+
journey.steps.forEach((step, index) => {
|
|
69
|
+
const expressions = [...stepBindings(step.def).map(item => item.expression), ...JSON.stringify(step.expected ?? {}).match(/\$inputs\.[\w-]+/g) ?? []];
|
|
70
|
+
for (const expression of expressions) {
|
|
71
|
+
const match = /^\$inputs\.([\w-]+)/.exec(expression);
|
|
72
|
+
if (!match) continue;
|
|
73
|
+
usage[match[1]] ??= [];
|
|
74
|
+
if (!usage[match[1]].includes(index + 1)) usage[match[1]].push(index + 1);
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
return usage;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The schema a binding's target names on a step's operation: a parameter, or a spot in the JSON request body. */
|
|
81
|
+
function targetSchema(op, target, document) {
|
|
82
|
+
const param = /^(path|query|header|cookie)\.(.+)$/.exec(target);
|
|
83
|
+
if (param) {
|
|
84
|
+
const parameter = (op.parameters ?? []).map(item => dereference(item, document)).find(item => item?.in === param[1] && item.name === param[2]);
|
|
85
|
+
return parameter?.schema ? resolve(parameter.schema, document) : null;
|
|
86
|
+
}
|
|
87
|
+
const body = dereference(op.operation?.requestBody, document);
|
|
88
|
+
const content = body?.content ?? {};
|
|
89
|
+
let node = content['application/json']?.schema ?? Object.values(content)[0]?.schema;
|
|
90
|
+
if (!node) return null;
|
|
91
|
+
for (const token of target.replace(/^body\/?/, '').split('/').filter(Boolean).map(part => part.replace(/~1/g, '/').replace(/~0/g, '~'))) {
|
|
92
|
+
const schema = resolve(node, document);
|
|
93
|
+
node = /^\d+$/.test(token) && schema.items ? schema.items : schema.properties?.[token];
|
|
94
|
+
if (!node) return null;
|
|
95
|
+
}
|
|
96
|
+
return resolve(node, document);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** What makes a field richer than plain text, and so is worth carrying to an input that feeds it. */
|
|
100
|
+
const RICH = ['enum', 'format', 'minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum', 'minLength', 'maxLength', 'pattern', 'multipleOf'];
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* The control keywords each journey input takes from the step fields it feeds, so an input bound to
|
|
104
|
+
* a field with a lookup (x-lookup), an enum or a format is the same control as that field: the
|
|
105
|
+
* customer picker for customerId, not a text box showing a UUID. The input keeps its own type,
|
|
106
|
+
* description and default; the step's keywords only fill in what it lacks.
|
|
107
|
+
*/
|
|
108
|
+
export function inputControls(journey, document) {
|
|
109
|
+
const controls = {};
|
|
110
|
+
for (const step of journey.steps) {
|
|
111
|
+
if (!step.op) continue;
|
|
112
|
+
for (const binding of stepBindings(step.def)) {
|
|
113
|
+
const name = /^\$inputs\.([\w-]+)$/.exec(binding.expression ?? '')?.[1];
|
|
114
|
+
if (!name || controls[name]) continue;
|
|
115
|
+
const schema = targetSchema(step.op, binding.target, document);
|
|
116
|
+
if (!schema) continue;
|
|
117
|
+
const picked = Object.fromEntries(Object.entries(schema).filter(([key]) => key.startsWith('x-') || RICH.includes(key)));
|
|
118
|
+
if (Object.keys(picked).length) controls[name] = picked;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return controls;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** The criteria a step passes on: Arazzo successCriteria conditions, as written. */
|
|
125
|
+
export const criteriaOf = step => (step.def.successCriteria ?? []).map(criterion => criterion.condition).filter(Boolean);
|
|
126
|
+
|
|
127
|
+
/** The expected status a step's criteria name (`$statusCode == 201`), if any. */
|
|
128
|
+
export function expectedStatus(step) {
|
|
129
|
+
for (const condition of criteriaOf(step)) {
|
|
130
|
+
const match = /^\s*\$statusCode\s*==\s*(\d{3})\s*$/.exec(condition);
|
|
131
|
+
if (match) return Number(match[1]);
|
|
132
|
+
}
|
|
133
|
+
return null;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Whether a step's expectations hold Redis or another store Preview can't hold, or its operation is `preview: false`. */
|
|
137
|
+
function sendOnlyReasonOf(entry, steps, capabilities) {
|
|
138
|
+
if (entry?.sendOnly) return entry.sendOnlyReason || '';
|
|
139
|
+
const guarded = new Set((capabilities?.dataStores ?? []).filter(store => store.mode === 'guard').map(store => store.system));
|
|
140
|
+
for (const step of steps) {
|
|
141
|
+
for (const write of step.expected?.writes ?? []) if (write.store === 'redis' || guarded.has(write.store)) return `${step.stepId}: ${write.store}`;
|
|
142
|
+
}
|
|
143
|
+
return null;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Reads one Arazzo document and its expectations into journeys. Each journey keeps the Arazzo
|
|
148
|
+
* workflow as `def`, its expectations entry as `expect`, and per step the operation it calls.
|
|
149
|
+
*/
|
|
150
|
+
export function readJourneys({ source, arazzo, expectations, ops, capabilities }) {
|
|
151
|
+
const workflows = Array.isArray(arazzo?.workflows) ? arazzo.workflows : [];
|
|
152
|
+
return workflows.filter(workflow => workflow?.workflowId).map(workflow => {
|
|
153
|
+
const entry = expectations?.journeys?.[workflow.workflowId] ?? {};
|
|
154
|
+
const steps = (workflow.steps ?? []).map((def, index) => {
|
|
155
|
+
const op = stepOperation(def, ops);
|
|
156
|
+
return { stepId: def.stepId, index, def, op, opKey: op ? opKey(op) : null, expected: entry.steps?.[def.stepId] ?? null, runnable: !!op && !def.workflowId };
|
|
157
|
+
});
|
|
158
|
+
const sendOnlyReason = sendOnlyReasonOf(entry, steps, capabilities);
|
|
159
|
+
return {
|
|
160
|
+
id: workflow.workflowId, name: workflow.summary || workflow.workflowId, description: workflow.description || '',
|
|
161
|
+
group: entry.group || source.name || 'Journeys', def: workflow, expect: entry, steps,
|
|
162
|
+
inputs: workflow.inputs && typeof workflow.inputs === 'object' ? workflow.inputs : null,
|
|
163
|
+
outputs: Object.keys(workflow.outputs ?? {}).length ? Object.keys(workflow.outputs) : [...new Set(steps.flatMap(step => Object.keys(step.def.outputs ?? {})))],
|
|
164
|
+
runAs: entry.runAs || null, definedIn: entry.definedIn || null,
|
|
165
|
+
sendOnly: sendOnlyReason !== null, sendOnlyReason: sendOnlyReason || '',
|
|
166
|
+
source: source.source === 'file' ? 'file' : 'code', sourceName: source.name || '', arazzoUrl: source.arazzoUrl, expectationsUrl: source.expectationsUrl,
|
|
167
|
+
expectations: expectations ?? { journeys: {}, approvedDifferences: [], ignore: [] },
|
|
168
|
+
approved: (expectations?.approvedDifferences ?? []).filter(record => record.journey === workflow.workflowId),
|
|
169
|
+
inferred: false,
|
|
170
|
+
};
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Simple journeys inferred from OpenAPI `links` (journeys.md, "Discovery"): a response link from
|
|
176
|
+
* one operation to another becomes a two-step journey whose second step takes the first's
|
|
177
|
+
* output. They carry no expectations.
|
|
178
|
+
*/
|
|
179
|
+
export function inferJourneys(document, ops) {
|
|
180
|
+
const journeys = [];
|
|
181
|
+
for (const op of ops) {
|
|
182
|
+
for (const [status, rawResponse] of Object.entries(op.operation.responses ?? {})) {
|
|
183
|
+
if (!/^2/.test(status)) continue;
|
|
184
|
+
const response = rawResponse?.$ref ? resolveRef(document, rawResponse.$ref) : rawResponse;
|
|
185
|
+
for (const [linkName, rawLink] of Object.entries(response?.links ?? {})) {
|
|
186
|
+
const link = rawLink?.$ref ? resolveRef(document, rawLink.$ref) : rawLink;
|
|
187
|
+
const target = link?.operationId ? ops.find(item => item.operation.operationId === link.operationId) : null;
|
|
188
|
+
if (!target || !op.operation.operationId) continue;
|
|
189
|
+
const outputs = {};
|
|
190
|
+
const parameters = [];
|
|
191
|
+
for (const [name, expression] of Object.entries(link.parameters ?? {})) {
|
|
192
|
+
const [where, param] = name.includes('.') ? name.split('.', 2) : [target.parameters.find(p => p.name === name)?.in ?? 'path', name];
|
|
193
|
+
if (typeof expression !== 'string' || !expression.startsWith('$response')) continue;
|
|
194
|
+
outputs[param] = expression;
|
|
195
|
+
parameters.push({ name: param, in: where, value: `$steps.first.outputs.${param}` });
|
|
196
|
+
}
|
|
197
|
+
const id = `${op.operation.operationId}→${linkName}`;
|
|
198
|
+
const def = {
|
|
199
|
+
workflowId: id, summary: `${op.title} → ${target.title}`, description: link.description || '',
|
|
200
|
+
steps: [
|
|
201
|
+
{ stepId: 'first', operationId: op.operation.operationId, successCriteria: [{ condition: `$statusCode == ${status}` }], outputs },
|
|
202
|
+
{ stepId: 'second', operationId: target.operation.operationId, parameters, successCriteria: [{ condition: '$statusCode == 200' }] },
|
|
203
|
+
],
|
|
204
|
+
};
|
|
205
|
+
const steps = def.steps.map((step, index) => {
|
|
206
|
+
const stepOp = index === 0 ? op : target;
|
|
207
|
+
return { stepId: step.stepId, index, def: step, op: stepOp, opKey: opKey(stepOp), expected: null, runnable: true };
|
|
208
|
+
});
|
|
209
|
+
journeys.push({
|
|
210
|
+
id, name: def.summary, description: def.description, group: '', def, expect: {}, steps, inputs: null, outputs: Object.keys(outputs),
|
|
211
|
+
runAs: null, definedIn: null, sendOnly: false, sendOnlyReason: '', source: 'inferred', sourceName: '', arazzoUrl: null, expectationsUrl: null,
|
|
212
|
+
expectations: { journeys: {}, approvedDifferences: [], ignore: [] }, approved: [], inferred: true,
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
return journeys;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function resolveRef(document, ref) {
|
|
221
|
+
if (!String(ref).startsWith('#/')) return undefined;
|
|
222
|
+
return ref.slice(2).split('/').reduce((node, part) => node?.[part.replace(/~1/g, '/').replace(/~0/g, '~')], document);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** Groups in the Arazzo documents' own order; the inferred ones last. Returns `[[name, journeys, inferred]]`. */
|
|
226
|
+
export function journeyGroups(journeys) {
|
|
227
|
+
const groups = new Map();
|
|
228
|
+
for (const journey of journeys.filter(item => !item.inferred)) {
|
|
229
|
+
if (!groups.has(journey.group)) groups.set(journey.group, []);
|
|
230
|
+
groups.get(journey.group).push(journey);
|
|
231
|
+
}
|
|
232
|
+
const result = [...groups].map(([name, items]) => [name, items, false]);
|
|
233
|
+
const inferred = journeys.filter(item => item.inferred);
|
|
234
|
+
if (inferred.length) result.push(['', inferred, true]);
|
|
235
|
+
return result;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* Loads every journey the host lists. `fetchJson(url)` resolves to parsed JSON or throws. A
|
|
240
|
+
* document that can't be read is reported in `problems` and leaves the others usable. Without
|
|
241
|
+
* published journeys, the OpenAPI document's links give inferred ones.
|
|
242
|
+
*/
|
|
243
|
+
export async function loadJourneys({ capabilities, document, ops, fetchJson }) {
|
|
244
|
+
const sources = Array.isArray(capabilities?.journeys) ? capabilities.journeys : [];
|
|
245
|
+
const problems = [];
|
|
246
|
+
const loaded = await Promise.all(sources.map(async source => {
|
|
247
|
+
try {
|
|
248
|
+
const [arazzo, expectations] = await Promise.all([fetchJson(source.arazzoUrl), source.expectationsUrl ? fetchJson(source.expectationsUrl) : null]);
|
|
249
|
+
return { source, arazzo, expectations };
|
|
250
|
+
} catch (error) {
|
|
251
|
+
problems.push({ source, message: error.message });
|
|
252
|
+
return null;
|
|
253
|
+
}
|
|
254
|
+
}));
|
|
255
|
+
const published = loaded.filter(Boolean).flatMap(item => readJourneys({ ...item, ops, capabilities }));
|
|
256
|
+
const ids = new Set(published.map(journey => journey.id));
|
|
257
|
+
const inferred = inferJourneys(document, ops).filter(journey => !ids.has(journey.id));
|
|
258
|
+
return { journeys: [...published, ...inferred], sources: loaded.filter(Boolean).map(item => item.source), problems };
|
|
259
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
// Journey runs kept in this browser, like Try it's history (journeys.md, "The model": a run lives
|
|
2
|
+
// in browser storage, or a file from the CLI). Each journey keeps its last 20 runs per API
|
|
3
|
+
// document, newest first. A stored run is the engine's exported run model (ui/journeys/run.js,
|
|
4
|
+
// the same JSON as the CLI's --out and MCP's get_run) plus what the summary shows about it: who
|
|
5
|
+
// ran it, what each store did with its writes, and the operation each step called. Runs never
|
|
6
|
+
// hold cookies, Authorization headers or request bodies: only statuses, outputs and findings.
|
|
7
|
+
|
|
8
|
+
/** How many runs each journey keeps. */
|
|
9
|
+
export const RUNS_KEPT = 20;
|
|
10
|
+
|
|
11
|
+
export const runsStorageKey = documentUrl => `sendproof-journey-runs:${documentUrl || ''}`;
|
|
12
|
+
|
|
13
|
+
/** Every stored run for one API document: `{ [journeyId]: run[] }`, newest first. Unreadable storage means none. */
|
|
14
|
+
export function loadRuns(storage, documentUrl) {
|
|
15
|
+
try {
|
|
16
|
+
const value = JSON.parse(storage?.getItem(runsStorageKey(documentUrl)) || 'null');
|
|
17
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return {};
|
|
18
|
+
return Object.fromEntries(Object.entries(value).filter(([, runs]) => Array.isArray(runs)).map(([id, runs]) => [id, runs.filter(run => run && typeof run === 'object' && run.runId)]));
|
|
19
|
+
} catch { return {}; }
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Adds or replaces a run (by runId) at the front of its journey's list, keeping RUNS_KEPT. Returns the new map. */
|
|
23
|
+
export function saveRun(storage, documentUrl, run) {
|
|
24
|
+
const all = loadRuns(storage, documentUrl);
|
|
25
|
+
const list = (all[run.journeyId] ?? []).filter(item => item.runId !== run.runId);
|
|
26
|
+
all[run.journeyId] = [run, ...list].slice(0, RUNS_KEPT);
|
|
27
|
+
try { storage?.setItem(runsStorageKey(documentUrl), JSON.stringify(all)); } catch { /* Full or blocked storage only forgets runs. */ }
|
|
28
|
+
return all;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Tallies a step's findings: matched, approved (whole findings or fields covered by a record),
|
|
33
|
+
* problems and not checked. A problem is what the step's detail lists: each differing field, each
|
|
34
|
+
* missing or extra write and each unmet success criterion, so the rail, the chips, the verdict and
|
|
35
|
+
* the tab's flag all say the same number.
|
|
36
|
+
*/
|
|
37
|
+
export function findingCounts(step) {
|
|
38
|
+
const counts = { match: 0, approved: 0, problems: 0, unchecked: 0 };
|
|
39
|
+
for (const finding of step?.findings ?? []) {
|
|
40
|
+
if (finding.kind === 'match') counts.match++;
|
|
41
|
+
else if (finding.kind === 'approved') counts.approved++;
|
|
42
|
+
else if (finding.kind === 'unchecked') counts.unchecked++;
|
|
43
|
+
if (finding.kind === 'differs') counts.approved += (finding.fields ?? []).filter(field => field.state === 'approved').length;
|
|
44
|
+
}
|
|
45
|
+
counts.problems = stepProblems(step).filter(item => item.kind !== 'approved').length + (step?.criteria ?? []).filter(criterion => !criterion.passed).length;
|
|
46
|
+
return counts;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The problems a step's findings hold, one per differing field or missing/extra write:
|
|
51
|
+
* `{ kind, finding, field? }`. Approved fields are listed separately with `kind: 'approved'`.
|
|
52
|
+
*/
|
|
53
|
+
export function stepProblems(step) {
|
|
54
|
+
const out = [];
|
|
55
|
+
for (const finding of step?.findings ?? []) {
|
|
56
|
+
if (finding.kind === 'missing' || finding.kind === 'extra') out.push({ kind: finding.kind, finding });
|
|
57
|
+
for (const field of finding.fields ?? []) {
|
|
58
|
+
if (field.state === 'differs') out.push({ kind: 'differs', finding, field });
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
for (const finding of step?.findings ?? []) {
|
|
62
|
+
for (const field of finding.fields ?? []) if (field.state === 'approved') out.push({ kind: 'approved', finding, field });
|
|
63
|
+
if (finding.kind === 'approved' && !(finding.fields ?? []).length) out.push({ kind: 'approved', finding });
|
|
64
|
+
}
|
|
65
|
+
return out;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** The step a run stopped or first failed at (its index), or -1 when every step passed. */
|
|
69
|
+
export function failedStepIndex(run) {
|
|
70
|
+
return (run?.steps ?? []).findIndex(step => ['failed', 'refused', 'blocked'].includes(step.status));
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Adds a store tally to a run's bookkeeping from one step's envelope: changes per store system
|
|
75
|
+
* (SQL changes carry no `store`, so they count under `sql`) and effects held or sent.
|
|
76
|
+
*/
|
|
77
|
+
export function tallyEnvelope(tally, envelope, sqlStore = 'sql') {
|
|
78
|
+
const next = { stores: { ...(tally?.stores ?? {}) }, effects: tally?.effects ?? 0 };
|
|
79
|
+
for (const change of envelope?.changes ?? []) {
|
|
80
|
+
const system = change.store || sqlStore;
|
|
81
|
+
next.stores[system] = (next.stores[system] ?? 0) + 1;
|
|
82
|
+
}
|
|
83
|
+
next.effects += (envelope?.effects ?? []).length;
|
|
84
|
+
return next;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* A run the person ended (End run, a persona switch, Stop run) or that expired: stopped, not failed.
|
|
89
|
+
* It is saved with `cancelled: true`; a run that also has a failing step is still a failure.
|
|
90
|
+
*/
|
|
91
|
+
export const runEnded = run => run?.cancelled === true && !(run.steps ?? []).some(step => ['failed', 'refused', 'blocked'].includes(step.status));
|
|
92
|
+
|
|
93
|
+
/** The index of the last step a run ran (not pending, not skipped), or -1. */
|
|
94
|
+
export const lastRanStep = run => (run?.steps ?? []).findLastIndex(step => !['pending', 'skipped'].includes(step.status));
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* What the sidebar shows for a journey: the status of its latest run that finished by itself (passed,
|
|
98
|
+
* failed, refused), else 'ended' when every run was ended early (a quiet mark, never red), else null.
|
|
99
|
+
* `list` is the journey's runs, newest first.
|
|
100
|
+
*/
|
|
101
|
+
export function lastStatusOf(list) {
|
|
102
|
+
const finished = list.find(run => !runEnded(run));
|
|
103
|
+
return finished?.status ?? (list.length ? 'ended' : null);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Runs of every journey, newest first, for "Earlier runs". */
|
|
107
|
+
export function recentRuns(all, journeyId) {
|
|
108
|
+
return (all?.[journeyId] ?? []).slice().sort((a, b) => String(b.startedAt).localeCompare(String(a.startedAt)));
|
|
109
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
// A Preview session for one journey run (spec/README.md, "Preview sessions"): every step of a
|
|
2
|
+
// Preview run previews inside it, so a later step sees an earlier step's uncommitted rows, and
|
|
3
|
+
// nothing is ever written. One session per run: opened when the run starts, rewound when a step
|
|
4
|
+
// is run again, ended (rolled back) when the run finishes or is cancelled. `fetch` and the
|
|
5
|
+
// workbench's base URL are injectable so tests drive it without a host.
|
|
6
|
+
|
|
7
|
+
/** The header a Preview carries to run inside a session. */
|
|
8
|
+
export const SESSION_HEADER = 'Sendproof-Session';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* A session problem: the RFC 9457 `code` (session_not_found, session_busy, session_failed,
|
|
12
|
+
* session_limit, store_busy), status, `title` and `detail`. `idleSeconds` is the idle timeout a
|
|
13
|
+
* `store_busy` refusal says the holder ends by.
|
|
14
|
+
*/
|
|
15
|
+
export class SessionError extends Error {
|
|
16
|
+
constructor(message, { status, code, title, detail, idleSeconds } = {}) {
|
|
17
|
+
super(message);
|
|
18
|
+
this.name = 'SessionError';
|
|
19
|
+
this.status = status;
|
|
20
|
+
this.code = code;
|
|
21
|
+
this.title = title;
|
|
22
|
+
this.detail = detail;
|
|
23
|
+
this.idleSeconds = idleSeconds;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** True when opening was refused because another Preview session holds the store (`store_busy`, 409). */
|
|
28
|
+
export const storeBusy = error => error?.code === 'store_busy';
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* True when a session call's error says the session is gone: unknown, expired, ended or foreign
|
|
32
|
+
* (`session_not_found`, 404), or closed by its store (`session_failed`). A busy session
|
|
33
|
+
* (`session_busy`, 409) is still there. A host that sends no `code` is read from the status.
|
|
34
|
+
*/
|
|
35
|
+
export function sessionGone(error) {
|
|
36
|
+
if (error?.code) return error.code === 'session_not_found' || error.code === 'session_failed';
|
|
37
|
+
return error?.status === 404 || /HTTP 404\b/.test(error?.message ?? '');
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async function problem(response, fallback) {
|
|
41
|
+
let body;
|
|
42
|
+
try { body = await response.json(); } catch { body = undefined; }
|
|
43
|
+
const idle = Number(body?.idleTimeoutSeconds);
|
|
44
|
+
return new SessionError(body?.title || body?.detail || fallback, {
|
|
45
|
+
status: response.status, code: body?.code, title: body?.title, detail: body?.detail, idleSeconds: idle > 0 ? idle : undefined,
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const SESSION_ID = /^[a-f\d]{30,}$/i;
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* This tab's held sessions are remembered in sessionStorage, per mount: it survives a reload and a
|
|
53
|
+
* crash-reload of the same tab, so the next load can end what the closed page left holding the
|
|
54
|
+
* store. `storage` is injectable; a missing or full one forgets nothing it needs to.
|
|
55
|
+
*/
|
|
56
|
+
const defaultStorage = () => { try { return globalThis.sessionStorage; } catch { return undefined; } };
|
|
57
|
+
const sessionsUrl = (base, path = '') => new URL(`./_api/sessions${path}`, base).href;
|
|
58
|
+
export const heldSessionsKey = (base = globalThis.document?.baseURI) => `sendproof-held-sessions:${sessionsUrl(base)}`;
|
|
59
|
+
|
|
60
|
+
function heldIds(storage, key) {
|
|
61
|
+
try {
|
|
62
|
+
const ids = JSON.parse(storage?.getItem(key) ?? '[]');
|
|
63
|
+
return Array.isArray(ids) ? ids.filter(id => SESSION_ID.test(String(id))) : [];
|
|
64
|
+
} catch { return []; }
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function keepIds(storage, key, ids) {
|
|
68
|
+
try { if (ids.length) storage?.setItem(key, JSON.stringify(ids)); else storage?.removeItem(key); } catch { /* Nothing to remember with. */ }
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Rolls a session back. A 404 means it is already gone; any other failure leaves it to the idle timeout. */
|
|
72
|
+
async function deleteSession(send, href, keepalive) {
|
|
73
|
+
try { await send(href, { method: 'DELETE', credentials: 'include', redirect: 'error', keepalive }); }
|
|
74
|
+
catch { /* The idle timeout rolls it back anyway. */ }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Ends every session this tab remembers (an orphan of a closed or crashed page, or all of them on
|
|
79
|
+
* `pagehide` with `keepalive`) and forgets them. Resolves to how many it asked the host to end.
|
|
80
|
+
*/
|
|
81
|
+
export async function endHeldSessions({ base = globalThis.document?.baseURI, fetch: send = globalThis.fetch, storage = defaultStorage(), keepalive = false } = {}) {
|
|
82
|
+
const key = heldSessionsKey(base);
|
|
83
|
+
const ids = heldIds(storage, key);
|
|
84
|
+
keepIds(storage, key, []);
|
|
85
|
+
await Promise.all(ids.map(id => deleteSession(send, sessionsUrl(base, `/${id}`), keepalive)));
|
|
86
|
+
return ids.length;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Opens a session. Resolves to a handle with `id`, `header()`, `rewind(step)`, `end()` and the
|
|
91
|
+
* `kept` count: how many steps the session holds, so the next Preview is step `kept + 1`. The
|
|
92
|
+
* tab remembers the ID until the session ends (see `endHeldSessions`).
|
|
93
|
+
*/
|
|
94
|
+
export async function openSession({ base = globalThis.document?.baseURI, fetch: send = globalThis.fetch, storage = defaultStorage() } = {}) {
|
|
95
|
+
const url = path => sessionsUrl(base, path);
|
|
96
|
+
const response = await send(url(''), { method: 'POST', credentials: 'include', redirect: 'error', headers: { Accept: 'application/json' } });
|
|
97
|
+
if (response.status !== 201) throw await problem(response, `The Preview session couldn't be opened (HTTP ${response.status}).`);
|
|
98
|
+
const opened = await response.json();
|
|
99
|
+
if (!SESSION_ID.test(String(opened?.id ?? ''))) throw new SessionError('The Preview session answered without an ID.', { status: response.status });
|
|
100
|
+
const key = heldSessionsKey(base);
|
|
101
|
+
keepIds(storage, key, [...heldIds(storage, key).filter(id => id !== opened.id), opened.id]);
|
|
102
|
+
let ended = false;
|
|
103
|
+
const session = {
|
|
104
|
+
id: opened.id,
|
|
105
|
+
idleTimeoutSeconds: opened.idleTimeoutSeconds ?? null,
|
|
106
|
+
maxLifetimeSeconds: opened.maxLifetimeSeconds ?? null,
|
|
107
|
+
/** Steps the session holds; a refused step leaves it unchanged. */
|
|
108
|
+
kept: 0,
|
|
109
|
+
get ended() { return ended; },
|
|
110
|
+
header: () => ({ [SESSION_HEADER]: opened.id }),
|
|
111
|
+
/** Notes a Preview's envelope: `session.step` is the step it ran as, which the session now keeps. */
|
|
112
|
+
record(envelope) {
|
|
113
|
+
const step = envelope?.session?.step;
|
|
114
|
+
if (Number.isInteger(step) && envelope?.rolledBack === true && !envelope.blocked && envelope.status < 500) session.kept = step;
|
|
115
|
+
return step;
|
|
116
|
+
},
|
|
117
|
+
/** Rolls back to the savepoint before session step `step` (from 1); that step and later are discarded. */
|
|
118
|
+
async rewind(step) {
|
|
119
|
+
if (step > session.kept) return;
|
|
120
|
+
const reply = await send(url(`/${opened.id}/rewind`), {
|
|
121
|
+
method: 'POST', credentials: 'include', redirect: 'error', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ step }),
|
|
122
|
+
});
|
|
123
|
+
if (reply.status !== 204) throw await problem(reply, `The Preview session couldn't rewind (HTTP ${reply.status}).`);
|
|
124
|
+
session.kept = step - 1;
|
|
125
|
+
},
|
|
126
|
+
/** Rolls everything back and ends the session. Safe to call twice; a gone session is already ended. */
|
|
127
|
+
async end({ keepalive = false } = {}) {
|
|
128
|
+
if (ended) return;
|
|
129
|
+
ended = true;
|
|
130
|
+
keepIds(storage, key, heldIds(storage, key).filter(id => id !== opened.id));
|
|
131
|
+
await deleteSession(send, url(`/${opened.id}`), keepalive);
|
|
132
|
+
},
|
|
133
|
+
};
|
|
134
|
+
return session;
|
|
135
|
+
}
|