@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.
Files changed (116) hide show
  1. package/assets/api.js +2 -1
  2. package/assets/app.css +612 -1
  3. package/assets/app.js +89 -13
  4. package/assets/bar-fit.js +91 -0
  5. package/assets/commands.js +27 -4
  6. package/assets/dialog.css +125 -0
  7. package/assets/dialog.js +191 -0
  8. package/assets/fields/lookup-source.js +5 -2
  9. package/assets/fields/lookup.js +3 -2
  10. package/assets/i18n.js +13 -2
  11. package/assets/icons.js +18 -0
  12. package/assets/index.html +1 -0
  13. package/assets/journeys/compare.js +225 -0
  14. package/assets/journeys/expressions.js +89 -0
  15. package/assets/journeys/index.js +7 -0
  16. package/assets/journeys/run.js +152 -0
  17. package/assets/journeys/steps.js +163 -0
  18. package/assets/journeys-code.js +193 -0
  19. package/assets/journeys-dialog-model.js +172 -0
  20. package/assets/journeys-dialogs.js +301 -0
  21. package/assets/journeys-model.js +259 -0
  22. package/assets/journeys-runs.js +109 -0
  23. package/assets/journeys-session.js +135 -0
  24. package/assets/journeys-view.js +961 -0
  25. package/assets/journeys.js +962 -0
  26. package/assets/locales/ar-journeys.js +468 -0
  27. package/assets/locales/ar.js +2 -0
  28. package/assets/locales/cs-journeys.js +468 -0
  29. package/assets/locales/cs.js +2 -0
  30. package/assets/locales/da-journeys.js +465 -0
  31. package/assets/locales/da.js +2 -0
  32. package/assets/locales/de-journeys.js +465 -0
  33. package/assets/locales/de.js +2 -0
  34. package/assets/locales/el-journeys.js +465 -0
  35. package/assets/locales/el.js +2 -0
  36. package/assets/locales/en-journeys.js +467 -0
  37. package/assets/locales/en.js +2 -0
  38. package/assets/locales/es-journeys.js +467 -0
  39. package/assets/locales/es.js +2 -0
  40. package/assets/locales/fa-journeys.js +465 -0
  41. package/assets/locales/fa.js +2 -0
  42. package/assets/locales/fi-journeys.js +465 -0
  43. package/assets/locales/fi.js +2 -0
  44. package/assets/locales/fr-journeys.js +467 -0
  45. package/assets/locales/fr.js +2 -0
  46. package/assets/locales/he-journeys.js +468 -0
  47. package/assets/locales/he.js +2 -0
  48. package/assets/locales/hi-journeys.js +465 -0
  49. package/assets/locales/hi.js +2 -0
  50. package/assets/locales/id-journeys.js +466 -0
  51. package/assets/locales/id.js +2 -0
  52. package/assets/locales/it-journeys.js +467 -0
  53. package/assets/locales/it.js +2 -0
  54. package/assets/locales/ja-journeys.js +466 -0
  55. package/assets/locales/ja.js +2 -0
  56. package/assets/locales/ko-journeys.js +465 -0
  57. package/assets/locales/ko.js +2 -0
  58. package/assets/locales/nb-journeys.js +465 -0
  59. package/assets/locales/nb.js +2 -0
  60. package/assets/locales/nl-journeys.js +465 -0
  61. package/assets/locales/nl.js +2 -0
  62. package/assets/locales/pl-journeys.js +468 -0
  63. package/assets/locales/pl.js +2 -0
  64. package/assets/locales/pt-BR-journeys.js +467 -0
  65. package/assets/locales/pt-BR.js +2 -0
  66. package/assets/locales/pt-PT-journeys.js +467 -0
  67. package/assets/locales/pt-PT.js +2 -0
  68. package/assets/locales/ru-journeys.js +468 -0
  69. package/assets/locales/ru.js +2 -0
  70. package/assets/locales/sv-journeys.js +465 -0
  71. package/assets/locales/sv.js +2 -0
  72. package/assets/locales/th-journeys.js +466 -0
  73. package/assets/locales/th.js +2 -0
  74. package/assets/locales/tr-journeys.js +468 -0
  75. package/assets/locales/tr.js +2 -0
  76. package/assets/locales/uk-journeys.js +468 -0
  77. package/assets/locales/uk.js +2 -0
  78. package/assets/locales/vi-journeys.js +466 -0
  79. package/assets/locales/vi.js +2 -0
  80. package/assets/locales/zh-Hans-journeys.js +466 -0
  81. package/assets/locales/zh-Hans.js +2 -0
  82. package/assets/locales/zh-Hant-journeys.js +466 -0
  83. package/assets/locales/zh-Hant.js +2 -0
  84. package/assets/manifest.json +349 -104
  85. package/assets/markdown.js +27 -2
  86. package/assets/request-editor.js +7 -1
  87. package/assets/result-states.js +2 -2
  88. package/assets/results.js +41 -14
  89. package/assets/router.js +25 -1
  90. package/assets/seeded-menu.js +2 -1
  91. package/assets/shortcuts-sheet.js +3 -1
  92. package/assets/shortcuts.js +6 -0
  93. package/assets/sidebar.js +54 -5
  94. package/assets/signin.js +6 -3
  95. package/assets/styles.css +8 -2
  96. package/assets/toast.js +29 -0
  97. package/assets/vendor/arazzo-runtime-expression.js +136 -0
  98. package/assets/vendor/json-pointer.js +48 -0
  99. package/assets/vendor/jsonpath-rfc9535.js +15 -0
  100. package/assets/view.js +11 -3
  101. package/assets/views.css +7 -0
  102. package/dist/index.d.ts +7 -3
  103. package/dist/index.js +217 -26
  104. package/dist/journey-builder.d.ts +178 -0
  105. package/dist/journey-builder.js +169 -0
  106. package/dist/journeys.d.ts +24 -0
  107. package/dist/journeys.js +157 -0
  108. package/dist/node-http.d.ts +2 -0
  109. package/dist/node-http.js +17 -0
  110. package/dist/sessions.d.ts +43 -0
  111. package/dist/sessions.js +145 -0
  112. package/dist/statements.js +2 -2
  113. package/dist/stores/tables.d.ts +213 -0
  114. package/dist/stores/tables.js +213 -0
  115. package/dist/types.d.ts +34 -2
  116. package/package.json +1 -1
@@ -0,0 +1,172 @@
1
+ // What the Journeys dialogs (dialog.js, journeys-dialogs.js) say, read from the real run and the
2
+ // journey's expectations, never made up. Pure: no DOM, so ui/journeys-dialog-model.test.mjs runs it
3
+ // in Node. Every number here is a count of something the run or the expectations really hold.
4
+ import { evaluate } from './journeys/expressions.js';
5
+ import { securityRequirements } from './security.js';
6
+ import { sqlSystem, storeKind } from './stores.js';
7
+
8
+ /** The place a write goes, as the store names it: a table, a collection or a key. */
9
+ const placeOf = write => write.table ?? write.collection ?? (typeof write.key === 'string' ? write.key : undefined);
10
+
11
+ const normal = system => String(system ?? '').trim().toLowerCase();
12
+
13
+ /** A recipient written as a literal or as `$inputs.x`; anything the run can't resolve yet is left out. */
14
+ function recipient(raw, inputs) {
15
+ if (typeof raw !== 'string') return null;
16
+ if (!raw.startsWith('$')) return raw;
17
+ try {
18
+ const value = evaluate(raw, { inputs: inputs ?? {}, steps: {} });
19
+ return typeof value === 'string' && value ? value : null;
20
+ } catch { return null; }
21
+ }
22
+
23
+ /**
24
+ * What a Send of `journey` keeps, per store, from its steps' expected writes and effects:
25
+ * `[{ system, kind, database?, records, places: [names] }]` for stores, then
26
+ * `{ system: 'email', emails, recipients }` and `{ system: 'effect', effect: kind, count }`.
27
+ * `records` counts expected writes (a row, a document or a key each), so it is what the run would
28
+ * commit, not a guess. A store with no written place named (Redis keys) lists none.
29
+ */
30
+ export function sendTargets(journey, capabilities = {}, { inputs } = {}) {
31
+ const sql = sqlSystem(capabilities);
32
+ const database = typeof capabilities.database === 'string' ? capabilities.database : capabilities.database?.name;
33
+ const stores = new Map();
34
+ const emails = { system: 'email', emails: 0, recipients: [] };
35
+ const effects = new Map();
36
+ for (const step of journey?.steps ?? []) {
37
+ for (const write of step.expected?.writes ?? []) {
38
+ const system = write.store ? normal(write.store) : sql;
39
+ const entry = stores.get(system) ?? { system, kind: storeKind(system), records: 0, places: [], ...(system === sql && database ? { database } : {}) };
40
+ entry.records++;
41
+ const place = placeOf(write);
42
+ if (place && entry.kind !== 'key' && !entry.places.includes(place)) entry.places.push(place);
43
+ stores.set(system, entry);
44
+ }
45
+ for (const effect of step.expected?.effects ?? []) {
46
+ if (effect.kind === 'email') {
47
+ emails.emails++;
48
+ const to = recipient(effect.to, inputs);
49
+ if (to && !emails.recipients.includes(to)) emails.recipients.push(to);
50
+ } else effects.set(effect.kind, (effects.get(effect.kind) ?? 0) + 1);
51
+ }
52
+ }
53
+ return [...stores.values(), ...(emails.emails ? [emails] : []), ...[...effects].map(([effect, count]) => ({ system: 'effect', effect, count }))];
54
+ }
55
+
56
+ /** What one step's recorded changes and effects hold, by store: `{ stores: [{ system, count }], emails, effects }`. */
57
+ export function heldBy(envelope, sqlStore = 'sql') {
58
+ const stores = new Map();
59
+ for (const change of envelope?.changes ?? []) {
60
+ const system = normal(change.store) || sqlStore;
61
+ stores.set(system, (stores.get(system) ?? 0) + 1);
62
+ }
63
+ const all = envelope?.effects ?? [];
64
+ const emails = all.filter(effect => effect.kind === 'email').length;
65
+ const kinds = new Map();
66
+ for (const effect of all) if (effect.kind !== 'email') kinds.set(String(effect.kind || ''), (kinds.get(String(effect.kind || '')) ?? 0) + 1);
67
+ return { stores: [...stores].map(([system, count]) => ({ system, count })), emails, effects: all.length - emails, kinds: [...kinds].map(([kind, count]) => ({ kind, count })) };
68
+ }
69
+
70
+ const GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
71
+ /** The fields a person would name a record by, best first. */
72
+ const KEY_FIELDS = ['number', 'code', 'sku', 'email', 'name', 'title', 'reference', 'slug'];
73
+ const lowered = row => Object.fromEntries(Object.entries(row && typeof row === 'object' ? row : {}).map(([key, value]) => [key.toLowerCase(), value]));
74
+ /** A short, readable value: a string or number, not an ID, no longer than a line. */
75
+ const human = value => (typeof value === 'string' || typeof value === 'number') && !GUID.test(String(value)) && String(value).length <= 40 ? String(value) : '';
76
+
77
+ /** An ID cut to its first eight characters ("4ef4416e…") when it is a GUID or long; a short ID stays whole. */
78
+ export const shortId = id => {
79
+ const text = String(id ?? '');
80
+ return GUID.test(text) || text.length > 14 ? `${text.slice(0, 8)}…` : text;
81
+ };
82
+
83
+ /**
84
+ * What a recorded change is called: the first business key its row has (Number, Code, Sku, Email,
85
+ * Name, Title…), else a short ID. Never a full GUID and never a status. `{ ref, field }`; `field`
86
+ * is the row's own field name when a business key was used.
87
+ */
88
+ export function changeRef(change) {
89
+ const row = lowered(change?.after ?? change?.before);
90
+ for (const field of KEY_FIELDS) {
91
+ const value = human(row[field]);
92
+ if (value) return { ref: value, field };
93
+ }
94
+ const id = Object.values(change?.key ?? {})[0] ?? row.id ?? row._id;
95
+ return { ref: id == null || id === '' ? '' : shortId(id), field: null };
96
+ }
97
+
98
+ /**
99
+ * What to call the record an ID points at, from the changes a run recorded: the business key of the
100
+ * change whose own key is that ID (an order's Number), else of a change that holds it, else a short ID.
101
+ */
102
+ export function refForId(changes, id) {
103
+ if (id == null || id === '') return '';
104
+ const wanted = String(id).toLowerCase();
105
+ const holds = values => Object.values(values && typeof values === 'object' ? values : {}).some(value => String(value).toLowerCase() === wanted);
106
+ const hit = changes.find(change => holds(change.key)) ?? changes.find(change => holds(change.after ?? change.before));
107
+ return (hit ? changeRef(hit).ref : '') || shortId(id);
108
+ }
109
+
110
+ /**
111
+ * One or two telling facts about a change, never the field used as its name: the status ("Pending"),
112
+ * the SKU, a quantity. `{ kind: 'text', value }` or `{ kind: 'units', n }`, for the caller to word.
113
+ */
114
+ export function changeFacts(change, usedField = null) {
115
+ const row = lowered(change?.after ?? change?.before);
116
+ const facts = [];
117
+ const status = human(row.status);
118
+ if (status) facts.push({ kind: 'text', value: status.charAt(0).toUpperCase() + status.slice(1) });
119
+ const sku = human(row.sku);
120
+ if (sku && usedField !== 'sku') facts.push({ kind: 'text', value: sku });
121
+ const quantity = row.quantity ?? row.qty ?? row.units;
122
+ if (typeof quantity === 'number' && Number.isFinite(quantity)) facts.push({ kind: 'units', n: quantity });
123
+ return facts.slice(0, 2);
124
+ }
125
+
126
+ /**
127
+ * Where the changes beyond the first few went, grouped for one line: the tables (SQL and item
128
+ * stores), a count of collections per other store, emails and other effects. Items are
129
+ * `{ store, target }`; an email effect has `store: 'effect'` and `target: 'email'`.
130
+ */
131
+ export function moreIn(items) {
132
+ const tables = new Set();
133
+ const collections = new Map();
134
+ let emails = 0, effects = 0;
135
+ for (const item of items) {
136
+ if (item.store === 'effect') { if (item.target === 'email') emails++; else effects++; continue; }
137
+ const kind = storeKind(item.store);
138
+ if (kind === 'sql' || kind === 'item') tables.add(String(item.target ?? ''));
139
+ else {
140
+ if (!collections.has(item.store)) collections.set(item.store, new Set());
141
+ collections.get(item.store).add(String(item.target ?? ''));
142
+ }
143
+ }
144
+ return { tables: [...tables], stores: [...collections].map(([system, set]) => ({ system, count: set.size })), emails, effects };
145
+ }
146
+
147
+ /** Whether a held or sent step left nothing: no changes and no effects (it only read). */
148
+ export const readsOnly = held => !held.stores.length && !held.emails && !held.effects;
149
+
150
+ /** The roles a persona entry names: `roles` (a list) or `role` (one), as the personas source sends them. */
151
+ export const personaRoles = user => (Array.isArray(user?.roles) ? user.roles : user?.role ? [user.role] : []).map(String).filter(Boolean);
152
+
153
+ /**
154
+ * Which of a journey's steps a persona may call, when the OpenAPI document says so: an operation's
155
+ * security alternatives name the roles (scopes) that may call it, so a step is allowed when the
156
+ * operation needs no role or one alternative's roles are all the persona's. Resolves to
157
+ * `{ allowed: boolean[], refused: number[] }`, or null when it can't be known (the persona has no
158
+ * known role, or no step's operation names a role), so callers show nothing rather than guess.
159
+ */
160
+ export function stepAccess(journey, roles, document) {
161
+ const mine = new Set((roles ?? []).map(role => String(role).toLowerCase()));
162
+ if (!mine.size) return null;
163
+ let known = false;
164
+ const allowed = (journey?.steps ?? []).map(step => {
165
+ const alternatives = step.op ? securityRequirements(step.op, document).map(alternative => alternative.flatMap(item => item.scopes)) : [];
166
+ if (!alternatives.length || alternatives.some(scopes => !scopes.length)) return true;
167
+ known = true;
168
+ return alternatives.some(scopes => scopes.every(scope => mine.has(String(scope).toLowerCase())));
169
+ });
170
+ if (!known) return null;
171
+ return { allowed, refused: allowed.flatMap((ok, index) => ok ? [] : [index]) };
172
+ }
@@ -0,0 +1,301 @@
1
+ // The five questions and notices of Journeys mode, each a dialog (dialog.js; mocks v8, screens
2
+ // 160–167, m43–m45) built from the real run and the journey's expectations. The workbench never
3
+ // opens a native browser dialog. Each function resolves like openDialog: the chosen value, or null
4
+ // when the person dismissed it (Esc, the close button, a swipe). The numbers come from
5
+ // journeys-dialog-model.js; nothing here is invented, and a line the data can't support is left out.
6
+ import { dialogEnv, dialogHint, dialogLabel, dialogList, dialogMark, dialogNote, dialogOffer, dialogRow, ltr, openDialog } from './dialog.js';
7
+ import { esc, icon } from './components.js';
8
+ import { formatCommaList, formatDuration, formatList, formatNumber, formatShortDateTime, formatTime, formatUnit, has, t, th } from './i18n.js';
9
+ import { dataStores, recordCount, sqlSystem, storeMark, storeName } from './stores.js';
10
+ import { heldBy, moreIn, personaRoles, readsOnly, sendTargets, shortId, stepAccess } from './journeys-dialog-model.js';
11
+ import { initials } from './view.js';
12
+ import { storeBusy } from './journeys-session.js';
13
+
14
+ /** The name a step goes by on screen: its operation's title, else its description, else its ID. */
15
+ const stepTitle = step => step.op?.title || step.def?.description || step.stepId;
16
+
17
+ const databaseOf = capabilities => typeof capabilities?.database === 'string' ? capabilities.database : capabilities?.database?.name;
18
+ const ran = run => (run?.steps ?? []).flatMap((step, index) => ['pending', 'skipped'].includes(step.status) ? [] : [index]);
19
+
20
+ /** Step numbers (from 1) as people say them: "1 and 2", "1 to 3 and 5". Three or more in a row are a range. */
21
+ export function stepList(indexes) {
22
+ const groups = [];
23
+ for (const index of [...indexes].sort((a, b) => a - b)) {
24
+ const last = groups.at(-1);
25
+ if (last && index === last.at(-1) + 1) last.push(index); else groups.push([index]);
26
+ }
27
+ return formatList(groups.flatMap(group => group.length >= 3
28
+ ? [t('dlg.range', { from: formatNumber(group[0] + 1), to: formatNumber(group.at(-1) + 1) })]
29
+ : group.map(index => formatNumber(index + 1))));
30
+ }
31
+
32
+ /** A length of time in words, in the largest sensible unit: "12 seconds", "2 minutes". */
33
+ export function spanText(ms) {
34
+ return ms < 60_000 ? formatUnit(Math.max(1, Math.round(ms / 1000)), 'second', 0, 'long') : formatUnit(Math.round(ms / 60_000), 'minute', 0, 'long');
35
+ }
36
+
37
+ const cancel = () => ({ label: t('dlg.cancel'), value: false });
38
+
39
+ /* ---------- Send a run for real ---------- */
40
+
41
+ function targetRow(target) {
42
+ if (target.system === 'email') {
43
+ const to = target.recipients.length && target.recipients.length <= 2 ? formatList(target.recipients.map(ltr)) : '';
44
+ return dialogRow({ mark: dialogMark('mail'), name: t('dlg.email'), sub: to ? th('dlg.email.to', { n: target.emails, to }) : esc(t('dlg.email.sent', { n: target.emails })) });
45
+ }
46
+ if (target.system === 'effect') return dialogRow({ mark: dialogMark('send'), name: target.effect, sub: esc(t('dlg.effect.sent', { n: target.count })) });
47
+ const count = recordCount(target.system, target.records);
48
+ let sub = esc(count);
49
+ if (target.places.length) {
50
+ const shown = target.places.slice(0, 3);
51
+ const more = target.places.length - shown.length;
52
+ const noun = target.kind === 'sql' || target.kind === 'item' ? 'table' : 'collection';
53
+ const places = formatList(shown.map(esc));
54
+ sub = more > 0 ? th(`dlg.store.inMore.${noun}`, { count: esc(count), places, n: more }) : th('dlg.store.in', { count: esc(count), places });
55
+ }
56
+ return dialogRow({ mark: storeMark(target.system, 16), name: storeName(target.system), code: target.database ?? '', sub });
57
+ }
58
+
59
+ /**
60
+ * Starting a Send run: the environment and database, a row per store the journey's expectations
61
+ * write to, and the reminder that a Preview run rolls back. Resolves true to send.
62
+ */
63
+ export function confirmSendRun({ journey, capabilities, inputs, preview }) {
64
+ const targets = sendTargets(journey, capabilities, { inputs });
65
+ const content = [
66
+ targets.length ? dialogLabel(t('dlg.sendrun.kept'), dialogEnv(capabilities?.environment, databaseOf(capabilities))) + dialogList(targets.map(targetRow))
67
+ : dialogHint('info', t('dlg.sendrun.unknown')),
68
+ preview ? dialogHint('flask', t('dlg.sendrun.hint')) : '',
69
+ ].join('');
70
+ return openDialog({
71
+ tone: 'warn', glyph: 'send', title: esc(t('dlg.sendrun.title')),
72
+ body: esc(t('dlg.sendrun.body', { name: journey.name, n: journey.steps.length })), content,
73
+ actions: [cancel(), { label: t('dlg.sendrun.go'), kind: 'primary', value: true, icon: 'send', shortcut: 'send' }],
74
+ });
75
+ }
76
+
77
+ /* ---------- End a Preview run partway ---------- */
78
+
79
+ /**
80
+ * What a step's envelope wrote, in words: "7 rows, 3 documents, 1 email", or "reads only". Other
81
+ * effects (a webhook, a message) are named only when nothing else was written, so the line stays short.
82
+ */
83
+ export function heldText(envelope, sqlStore) {
84
+ const held = heldBy(envelope, sqlStore);
85
+ if (readsOnly(held)) return t('dlg.readsOnly');
86
+ const parts = [...held.stores.map(item => recordCount(item.system, item.count)), ...(held.emails ? [t('dlg.held.emails', { n: held.emails })] : [])];
87
+ if (!parts.length) parts.push(...held.kinds.map(item => item.kind ? t('dlg.held.effect', { n: formatNumber(item.count), kind: item.kind }) : t('dlg.held.effects', { n: item.count })));
88
+ return formatCommaList(parts);
89
+ }
90
+
91
+ /** The End run body: the step, both steps, or all N steps (a language with its own dual still gets "both" here). */
92
+ export const endRunBody = n => t(n === 2 ? 'dlg.endrun.bodyTwo' : 'dlg.endrun.body', { n });
93
+
94
+ /**
95
+ * Ending a Preview run that has run steps: the held session rolls them all back. One row per step
96
+ * run, with its status, time and what it held. Resolves true to end the run.
97
+ */
98
+ export function confirmEndRun({ journey, run, envelopes = [], heldMs, capabilities }) {
99
+ const indexes = ran(run);
100
+ const rows = indexes.map(index => {
101
+ const step = run.steps[index];
102
+ const good = ['passed'].includes(step.status);
103
+ const status = step.httpStatus != null ? `${ltr(step.httpStatus)} · ` : '';
104
+ return dialogRow({
105
+ mark: good ? dialogMark('check', 'ok') : dialogMark('x', 'danger'), name: stepTitle(journey.steps[index]),
106
+ sub: `${status}${esc(formatDuration(step.durationMs ?? 0))} · ${esc(heldText(envelopes[index], sqlSystem(capabilities)))}`,
107
+ });
108
+ });
109
+ return openDialog({
110
+ tone: 'neutral', glyph: 'flask', title: esc(t('dlg.endrun.title')),
111
+ body: esc(endRunBody(indexes.length)), content: dialogList(rows),
112
+ foot: heldMs != null ? dialogNote('clock', t('dlg.endrun.held', { time: spanText(heldMs) })) : '',
113
+ actions: [{ label: t('dlg.endrun.keep'), value: false }, { label: t('dlg.endrun.end'), kind: 'primary', value: true }],
114
+ });
115
+ }
116
+
117
+ /* ---------- Stop a Send run partway ---------- */
118
+
119
+ const MAX_LEFT = 4;
120
+
121
+ /** A fact about a change in words: "Pending", "NPK-JKT-BLK-M", "2 units". */
122
+ export const factText = fact => fact.kind === 'units' ? t('dlg.units', { n: formatNumber(fact.n) }) : String(fact.value);
123
+
124
+ /**
125
+ * One line of what a Send left behind: the table and the record's business key (or a short ID),
126
+ * then "Inserted by step 1" and one or two telling facts. `item` comes from the run's recorded
127
+ * changes (`ref` and `facts` are worked out when the run is read, see journeys-dialog-model.js).
128
+ */
129
+ export function leftParts(item) {
130
+ const effect = item.store === 'effect';
131
+ const what = effect ? t('dlg.op.email') : has(`dlg.op.${item.op}`) ? t(`dlg.op.${item.op}`) : String(item.op || t('dlg.op.write'));
132
+ const detail = ['string', 'number'].includes(typeof item.detail) && String(item.detail).length <= 40 ? String(item.detail) : '';
133
+ const facts = effect ? (detail ? [esc(detail)] : []) : (item.facts ?? []).map(fact => esc(factText(fact)));
134
+ return {
135
+ effect, name: effect && item.target === 'email' ? t('dlg.email') : String(item.target ?? ''), code: effect ? '' : item.ref ?? '',
136
+ sub: [esc(t('dlg.stopsend.by', { what, n: formatNumber(item.step) })), ...facts].join(' · '),
137
+ };
138
+ }
139
+
140
+ export function leftRow(item) {
141
+ const { effect, name, code, sub } = leftParts(item);
142
+ return dialogRow({ mark: effect ? dialogMark('mail') : storeMark(item.store, 16), name, code, sub });
143
+ }
144
+
145
+ /** "10 more in Stock, Payments, AuditEvents and 2 MongoDB collections": the rest, on one line. */
146
+ export function moreText(rest) {
147
+ const where = moreIn(rest);
148
+ const tables = where.tables.length > 3 ? [...where.tables.slice(0, 3), t('dlg.stopsend.moreTables', { n: where.tables.length - 3 })] : where.tables;
149
+ const parts = [
150
+ ...tables,
151
+ ...where.stores.map(item => t('dlg.stopsend.moreStore', { n: item.count, store: storeName(item.system) })),
152
+ ...(where.emails ? [t('dlg.held.emails', { n: where.emails })] : []),
153
+ ...(where.effects ? [t('dlg.held.effects', { n: where.effects })] : []),
154
+ ];
155
+ return parts.length ? t('dlg.stopsend.moreIn', { n: formatNumber(rest.length), where: formatList(parts) }) : t('dlg.stopsend.more', { n: rest.length });
156
+ }
157
+
158
+ /** The undo row's line about itself: "Undoes step 1 for AS-2026-004641". */
159
+ export const undoSub = undo => undo.value != null && undo.value !== '' && undo.step
160
+ ? t('dlg.stopsend.undoes', { n: formatNumber(undo.step), ref: undo.ref || shortId(undo.value) })
161
+ : undo.step ? t('dlg.stopsend.undoesStep', { n: formatNumber(undo.step) }) : '';
162
+
163
+ /**
164
+ * Stopping a Send run partway: steps already sent keep what they wrote. Lists what they left and,
165
+ * when the journey's operations include an obvious undo (a cancel, void or refund of what a step
166
+ * created), a row that opens it. Resolves true to stop, 'undo' to stop and open the undo.
167
+ */
168
+ export function confirmStopSend({ journey, run, left, undo, capabilities }) {
169
+ const sent = ran(run);
170
+ const pending = (run?.steps ?? []).flatMap((step, index) => step.status === 'pending' ? [index] : []);
171
+ const shown = left.slice(0, MAX_LEFT);
172
+ const rest = left.length - shown.length;
173
+ const rows = shown.map(item => leftRow(item));
174
+ if (rest > 0) rows.push(dialogRow({ mark: dialogMark('more'), name: moreText(left.slice(MAX_LEFT)) }));
175
+ const offer = undo ? dialogOffer({ value: 'undo', httpMethod: undo.op.method, name: undo.op.title || undo.op.operation?.summary || undo.op.path, sub: undoSub(undo) }) : '';
176
+ const body = `${t('dlg.stopsend.sent', { steps: stepList(sent), n: sent.length })}${pending.length ? ` ${t('dlg.stopsend.skipped', { steps: stepList(pending), n: pending.length })}` : ''}`;
177
+ return openDialog({
178
+ tone: 'danger', glyph: 'stop', title: esc(t('dlg.stopsend.title')), body: esc(body),
179
+ content: dialogLabel(t('dlg.stopsend.left'), dialogEnv(capabilities?.environment, databaseOf(capabilities))) + dialogList(rows) + offer,
180
+ actions: [{ label: t('dlg.stopsend.keep'), value: false }, { label: t('dlg.stopsend.stop'), kind: 'danger', value: true, icon: 'stop' }],
181
+ });
182
+ }
183
+
184
+ /* ---------- Switch persona while a Preview session is held ---------- */
185
+
186
+ const firstName = name => String(name ?? '').trim().split(/\s+/)[0] ?? '';
187
+ const roleText = roles => roles.join(', ');
188
+
189
+ /**
190
+ * Switching persona while a Preview session is held ends it, so the question is who the person
191
+ * becomes. Two cards (the held persona quiet, the next lifted); when the OpenAPI document says
192
+ * which roles may call each step's operation, each card also shows one segment per step and the
193
+ * steps the new persona would be refused are named. Without that, nothing is guessed.
194
+ * `from` is the signed-in `{ name, role }`; `to` is the personas entry `{ name, role | roles }`;
195
+ * `held` is how many steps the session holds. Resolves true to switch and end the run.
196
+ */
197
+ export function confirmPersonaSwitch({ journey, from, to, held, document }) {
198
+ const fromRoles = personaRoles(from);
199
+ const toRoles = personaRoles(to);
200
+ const fromAccess = stepAccess(journey, fromRoles, document);
201
+ const toAccess = stepAccess(journey, toRoles, document);
202
+ const showBars = !!(fromAccess && toAccess);
203
+ const steps = journey.steps.map(stepTitle);
204
+ const bar = access => {
205
+ const total = steps.length;
206
+ const ok = total - access.refused.length;
207
+ const segments = steps.map((title, index) => `<span class="dl-seg${access.refused.includes(index) ? ' is-no' : ''}" title="${esc(t(access.refused.includes(index) ? 'dlg.persona.segRefused' : 'dlg.persona.seg', { n: formatNumber(index + 1), step: title }))}"></span>`).join('');
208
+ return `<span class="dl-pc-access"><span class="dl-steps" role="img" aria-label="${esc(t('dlg.persona.access', { ok: formatNumber(ok), total: formatNumber(total), n: total }))}">${segments}</span><span class="dl-pc-count">${esc(t('dlg.persona.count', { ok: formatNumber(ok), total: formatNumber(total) }))}</span></span>`;
209
+ };
210
+ const card = ({ person, roles, alt, now, access }) => `<div class="dl-pc ${now ? 'is-now' : 'is-next'}">
211
+ <span class="dl-pc-tag">${now ? `${icon('flask', true)}${esc(t('dlg.persona.held'))}` : esc(t('dlg.persona.next'))}</span>
212
+ <span class="dl-pc-who"><span class="avatar dl-av${alt ? ' is-alt' : ''}" aria-hidden="true">${esc(initials(person.name))}</span>
213
+ <span class="dl-text"><span class="dl-name" title="${esc(person.name)}">${esc(person.name)}</span>${roles.length ? `<span class="dl-sub"><span class="dl-role">${esc(roleText(roles))}</span></span>` : ''}</span></span>
214
+ ${showBars ? bar(access) : ''}
215
+ </div>`;
216
+ const refused = toAccess?.refused ?? [];
217
+ const refusedRow = refused.length ? dialogList([dialogRow({
218
+ mark: dialogMark('lock', 'warn'), name: t('dlg.persona.refused', { n: refused.length }),
219
+ sub: esc(t('dlg.persona.refusedSub', { n: refused.length, steps: formatList(refused.map(index => steps[index])), role: roleText(toRoles) })),
220
+ })]) : '';
221
+ const stay = from?.name ? t('dlg.persona.stay', { name: firstName(from.name) }) : t('dlg.persona.stayAnon');
222
+ return openDialog({
223
+ tone: 'neutral', glyph: 'user',
224
+ head: `<span class="dl-pair" aria-hidden="true"><span class="avatar dl-av is-alt">${esc(initials(to.name))}</span><span class="dl-pair-badge">${icon('refresh')}</span></span>`,
225
+ title: esc(t('dlg.persona.title', { name: to.name })),
226
+ body: esc(from?.name ? t('dlg.persona.body', { from: from.name, n: held }) : t('dlg.persona.bodyAnon', { n: held })),
227
+ content: `<div class="dl-people">${card({ person: from ?? { name: '' }, roles: fromRoles, now: true, access: fromAccess })}<span class="dl-hop" aria-hidden="true">${icon('arrow-right', true)}</span>${card({ person: to, roles: toRoles, alt: true, access: toAccess })}</div>${refusedRow}`,
228
+ foot: dialogNote('undo', t('dlg.persona.foot', { n: held })),
229
+ actions: [{ label: stay, value: false }, { label: t('dlg.persona.switch'), kind: 'primary', value: true }],
230
+ });
231
+ }
232
+
233
+ /* ---------- The Preview session ended on its own ---------- */
234
+
235
+ /**
236
+ * The stores a Preview session rolls back, each by its kind and, where it has one, its name, as
237
+ * trusted HTML for a list: "SQLite store.db" and "MongoDB store".
238
+ */
239
+ export function sessionStores(capabilities) {
240
+ const database = databaseOf(capabilities);
241
+ const sql = sqlSystem(capabilities);
242
+ return [`${esc(storeName(sql))}${database ? ` ${ltr(database)}` : ''}`,
243
+ ...dataStores(capabilities).filter(store => store.mode === 'preview' && store.system !== sql)
244
+ .map(store => `${esc(storeName(store.system))}${store.name && store.name !== storeName(store.system) ? ` ${ltr(store.name)}` : ''}`)];
245
+ }
246
+
247
+ /**
248
+ * A Preview session couldn't open because another one holds the SQL store (`store_busy`): another
249
+ * tab's, or one a closed tab left behind. It ends by itself after `idleSeconds` (the problem says
250
+ * how long). Resolves true to try again.
251
+ */
252
+ export function confirmStoreBusy({ capabilities, idleSeconds }) {
253
+ const system = sqlSystem(capabilities);
254
+ const database = databaseOf(capabilities);
255
+ const store = database || storeName(system);
256
+ return openDialog({
257
+ tone: 'warn', glyph: 'db', title: esc(t('dlg.busy.title', { store })),
258
+ body: esc(idleSeconds > 0 ? t('dlg.busy.body', { time: spanText(idleSeconds * 1000) }) : t('dlg.busy.bodyNoTime')),
259
+ content: dialogList([dialogRow({ mark: storeMark(system, 16), name: storeName(system), code: database ?? '', sub: esc(t('dlg.busy.held')) })]),
260
+ actions: [{ label: t('dlg.close'), value: false }, { label: t('dlg.busy.again'), kind: 'primary', value: true, icon: 'refresh', focus: true }],
261
+ });
262
+ }
263
+
264
+ /**
265
+ * A Preview session couldn't open for any other reason: the problem's title and, when it has one,
266
+ * its detail. Resolves true to try again.
267
+ */
268
+ export function confirmOpenFailed({ title, detail }) {
269
+ return openDialog({
270
+ tone: 'warn', glyph: 'alert', title: esc(t('dlg.openfail.title')), body: esc(title),
271
+ content: detail && detail !== title ? dialogHint('alert', detail) : '',
272
+ actions: [{ label: t('dlg.close'), value: false }, { label: t('dlg.busy.again'), kind: 'primary', value: true, icon: 'refresh', focus: true }],
273
+ });
274
+ }
275
+
276
+ /** The dialog for a refused or failed session open: the busy store's, else the problem's own title and detail. */
277
+ export function confirmSessionOpenFailed({ error, capabilities }) {
278
+ if (storeBusy(error)) return confirmStoreBusy({ capabilities, idleSeconds: error.idleSeconds });
279
+ return confirmOpenFailed({ title: error?.title || error?.message || '', detail: error?.detail });
280
+ }
281
+
282
+ /**
283
+ * The held session was rolled back without the person asking (idle timeout, its maximum lifetime,
284
+ * the host restarting). Says what is safe: steps that had run keep their results, nothing was
285
+ * written. `idleSeconds` and `lastActivity` (ms) are used only when they explain it; an
286
+ * unexplained end says so plainly. Resolves true to start the run again.
287
+ */
288
+ export function confirmSessionEnded({ journey, run, capabilities, idleSeconds, lastActivity, now = Date.now() }) {
289
+ const indexes = ran(run);
290
+ const idle = idleSeconds > 0 && lastActivity != null && now - lastActivity >= idleSeconds * 900;
291
+ const stores = sessionStores(capabilities);
292
+ const rows = [
293
+ ...(indexes.length ? [dialogRow({ mark: dialogMark('check', 'ok'), name: t('dlg.expired.ran', { steps: stepList(indexes), n: indexes.length }), sub: esc(t('dlg.expired.ranSub', { n: indexes.length })) })] : []),
294
+ dialogRow({ mark: dialogMark('undo'), name: idle ? t('dlg.expired.rolledAt', { time: formatTime(lastActivity + idleSeconds * 1000) }) : t('dlg.expired.rolledBy', { time: formatTime(now) }), sub: formatList(stores) }),
295
+ ];
296
+ return openDialog({
297
+ tone: 'warn', glyph: 'clock', title: esc(t('dlg.expired.title')),
298
+ body: esc(idle ? t('dlg.expired.idle', { time: spanText(idleSeconds * 1000) }) : t('dlg.expired.gone')), content: dialogList(rows),
299
+ actions: [{ label: t('dlg.close'), value: false }, { label: t('dlg.expired.again'), kind: 'primary', value: true, icon: 'refresh', focus: true }],
300
+ });
301
+ }