@sendproof/core 0.0.0-stage → 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 (253) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +16 -2
  3. package/assets/action-bar.js +91 -0
  4. package/assets/api.js +240 -0
  5. package/assets/app.css +1459 -0
  6. package/assets/app.js +818 -0
  7. package/assets/autofill.js +137 -0
  8. package/assets/bar-fit.js +91 -0
  9. package/assets/code-copy.js +71 -0
  10. package/assets/code-picker.js +149 -0
  11. package/assets/commands.js +220 -0
  12. package/assets/components.js +77 -0
  13. package/assets/context-bar.js +82 -0
  14. package/assets/copy.js +92 -0
  15. package/assets/coverage-popover.js +35 -0
  16. package/assets/crumb-fit.js +80 -0
  17. package/assets/deprecation.js +164 -0
  18. package/assets/dialog.css +125 -0
  19. package/assets/dialog.js +191 -0
  20. package/assets/display-settings.js +175 -0
  21. package/assets/doc-diff.js +209 -0
  22. package/assets/docs-view.js +347 -0
  23. package/assets/favicon.png +0 -0
  24. package/assets/favicon.svg +1 -0
  25. package/assets/field-help.js +52 -0
  26. package/assets/field-modules.js +23 -0
  27. package/assets/fields/controls.js +179 -0
  28. package/assets/fields/dom.js +36 -0
  29. package/assets/fields/infer.js +71 -0
  30. package/assets/fields/lookup-source.js +66 -0
  31. package/assets/fields/lookup.js +286 -0
  32. package/assets/fields/render.js +496 -0
  33. package/assets/fields/select.js +175 -0
  34. package/assets/fields/validate.js +363 -0
  35. package/assets/fields/validation-formats.js +164 -0
  36. package/assets/fields/validation-references.js +68 -0
  37. package/assets/fields/validation-values.js +137 -0
  38. package/assets/generate-menu.js +44 -0
  39. package/assets/generate.js +184 -0
  40. package/assets/header-editor.js +777 -0
  41. package/assets/headers.js +188 -0
  42. package/assets/highlight.js +257 -0
  43. package/assets/history-popover.js +24 -0
  44. package/assets/i18n.js +264 -0
  45. package/assets/icons.js +105 -0
  46. package/assets/index.html +71 -0
  47. package/assets/issues.js +187 -0
  48. package/assets/journeys/compare.js +225 -0
  49. package/assets/journeys/expressions.js +89 -0
  50. package/assets/journeys/index.js +7 -0
  51. package/assets/journeys/run.js +152 -0
  52. package/assets/journeys/steps.js +163 -0
  53. package/assets/journeys-code.js +193 -0
  54. package/assets/journeys-dialog-model.js +172 -0
  55. package/assets/journeys-dialogs.js +301 -0
  56. package/assets/journeys-model.js +259 -0
  57. package/assets/journeys-runs.js +109 -0
  58. package/assets/journeys-session.js +135 -0
  59. package/assets/journeys-view.js +961 -0
  60. package/assets/journeys.js +962 -0
  61. package/assets/json-view.js +166 -0
  62. package/assets/lang-icons.js +62 -0
  63. package/assets/layout.js +262 -0
  64. package/assets/listbox.js +334 -0
  65. package/assets/locales/ar-capture.js +366 -0
  66. package/assets/locales/ar-journeys.js +468 -0
  67. package/assets/locales/ar-stores.js +116 -0
  68. package/assets/locales/ar.js +563 -0
  69. package/assets/locales/cs-capture.js +442 -0
  70. package/assets/locales/cs-journeys.js +468 -0
  71. package/assets/locales/cs-stores.js +116 -0
  72. package/assets/locales/cs.js +691 -0
  73. package/assets/locales/da-capture.js +347 -0
  74. package/assets/locales/da-journeys.js +465 -0
  75. package/assets/locales/da-stores.js +116 -0
  76. package/assets/locales/da.js +524 -0
  77. package/assets/locales/de-capture.js +347 -0
  78. package/assets/locales/de-journeys.js +465 -0
  79. package/assets/locales/de-stores.js +116 -0
  80. package/assets/locales/de.js +521 -0
  81. package/assets/locales/el-capture.js +347 -0
  82. package/assets/locales/el-journeys.js +465 -0
  83. package/assets/locales/el-stores.js +116 -0
  84. package/assets/locales/el.js +522 -0
  85. package/assets/locales/en-capture.js +349 -0
  86. package/assets/locales/en-journeys.js +467 -0
  87. package/assets/locales/en-stores.js +95 -0
  88. package/assets/locales/en.js +524 -0
  89. package/assets/locales/es-capture.js +353 -0
  90. package/assets/locales/es-journeys.js +467 -0
  91. package/assets/locales/es-stores.js +116 -0
  92. package/assets/locales/es.js +527 -0
  93. package/assets/locales/fa-capture.js +348 -0
  94. package/assets/locales/fa-journeys.js +465 -0
  95. package/assets/locales/fa-stores.js +116 -0
  96. package/assets/locales/fa.js +523 -0
  97. package/assets/locales/fi-capture.js +347 -0
  98. package/assets/locales/fi-journeys.js +465 -0
  99. package/assets/locales/fi-stores.js +116 -0
  100. package/assets/locales/fi.js +525 -0
  101. package/assets/locales/fr-capture.js +353 -0
  102. package/assets/locales/fr-journeys.js +467 -0
  103. package/assets/locales/fr-stores.js +116 -0
  104. package/assets/locales/fr.js +527 -0
  105. package/assets/locales/he-capture.js +358 -0
  106. package/assets/locales/he-journeys.js +468 -0
  107. package/assets/locales/he-stores.js +116 -0
  108. package/assets/locales/he.js +531 -0
  109. package/assets/locales/hi-capture.js +348 -0
  110. package/assets/locales/hi-journeys.js +465 -0
  111. package/assets/locales/hi-stores.js +116 -0
  112. package/assets/locales/hi.js +525 -0
  113. package/assets/locales/id-capture.js +347 -0
  114. package/assets/locales/id-journeys.js +466 -0
  115. package/assets/locales/id-stores.js +116 -0
  116. package/assets/locales/id.js +523 -0
  117. package/assets/locales/it-capture.js +361 -0
  118. package/assets/locales/it-journeys.js +467 -0
  119. package/assets/locales/it-stores.js +116 -0
  120. package/assets/locales/it.js +525 -0
  121. package/assets/locales/ja-capture.js +346 -0
  122. package/assets/locales/ja-journeys.js +466 -0
  123. package/assets/locales/ja-stores.js +116 -0
  124. package/assets/locales/ja.js +523 -0
  125. package/assets/locales/ko-capture.js +346 -0
  126. package/assets/locales/ko-journeys.js +465 -0
  127. package/assets/locales/ko-stores.js +116 -0
  128. package/assets/locales/ko.js +524 -0
  129. package/assets/locales/nb-capture.js +349 -0
  130. package/assets/locales/nb-journeys.js +465 -0
  131. package/assets/locales/nb-stores.js +116 -0
  132. package/assets/locales/nb.js +523 -0
  133. package/assets/locales/nl-capture.js +355 -0
  134. package/assets/locales/nl-journeys.js +465 -0
  135. package/assets/locales/nl-stores.js +116 -0
  136. package/assets/locales/nl.js +522 -0
  137. package/assets/locales/pl-capture.js +432 -0
  138. package/assets/locales/pl-journeys.js +468 -0
  139. package/assets/locales/pl-stores.js +116 -0
  140. package/assets/locales/pl.js +530 -0
  141. package/assets/locales/pt-BR-capture.js +350 -0
  142. package/assets/locales/pt-BR-journeys.js +467 -0
  143. package/assets/locales/pt-BR-stores.js +116 -0
  144. package/assets/locales/pt-BR.js +525 -0
  145. package/assets/locales/pt-PT-capture.js +350 -0
  146. package/assets/locales/pt-PT-journeys.js +467 -0
  147. package/assets/locales/pt-PT-stores.js +116 -0
  148. package/assets/locales/pt-PT.js +525 -0
  149. package/assets/locales/ru-capture.js +437 -0
  150. package/assets/locales/ru-journeys.js +468 -0
  151. package/assets/locales/ru-stores.js +116 -0
  152. package/assets/locales/ru.js +626 -0
  153. package/assets/locales/sv-capture.js +349 -0
  154. package/assets/locales/sv-journeys.js +465 -0
  155. package/assets/locales/sv-stores.js +116 -0
  156. package/assets/locales/sv.js +520 -0
  157. package/assets/locales/th-capture.js +347 -0
  158. package/assets/locales/th-journeys.js +466 -0
  159. package/assets/locales/th-stores.js +116 -0
  160. package/assets/locales/th.js +523 -0
  161. package/assets/locales/tr-capture.js +348 -0
  162. package/assets/locales/tr-journeys.js +468 -0
  163. package/assets/locales/tr-stores.js +116 -0
  164. package/assets/locales/tr.js +523 -0
  165. package/assets/locales/uk-capture.js +442 -0
  166. package/assets/locales/uk-journeys.js +468 -0
  167. package/assets/locales/uk-stores.js +116 -0
  168. package/assets/locales/uk.js +632 -0
  169. package/assets/locales/vi-capture.js +346 -0
  170. package/assets/locales/vi-journeys.js +466 -0
  171. package/assets/locales/vi-stores.js +116 -0
  172. package/assets/locales/vi.js +525 -0
  173. package/assets/locales/zh-Hans-capture.js +347 -0
  174. package/assets/locales/zh-Hans-journeys.js +466 -0
  175. package/assets/locales/zh-Hans-stores.js +116 -0
  176. package/assets/locales/zh-Hans.js +525 -0
  177. package/assets/locales/zh-Hant-capture.js +346 -0
  178. package/assets/locales/zh-Hant-journeys.js +466 -0
  179. package/assets/locales/zh-Hant-stores.js +116 -0
  180. package/assets/locales/zh-Hant.js +524 -0
  181. package/assets/manifest.json +1111 -0
  182. package/assets/markdown.js +64 -0
  183. package/assets/model-view.js +182 -0
  184. package/assets/navigation.js +233 -0
  185. package/assets/operation-header.js +76 -0
  186. package/assets/operations.js +7 -0
  187. package/assets/overview-view.js +63 -0
  188. package/assets/personas.js +59 -0
  189. package/assets/popover.js +71 -0
  190. package/assets/preview-false.js +108 -0
  191. package/assets/request-editor.js +502 -0
  192. package/assets/response-metadata.js +354 -0
  193. package/assets/response-viewer.js +618 -0
  194. package/assets/result-blocked.js +155 -0
  195. package/assets/result-capture.js +25 -0
  196. package/assets/result-database.js +185 -0
  197. package/assets/result-effects.js +176 -0
  198. package/assets/result-headers.js +106 -0
  199. package/assets/result-logs.js +408 -0
  200. package/assets/result-states.js +213 -0
  201. package/assets/results.js +398 -0
  202. package/assets/router.js +142 -0
  203. package/assets/schema-model.js +336 -0
  204. package/assets/schema-tree.js +344 -0
  205. package/assets/schema.js +397 -0
  206. package/assets/security.js +31 -0
  207. package/assets/seeded-menu.js +70 -0
  208. package/assets/settings.js +93 -0
  209. package/assets/shortcuts-sheet.js +75 -0
  210. package/assets/shortcuts.js +196 -0
  211. package/assets/sidebar.js +338 -0
  212. package/assets/signin.js +262 -0
  213. package/assets/snippets.js +530 -0
  214. package/assets/store-marks.js +47 -0
  215. package/assets/stores.js +131 -0
  216. package/assets/styles.css +977 -0
  217. package/assets/toast.js +29 -0
  218. package/assets/toggletip.js +53 -0
  219. package/assets/uuid.js +10 -0
  220. package/assets/vendor/arazzo-runtime-expression.js +136 -0
  221. package/assets/vendor/json-pointer.js +48 -0
  222. package/assets/vendor/jsonpath-rfc9535.js +15 -0
  223. package/assets/view.js +130 -0
  224. package/assets/views.css +660 -0
  225. package/dist/capture.d.ts +77 -0
  226. package/dist/capture.js +265 -0
  227. package/dist/index.d.ts +28 -0
  228. package/dist/index.js +527 -0
  229. package/dist/journey-builder.d.ts +178 -0
  230. package/dist/journey-builder.js +169 -0
  231. package/dist/journeys.d.ts +24 -0
  232. package/dist/journeys.js +157 -0
  233. package/dist/node-http.d.ts +21 -0
  234. package/dist/node-http.js +119 -0
  235. package/dist/paths.d.ts +6 -0
  236. package/dist/paths.js +40 -0
  237. package/dist/secrets.d.ts +16 -0
  238. package/dist/secrets.js +49 -0
  239. package/dist/sessions.d.ts +43 -0
  240. package/dist/sessions.js +145 -0
  241. package/dist/statements.d.ts +87 -0
  242. package/dist/statements.js +347 -0
  243. package/dist/stores/classify-batch-two.d.ts +103 -0
  244. package/dist/stores/classify-batch-two.js +306 -0
  245. package/dist/stores/classify.d.ts +28 -0
  246. package/dist/stores/classify.js +116 -0
  247. package/dist/stores/guard.d.ts +63 -0
  248. package/dist/stores/guard.js +139 -0
  249. package/dist/stores/tables.d.ts +853 -0
  250. package/dist/stores/tables.js +1687 -0
  251. package/dist/types.d.ts +303 -0
  252. package/dist/types.js +1 -0
  253. package/package.json +44 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sendproof contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,17 @@
1
- # Temporary Holding Version
1
+ # @sendproof/core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Protocol and capture shared by the Node framework adapters. Install the framework package for your application. It depends on this package and serves the bundled assets.
4
+
5
+ Use `deliverEffect` where the application sends an email, enqueues work or makes a similar external call. It records the effect and suppresses delivery during Preview. During ordinary Send it invokes the supplied callback and, when the request is observed, records successful delivery.
6
+
7
+ ```js
8
+ import { currentCapture, deliverEffect } from '@sendproof/core';
9
+
10
+ currentCapture()?.log({ level: 'Information', category: 'Items', message: 'Created an item' });
11
+ await deliverEffect({ kind: 'email', description: 'Item created', data: { subject: 'Item created' } },
12
+ () => mailer.send(message));
13
+ ```
14
+
15
+ Logs and database snapshots are request-scoped. Secret names are judged by whole words (`password`, `passwd`, `pwd`, `secret`, `token`, `hash`, `salt`, `credential(s)`, `apikey`, and `key` after `api`, `private`, `secret`, `access`, `signing`, `encryption` or `client`): such SQL parameters, every parameter of a statement whose text names a secret, and secret-named columns and keys in change snapshots are recorded as `[REDACTED]`. `database` must be a display name such as `PostgreSQL`; connection strings, URLs, host:port and paths are rejected. A trace belongs to the identity's `subject`, `scheme` and optional `issuer` within the path base, and its id carries 128 random bits. `endsTransaction`, `mayWrite` and `splitStatements` are the statement classifier the database providers share. See [the TypeScript types](src/types.ts) for option and provider contracts. The provider's `preview(dispatch)` must forward the handler's result only after the enrolled transaction has rolled back, and reject if rollback fails.
16
+
17
+ `npm pack` runs the shared asset packer and includes the generated assets and manifest. Use `npm run build --prefix adapters/node` when working from a checkout.
@@ -0,0 +1,91 @@
1
+ // The action bar under the request (mock: request.js "action bar"): a status line that wraps to
2
+ // two lines rather than truncating, then fixed-width Send and Preview buttons. Safe methods
3
+ // show one primary Send and say why there is no Preview instead of disabling it.
4
+ import { esc, icon } from './components.js';
5
+ import { t, th } from './i18n.js';
6
+ import { shortcutAttrs, shortcutHint, shortcutLong, shortcutLabel } from './shortcuts.js';
7
+ import { storeMark, storeNames } from './stores.js';
8
+
9
+ const SAFE = new Set(['GET', 'HEAD', 'OPTIONS']);
10
+
11
+ /** True for methods that can't change anything, so Preview has nothing to roll back. */
12
+ export const isReadOnly = op => SAFE.has(op?.method);
13
+
14
+ /**
15
+ * The default status line for an operation. `unavailable` is its previewUnavailable entry (an API
16
+ * author marked it preview: false); `blocked` is set when its last Preview was stopped by the
17
+ * write guard, and names the store.
18
+ */
19
+ export function idleStatus(op, previewAvailable, { unavailable, blocked } = {}) {
20
+ if (blocked) return `<span class="status is-blocked">${icon('ban', true)}<span>${esc(t('bar.lastBlocked', { store: blocked }))}</span></span>`;
21
+ if (unavailable) return `<span class="status">${icon('send', true)}<span>${esc(t('bar.sendOnly'))}</span></span>`;
22
+ if (isReadOnly(op)) return `<span class="status">${icon('eye', true)}<span>${esc(t('bar.readOnly', { method: op.method }))}</span></span>`;
23
+ if (!previewAvailable) return `<span class="status">${icon('info', true)}<span>${esc(t('bar.noPreview'))}</span></span>`;
24
+ return `<span class="status">${icon('undo', true)}<span>${esc(t('bar.rule'))}</span></span>`;
25
+ }
26
+
27
+ /**
28
+ * Send and Preview. Preview only exists when the operation can be previewed and isn't read-only.
29
+ * An operation marked preview: false keeps a disabled Preview in its place (no layout shift
30
+ * between operations), described by the reason docked above the bar; Send becomes primary.
31
+ */
32
+ export function runButtons(op, previewAvailable, { unavailable } = {}) {
33
+ const readOnly = isReadOnly(op);
34
+ if (unavailable && !readOnly) {
35
+ return `<button type="button" class="btn btn-run btn-send btn-primary" id="send-btn" data-action="send" ${shortcutAttrs('send')} title="${esc(t('bar.sendTip') + ' · ' + shortcutLong('send'))}">${icon('send', true)}<span>${esc(t('bar.send'))}</span>${shortcutHint('send')}</button>`
36
+ + `<button type="button" class="btn btn-run btn-preview is-unavailable" data-action="preview" aria-disabled="true" aria-describedby="preview-dock-title" title="${esc(t('bar.previewOffTip'))}">${icon('flask-off', true)}<span>${esc(t('bar.preview'))}</span></button>`;
37
+ }
38
+ const sendShortcut = readOnly ? 'send-read-only' : 'send';
39
+ const send = `<button type="button" class="btn btn-run btn-send${readOnly || !previewAvailable ? ' btn-primary' : ''}" id="send-btn" data-action="send" ${shortcutAttrs(sendShortcut)} title="${esc(t(readOnly ? 'bar.sendTipReadOnly' : 'bar.sendTip') + ' · ' + shortcutLong(sendShortcut))}">${icon('send', true)}<span>${esc(t('bar.send'))}</span>${shortcutHint(sendShortcut)}</button>`;
40
+ const preview = readOnly || !previewAvailable ? ''
41
+ : `<button type="button" class="btn btn-primary btn-run btn-preview" data-action="preview" ${shortcutAttrs('preview')} title="${esc(shortcutLabel('preview') + ' · ' + shortcutLong('preview'))}">${icon('flask', true)}<span>${esc(t('bar.preview'))}</span>${shortcutHint('preview')}</button>`;
42
+ return send + preview;
43
+ }
44
+
45
+ /** The whole bar for an idle operation. `options` as for idleStatus. */
46
+ export const actionBar = (op, previewAvailable, options = {}) =>
47
+ op ? idleStatus(op, previewAvailable, options) + runButtons(op, previewAvailable, options) : '';
48
+
49
+ /**
50
+ * The reason a marked operation can't Preview, docked right above the action bar with a caret to
51
+ * the disabled Preview button (mocks 122, 128, 130, m29): the store's mark, "Preview unavailable",
52
+ * the author's reason (their words, in English, so lang="en"), why, and who marked it. It takes
53
+ * layout space, so it never covers the form. On a phone "Why?" opens the explanation.
54
+ */
55
+ export function previewDock(entry) {
56
+ if (!entry) return '';
57
+ const store = entry.stores[0];
58
+ const why = entry.stores.length ? t('dock.why', { stores: storeNames(entry.stores) }) : t('dock.whyNoStore');
59
+ return `<span class="pv-tile">${store ? storeMark(store, 20) : icon('flask-off')}</span>
60
+ <div class="pv-text">
61
+ <p class="pv-title"><strong id="preview-dock-title">${esc(t('dock.title'))}</strong>${entry.reason ? `<span class="pv-reason" lang="en">${esc(entry.reason)}</span>` : ''}</p>
62
+ <p class="pv-sub"><span class="pv-why" id="preview-dock-why">${esc(why)} </span><span class="pv-by">${th('dock.by', { mark: '<code class="ltr">preview: false</code>' })}</span>
63
+ <button type="button" class="pv-more" data-action="dock-why" aria-expanded="false" aria-controls="preview-dock-why">${esc(t('dock.more'))}</button></p>
64
+ </div>
65
+ <span class="pv-caret" aria-hidden="true"></span>`;
66
+ }
67
+
68
+ /** The status while a request runs: who it runs as, and that editing stays possible. */
69
+ export function runningStatus(preview, identity) {
70
+ const key = preview ? (identity ? 'bar.previewingAs' : 'bar.previewing') : (identity ? 'bar.sendingAs' : 'bar.sending');
71
+ return `<span class="spinner" aria-hidden="true"></span><span>${esc(t(key, { name: identity }))}</span>`;
72
+ }
73
+
74
+ /** The status after generated values were filled in, with Undo. */
75
+ export function generatedStatus(count) {
76
+ return `<span class="status is-ok" role="status">${icon('wand', true)}<span>${esc(t('bar.filled', { n: count }))}</span><button type="button" class="btn btn-ghost btn-xs" data-action="undo-fill" ${shortcutAttrs('autofill-undo')}>${esc(t('bar.undo'))} ${shortcutHint('autofill-undo')}</button></span>`;
77
+ }
78
+
79
+ /**
80
+ * The confirmation that replaces the buttons before a committing Send. Cancel and Confirm send sit
81
+ * in one pair that is at least as wide as Send + Preview, so the status keeps its room, and that
82
+ * grows to fit a long translation instead of clipping it (see .run-pair in app.css).
83
+ */
84
+ export function confirmation(method, path, stores = []) {
85
+ const text = stores.length ? t('bar.confirmStores', { stores: storeNames(stores) }) : t('bar.confirm', { method, path });
86
+ return `<span class="status${stores.length ? ' is-confirm-store' : ''}" role="status">${stores.length ? icon('warn', true) : ''}<span>${esc(text)}</span></span>
87
+ <span class="run-pair">
88
+ <button type="button" class="btn btn-run btn-ghost" data-action="cancel-confirm" ${shortcutAttrs('escape')}>${esc(t('bar.cancel'))} ${shortcutHint('escape')}</button>
89
+ <button type="button" class="btn btn-run btn-primary" data-action="confirm-send" ${shortcutAttrs('send')}>${icon('send', true)}<span>${esc(t('bar.confirmSend'))}</span>${shortcutHint('send')}</button>
90
+ </span>`;
91
+ }
package/assets/api.js ADDED
@@ -0,0 +1,240 @@
1
+ import { blockedPreview } from './stores.js';
2
+
3
+ const methods = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace'];
4
+
5
+ /** Resolve a local OpenAPI Reference Object without requesting external documents. */
6
+ export function dereference(value, document) {
7
+ if (!value?.$ref?.startsWith('#/')) return value;
8
+ const parts = value.$ref.slice(2).split('/');
9
+ return parts.reduce((node, part) => {
10
+ const key = part.replace(/~1/g, '/').replace(/~0/g, '~');
11
+ return node && Object.hasOwn(node, key) ? node[key] : undefined;
12
+ }, document);
13
+ }
14
+
15
+ /** Operation parameters override path-level parameters with the same name and location. */
16
+ export function operations(document) {
17
+ const discovered = [];
18
+ for (const [path, rawItem] of Object.entries(document.paths || {})) {
19
+ const item = dereference(rawItem, document);
20
+ for (const verb of methods) {
21
+ const operation = item?.[verb];
22
+ if (!operation) continue;
23
+ const parameters = new Map();
24
+ for (const raw of [...(item.parameters || []), ...(operation.parameters || [])]) {
25
+ const parameter = dereference(raw, document);
26
+ if (parameter) parameters.set(parameter.in + ':' + parameter.name, parameter);
27
+ }
28
+ const method = verb.toUpperCase();
29
+ discovered.push({
30
+ method, path, operation, parameters: [...parameters.values()],
31
+ title: operation.summary || operation.operationId || method + ' ' + path,
32
+ group: operation.tags?.[0] || 'Operations',
33
+ });
34
+ }
35
+ }
36
+ return discovered;
37
+ }
38
+
39
+ /**
40
+ * Prepare the browser body and its matching media type together. The caller
41
+ * passes the same mutable headers object to makeRequest. For multipart bodies
42
+ * fetch supplies the boundary and Content-Type itself.
43
+ */
44
+ export function encodeRequestBody(value, mediaType = 'application/json', headers = {}) {
45
+ if (value === undefined) return undefined;
46
+ const type = mediaType.split(';')[0].trim().toLowerCase();
47
+ const multipart = type === 'multipart/form-data';
48
+ if (headers instanceof Headers) {
49
+ headers.delete('Content-Type');
50
+ if (!multipart) headers.set('Content-Type', mediaType);
51
+ } else {
52
+ for (const key of Object.keys(headers)) {
53
+ if (key.toLowerCase() === 'content-type') delete headers[key];
54
+ }
55
+ if (!multipart) headers['Content-Type'] = mediaType;
56
+ }
57
+ if (type === 'application/json' || type.endsWith('+json')) return JSON.stringify(value);
58
+ if (multipart || type === 'application/x-www-form-urlencoded') {
59
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
60
+ throw new Error('Form-encoded requests require named fields.');
61
+ }
62
+ const data = multipart ? new FormData() : new URLSearchParams();
63
+ for (const [name, field] of Object.entries(value)) {
64
+ for (const item of Array.isArray(field) ? field : [field]) {
65
+ if (item === undefined) continue;
66
+ if (item instanceof Blob) {
67
+ if (!multipart) throw new Error('File uploads require multipart/form-data.');
68
+ data.append(name, item);
69
+ } else {
70
+ data.append(name, item !== null && typeof item === 'object' ? JSON.stringify(item) : String(item ?? ''));
71
+ }
72
+ }
73
+ }
74
+ return data;
75
+ }
76
+ if (value instanceof Blob || typeof value === 'string') return value;
77
+ throw new Error('Supply text or a file for ' + mediaType + '.');
78
+ }
79
+
80
+ function scalarParts(value, explode) {
81
+ if (Array.isArray(value)) return value.map(String);
82
+ if (typeof value === 'object') {
83
+ return Object.entries(value).flatMap(([key, item]) => explode ? [key + '=' + item] : [key, String(item)]);
84
+ }
85
+ return [String(value)];
86
+ }
87
+
88
+ function addQuery(query, parameter) {
89
+ const { name, value, style = 'form', explode = style === 'form' } = parameter;
90
+ if (!Array.isArray(value) && typeof value === 'object' && (explode || style === 'deepObject')) {
91
+ for (const [key, item] of Object.entries(value)) {
92
+ query.append(style === 'deepObject' ? name + '[' + key + ']' : key, String(item));
93
+ }
94
+ } else if (Array.isArray(value) && explode) {
95
+ for (const item of value) query.append(name, String(item));
96
+ } else {
97
+ const separator = { spaceDelimited: ' ', pipeDelimited: '|' }[style] ?? ',';
98
+ query.append(name, scalarParts(value, false).join(separator));
99
+ }
100
+ }
101
+
102
+ function pathParameter({ name, value, style = 'simple', explode = false }) {
103
+ const isObject = typeof value === 'object' && !Array.isArray(value);
104
+ const parts = isObject && explode
105
+ ? Object.entries(value).map(([key, item]) => encodeURIComponent(key) + '=' + encodeURIComponent(item))
106
+ : scalarParts(value, false).map(encodeURIComponent);
107
+ if (style === 'label') return '.' + parts.join(explode ? '.' : ',');
108
+ if (style === 'matrix') {
109
+ if (explode && isObject) return ';' + parts.join(';');
110
+ const prefix = ';' + encodeURIComponent(name) + '=';
111
+ return prefix + parts.join(explode ? prefix : ',');
112
+ }
113
+ return parts.join(',');
114
+ }
115
+
116
+ /** Construct a same-origin request relative to the mounted application's PathBase. */
117
+ export function makeRequest(op, parameters, body, extraHeaders, basePath) {
118
+ let path = op.path;
119
+ const query = new URLSearchParams();
120
+ const headers = new Headers(extraHeaders);
121
+ for (const parameter of parameters) {
122
+ const { name, value } = parameter;
123
+ if (value === undefined || value === null || value === '') {
124
+ if (parameter.required) throw new Error(name + ' is required');
125
+ continue;
126
+ }
127
+ switch (parameter.in) {
128
+ case 'path': path = path.replace('{' + name + '}', () => pathParameter(parameter)); break;
129
+ case 'query': addQuery(query, parameter); break;
130
+ case 'header': headers.set(name, scalarParts(value, parameter.explode).join(',')); break;
131
+ case 'cookie': throw new Error('Cookie parameter ' + name + ' must be supplied by the browser session.');
132
+ }
133
+ }
134
+ if (/\{[^}]+\}/.test(path)) throw new Error('Complete all path parameters.');
135
+ if (!path.startsWith('/') || path.startsWith('//') || /[\\?#]/.test(path)) {
136
+ throw new Error('The operation must have an application-relative path.');
137
+ }
138
+ const url = new URL(basePath + path.slice(1), location.origin);
139
+ if (url.origin !== location.origin || !url.pathname.startsWith(basePath)) {
140
+ throw new Error('The operation is outside the application path.');
141
+ }
142
+ url.search = query.toString();
143
+ return { method: op.method, url: url.href, headers, body };
144
+ }
145
+
146
+ /** Resolve the same-origin wire request for execution or export, including rollback intent. */
147
+ export function transportRequest(request, preview, basePath, { observedSend = false } = {}) {
148
+ const target = new URL(request.url);
149
+ if (target.origin !== location.origin || !target.pathname.startsWith(basePath)) {
150
+ throw new Error('The request is outside the application path.');
151
+ }
152
+ const headers = new Headers(request.headers);
153
+ let url = target.href;
154
+ if (preview) {
155
+ url = new URL('./_preview/' + target.pathname.slice(basePath.length) + target.search, document.baseURI).href;
156
+ headers.set('Prefer', 'tx=rollback');
157
+ } else if (observedSend) {
158
+ const preferences = (headers.get('Prefer') || '').split(',').map(value => value.trim()).filter(Boolean);
159
+ if (!preferences.some(value => /^trace(?:\s*;|$)/i.test(value))) preferences.push('trace');
160
+ headers.set('Prefer', preferences.join(', '));
161
+ }
162
+ return { ...request, url, headers };
163
+ }
164
+
165
+ export class RequestTransportError extends Error {}
166
+
167
+ async function readTrace(id, signal) {
168
+ if (!/^(?:[a-f\d]{32}|[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12})$/i.test(id || '')) return {};
169
+ try {
170
+ const url = new URL('./_api/traces/' + id, document.baseURI);
171
+ const response = await fetch(url.href, { signal, credentials: 'include', redirect: 'error' });
172
+ if (!response.ok) return {};
173
+ const trace = await response.json();
174
+ if (!trace || typeof trace !== 'object') return {};
175
+ const evidence = { traceId: id };
176
+ for (const name of ['changes', 'effects', 'logs']) {
177
+ if (Array.isArray(trace[name])) evidence[name] = trace[name];
178
+ if (trace[name + 'Truncated'] === true) evidence[name + 'Truncated'] = true;
179
+ }
180
+ if (trace.timing && typeof trace.timing === 'object') evidence.timing = trace.timing;
181
+ return evidence;
182
+ } catch (error) {
183
+ if (signal?.aborted) throw error;
184
+ // The original request may have committed. Optional trace loss never changes its outcome.
185
+ return {};
186
+ }
187
+ }
188
+
189
+ export async function execute(request, preview, basePath, signal, { observedSend = false } = {}) {
190
+ const wireRequest = transportRequest(request, preview, basePath, { observedSend });
191
+ const { url, method, headers, body: payload } = wireRequest;
192
+ const started = performance.now();
193
+ let response, raw;
194
+ try {
195
+ response = await fetch(url, {
196
+ method, headers, body: payload, signal,
197
+ credentials: 'include', redirect: 'error',
198
+ });
199
+ raw = await response.text();
200
+ } catch (error) {
201
+ if (signal?.aborted || error.name === 'AbortError') throw error;
202
+ const failure = new RequestTransportError(error.message, { cause: error });
203
+ failure.wireRequest = wireRequest;
204
+ throw failure;
205
+ }
206
+ let body = raw || null;
207
+ if (raw) {
208
+ try { body = JSON.parse(raw); } catch { /* Keep text responses as received. */ }
209
+ }
210
+ const duration = Math.round(performance.now() - started);
211
+ const byteCount = value => new TextEncoder().encode(value).length;
212
+ const metadata = {
213
+ duration, wireRequest, requestUrl: request.url, requestHeaders: Object.fromEntries(headers),
214
+ serverTiming: response.headers.get('Server-Timing') || undefined,
215
+ };
216
+ if (preview) {
217
+ // The write guard stopped the Preview (spec/data-stores.md): a designed result, not an error.
218
+ // Nothing ran to completion, so there are no captured changes, effects or logs to show.
219
+ const blocked = blockedPreview(response.status, body);
220
+ if (blocked) {
221
+ return {
222
+ status: response.status, headers: Object.fromEntries(response.headers), body, raw, blocked,
223
+ changes: [], effects: [], logs: [], ...metadata, size: byteCount(raw), preview: true,
224
+ };
225
+ }
226
+ if (!response.ok || body?.rolledBack !== true || !Number.isInteger(body.status)) {
227
+ // The problem's `code` (session_not_found, session_failed…) says why, so a run can tell an ended session from a failed step.
228
+ throw Object.assign(new Error('Preview was not acknowledged as rolled back (HTTP ' + response.status + '). ' + (body?.title || '')), { status: response.status, code: typeof body?.code === 'string' ? body.code : undefined });
229
+ }
230
+ const type = Object.entries(body.headers || {}).find(([name]) => name.toLowerCase() === 'content-type')?.[1] || '';
231
+ const content = body.body == null ? '' :
232
+ typeof body.body === 'string' && !/json/i.test(type) ? body.body : JSON.stringify(body.body);
233
+ return { ...body, ...metadata, raw: content, size: byteCount(content), preview: true };
234
+ }
235
+ const trace = observedSend ? await readTrace(response.headers.get('X-Sendproof-Trace'), signal) : {};
236
+ return {
237
+ status: response.status, headers: Object.fromEntries(response.headers), body, raw,
238
+ changes: [], effects: [], logs: [], ...trace, ...metadata, size: byteCount(raw), preview: false,
239
+ };
240
+ }