@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,169 @@
|
|
|
1
|
+
const refValue = Symbol('journey reference value');
|
|
2
|
+
const buildJourney = Symbol('build journey');
|
|
3
|
+
class JourneyRef {
|
|
4
|
+
expression;
|
|
5
|
+
owner;
|
|
6
|
+
constructor(expression, owner) {
|
|
7
|
+
this.expression = expression;
|
|
8
|
+
this.owner = owner;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
export const match = {
|
|
12
|
+
any: (type = 'any') => ({ type }),
|
|
13
|
+
pattern: (pattern) => ({ pattern }),
|
|
14
|
+
changed: (from, to) => ({ from, to }),
|
|
15
|
+
};
|
|
16
|
+
export class JourneyStep {
|
|
17
|
+
step;
|
|
18
|
+
expectations;
|
|
19
|
+
owner;
|
|
20
|
+
problems;
|
|
21
|
+
/** @internal Created by the journey builder. */
|
|
22
|
+
constructor(step, expectations, owner, problems) {
|
|
23
|
+
this.step = step;
|
|
24
|
+
this.expectations = expectations;
|
|
25
|
+
this.owner = owner;
|
|
26
|
+
this.problems = problems;
|
|
27
|
+
}
|
|
28
|
+
set(location, name, value) {
|
|
29
|
+
(this.step.parameters ??= []).push({ in: location, name, value });
|
|
30
|
+
return this;
|
|
31
|
+
}
|
|
32
|
+
body(payload, contentType = 'application/json') {
|
|
33
|
+
this.step.requestBody = { contentType, payload };
|
|
34
|
+
return this;
|
|
35
|
+
}
|
|
36
|
+
succeedsWith(status) {
|
|
37
|
+
return this.succeedsWhen(`$statusCode == ${status}`);
|
|
38
|
+
}
|
|
39
|
+
succeedsWhen(condition) {
|
|
40
|
+
(this.step.successCriteria ??= []).push({ condition });
|
|
41
|
+
return this;
|
|
42
|
+
}
|
|
43
|
+
/** Declare the response expression and, for typed consumers, its resolved type. */
|
|
44
|
+
output(name, expression) {
|
|
45
|
+
const outputs = this.step.outputs ??= Object.create(null);
|
|
46
|
+
if (!referenceName.test(name) || Object.hasOwn(outputs, name)) {
|
|
47
|
+
this.problems.push(`Step "${this.step.stepId}": invalid or duplicate output "${name}".`);
|
|
48
|
+
}
|
|
49
|
+
outputs[name] = expression;
|
|
50
|
+
return new JourneyRef(`$steps.${this.step.stepId}.outputs.${name}`, this.owner);
|
|
51
|
+
}
|
|
52
|
+
runAs(persona) {
|
|
53
|
+
this.expectations.persona = persona;
|
|
54
|
+
return this;
|
|
55
|
+
}
|
|
56
|
+
/** Use an empty writes array to assert that a step writes nothing. */
|
|
57
|
+
expectWrites(expectations) {
|
|
58
|
+
Object.assign(this.expectations, { writes: [], unlisted: 'fail', ...expectations });
|
|
59
|
+
return this;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
const referenceName = /^[A-Za-z0-9_-]+$/;
|
|
63
|
+
const inputReference = /^\$inputs\.([\w-]+)(?:\.[\w-]+)*$/;
|
|
64
|
+
const stepReference = /^\$steps\.([\w-]+)\.outputs\.([\w-]+)(?:\.[\w-]+)*$/;
|
|
65
|
+
/** Define a workflow once. The adapter evaluates its definition during startup. */
|
|
66
|
+
export function defineJourney(options, define) {
|
|
67
|
+
return {
|
|
68
|
+
id: options.id,
|
|
69
|
+
[buildJourney](operationIds) {
|
|
70
|
+
const { id, name, summary = name, description, inputs, group, runAs, definedIn } = options;
|
|
71
|
+
const owner = Symbol(id);
|
|
72
|
+
const problems = [];
|
|
73
|
+
const steps = new Map();
|
|
74
|
+
const outputs = new Map();
|
|
75
|
+
const differences = [];
|
|
76
|
+
const properties = inputs?.properties ?? {};
|
|
77
|
+
const knownInput = (key) => Object.hasOwn(properties, key);
|
|
78
|
+
define({
|
|
79
|
+
input(key) {
|
|
80
|
+
if (!referenceName.test(key) || !knownInput(key))
|
|
81
|
+
problems.push(`Unknown input "${key}".`);
|
|
82
|
+
return new JourneyRef(`$inputs.${key}`, owner);
|
|
83
|
+
},
|
|
84
|
+
step(stepId, operationId) {
|
|
85
|
+
if (!referenceName.test(stepId) || steps.has(stepId))
|
|
86
|
+
problems.push(`Invalid or duplicate step "${stepId}".`);
|
|
87
|
+
if (!operationIds.has(operationId)) {
|
|
88
|
+
problems.push(`Step "${stepId}": unknown operationId "${operationId}" in the served OpenAPI document.`);
|
|
89
|
+
}
|
|
90
|
+
const step = { stepId, operationId };
|
|
91
|
+
const expectations = {};
|
|
92
|
+
steps.set(stepId, { step, expectations });
|
|
93
|
+
return new JourneyStep(step, expectations, owner, problems);
|
|
94
|
+
},
|
|
95
|
+
output(key, value) {
|
|
96
|
+
if (!referenceName.test(key) || outputs.has(key))
|
|
97
|
+
problems.push(`Invalid or duplicate workflow output "${key}".`);
|
|
98
|
+
outputs.set(key, value);
|
|
99
|
+
},
|
|
100
|
+
approveDifference(record) {
|
|
101
|
+
differences.push({ ...record, journey: id });
|
|
102
|
+
},
|
|
103
|
+
});
|
|
104
|
+
if (!id.trim() || !name.trim() || !steps.size)
|
|
105
|
+
problems.push('A journey needs an ID, a name and at least one step.');
|
|
106
|
+
// Keep references as Arazzo expressions in JSON. Request bindings only see earlier outputs;
|
|
107
|
+
// expectations can see the current output because they are checked after the response.
|
|
108
|
+
const available = new Map();
|
|
109
|
+
function encode(value, location) {
|
|
110
|
+
return JSON.parse(JSON.stringify(value, (_key, current) => {
|
|
111
|
+
if (current instanceof JourneyRef) {
|
|
112
|
+
if (current.owner !== owner)
|
|
113
|
+
problems.push(`${location}: reference belongs to another journey.`);
|
|
114
|
+
current = current.expression;
|
|
115
|
+
}
|
|
116
|
+
if (typeof current === 'string') {
|
|
117
|
+
const expressions = current.startsWith('$inputs.') || current.startsWith('$steps.') ? [current]
|
|
118
|
+
: [...current.matchAll(/\{(\$(?:inputs|steps)\.[^{}]+)\}/g)].map(([, expression]) => expression);
|
|
119
|
+
for (const expression of expressions) {
|
|
120
|
+
const input = inputReference.exec(expression);
|
|
121
|
+
const step = stepReference.exec(expression);
|
|
122
|
+
if (input ? !knownInput(input[1]) : !step || !Object.hasOwn(available.get(step[1]) ?? {}, step[2])) {
|
|
123
|
+
problems.push(`${location}: unresolved input or step output "${expression}".`);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return current;
|
|
128
|
+
}));
|
|
129
|
+
}
|
|
130
|
+
const stepEntries = new Map();
|
|
131
|
+
const workflowSteps = [];
|
|
132
|
+
let sendOnly = options.sendOnly;
|
|
133
|
+
for (const { step, expectations } of steps.values()) {
|
|
134
|
+
const location = `Step "${step.stepId}"`;
|
|
135
|
+
workflowSteps.push(encode(step, location));
|
|
136
|
+
available.set(step.stepId, step.outputs);
|
|
137
|
+
if (Object.keys(expectations).length)
|
|
138
|
+
stepEntries.set(step.stepId, encode(expectations, location));
|
|
139
|
+
if (expectations.writes?.some(write => write.store === 'redis')) {
|
|
140
|
+
sendOnly ??= `${location} writes to Redis, which cannot roll back.`;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
const workflow = {
|
|
144
|
+
workflowId: id, summary, description, inputs, steps: workflowSteps,
|
|
145
|
+
...(outputs.size ? { outputs: encode(Object.fromEntries(outputs), 'Workflow outputs') } : {}),
|
|
146
|
+
};
|
|
147
|
+
const expectations = {
|
|
148
|
+
group, runAs, definedIn,
|
|
149
|
+
...(sendOnly !== undefined ? { sendOnly: true, sendOnlyReason: sendOnly } : {}),
|
|
150
|
+
};
|
|
151
|
+
const approvals = new Set();
|
|
152
|
+
for (const record of differences) {
|
|
153
|
+
if (!steps.has(record.step))
|
|
154
|
+
problems.push(`Approved difference "${record.id}": unknown step "${record.step}".`);
|
|
155
|
+
if (!record.id.trim() || !record.reason.trim() || !record.approvedBy.trim() || approvals.has(record.id)) {
|
|
156
|
+
problems.push(`Approved difference "${record.id}" needs a unique ID, a reason and an approver.`);
|
|
157
|
+
}
|
|
158
|
+
approvals.add(record.id);
|
|
159
|
+
}
|
|
160
|
+
return {
|
|
161
|
+
workflow, differences, problems: [...new Set(problems)],
|
|
162
|
+
expectations: { ...expectations, steps: Object.fromEntries(stepEntries) },
|
|
163
|
+
};
|
|
164
|
+
},
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
export function compileJourney(journey, operationIds) {
|
|
168
|
+
return journey[buildJourney](operationIds);
|
|
169
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { type CodeJourney } from './journey-builder.js';
|
|
2
|
+
export declare const journeyPrefix = "/sendproof/journeys/";
|
|
3
|
+
interface CodeOptions {
|
|
4
|
+
apiName: string;
|
|
5
|
+
openApiUrl: string;
|
|
6
|
+
openApiDocument?: object;
|
|
7
|
+
document?: {
|
|
8
|
+
id?: string;
|
|
9
|
+
title?: string;
|
|
10
|
+
};
|
|
11
|
+
development: boolean;
|
|
12
|
+
enabled: boolean;
|
|
13
|
+
}
|
|
14
|
+
export declare function registerJourneys(journeys: readonly (string | URL | CodeJourney)[], options: CodeOptions): {
|
|
15
|
+
readonly size: number;
|
|
16
|
+
discover(basePath: string): {
|
|
17
|
+
name: string;
|
|
18
|
+
source: "code" | "file";
|
|
19
|
+
arazzoUrl: string;
|
|
20
|
+
expectationsUrl: string;
|
|
21
|
+
}[];
|
|
22
|
+
document(path: string, basePath: string): unknown;
|
|
23
|
+
};
|
|
24
|
+
export {};
|
package/dist/journeys.js
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { basename } from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { compileJourney } from './journey-builder.js';
|
|
5
|
+
import { localPath } from './paths.js';
|
|
6
|
+
export const journeyPrefix = '/sendproof/journeys/';
|
|
7
|
+
const documentId = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
8
|
+
const methods = ['get', 'put', 'post', 'delete', 'options', 'head', 'patch', 'trace'];
|
|
9
|
+
const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
10
|
+
function operationIds(document) {
|
|
11
|
+
const ids = new Set();
|
|
12
|
+
if (!isObject(document) || !isObject(document.paths))
|
|
13
|
+
return ids;
|
|
14
|
+
for (const [path, rawItem] of Object.entries(document.paths)) {
|
|
15
|
+
if (!path.startsWith('/') || !isObject(rawItem))
|
|
16
|
+
continue;
|
|
17
|
+
let item = rawItem;
|
|
18
|
+
if (typeof rawItem.$ref === 'string' && rawItem.$ref.startsWith('#/')) {
|
|
19
|
+
item = rawItem.$ref.slice(2).split('/').reduce((node, token) => {
|
|
20
|
+
const key = token.replace(/~1/g, '/').replace(/~0/g, '~');
|
|
21
|
+
return isObject(node) && Object.hasOwn(node, key) ? node[key] : undefined;
|
|
22
|
+
}, document);
|
|
23
|
+
}
|
|
24
|
+
if (!isObject(item))
|
|
25
|
+
continue;
|
|
26
|
+
for (const method of methods) {
|
|
27
|
+
const operation = item[method];
|
|
28
|
+
if (isObject(operation) && typeof operation.operationId === 'string')
|
|
29
|
+
ids.add(operation.operationId);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return ids;
|
|
33
|
+
}
|
|
34
|
+
function registerCode(entries, journeys, options) {
|
|
35
|
+
const { apiName, openApiDocument, openApiUrl, development } = options;
|
|
36
|
+
const { id = 'journeys', title = `${apiName} journeys` } = options.document ?? {};
|
|
37
|
+
const problems = [];
|
|
38
|
+
const workflows = [];
|
|
39
|
+
const expectations = new Map();
|
|
40
|
+
const differences = [];
|
|
41
|
+
const workflowIds = new Set();
|
|
42
|
+
const approvalIds = new Set();
|
|
43
|
+
for (const { arazzo } of entries.values()) {
|
|
44
|
+
if (!Array.isArray(arazzo.workflows))
|
|
45
|
+
continue;
|
|
46
|
+
for (const workflow of arazzo.workflows) {
|
|
47
|
+
if (isObject(workflow) && typeof workflow.workflowId === 'string')
|
|
48
|
+
workflowIds.add(workflow.workflowId);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
if (!documentId.test(id) || !title.trim() || entries.has(id)) {
|
|
52
|
+
problems.push('The code journey document needs a unique, URL-safe ID and a title.');
|
|
53
|
+
}
|
|
54
|
+
else if (!openApiDocument) {
|
|
55
|
+
problems.push('Code journeys require openApiDocument, the same document the application serves at openApiUrl.');
|
|
56
|
+
}
|
|
57
|
+
else {
|
|
58
|
+
const operations = operationIds(openApiDocument);
|
|
59
|
+
for (const journey of journeys) {
|
|
60
|
+
try {
|
|
61
|
+
if (workflowIds.has(journey.id))
|
|
62
|
+
throw new TypeError('Duplicate workflow ID.');
|
|
63
|
+
const built = compileJourney(journey, operations);
|
|
64
|
+
for (const { id } of built.differences) {
|
|
65
|
+
if (approvalIds.has(id))
|
|
66
|
+
built.problems.push(`Duplicate approved difference ID "${id}".`);
|
|
67
|
+
}
|
|
68
|
+
if (built.problems.length) {
|
|
69
|
+
problems.push(...built.problems.map(problem => `${journey.id}: ${problem}`));
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
workflows.push(built.workflow);
|
|
73
|
+
workflowIds.add(journey.id);
|
|
74
|
+
expectations.set(journey.id, built.expectations);
|
|
75
|
+
differences.push(...built.differences);
|
|
76
|
+
for (const { id } of built.differences)
|
|
77
|
+
approvalIds.add(id);
|
|
78
|
+
}
|
|
79
|
+
catch (error) {
|
|
80
|
+
problems.push(`${journey.id}: ${error instanceof Error ? error.message : String(error)}`);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
if (problems.length) {
|
|
85
|
+
if (development)
|
|
86
|
+
throw new TypeError(`Invalid Sendproof journeys:\n${problems.join('\n')}`);
|
|
87
|
+
for (const problem of problems)
|
|
88
|
+
console.warn(`Sendproof skipped a journey: ${problem}`);
|
|
89
|
+
}
|
|
90
|
+
if (!workflows.length)
|
|
91
|
+
return;
|
|
92
|
+
const words = apiName.match(/[A-Za-z0-9]+/g) ?? ['api'];
|
|
93
|
+
const name = words.map((word, index) => (index === 0 ? word[0].toLowerCase() : word[0].toUpperCase()) + word.slice(1)).join('');
|
|
94
|
+
entries.set(id, {
|
|
95
|
+
source: 'code',
|
|
96
|
+
arazzo: {
|
|
97
|
+
arazzo: '1.1.0', info: { title, version: '1.0.0' },
|
|
98
|
+
sourceDescriptions: [{ name, url: openApiUrl, type: 'openapi' }], workflows,
|
|
99
|
+
},
|
|
100
|
+
expectations: {
|
|
101
|
+
sendproofExpectations: '1.0', arazzo: id + '.arazzo.json', journeys: Object.fromEntries(expectations),
|
|
102
|
+
...(differences.length ? { approvedDifferences: differences } : {}),
|
|
103
|
+
},
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
export function registerJourneys(journeys, options) {
|
|
107
|
+
const entries = new Map();
|
|
108
|
+
const code = [];
|
|
109
|
+
for (const journey of journeys) {
|
|
110
|
+
if (typeof journey !== 'string' && !(journey instanceof URL)) {
|
|
111
|
+
code.push(journey);
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
const path = journey instanceof URL ? fileURLToPath(journey) : journey;
|
|
115
|
+
const name = basename(path).match(/^([A-Za-z0-9][A-Za-z0-9._-]*)\.arazzo\.json$/)?.[1];
|
|
116
|
+
if (!name || entries.has(name))
|
|
117
|
+
throw new TypeError('Journey files need unique <name>.arazzo.json filenames.');
|
|
118
|
+
const arazzo = JSON.parse(readFileSync(path, 'utf8'));
|
|
119
|
+
if (arazzo?.arazzo !== '1.1.0' || typeof arazzo.info?.title !== 'string' || !arazzo.info.title.trim()
|
|
120
|
+
|| !Array.isArray(arazzo.sourceDescriptions) || arazzo.sourceDescriptions.some(source => typeof source?.url !== 'string')) {
|
|
121
|
+
throw new TypeError('Journey files need an Arazzo 1.1.0 title and source descriptions.');
|
|
122
|
+
}
|
|
123
|
+
const expectations = JSON.parse(readFileSync(path.replace(/\.arazzo\.json$/, '.expect.json'), 'utf8'));
|
|
124
|
+
if (expectations?.sendproofExpectations !== '1.0' || expectations.arazzo !== name + '.arazzo.json') {
|
|
125
|
+
throw new TypeError('Journey expectations must name the paired Arazzo file and use version 1.0.');
|
|
126
|
+
}
|
|
127
|
+
entries.set(name, { arazzo, expectations, source: 'file' });
|
|
128
|
+
}
|
|
129
|
+
if (code.length && options.enabled)
|
|
130
|
+
registerCode(entries, code, options);
|
|
131
|
+
return {
|
|
132
|
+
get size() { return entries.size; },
|
|
133
|
+
discover(basePath) {
|
|
134
|
+
return Array.from(entries, ([name, { arazzo, source }]) => ({
|
|
135
|
+
name: arazzo.info.title,
|
|
136
|
+
source,
|
|
137
|
+
arazzoUrl: basePath + journeyPrefix + name + '.arazzo.json',
|
|
138
|
+
expectationsUrl: basePath + journeyPrefix + name + '.expect.json',
|
|
139
|
+
}));
|
|
140
|
+
},
|
|
141
|
+
document(path, basePath) {
|
|
142
|
+
const route = path.slice(journeyPrefix.length).match(/^([^/]+)\.(arazzo|expect)\.json$/);
|
|
143
|
+
const entry = route && entries.get(route[1]);
|
|
144
|
+
if (!entry)
|
|
145
|
+
return undefined;
|
|
146
|
+
if (route[2] === 'expect')
|
|
147
|
+
return entry.expectations;
|
|
148
|
+
const { arazzo } = entry;
|
|
149
|
+
return {
|
|
150
|
+
...arazzo,
|
|
151
|
+
sourceDescriptions: arazzo.sourceDescriptions.map(source => ({
|
|
152
|
+
...source, url: localPath(source.url) ? basePath + source.url : source.url,
|
|
153
|
+
})),
|
|
154
|
+
};
|
|
155
|
+
},
|
|
156
|
+
};
|
|
157
|
+
}
|
package/dist/node-http.d.ts
CHANGED
|
@@ -11,6 +11,8 @@ interface CapturedRequest extends IncomingMessage {
|
|
|
11
11
|
interface CapturedResponse extends ServerResponse {
|
|
12
12
|
locals?: Record<string, unknown>;
|
|
13
13
|
}
|
|
14
|
+
/** Read the small rewind payload when the host has no JSON middleware ahead of Sendproof. */
|
|
15
|
+
export declare function readSessionBody(req: IncomingMessage): Promise<unknown>;
|
|
14
16
|
/** Execute an in-process Node request against a bounded, socket-free response. */
|
|
15
17
|
export declare function captureResponse<Request extends CapturedRequest, Response extends CapturedResponse>(router: (request: Request, response: Response, done: (error?: unknown) => void) => void, req: Request, original: Response, target: string, limit: number, originalUrl?: string): Promise<DispatchResponse>;
|
|
16
18
|
export declare function sendResponse<Response extends ServerResponse>(req: IncomingMessage, res: Response, { status, headers, body }: TransportResponse): Response;
|
package/dist/node-http.js
CHANGED
|
@@ -1,4 +1,21 @@
|
|
|
1
1
|
import { ServerResponse } from 'node:http';
|
|
2
|
+
/** Read the small rewind payload when the host has no JSON middleware ahead of Sendproof. */
|
|
3
|
+
export async function readSessionBody(req) {
|
|
4
|
+
if ('body' in req && req.body !== undefined)
|
|
5
|
+
return req.body;
|
|
6
|
+
const chunks = [];
|
|
7
|
+
let bytes = 0;
|
|
8
|
+
for await (const chunk of req.iterator({ destroyOnReturn: false })) {
|
|
9
|
+
const buffer = Buffer.from(chunk);
|
|
10
|
+
bytes += buffer.length;
|
|
11
|
+
if (bytes > 1024) {
|
|
12
|
+
req.resume();
|
|
13
|
+
return null;
|
|
14
|
+
}
|
|
15
|
+
chunks.push(buffer);
|
|
16
|
+
}
|
|
17
|
+
return JSON.parse(Buffer.concat(chunks).toString());
|
|
18
|
+
}
|
|
2
19
|
/** Execute an in-process Node request against a bounded, socket-free response. */
|
|
3
20
|
export function captureResponse(router, req, original, target, limit, originalUrl = (req.baseUrl ?? '') + target) {
|
|
4
21
|
const response = Object.setPrototypeOf(new ServerResponse(req), Object.getPrototypeOf(original));
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { DataStore, HeldPreview, SessionAccess } from './types.js';
|
|
2
|
+
export declare class PreviewStoreBusyError extends Error {
|
|
3
|
+
readonly store: string;
|
|
4
|
+
constructor(store: string);
|
|
5
|
+
}
|
|
6
|
+
export declare class PreviewSessionEndedError extends Error {
|
|
7
|
+
}
|
|
8
|
+
export declare class SessionProblem extends Error {
|
|
9
|
+
readonly status: number;
|
|
10
|
+
readonly code: string;
|
|
11
|
+
constructor(status: number, code: string, title: string);
|
|
12
|
+
}
|
|
13
|
+
export declare const notFound: () => SessionProblem;
|
|
14
|
+
export declare const failed: () => SessionProblem;
|
|
15
|
+
interface Session {
|
|
16
|
+
id: string;
|
|
17
|
+
owner: string;
|
|
18
|
+
deadline: number;
|
|
19
|
+
idleDeadline: number;
|
|
20
|
+
parts: HeldPreview[];
|
|
21
|
+
guards: DataStore[];
|
|
22
|
+
nextStep: number;
|
|
23
|
+
active?: ReturnType<typeof Promise.withResolvers<void>>;
|
|
24
|
+
timer?: NodeJS.Timeout;
|
|
25
|
+
closing?: Promise<void>;
|
|
26
|
+
onError: (error: unknown) => void;
|
|
27
|
+
}
|
|
28
|
+
export declare class Sessions {
|
|
29
|
+
#private;
|
|
30
|
+
readonly idleTimeoutSeconds: number;
|
|
31
|
+
readonly maxLifetimeSeconds: number;
|
|
32
|
+
constructor(idleTimeoutSeconds: number, maxLifetimeSeconds: number);
|
|
33
|
+
open(owner: string, guards: DataStore[], acquire: (add: (part: HeldPreview) => Promise<void>) => Promise<void>, onError: (error: unknown) => void): Promise<{
|
|
34
|
+
id: string;
|
|
35
|
+
idleTimeoutSeconds: number;
|
|
36
|
+
maxLifetimeSeconds: number;
|
|
37
|
+
}>;
|
|
38
|
+
enter({ id, owner }: SessionAccess): Session;
|
|
39
|
+
exit(session: Session): Promise<void>;
|
|
40
|
+
close(session: Session): Promise<void>;
|
|
41
|
+
shutdown(): Promise<void>;
|
|
42
|
+
}
|
|
43
|
+
export {};
|
package/dist/sessions.js
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { performance } from 'node:perf_hooks';
|
|
3
|
+
export class PreviewStoreBusyError extends Error {
|
|
4
|
+
store;
|
|
5
|
+
constructor(store) {
|
|
6
|
+
super('A Preview store is busy.');
|
|
7
|
+
this.store = store;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
export class PreviewSessionEndedError extends Error {
|
|
11
|
+
}
|
|
12
|
+
export class SessionProblem extends Error {
|
|
13
|
+
status;
|
|
14
|
+
code;
|
|
15
|
+
constructor(status, code, title) {
|
|
16
|
+
super(title);
|
|
17
|
+
this.status = status;
|
|
18
|
+
this.code = code;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
export const notFound = () => new SessionProblem(404, 'session_not_found', 'Preview session not found.');
|
|
22
|
+
export const failed = () => new SessionProblem(409, 'session_failed', 'A required Preview transaction is unavailable.');
|
|
23
|
+
export class Sessions {
|
|
24
|
+
idleTimeoutSeconds;
|
|
25
|
+
maxLifetimeSeconds;
|
|
26
|
+
#sessions = new Map();
|
|
27
|
+
#stopping = false;
|
|
28
|
+
constructor(idleTimeoutSeconds, maxLifetimeSeconds) {
|
|
29
|
+
this.idleTimeoutSeconds = idleTimeoutSeconds;
|
|
30
|
+
this.maxLifetimeSeconds = maxLifetimeSeconds;
|
|
31
|
+
for (const seconds of [idleTimeoutSeconds, maxLifetimeSeconds]) {
|
|
32
|
+
if (!Number.isSafeInteger(seconds) || seconds <= 0 || seconds * 1000 > 2 ** 31 - 1) {
|
|
33
|
+
throw new RangeError('Preview session timeouts must be positive whole seconds within the Node timer range.');
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
async open(owner, guards, acquire, onError) {
|
|
38
|
+
if (this.#stopping)
|
|
39
|
+
throw failed();
|
|
40
|
+
if (this.#sessions.size >= 16 || [...this.#sessions.values()].filter(session => session.owner === owner).length >= 4) {
|
|
41
|
+
throw new SessionProblem(429, 'session_limit', 'Too many Preview sessions are open. End one first.');
|
|
42
|
+
}
|
|
43
|
+
// Reserve an admission slot before touching any store, including during parallel opens.
|
|
44
|
+
const id = randomBytes(16).toString('hex');
|
|
45
|
+
const now = performance.now();
|
|
46
|
+
const session = {
|
|
47
|
+
id, owner, parts: [], guards, deadline: now + this.maxLifetimeSeconds * 1000, idleDeadline: 0,
|
|
48
|
+
nextStep: 1, active: Promise.withResolvers(), onError,
|
|
49
|
+
};
|
|
50
|
+
this.#sessions.set(id, session);
|
|
51
|
+
let timer;
|
|
52
|
+
try {
|
|
53
|
+
await Promise.race([
|
|
54
|
+
acquire(async (part) => {
|
|
55
|
+
if (session.closing || this.#stopping) {
|
|
56
|
+
await part.close().catch(onError);
|
|
57
|
+
throw failed();
|
|
58
|
+
}
|
|
59
|
+
session.parts.push(part);
|
|
60
|
+
}),
|
|
61
|
+
new Promise((_, reject) => {
|
|
62
|
+
timer = setTimeout(() => reject(failed()), Math.min(4000, this.maxLifetimeSeconds * 1000));
|
|
63
|
+
timer.unref();
|
|
64
|
+
}),
|
|
65
|
+
]);
|
|
66
|
+
if (this.#stopping || performance.now() >= session.deadline)
|
|
67
|
+
throw failed();
|
|
68
|
+
return { id, idleTimeoutSeconds: this.idleTimeoutSeconds, maxLifetimeSeconds: this.maxLifetimeSeconds };
|
|
69
|
+
}
|
|
70
|
+
catch (error) {
|
|
71
|
+
await this.close(session).catch(onError);
|
|
72
|
+
if (error instanceof PreviewStoreBusyError) {
|
|
73
|
+
throw new SessionProblem(409, 'store_busy', `Another Preview session is holding ${error.store}.`);
|
|
74
|
+
}
|
|
75
|
+
onError(error);
|
|
76
|
+
throw failed();
|
|
77
|
+
}
|
|
78
|
+
finally {
|
|
79
|
+
clearTimeout(timer);
|
|
80
|
+
await this.exit(session);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
enter({ id, owner }) {
|
|
84
|
+
const session = this.#sessions.get(id);
|
|
85
|
+
if (this.#stopping || !session || session.closing || session.owner !== owner)
|
|
86
|
+
throw notFound();
|
|
87
|
+
const now = performance.now();
|
|
88
|
+
if (now >= session.deadline || (!session.active && now >= session.idleDeadline)) {
|
|
89
|
+
if (!session.active)
|
|
90
|
+
void this.close(session).catch(session.onError);
|
|
91
|
+
throw notFound();
|
|
92
|
+
}
|
|
93
|
+
if (session.active)
|
|
94
|
+
throw new SessionProblem(409, 'session_busy', 'The Preview session is serving another request.');
|
|
95
|
+
clearTimeout(session.timer);
|
|
96
|
+
session.active = Promise.withResolvers();
|
|
97
|
+
return session;
|
|
98
|
+
}
|
|
99
|
+
async exit(session) {
|
|
100
|
+
const active = session.active;
|
|
101
|
+
session.active = undefined;
|
|
102
|
+
session.idleDeadline = performance.now() + this.idleTimeoutSeconds * 1000;
|
|
103
|
+
const delay = Math.min(session.idleDeadline, session.deadline) - performance.now();
|
|
104
|
+
try {
|
|
105
|
+
if (session.closing || this.#stopping || delay <= 0) {
|
|
106
|
+
await this.close(session).catch(session.onError);
|
|
107
|
+
}
|
|
108
|
+
else {
|
|
109
|
+
session.timer = setTimeout(() => void this.close(session).catch(session.onError), Math.ceil(delay));
|
|
110
|
+
session.timer.unref();
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
finally {
|
|
114
|
+
active?.resolve();
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
close(session) {
|
|
118
|
+
clearTimeout(session.timer);
|
|
119
|
+
return session.closing ??= (async () => {
|
|
120
|
+
const errors = [];
|
|
121
|
+
try {
|
|
122
|
+
for (const part of session.parts.toReversed()) {
|
|
123
|
+
try {
|
|
124
|
+
await part.close();
|
|
125
|
+
}
|
|
126
|
+
catch (error) {
|
|
127
|
+
errors.push(error);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
if (errors.length)
|
|
131
|
+
throw new AggregateError(errors, 'Preview session rollback failed.');
|
|
132
|
+
}
|
|
133
|
+
finally {
|
|
134
|
+
this.#sessions.delete(session.id);
|
|
135
|
+
}
|
|
136
|
+
})();
|
|
137
|
+
}
|
|
138
|
+
async shutdown() {
|
|
139
|
+
this.#stopping = true;
|
|
140
|
+
await Promise.all([...this.#sessions.values()].map(async (session) => {
|
|
141
|
+
await session.active?.promise;
|
|
142
|
+
await this.close(session).catch(session.onError);
|
|
143
|
+
}));
|
|
144
|
+
}
|
|
145
|
+
}
|
package/dist/statements.js
CHANGED
|
@@ -278,8 +278,8 @@ export function rollsBackTransaction(error, provider) {
|
|
|
278
278
|
* during a Preview.
|
|
279
279
|
*/
|
|
280
280
|
export const previewSavepoint = 'sendproof_preview';
|
|
281
|
-
/** A handler's
|
|
282
|
-
const previewSavepointStatement = /^(?:SAVEPOINT|RELEASE(?:\s+SAVEPOINT)?|ROLLBACK(?:\s+(?:WORK|TRANSACTION))?\s+TO(?:\s+SAVEPOINT)?|SAVE\s+TRAN(?:SACTION)?)\s+[`"[]?sendproof_preview[`"\]]?$/i;
|
|
281
|
+
/** A handler's statement naming a reserved Preview or session savepoint. */
|
|
282
|
+
const previewSavepointStatement = /^(?:SAVEPOINT|RELEASE(?:\s+SAVEPOINT)?|ROLLBACK(?:\s+(?:WORK|TRANSACTION))?\s+TO(?:\s+SAVEPOINT)?|SAVE\s+TRAN(?:SACTION)?)\s+[`"[]?sendproof_preview(?:_check|_step_[0-9]+)?[`"\]]?$/i;
|
|
283
283
|
const isSqlServer = (provider) => provider === 'mssql' || provider === 'sqlserver';
|
|
284
284
|
/**
|
|
285
285
|
* Sets {@link previewSavepoint} through `run`, which sends one statement on the Preview connection. Providers call it
|