@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,152 @@
|
|
|
1
|
+
// The run model (journeys-build.md, Contract 3): recording a journey run step by step and
|
|
2
|
+
// exporting it. All Sendproof's own: no Arazzo library models a run or writes JUnit. A browser-
|
|
3
|
+
// safe, maintained JUnit XML writer wasn't available either (junit-report-builder, MIT, imports
|
|
4
|
+
// node:fs and node:path at the top level and won't bundle for the browser), so toJUnit() is a
|
|
5
|
+
// small hand-written writer, matched against the JUnit XML schema most CI tools read.
|
|
6
|
+
import { bindStep, checkCriteria, stepOutputs } from './steps.js';
|
|
7
|
+
import { compareStep } from './compare.js';
|
|
8
|
+
|
|
9
|
+
const INTERNAL = Symbol('journeys-run-internal');
|
|
10
|
+
const newId = () => (globalThis.crypto?.randomUUID?.() ?? `run-${Date.now()}-${Math.random().toString(16).slice(2)}`);
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Starts a run of one Arazzo workflow (`journey`) against its expectations document. `store` is
|
|
14
|
+
* the SQL system id expectations use for store-less changes (default "sqlite"); `clock` (default
|
|
15
|
+
* the real clock) is the clock approved-difference expiry is read against.
|
|
16
|
+
*/
|
|
17
|
+
export function createRun({ journey, expectations, mode = 'preview', inputs = {}, persona, store = 'sqlite', clock = () => new Date() }) {
|
|
18
|
+
const steps = (journey.steps ?? []).map(step => ({
|
|
19
|
+
stepId: step.stepId, operationId: step.operationId, status: 'pending',
|
|
20
|
+
httpStatus: null, durationMs: null, startMs: null,
|
|
21
|
+
criteria: [], outputs: {}, findings: [], verdict: null, bound: null,
|
|
22
|
+
}));
|
|
23
|
+
return {
|
|
24
|
+
runId: newId(), journeyId: journey.workflowId, name: journey.summary ?? journey.workflowId,
|
|
25
|
+
mode, status: 'running', startedAt: clock().toISOString(), finishedAt: null, durationMs: null,
|
|
26
|
+
persona, inputs, steps, approvedUsed: [], approvedUnused: [], approvedExpired: [],
|
|
27
|
+
[INTERNAL]: { journey, expectations, store, clock, context: { inputs, steps: {} } },
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function computeApproved(run) {
|
|
32
|
+
const { expectations, clock } = run[INTERNAL];
|
|
33
|
+
const now = clock();
|
|
34
|
+
const usedIds = new Set();
|
|
35
|
+
for (const step of run.steps) for (const finding of step.findings) {
|
|
36
|
+
if (finding.record) usedIds.add(finding.record);
|
|
37
|
+
for (const field of finding.fields ?? []) if (field.record) usedIds.add(field.record);
|
|
38
|
+
}
|
|
39
|
+
const used = [], unused = [], expired = [];
|
|
40
|
+
for (const record of (expectations.approvedDifferences ?? []).filter(r => r.journey === run.journeyId)) {
|
|
41
|
+
if (record.expires && new Date(record.expires) < now) expired.push(record.id);
|
|
42
|
+
else if (usedIds.has(record.id)) used.push(record.id);
|
|
43
|
+
else unused.push(record.id);
|
|
44
|
+
}
|
|
45
|
+
run.approvedUsed = used; run.approvedUnused = unused; run.approvedExpired = expired;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function finalize(run, status) {
|
|
49
|
+
const { clock } = run[INTERNAL];
|
|
50
|
+
run.status = status;
|
|
51
|
+
run.finishedAt = clock().toISOString();
|
|
52
|
+
run.durationMs = new Date(run.finishedAt).getTime() - new Date(run.startedAt).getTime();
|
|
53
|
+
computeApproved(run);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Records one step's result: binds its outputs, checks its `successCriteria`, and compares its
|
|
58
|
+
* captured `envelope.changes`/`envelope.effects` with its expectations. A step that is blocked,
|
|
59
|
+
* is refused with an unexpected HTTP status, or fails its criteria stops the run (`status:
|
|
60
|
+
* 'stopped'`, remaining pending steps marked 'skipped'); a write or effect mismatch alone does
|
|
61
|
+
* not, per journeys.md ("write mismatches don't stop a run by default").
|
|
62
|
+
*/
|
|
63
|
+
export function recordStep(run, stepId, { response, envelope = {}, durationMs } = {}) {
|
|
64
|
+
const internal = run[INTERNAL];
|
|
65
|
+
const stepDef = internal.journey.steps?.find(step => step.stepId === stepId);
|
|
66
|
+
const stepResult = run.steps.find(step => step.stepId === stepId);
|
|
67
|
+
if (!stepDef || !stepResult) throw new RangeError(`Unknown step "${stepId}"`);
|
|
68
|
+
|
|
69
|
+
const bound = bindStep(stepDef, internal.context).bound;
|
|
70
|
+
const criteria = checkCriteria(stepDef.successCriteria, response);
|
|
71
|
+
const outputs = stepOutputs(stepDef, response);
|
|
72
|
+
internal.context.steps[stepId] = { outputs };
|
|
73
|
+
|
|
74
|
+
const stepExpectations = internal.expectations.journeys?.[run.journeyId]?.steps?.[stepId] ?? {};
|
|
75
|
+
const relevantApproved = (internal.expectations.approvedDifferences ?? [])
|
|
76
|
+
.filter(record => record.journey === run.journeyId && record.step === stepId);
|
|
77
|
+
const { verdict, findings } = compareStep({
|
|
78
|
+
expected: stepExpectations, changes: envelope.changes ?? [], effects: envelope.effects ?? [], logs: envelope.logs ?? [],
|
|
79
|
+
context: { ...internal.context, response, request: response?.request }, approved: relevantApproved,
|
|
80
|
+
ignore: internal.expectations.ignore ?? [], unlisted: stepExpectations.unlisted ?? 'fail',
|
|
81
|
+
store: internal.store, clock: internal.clock,
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
const blocked = Boolean(envelope.blocked);
|
|
85
|
+
const criteriaPassed = criteria.every(criterion => criterion.passed);
|
|
86
|
+
const httpStatus = response?.statusCode ?? null;
|
|
87
|
+
const status = blocked ? 'blocked'
|
|
88
|
+
: !criteriaPassed ? (httpStatus != null && httpStatus >= 400 ? 'refused' : 'failed')
|
|
89
|
+
: verdict === 'failed' ? 'failed' : 'passed';
|
|
90
|
+
Object.assign(stepResult, { httpStatus, durationMs: durationMs ?? null, criteria, outputs, findings, verdict, status, bound });
|
|
91
|
+
|
|
92
|
+
const stops = blocked || !criteriaPassed;
|
|
93
|
+
const stepIndex = run.steps.indexOf(stepResult);
|
|
94
|
+
if (stops) {
|
|
95
|
+
for (let i = stepIndex + 1; i < run.steps.length; i++) if (run.steps[i].status === 'pending') run.steps[i].status = 'skipped';
|
|
96
|
+
finalize(run, 'stopped');
|
|
97
|
+
} else if (stepIndex === run.steps.length - 1) {
|
|
98
|
+
finalize(run, run.steps.every(step => step.status === 'passed') ? 'passed' : 'failed');
|
|
99
|
+
} else {
|
|
100
|
+
run.status = 'running';
|
|
101
|
+
}
|
|
102
|
+
return stepResult;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Marks a run that was never started (a Send-only journey in a Preview run of every journey)
|
|
106
|
+
* skipped: every step skipped, `status: 'skipped'`, and `skipReason` saying why. toJUnit()
|
|
107
|
+
* writes it as a testsuite whose cases are all skipped. */
|
|
108
|
+
export function skipRun(run, reason) {
|
|
109
|
+
for (const step of run.steps) step.status = 'skipped';
|
|
110
|
+
finalize(run, 'skipped');
|
|
111
|
+
run.skipReason = reason;
|
|
112
|
+
return run;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** The run as plain JSON (its internal bookkeeping, kept under a Symbol key, is dropped). */
|
|
116
|
+
export function exportRun(run) {
|
|
117
|
+
return JSON.parse(JSON.stringify(run));
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const xmlEscape = text => String(text).replace(/[&<>"']/g, char => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[char]);
|
|
121
|
+
|
|
122
|
+
function findingText(finding) {
|
|
123
|
+
const where = `${finding.store} ${finding.target}${finding.op ? ` (${finding.op})` : ''}`;
|
|
124
|
+
if (finding.kind === 'missing') return `Missing: expected a write to ${where}, nothing matched.`;
|
|
125
|
+
if (finding.kind === 'extra') return `Extra: an unlisted write to ${where} was made.`;
|
|
126
|
+
const badFields = finding.fields.filter(field => field.state === 'differs')
|
|
127
|
+
.map(field => `${field.name}: expected ${JSON.stringify(field.expected)}, got ${JSON.stringify(field.actual)}`);
|
|
128
|
+
return `Differs: ${where} — ${badFields.join('; ')}`;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** The run as JUnit XML: one `<testsuite>`, one `<testcase>` per step, failures listing the
|
|
132
|
+
* unmet criteria and findings as text. */
|
|
133
|
+
export function toJUnit(run) {
|
|
134
|
+
const seconds = ms => ((ms ?? 0) / 1000).toFixed(3);
|
|
135
|
+
const cases = run.steps.map(step => {
|
|
136
|
+
const name = xmlEscape(step.stepId);
|
|
137
|
+
const classname = xmlEscape(run.journeyId);
|
|
138
|
+
const time = seconds(step.durationMs);
|
|
139
|
+
if (step.status === 'skipped') return `<testcase name="${name}" classname="${classname}" time="${time}"><skipped/></testcase>`;
|
|
140
|
+
const problems = [
|
|
141
|
+
...step.criteria.filter(criterion => !criterion.passed).map(criterion => `Criterion failed: ${criterion.condition} (actual: ${JSON.stringify(criterion.actual)})`),
|
|
142
|
+
...step.findings.filter(finding => finding.kind === 'differs' || finding.kind === 'missing' || finding.kind === 'extra').map(findingText),
|
|
143
|
+
...(step.status === 'blocked' ? ['Preview blocked by the write guard.'] : []),
|
|
144
|
+
...(step.status === 'refused' ? [`Unexpected response: ${step.httpStatus}`] : []),
|
|
145
|
+
];
|
|
146
|
+
if (!problems.length) return `<testcase name="${name}" classname="${classname}" time="${time}"/>`;
|
|
147
|
+
return `<testcase name="${name}" classname="${classname}" time="${time}"><failure message="${xmlEscape(problems[0])}">${xmlEscape(problems.join('\n'))}</failure></testcase>`;
|
|
148
|
+
});
|
|
149
|
+
const failures = run.steps.filter(step => step.status !== 'passed' && step.status !== 'skipped').length;
|
|
150
|
+
const skipped = run.steps.filter(step => step.status === 'skipped').length;
|
|
151
|
+
return `<?xml version="1.0" encoding="UTF-8"?>\n<testsuite name="${xmlEscape(run.name)}" tests="${run.steps.length}" failures="${failures}" skipped="${skipped}" time="${seconds(run.durationMs)}">\n${cases.join('\n')}\n</testsuite>\n`;
|
|
152
|
+
}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
// Binding a step's request from its Arazzo `parameters` and `requestBody`, checking its
|
|
2
|
+
// `successCriteria` and reading its `outputs`. Runtime-expression resolution is expressions.js;
|
|
3
|
+
// the "simple" success-criteria comparator grammar (`==`, `&&`, …) has no published library (the
|
|
4
|
+
// swaggerexpert and jsonpath-rfc9535 packages parse runtime expressions and JSONPath, not this
|
|
5
|
+
// small boolean grammar Arazzo defines for successCriteria), so it's hand-written here. The
|
|
6
|
+
// `jsonpath` criterion type uses the vendored jsonpath-rfc9535 (RFC 9535, Apache-2.0); `xpath`
|
|
7
|
+
// has no vendored library and always reports unmet, since the APIs this engine targets are JSON.
|
|
8
|
+
import { evaluate, interpolate } from './expressions.js';
|
|
9
|
+
import { query as jsonpathQuery } from '../vendor/jsonpath-rfc9535.js';
|
|
10
|
+
|
|
11
|
+
const escapePointer = token => String(token).replace(/~/g, '~0').replace(/\//g, '~1');
|
|
12
|
+
|
|
13
|
+
function classifyBinding(expression) {
|
|
14
|
+
if (typeof expression !== 'string' || !expression.startsWith('$')) return { from: 'fixed' };
|
|
15
|
+
if (expression === '$inputs' || expression.startsWith('$inputs.')) return { from: 'input' };
|
|
16
|
+
const stepMatch = /^\$steps\.([^.]+)\./.exec(expression);
|
|
17
|
+
if (stepMatch) return { from: 'step', stepId: stepMatch[1] };
|
|
18
|
+
return { from: 'fixed' };
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Interpolates a request-body value, recording a bound entry for every leaf that is itself a
|
|
22
|
+
* whole expression (an embedded "{$expr}" inside a literal string isn't separately tracked). */
|
|
23
|
+
function bindBody(value, context, pointer, bound) {
|
|
24
|
+
if (Array.isArray(value)) return value.map((item, index) => bindBody(item, context, `${pointer}/${index}`, bound));
|
|
25
|
+
if (value !== null && typeof value === 'object') {
|
|
26
|
+
return Object.fromEntries(Object.entries(value).map(([key, inner]) => [key, bindBody(inner, context, `${pointer}/${escapePointer(key)}`, bound)]));
|
|
27
|
+
}
|
|
28
|
+
if (typeof value === 'string' && value.startsWith('$')) {
|
|
29
|
+
const resolved = evaluate(value, context);
|
|
30
|
+
bound.push({ target: `body${pointer}`, expression: value, value: resolved, ...classifyBinding(value) });
|
|
31
|
+
return resolved;
|
|
32
|
+
}
|
|
33
|
+
return interpolate(value, context);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Binds one Arazzo step's `parameters` and `requestBody` against a run context, following any
|
|
38
|
+
* `requestBody.replacements`. Returns { path, query, headers, body, bound }, where `bound` lists
|
|
39
|
+
* every value that came from an input or an earlier step's output, for the "From step 1 · x" UI.
|
|
40
|
+
*/
|
|
41
|
+
export function bindStep(step, context = {}) {
|
|
42
|
+
const path = {}, query = {}, headers = {};
|
|
43
|
+
const bound = [];
|
|
44
|
+
for (const parameter of step.parameters ?? []) {
|
|
45
|
+
const value = interpolate(parameter.value, context);
|
|
46
|
+
const target = { path, query, header: headers, cookie: headers }[parameter.in];
|
|
47
|
+
if (target) target[parameter.name] = value;
|
|
48
|
+
if (typeof parameter.value === 'string' && parameter.value.startsWith('$')) {
|
|
49
|
+
bound.push({ target: `${parameter.in}.${parameter.name}`, expression: parameter.value, value, ...classifyBinding(parameter.value) });
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
let body;
|
|
53
|
+
if (step.requestBody) {
|
|
54
|
+
body = bindBody(step.requestBody.payload, context, '', bound);
|
|
55
|
+
for (const replacement of step.requestBody.replacements ?? []) {
|
|
56
|
+
const value = interpolate(replacement.value, context);
|
|
57
|
+
body = writePointer(body, replacement.target, value);
|
|
58
|
+
if (typeof replacement.value === 'string' && replacement.value.startsWith('$')) {
|
|
59
|
+
bound.push({ target: `body${replacement.target}`, expression: replacement.value, value, ...classifyBinding(replacement.value) });
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return { path, query, headers, body, bound };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Sets the value at an RFC 6901 JSON Pointer inside `root`, cloning only the path it walks. */
|
|
67
|
+
function writePointer(root, pointer, value) {
|
|
68
|
+
const tokens = pointer.split('/').slice(1).map(token => token.replace(/~1/g, '/').replace(/~0/g, '~'));
|
|
69
|
+
if (tokens.length === 0) return value;
|
|
70
|
+
const clone = Array.isArray(root) ? [...root] : { ...root };
|
|
71
|
+
let node = clone;
|
|
72
|
+
for (let i = 0; i < tokens.length - 1; i++) {
|
|
73
|
+
const key = tokens[i];
|
|
74
|
+
const next = node[key];
|
|
75
|
+
node[key] = Array.isArray(next) ? [...next] : { ...next };
|
|
76
|
+
node = node[key];
|
|
77
|
+
}
|
|
78
|
+
node[tokens[tokens.length - 1]] = value;
|
|
79
|
+
return clone;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const looseEqual = (a, b) => a === b || (a != null && b != null && JSON.stringify(a) === JSON.stringify(b));
|
|
83
|
+
|
|
84
|
+
function parseOperand(token, response) {
|
|
85
|
+
const trimmed = token.trim();
|
|
86
|
+
if (trimmed.startsWith('$')) return evaluate(trimmed, { response });
|
|
87
|
+
if (/^-?\d+(\.\d+)?$/.test(trimmed)) return Number(trimmed);
|
|
88
|
+
if (trimmed === 'true') return true;
|
|
89
|
+
if (trimmed === 'false') return false;
|
|
90
|
+
if (trimmed === 'null') return null;
|
|
91
|
+
if ((trimmed.startsWith("'") && trimmed.endsWith("'")) || (trimmed.startsWith('"') && trimmed.endsWith('"'))) return trimmed.slice(1, -1);
|
|
92
|
+
return trimmed;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const COMPARISON = /^(.+?)\s*(==|!=|<=|>=|<|>)\s*(.+)$/;
|
|
96
|
+
|
|
97
|
+
/** Splits on a top-level "&&" or "||", ignoring one inside a quoted operand. */
|
|
98
|
+
function splitTop(text, token) {
|
|
99
|
+
const parts = [];
|
|
100
|
+
let quote = null, start = 0;
|
|
101
|
+
for (let i = 0; i < text.length; i++) {
|
|
102
|
+
const char = text[i];
|
|
103
|
+
if (quote) { if (char === quote) quote = null; continue; }
|
|
104
|
+
if (char === "'" || char === '"') { quote = char; continue; }
|
|
105
|
+
if (text.startsWith(token, i)) { parts.push(text.slice(start, i)); i += token.length - 1; start = i + 1; }
|
|
106
|
+
}
|
|
107
|
+
parts.push(text.slice(start));
|
|
108
|
+
return parts;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function evaluateSimple(condition, response) {
|
|
112
|
+
const orParts = splitTop(condition, '||');
|
|
113
|
+
if (orParts.length > 1) {
|
|
114
|
+
const results = orParts.map(part => evaluateSimple(part, response));
|
|
115
|
+
return { passed: results.some(result => result.passed), actual: results.map(result => result.actual) };
|
|
116
|
+
}
|
|
117
|
+
const andParts = splitTop(condition, '&&');
|
|
118
|
+
if (andParts.length > 1) {
|
|
119
|
+
const results = andParts.map(part => evaluateSimple(part, response));
|
|
120
|
+
return { passed: results.every(result => result.passed), actual: results.map(result => result.actual) };
|
|
121
|
+
}
|
|
122
|
+
const match = COMPARISON.exec(condition.trim());
|
|
123
|
+
if (!match) { const value = parseOperand(condition.trim(), response); return { passed: Boolean(value), actual: value }; }
|
|
124
|
+
const [, leftToken, operator, rightToken] = match;
|
|
125
|
+
const left = parseOperand(leftToken, response);
|
|
126
|
+
const right = parseOperand(rightToken, response);
|
|
127
|
+
const passed = operator === '==' ? looseEqual(left, right)
|
|
128
|
+
: operator === '!=' ? !looseEqual(left, right)
|
|
129
|
+
: operator === '<' ? left < right : operator === '<=' ? left <= right
|
|
130
|
+
: operator === '>' ? left > right : left >= right;
|
|
131
|
+
return { passed, actual: left };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Checks each Arazzo `successCriteria` entry against a step's response. `type` defaults to
|
|
135
|
+
* "simple" (the `==`/`!=`/`<`/`<=`/`>`/`>=`/`&&`/`||` grammar); "jsonpath" and "regex" apply the
|
|
136
|
+
* condition to `context` (a runtime expression, default "$response.body"); "xpath" always fails,
|
|
137
|
+
* unsupported. Returns [{ condition, passed, actual }]. */
|
|
138
|
+
export function checkCriteria(criteria = [], response) {
|
|
139
|
+
return criteria.map(criterion => {
|
|
140
|
+
const type = criterion.type ?? 'simple';
|
|
141
|
+
if (type === 'simple') {
|
|
142
|
+
const { passed, actual } = evaluateSimple(criterion.condition, response);
|
|
143
|
+
return { condition: criterion.condition, passed, actual };
|
|
144
|
+
}
|
|
145
|
+
const data = criterion.context ? evaluate(criterion.context, { response }) : response?.body;
|
|
146
|
+
if (type === 'jsonpath') {
|
|
147
|
+
const result = jsonpathQuery(data, criterion.condition);
|
|
148
|
+
return { condition: criterion.condition, passed: Array.isArray(result) && result.length > 0, actual: result };
|
|
149
|
+
}
|
|
150
|
+
if (type === 'regex') {
|
|
151
|
+
const text = typeof data === 'string' ? data : JSON.stringify(data);
|
|
152
|
+
return { condition: criterion.condition, passed: new RegExp(criterion.condition).test(text), actual: text };
|
|
153
|
+
}
|
|
154
|
+
return { condition: criterion.condition, passed: false, actual: undefined };
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Reads a step's Arazzo `outputs` (each value a runtime expression over its own response). */
|
|
159
|
+
export function stepOutputs(step, response) {
|
|
160
|
+
const outputs = {};
|
|
161
|
+
for (const [name, expression] of Object.entries(step.outputs ?? {})) outputs[name] = evaluate(expression, { response });
|
|
162
|
+
return outputs;
|
|
163
|
+
}
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
// Code the workbench drafts for an author to commit (journeys.md, "Approved differences" and
|
|
2
|
+
// "Writing them, and running them"). The workbench never approves or writes a file: it copies
|
|
3
|
+
// text. Pure, so it's tested in Node.
|
|
4
|
+
//
|
|
5
|
+
// - Draft approved difference: the C# ApprovedDifference<T> object for a journey defined in code
|
|
6
|
+
// (Sendproof.Journeys relaxes one value with it), or the JSON record for a journey read from a
|
|
7
|
+
// file, ready for the expectations document.
|
|
8
|
+
// - Copy as C#: a Preview's actual writes as an ExpectWrites block, with values that came from
|
|
9
|
+
// the journey's inputs or an earlier step's outputs written as the refs that hold them.
|
|
10
|
+
|
|
11
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
12
|
+
const DATE_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;
|
|
13
|
+
|
|
14
|
+
const csString = value => `"${String(value).replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t')}"`;
|
|
15
|
+
const pascal = name => String(name).replace(/^_+/, '').replace(/(^|[_\s-])([a-z0-9])/gi, (match, separator, letter) => letter.toUpperCase());
|
|
16
|
+
const camel = name => { const text = pascal(name); return text.charAt(0).toLowerCase() + text.slice(1); };
|
|
17
|
+
const isoDay = date => date.toISOString().slice(0, 10);
|
|
18
|
+
const addDays = (date, days) => new Date(date.getTime() + days * 86_400_000);
|
|
19
|
+
|
|
20
|
+
/** The C# type and literal for a captured value, as an ApprovedDifference<T> or a Set() value needs it. */
|
|
21
|
+
export function csharpValue(value) {
|
|
22
|
+
if (value === null || value === undefined) return { type: 'string?', literal: 'null' };
|
|
23
|
+
if (typeof value === 'boolean') return { type: 'bool', literal: String(value) };
|
|
24
|
+
if (typeof value === 'number') return Number.isInteger(value) ? { type: 'int', literal: String(value) } : { type: 'decimal', literal: `${value}m` };
|
|
25
|
+
if (typeof value === 'string' && UUID.test(value)) return { type: 'Guid', literal: `Guid.Parse(${csString(value)})` };
|
|
26
|
+
if (typeof value === 'string' && DATE_TIME.test(value)) return { type: 'DateTimeOffset', literal: `DateTimeOffset.Parse(${csString(value)})` };
|
|
27
|
+
if (typeof value === 'string') return { type: 'string', literal: csString(value) };
|
|
28
|
+
return { type: 'string', literal: csString(JSON.stringify(value)) };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** A C# identifier for a record: "Shipments.Carrier" → ShipmentsCarrierChanged. */
|
|
32
|
+
const recordName = (target, field) => `${pascal(target)}${field ? pascal(field) : ''}Changed`.replace(/[^\w]/g, '');
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* A draft approved-difference record for one finding (and, for a `differs` finding, one field).
|
|
36
|
+
* Returns `{ language: 'csharp' | 'json', text }`. A journey defined in code gets the C# object
|
|
37
|
+
* when the difference is a value (that's what ApprovedDifference<T> relaxes); missing and extra
|
|
38
|
+
* writes, and file journeys, get the JSON record.
|
|
39
|
+
*/
|
|
40
|
+
export function draftApprovedDifference({ journey, stepId, finding, field, approvedBy = '', today = new Date(), days = 90, sqlStore = 'sqlite' }) {
|
|
41
|
+
const kind = field ? 'value' : finding.kind === 'extra' ? 'extra' : 'missing';
|
|
42
|
+
const store = finding.store === 'sql' ? sqlStore : finding.store;
|
|
43
|
+
const approvedOn = isoDay(today);
|
|
44
|
+
const expires = isoDay(addDays(today, days));
|
|
45
|
+
const reason = 'Why this difference is acceptable, and when the expectation will change.';
|
|
46
|
+
if (journey.source === 'code' && kind === 'value') {
|
|
47
|
+
const { type, literal } = csharpValue(field.actual);
|
|
48
|
+
const [y, m, d] = approvedOn.split('-').map(Number);
|
|
49
|
+
const [ey, em, ed] = expires.split('-').map(Number);
|
|
50
|
+
const name = recordName(finding.target, field.name);
|
|
51
|
+
const owner = journey.definedIn?.type ? `${journey.definedIn.type.replace(/Journey$/, '')}ApprovedDifferences` : 'ApprovedDifferences';
|
|
52
|
+
return {
|
|
53
|
+
language: 'csharp',
|
|
54
|
+
text: [
|
|
55
|
+
`// Pass it to the expectation it relaxes: .Set(r => r.${pascal(field.name)}, <expected>, ${owner}.${name})`,
|
|
56
|
+
`public static readonly ApprovedDifference<${type}> ${name} = new()`,
|
|
57
|
+
'{',
|
|
58
|
+
' Id = "AD-0000",',
|
|
59
|
+
` Actual = ${literal},`,
|
|
60
|
+
` Reason = ${csString(reason)},`,
|
|
61
|
+
` ApprovedBy = ${csString(approvedBy)},`,
|
|
62
|
+
` ApprovedOn = new DateOnly(${y}, ${m}, ${d}),`,
|
|
63
|
+
` Expires = new DateOnly(${ey}, ${em}, ${ed}),`,
|
|
64
|
+
' Link = "",',
|
|
65
|
+
'};',
|
|
66
|
+
].join('\n'),
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
const record = {
|
|
70
|
+
id: 'AD-0000', journey: journey.id, step: stepId,
|
|
71
|
+
target: { store, [finding.store === 'mongodb' || finding.target?.includes?.(':') ? 'collection' : 'table']: finding.target, ...(field ? { field: field.name } : {}) },
|
|
72
|
+
kind,
|
|
73
|
+
...(field ? { expected: field.expected, actual: field.actual } : {}),
|
|
74
|
+
reason, approvedBy, approvedOn, expires, link: '',
|
|
75
|
+
};
|
|
76
|
+
// The engine matches records by target.table for every store; keep `table` so the record covers the finding.
|
|
77
|
+
if (record.target.collection !== undefined) { record.target.table = record.target.collection; delete record.target.collection; }
|
|
78
|
+
return { language: 'json', text: JSON.stringify(record, null, 2) };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* The refs a step can use: each journey input and each earlier step's output, with the value it
|
|
83
|
+
* held in this run, so a written value equal to one is written as that ref. Returns
|
|
84
|
+
* `[{ name, value, code, expression }]`; longer values first, so an ID beats a coincidental 1.
|
|
85
|
+
*/
|
|
86
|
+
export function refsFor(journey, run, stepIndex) {
|
|
87
|
+
const refs = [];
|
|
88
|
+
for (const [name, value] of Object.entries(run?.inputs ?? {})) {
|
|
89
|
+
if (value === undefined || value === null || value === '') continue;
|
|
90
|
+
refs.push({ name: camel(name), value, code: `journey.Input(i => i.${pascal(name)})`, expression: `$inputs.${name}` });
|
|
91
|
+
}
|
|
92
|
+
(run?.steps ?? []).slice(0, stepIndex + 1).forEach(step => {
|
|
93
|
+
for (const [name, value] of Object.entries(step.outputs ?? {})) {
|
|
94
|
+
if (value === undefined || value === null) continue;
|
|
95
|
+
refs.push({ name: camel(name), value, code: camel(name), expression: `$steps.${step.stepId}.outputs.${name}` });
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
return refs.filter(ref => typeof ref.value !== 'boolean' && String(ref.value).length > 1)
|
|
99
|
+
.sort((a, b) => String(b.value).length - String(a.value).length);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** MongoDB Extended JSON ({ "$date": … }, { "$oid": … }, { "$numberLong": … }) as the plain value it stands for. */
|
|
103
|
+
function plain(value) {
|
|
104
|
+
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
|
105
|
+
const keys = Object.keys(value);
|
|
106
|
+
if (keys.length === 1 && ['$oid', '$numberLong', '$numberInt', '$numberDecimal', '$numberDouble', '$uuid'].includes(keys[0])) return keys[0] === '$oid' || keys[0] === '$uuid' ? value[keys[0]] : Number(value[keys[0]]);
|
|
107
|
+
if (keys.length === 1 && keys[0] === '$date') return { date: true };
|
|
108
|
+
}
|
|
109
|
+
return value;
|
|
110
|
+
}
|
|
111
|
+
const nested = value => value !== null && typeof value === 'object' && !value.date;
|
|
112
|
+
|
|
113
|
+
function valueCode(raw, refs) {
|
|
114
|
+
const value = plain(raw);
|
|
115
|
+
if (value?.date) return { code: 'Match.Any<DateTime>()' };
|
|
116
|
+
const ref = refs.find(item => item.value === value || (typeof value === 'string' && String(item.value) === value));
|
|
117
|
+
if (ref) return { code: ref.code, note: ref.expression };
|
|
118
|
+
if (typeof value === 'string' && DATE_TIME.test(value)) return { code: 'Match.Any<DateTimeOffset>()' };
|
|
119
|
+
return { code: csharpValue(value).literal };
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const lambda = (table, prefix) => (prefix || String(table).charAt(0).toLowerCase() || 'r').replace(/[^a-z]/g, 'r');
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* A Preview's changes and effects as an ExpectWrites block. `changes` and `effects` are the
|
|
126
|
+
* envelope's; `refs` come from refsFor(); `sqlStore` is the capabilities' SQL system id and
|
|
127
|
+
* `stepVariable` the step's C# variable (its stepId).
|
|
128
|
+
*/
|
|
129
|
+
export function expectWritesCode({ changes = [], effects = [], refs = [], stepVariable = 'step', dbContext = 'AppDbContext' }) {
|
|
130
|
+
const lines = [`${stepVariable}.ExpectWrites(writes =>`, '{'];
|
|
131
|
+
const sql = changes.filter(change => !change.store);
|
|
132
|
+
const documents = changes.filter(change => change.store === 'mongodb');
|
|
133
|
+
const others = changes.filter(change => change.store && change.store !== 'mongodb');
|
|
134
|
+
const set = (indent, letter, name, value) => {
|
|
135
|
+
const { code, note } = valueCode(value, refs);
|
|
136
|
+
return `${indent}.Set(${letter} => ${letter}.${pascal(name)}, ${code})${note ? ` // ${note}` : ''}`;
|
|
137
|
+
};
|
|
138
|
+
const body = (change, indent, letter, keyFields) => {
|
|
139
|
+
const out = [];
|
|
140
|
+
for (const [name, value] of Object.entries(change.key ?? {})) {
|
|
141
|
+
if (change.operation !== 'insert') out.push(`${indent}.Where(${letter} => ${letter}.${pascal(name)}, ${valueCode(value, refs).code})`);
|
|
142
|
+
}
|
|
143
|
+
if (change.operation === 'update') {
|
|
144
|
+
for (const [name, rawAfter] of Object.entries(change.after ?? {})) {
|
|
145
|
+
const before = plain(change.before?.[name]);
|
|
146
|
+
const after = plain(rawAfter);
|
|
147
|
+
// Nested documents and lists are left for the author: a field-by-field Set can't say them.
|
|
148
|
+
if (JSON.stringify(change.before?.[name]) === JSON.stringify(rawAfter) || keyFields.has(name) || nested(after)) continue;
|
|
149
|
+
out.push(after?.date || (typeof after === 'string' && DATE_TIME.test(after))
|
|
150
|
+
? `${indent}.Set(${letter} => ${letter}.${pascal(name)}, ${after?.date ? 'Match.Any<DateTime>()' : 'Match.Any<DateTimeOffset>()'})`
|
|
151
|
+
: `${indent}.Set(${letter} => ${letter}.${pascal(name)}, Match.Changed(${csharpValue(before).literal}, ${valueCode(after, refs).code}))`);
|
|
152
|
+
}
|
|
153
|
+
} else if (change.operation === 'insert') {
|
|
154
|
+
for (const [name, raw] of Object.entries(change.after ?? {})) {
|
|
155
|
+
const value = plain(raw);
|
|
156
|
+
if (value === null || value === undefined || nested(value)) continue;
|
|
157
|
+
// A new row's own generated key isn't known in advance; its other values are.
|
|
158
|
+
if (keyFields.has(name) && !refs.some(ref => ref.value === value)) continue;
|
|
159
|
+
out.push(set(indent, letter, name, value));
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
// The statement ends before its trailing comment: `.Set(s => s.OrderId, orderId); // $steps…`.
|
|
163
|
+
if (out.length) { const last = out.length - 1; const at = out[last].indexOf(' // '); out[last] = at < 0 ? out[last] + ';' : out[last].slice(0, at) + ';' + out[last].slice(at); }
|
|
164
|
+
else out.push(`${indent};`);
|
|
165
|
+
return out;
|
|
166
|
+
};
|
|
167
|
+
if (sql.length) {
|
|
168
|
+
lines.push(` var sql = writes.Sql<${dbContext}>();`);
|
|
169
|
+
for (const change of sql) {
|
|
170
|
+
const verb = { insert: 'Insert', update: 'Update', delete: 'Delete' }[change.operation] ?? 'Update';
|
|
171
|
+
const letter = lambda(change.table);
|
|
172
|
+
lines.push('', ` sql.${verb}(db => db.${pascal(change.table)})`, ...body(change, ' ', letter, new Set(Object.keys(change.key ?? {}))));
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
if (documents.length) {
|
|
176
|
+
lines.push('', ' var mongo = writes.Mongo();');
|
|
177
|
+
for (const change of documents) {
|
|
178
|
+
const verb = { insert: 'Insert', update: 'Update', delete: 'Delete' }[change.operation] ?? 'Update';
|
|
179
|
+
const type = `${pascal(String(change.table).replace(/s$/, ''))}Document`;
|
|
180
|
+
lines.push('', ` mongo.${verb}<${type}>() // collection ${change.table}`, ...body(change, ' ', 'd', new Set(Object.keys(change.key ?? {}))));
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
for (const change of others) lines.push('', ` // ${change.store}: ${change.operation} ${change.table}`);
|
|
184
|
+
for (const effect of effects) {
|
|
185
|
+
if (effect.kind === 'email') {
|
|
186
|
+
const to = Array.isArray(effect.data?.to) ? effect.data.to[0] : effect.data?.to;
|
|
187
|
+
lines.push('', ` writes.Email()${to !== undefined ? `\n .To(${valueCode(to, refs).code})` : ''}${effect.data?.subject ? `\n .Subject(${csString(effect.data.subject)})` : ''};`);
|
|
188
|
+
} else lines.push('', ` // ${effect.kind}: ${effect.description ?? ''}`.trimEnd());
|
|
189
|
+
}
|
|
190
|
+
if (!changes.length && !effects.length) lines.push(' writes.Nothing();');
|
|
191
|
+
lines.push('});');
|
|
192
|
+
return lines.join('\n');
|
|
193
|
+
}
|