sendproof-core 0.1.0.alpha.1

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 (229) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE +21 -0
  3. data/README.md +55 -0
  4. data/lib/sendproof/assets.rb +70 -0
  5. data/lib/sendproof/attribution.rb +98 -0
  6. data/lib/sendproof/capture.rb +66 -0
  7. data/lib/sendproof/clock.rb +54 -0
  8. data/lib/sendproof/configuration.rb +241 -0
  9. data/lib/sendproof/data_store.rb +34 -0
  10. data/lib/sendproof/dynamodb/store.rb +183 -0
  11. data/lib/sendproof/dynamodb.rb +17 -0
  12. data/lib/sendproof/elasticsearch/store.rb +24 -0
  13. data/lib/sendproof/elasticsearch.rb +17 -0
  14. data/lib/sendproof/firestore/interceptor.rb +38 -0
  15. data/lib/sendproof/firestore/store.rb +150 -0
  16. data/lib/sendproof/firestore.rb +99 -0
  17. data/lib/sendproof/handler.rb +23 -0
  18. data/lib/sendproof/identity.rb +37 -0
  19. data/lib/sendproof/limits.rb +113 -0
  20. data/lib/sendproof/middleware.rb +68 -0
  21. data/lib/sendproof/mongo/engine.rb +692 -0
  22. data/lib/sendproof/mongo/guarded.rb +100 -0
  23. data/lib/sendproof/mongo/plain.rb +45 -0
  24. data/lib/sendproof/mongo/store.rb +54 -0
  25. data/lib/sendproof/mongo/subscriber.rb +21 -0
  26. data/lib/sendproof/mongo.rb +41 -0
  27. data/lib/sendproof/mongoid/store.rb +58 -0
  28. data/lib/sendproof/mongoid.rb +65 -0
  29. data/lib/sendproof/observed_request.rb +108 -0
  30. data/lib/sendproof/opensearch/store.rb +21 -0
  31. data/lib/sendproof/opensearch.rb +17 -0
  32. data/lib/sendproof/operation_matcher.rb +28 -0
  33. data/lib/sendproof/pool_hooks.rb +80 -0
  34. data/lib/sendproof/preview_request.rb +44 -0
  35. data/lib/sendproof/preview_transport.rb +331 -0
  36. data/lib/sendproof/protocol.rb +81 -0
  37. data/lib/sendproof/provider.rb +83 -0
  38. data/lib/sendproof/recorder.rb +298 -0
  39. data/lib/sendproof/redaction.rb +98 -0
  40. data/lib/sendproof/redis/commands.rb +76 -0
  41. data/lib/sendproof/redis/store.rb +205 -0
  42. data/lib/sendproof/redis.rb +18 -0
  43. data/lib/sendproof/search/middleware.rb +39 -0
  44. data/lib/sendproof/search/store.rb +213 -0
  45. data/lib/sendproof/search.rb +82 -0
  46. data/lib/sendproof/stores/classify.rb +346 -0
  47. data/lib/sendproof/stores/guard.rb +127 -0
  48. data/lib/sendproof/stores/tables.rb +1328 -0
  49. data/lib/sendproof/stores.rb +12 -0
  50. data/lib/sendproof/trace_store.rb +110 -0
  51. data/lib/sendproof/transaction_control.rb +187 -0
  52. data/lib/sendproof/ui/action-bar.js +91 -0
  53. data/lib/sendproof/ui/api.js +239 -0
  54. data/lib/sendproof/ui/app.css +848 -0
  55. data/lib/sendproof/ui/app.js +742 -0
  56. data/lib/sendproof/ui/autofill.js +137 -0
  57. data/lib/sendproof/ui/code-copy.js +71 -0
  58. data/lib/sendproof/ui/code-picker.js +149 -0
  59. data/lib/sendproof/ui/commands.js +197 -0
  60. data/lib/sendproof/ui/components.js +77 -0
  61. data/lib/sendproof/ui/context-bar.js +82 -0
  62. data/lib/sendproof/ui/copy.js +92 -0
  63. data/lib/sendproof/ui/coverage-popover.js +35 -0
  64. data/lib/sendproof/ui/crumb-fit.js +80 -0
  65. data/lib/sendproof/ui/deprecation.js +164 -0
  66. data/lib/sendproof/ui/display-settings.js +175 -0
  67. data/lib/sendproof/ui/doc-diff.js +209 -0
  68. data/lib/sendproof/ui/docs-view.js +347 -0
  69. data/lib/sendproof/ui/favicon.png +0 -0
  70. data/lib/sendproof/ui/favicon.svg +1 -0
  71. data/lib/sendproof/ui/field-help.js +52 -0
  72. data/lib/sendproof/ui/field-modules.js +23 -0
  73. data/lib/sendproof/ui/fields/controls.js +179 -0
  74. data/lib/sendproof/ui/fields/dom.js +36 -0
  75. data/lib/sendproof/ui/fields/infer.js +71 -0
  76. data/lib/sendproof/ui/fields/lookup-source.js +63 -0
  77. data/lib/sendproof/ui/fields/lookup.js +285 -0
  78. data/lib/sendproof/ui/fields/render.js +496 -0
  79. data/lib/sendproof/ui/fields/select.js +175 -0
  80. data/lib/sendproof/ui/fields/validate.js +363 -0
  81. data/lib/sendproof/ui/fields/validation-formats.js +164 -0
  82. data/lib/sendproof/ui/fields/validation-references.js +68 -0
  83. data/lib/sendproof/ui/fields/validation-values.js +137 -0
  84. data/lib/sendproof/ui/generate-menu.js +44 -0
  85. data/lib/sendproof/ui/generate.js +184 -0
  86. data/lib/sendproof/ui/header-editor.js +777 -0
  87. data/lib/sendproof/ui/headers.js +188 -0
  88. data/lib/sendproof/ui/highlight.js +257 -0
  89. data/lib/sendproof/ui/history-popover.js +24 -0
  90. data/lib/sendproof/ui/i18n.js +253 -0
  91. data/lib/sendproof/ui/icons.js +87 -0
  92. data/lib/sendproof/ui/index.html +70 -0
  93. data/lib/sendproof/ui/issues.js +187 -0
  94. data/lib/sendproof/ui/json-view.js +166 -0
  95. data/lib/sendproof/ui/lang-icons.js +62 -0
  96. data/lib/sendproof/ui/layout.js +262 -0
  97. data/lib/sendproof/ui/listbox.js +334 -0
  98. data/lib/sendproof/ui/locales/ar-capture.js +366 -0
  99. data/lib/sendproof/ui/locales/ar-stores.js +116 -0
  100. data/lib/sendproof/ui/locales/ar.js +561 -0
  101. data/lib/sendproof/ui/locales/cs-capture.js +442 -0
  102. data/lib/sendproof/ui/locales/cs-stores.js +116 -0
  103. data/lib/sendproof/ui/locales/cs.js +689 -0
  104. data/lib/sendproof/ui/locales/da-capture.js +347 -0
  105. data/lib/sendproof/ui/locales/da-stores.js +116 -0
  106. data/lib/sendproof/ui/locales/da.js +522 -0
  107. data/lib/sendproof/ui/locales/de-capture.js +347 -0
  108. data/lib/sendproof/ui/locales/de-stores.js +116 -0
  109. data/lib/sendproof/ui/locales/de.js +519 -0
  110. data/lib/sendproof/ui/locales/el-capture.js +347 -0
  111. data/lib/sendproof/ui/locales/el-stores.js +116 -0
  112. data/lib/sendproof/ui/locales/el.js +520 -0
  113. data/lib/sendproof/ui/locales/en-capture.js +349 -0
  114. data/lib/sendproof/ui/locales/en-stores.js +95 -0
  115. data/lib/sendproof/ui/locales/en.js +522 -0
  116. data/lib/sendproof/ui/locales/es-capture.js +353 -0
  117. data/lib/sendproof/ui/locales/es-stores.js +116 -0
  118. data/lib/sendproof/ui/locales/es.js +525 -0
  119. data/lib/sendproof/ui/locales/fa-capture.js +348 -0
  120. data/lib/sendproof/ui/locales/fa-stores.js +116 -0
  121. data/lib/sendproof/ui/locales/fa.js +521 -0
  122. data/lib/sendproof/ui/locales/fi-capture.js +347 -0
  123. data/lib/sendproof/ui/locales/fi-stores.js +116 -0
  124. data/lib/sendproof/ui/locales/fi.js +523 -0
  125. data/lib/sendproof/ui/locales/fr-capture.js +353 -0
  126. data/lib/sendproof/ui/locales/fr-stores.js +116 -0
  127. data/lib/sendproof/ui/locales/fr.js +525 -0
  128. data/lib/sendproof/ui/locales/he-capture.js +358 -0
  129. data/lib/sendproof/ui/locales/he-stores.js +116 -0
  130. data/lib/sendproof/ui/locales/he.js +529 -0
  131. data/lib/sendproof/ui/locales/hi-capture.js +348 -0
  132. data/lib/sendproof/ui/locales/hi-stores.js +116 -0
  133. data/lib/sendproof/ui/locales/hi.js +523 -0
  134. data/lib/sendproof/ui/locales/id-capture.js +347 -0
  135. data/lib/sendproof/ui/locales/id-stores.js +116 -0
  136. data/lib/sendproof/ui/locales/id.js +521 -0
  137. data/lib/sendproof/ui/locales/it-capture.js +361 -0
  138. data/lib/sendproof/ui/locales/it-stores.js +116 -0
  139. data/lib/sendproof/ui/locales/it.js +523 -0
  140. data/lib/sendproof/ui/locales/ja-capture.js +346 -0
  141. data/lib/sendproof/ui/locales/ja-stores.js +116 -0
  142. data/lib/sendproof/ui/locales/ja.js +521 -0
  143. data/lib/sendproof/ui/locales/ko-capture.js +346 -0
  144. data/lib/sendproof/ui/locales/ko-stores.js +116 -0
  145. data/lib/sendproof/ui/locales/ko.js +522 -0
  146. data/lib/sendproof/ui/locales/nb-capture.js +349 -0
  147. data/lib/sendproof/ui/locales/nb-stores.js +116 -0
  148. data/lib/sendproof/ui/locales/nb.js +521 -0
  149. data/lib/sendproof/ui/locales/nl-capture.js +355 -0
  150. data/lib/sendproof/ui/locales/nl-stores.js +116 -0
  151. data/lib/sendproof/ui/locales/nl.js +520 -0
  152. data/lib/sendproof/ui/locales/pl-capture.js +432 -0
  153. data/lib/sendproof/ui/locales/pl-stores.js +116 -0
  154. data/lib/sendproof/ui/locales/pl.js +528 -0
  155. data/lib/sendproof/ui/locales/pt-BR-capture.js +350 -0
  156. data/lib/sendproof/ui/locales/pt-BR-stores.js +116 -0
  157. data/lib/sendproof/ui/locales/pt-BR.js +523 -0
  158. data/lib/sendproof/ui/locales/pt-PT-capture.js +350 -0
  159. data/lib/sendproof/ui/locales/pt-PT-stores.js +116 -0
  160. data/lib/sendproof/ui/locales/pt-PT.js +523 -0
  161. data/lib/sendproof/ui/locales/ru-capture.js +437 -0
  162. data/lib/sendproof/ui/locales/ru-stores.js +116 -0
  163. data/lib/sendproof/ui/locales/ru.js +624 -0
  164. data/lib/sendproof/ui/locales/sv-capture.js +349 -0
  165. data/lib/sendproof/ui/locales/sv-stores.js +116 -0
  166. data/lib/sendproof/ui/locales/sv.js +518 -0
  167. data/lib/sendproof/ui/locales/th-capture.js +347 -0
  168. data/lib/sendproof/ui/locales/th-stores.js +116 -0
  169. data/lib/sendproof/ui/locales/th.js +521 -0
  170. data/lib/sendproof/ui/locales/tr-capture.js +348 -0
  171. data/lib/sendproof/ui/locales/tr-stores.js +116 -0
  172. data/lib/sendproof/ui/locales/tr.js +521 -0
  173. data/lib/sendproof/ui/locales/uk-capture.js +442 -0
  174. data/lib/sendproof/ui/locales/uk-stores.js +116 -0
  175. data/lib/sendproof/ui/locales/uk.js +630 -0
  176. data/lib/sendproof/ui/locales/vi-capture.js +346 -0
  177. data/lib/sendproof/ui/locales/vi-stores.js +116 -0
  178. data/lib/sendproof/ui/locales/vi.js +523 -0
  179. data/lib/sendproof/ui/locales/zh-Hans-capture.js +347 -0
  180. data/lib/sendproof/ui/locales/zh-Hans-stores.js +116 -0
  181. data/lib/sendproof/ui/locales/zh-Hans.js +523 -0
  182. data/lib/sendproof/ui/locales/zh-Hant-capture.js +346 -0
  183. data/lib/sendproof/ui/locales/zh-Hant-stores.js +116 -0
  184. data/lib/sendproof/ui/locales/zh-Hant.js +522 -0
  185. data/lib/sendproof/ui/manifest.json +866 -0
  186. data/lib/sendproof/ui/markdown.js +39 -0
  187. data/lib/sendproof/ui/model-view.js +182 -0
  188. data/lib/sendproof/ui/navigation.js +233 -0
  189. data/lib/sendproof/ui/operation-header.js +76 -0
  190. data/lib/sendproof/ui/operations.js +7 -0
  191. data/lib/sendproof/ui/overview-view.js +63 -0
  192. data/lib/sendproof/ui/personas.js +59 -0
  193. data/lib/sendproof/ui/popover.js +71 -0
  194. data/lib/sendproof/ui/preview-false.js +108 -0
  195. data/lib/sendproof/ui/request-editor.js +496 -0
  196. data/lib/sendproof/ui/response-metadata.js +354 -0
  197. data/lib/sendproof/ui/response-viewer.js +618 -0
  198. data/lib/sendproof/ui/result-blocked.js +155 -0
  199. data/lib/sendproof/ui/result-capture.js +25 -0
  200. data/lib/sendproof/ui/result-database.js +185 -0
  201. data/lib/sendproof/ui/result-effects.js +176 -0
  202. data/lib/sendproof/ui/result-headers.js +106 -0
  203. data/lib/sendproof/ui/result-logs.js +408 -0
  204. data/lib/sendproof/ui/result-states.js +213 -0
  205. data/lib/sendproof/ui/results.js +371 -0
  206. data/lib/sendproof/ui/router.js +118 -0
  207. data/lib/sendproof/ui/schema-model.js +336 -0
  208. data/lib/sendproof/ui/schema-tree.js +344 -0
  209. data/lib/sendproof/ui/schema.js +397 -0
  210. data/lib/sendproof/ui/security.js +31 -0
  211. data/lib/sendproof/ui/seeded-menu.js +69 -0
  212. data/lib/sendproof/ui/settings.js +93 -0
  213. data/lib/sendproof/ui/shortcuts-sheet.js +73 -0
  214. data/lib/sendproof/ui/shortcuts.js +190 -0
  215. data/lib/sendproof/ui/sidebar.js +289 -0
  216. data/lib/sendproof/ui/signin.js +259 -0
  217. data/lib/sendproof/ui/snippets.js +530 -0
  218. data/lib/sendproof/ui/store-marks.js +47 -0
  219. data/lib/sendproof/ui/stores.js +131 -0
  220. data/lib/sendproof/ui/styles.css +971 -0
  221. data/lib/sendproof/ui/toggletip.js +53 -0
  222. data/lib/sendproof/ui/uuid.js +10 -0
  223. data/lib/sendproof/ui/view.js +122 -0
  224. data/lib/sendproof/ui/views.css +653 -0
  225. data/lib/sendproof/version.rb +9 -0
  226. data/lib/sendproof/workbench.rb +102 -0
  227. data/lib/sendproof-core.rb +3 -0
  228. data/lib/sendproof.rb +121 -0
  229. metadata +292 -0
@@ -0,0 +1,213 @@
1
+ // Every state of the result pane that isn't captured data (mock: results.js). All five tabs
2
+ // always exist and are always clickable; each shows content, a zero state, or why nothing was
3
+ // captured. The head row says what ran, how it ended and how long it took.
4
+ import { esc, ghostRows, icon, stateBlock, statusTone } from './components.js';
5
+ import { formatBytes, formatDuration, formatNumber, formatTime, t, th } from './i18n.js';
6
+ import { shortcutAttrs, shortcutHint } from './shortcuts.js';
7
+ import { inline } from './markdown.js';
8
+ import { blockedSkeleton } from './result-blocked.js';
9
+ import { storeMark, storeName, storeNames } from './stores.js';
10
+
11
+ export const RESULT_TABS = ['Response', 'Database', 'Side effects', 'Logs', 'Headers'];
12
+ export const resultTabLabel = tab => t('res.tab.' + tab);
13
+
14
+ const statusNames = new Map([
15
+ [200, 'OK'], [201, 'Created'], [202, 'Accepted'], [204, 'No Content'], [301, 'Moved Permanently'],
16
+ [302, 'Found'], [304, 'Not Modified'], [400, 'Bad Request'], [401, 'Unauthorized'], [403, 'Forbidden'],
17
+ [404, 'Not Found'], [405, 'Method Not Allowed'], [409, 'Conflict'], [412, 'Precondition Failed'],
18
+ [415, 'Unsupported Media Type'], [422, 'Unprocessable Content'], [429, 'Too Many Requests'],
19
+ [500, 'Internal Server Error'], [502, 'Bad Gateway'], [503, 'Service Unavailable'], [504, 'Gateway Timeout'],
20
+ ]);
21
+ /** "201 Created": the code with its standard reason phrase, which is protocol text, not UI text. */
22
+ export const statusText = status => [status, statusNames.get(status)].filter(Boolean).join(' ');
23
+
24
+ const header = (result, name) => Object.entries(result?.headers || {}).find(([key]) => key.toLowerCase() === name)?.[1];
25
+ /** A rejection before any handler ran: Sendproof can say nothing was read or changed. */
26
+ export const rejectedEarly = result => result?.status === 401 || result?.status === 403;
27
+ /** Whether this result carries captured changes, effects and logs. */
28
+ export const captured = result => !!result && (result.preview || !!result.traceId);
29
+
30
+ /** Counts for the five tabs: a number, or '–' when not known. Response has no badge. */
31
+ export function resultCounts(result) {
32
+ if (!result || result.error) return [undefined, '–', '–', '–', '–'];
33
+ const headers = Object.keys(result.headers || {}).length;
34
+ // A blocked Preview kept nothing, so its capture tabs are not known rather than zero.
35
+ if (result.blocked) return [undefined, '–', '–', '–', headers];
36
+ if (captured(result)) return [undefined, result.changes?.length ?? 0, result.effects?.length ?? 0, result.logs?.length ?? 0, headers];
37
+ if (rejectedEarly(result)) return [undefined, 0, 0, '–', headers];
38
+ return [undefined, '–', '–', '–', headers];
39
+ }
40
+
41
+ const pill = preview => preview
42
+ ? `<span class="pill pill-accent">${icon('flask', true)}${esc(t('res.preview'))}</span>`
43
+ : `<span class="pill pill-ok">${icon('send', true)}${esc(t('res.sent'))}</span>`;
44
+
45
+ // The size gives way first in a very narrow result pane (views.css), so the line never wraps.
46
+ const metrics = result => `<span class="metric"><bdi>${esc(formatDuration(result.duration ?? 0))}</bdi><span class="size"> · <bdi>${esc(formatBytes(result.size ?? 0))}</bdi></span></span>`;
47
+
48
+ /** The head row before anything has run. */
49
+ export const idleHeader = () => `<span class="faint">${esc(t('res.none'))}</span><span class="spacer"></span>`;
50
+
51
+ /**
52
+ * The result bar under the result pane: when and how the shown result was produced, and the way
53
+ * to older runs (History). `result` is the current result, `running` the run in flight, if any.
54
+ */
55
+ export function resultBar(result, { running, identity } = {}) {
56
+ let glyph = 'clock';
57
+ let text = t('bar.noRuns');
58
+ if (running) text = t('bar.runningShort');
59
+ else if (result?.network || result?.error) text = t('bar.noResponse');
60
+ else if (result) {
61
+ const traced = !result.preview && result.traceId;
62
+ glyph = result.blocked ? 'ban' : result.preview ? 'undo' : 'send';
63
+ const what = t(result.blocked ? 'bar.previewBlocked' : result.preview ? 'bar.previewRun' : traced ? 'bar.sendTraced' : 'bar.sendRun');
64
+ const time = formatTime(result.finishedAt ?? Date.now());
65
+ text = identity ? t('bar.lastRunAs', { what, time, name: identity }) : t('bar.lastRun', { what, time });
66
+ }
67
+ return `<span class="bar-text">${icon(glyph, true)}<span>${esc(text)}</span></span>
68
+ <button type="button" class="btn btn-ghost btn-sm" data-action="history" ${shortcutAttrs('history')}>${icon('history', true)}${esc(t('shell.history'))}${shortcutHint('history')}</button>`;
69
+ }
70
+
71
+ /** The head row while a request runs, with Cancel. */
72
+ export const runningHeader = (preview, identity) =>
73
+ `<span class="pill pill-accent"><span class="spinner" aria-hidden="true"></span>${esc(t(preview ? 'res.preview' : 'res.sending'))}</span>
74
+ <span class="faint running-label">${esc(identity ? t('res.runningAs', { name: identity }) : t('res.running'))}</span>
75
+ <span class="metric" data-elapsed aria-hidden="true">${esc(formatDuration(0))}</span><span class="spacer"></span>
76
+ <button type="button" class="btn btn-ghost btn-sm" data-action="cancel-request" ${shortcutAttrs('escape')}>${esc(t('bar.cancel'))} ${shortcutHint('escape')}</button>`;
77
+
78
+ /** The head row for a response, with Copy as cURL and the next step. */
79
+ export function responseHeader(result, { resourceLabel, match = '' } = {}) {
80
+ const ok = result.status < 400;
81
+ const location = header(result, 'location');
82
+ let resource;
83
+ if (!result.preview && location) {
84
+ try {
85
+ const url = new URL(location, result.requestUrl);
86
+ if (/^https?:$/.test(url.protocol)) resource = url.href;
87
+ } catch { /* Skip malformed Location values. */ }
88
+ }
89
+ const tracedPill = !result.preview && result.traceId
90
+ ? `<span class="pill pill-ok">${icon('send', true)}${esc(t('res.traced'))}</span>` : pill(result.preview);
91
+ const action = result.preview && ok
92
+ ? `<button type="button" class="btn btn-sm" data-action="send" ${shortcutAttrs('send')}>${icon('send', true)}${esc(t('res.sendForReal'))}</button>`
93
+ : resource ? `<a class="btn btn-sm result-open" href="${esc(resource)}" target="_blank" rel="noopener noreferrer" data-location-open ${shortcutAttrs('follow-response')}>${esc(resourceLabel || t('res.openResource'))} ${shortcutHint('follow-response')}</a>` : '';
94
+ return `${tracedPill}<span class="status-code ${statusTone(result.status)}">${icon(ok ? 'check' : result.status === 401 ? 'lock' : 'alert', true)}<bdi class="ltr">${esc(statusText(result.status))}</bdi></span>${metrics(result)}${match}<span class="spacer"></span>
95
+ ${result.wireRequest ? `<button type="button" class="btn btn-ghost btn-icon btn-sm copy" data-action="copy-curl" aria-label="${esc(t('shortcut.copy-curl'))}" title="${esc(t('shortcut.copy-curl'))}" ${shortcutAttrs('copy-curl')}>${icon('copy', true, 'i-idle')}${icon('check', true, 'i-done')}</button>` : ''}
96
+ ${action}`;
97
+ }
98
+
99
+ /** The head row when nothing came back. */
100
+ export const networkHeader = result =>
101
+ `<span class="pill pill-danger">${icon('wifi-off', true)}${esc(t('res.noResponse'))}</span><span class="metric">${esc(t('res.after', { time: formatDuration(result.seconds * 1000) }))}</span><span class="spacer"></span>`;
102
+
103
+ /** The head row when the request couldn't be made or acknowledged. */
104
+ export const errorHeader = () =>
105
+ `<span class="status-code err">${icon('alert', true)}${esc(t('res.failed'))}</span><span class="spacer"></span>`;
106
+
107
+ const previewButton = () => `<button type="button" class="btn btn-primary btn-sm" data-action="preview" ${shortcutAttrs('preview')}>${icon('flask', true)}${esc(t('bar.preview'))} ${shortcutHint('preview')}</button>`;
108
+ const sendButton = readOnly => `<button type="button" class="btn btn-sm" data-action="send" ${shortcutAttrs(readOnly ? 'send-read-only' : 'send')}>${icon('send', true)}${esc(t('bar.send'))} ${shortcutHint(readOnly ? 'send-read-only' : 'send')}</button>`;
109
+ const runButton = context => context.canPreview ? previewButton() : sendButton(context.readOnly);
110
+
111
+ /** The documented responses of the operation, each linking to its schema. */
112
+ function documentedResponses(context) {
113
+ const entries = Object.entries(context.op?.operation.responses || {});
114
+ if (!entries.length) return '';
115
+ return `<div class="expect"><div class="expect-h">${esc(t('res.documented'))}</div>${entries.map(([code, response]) => {
116
+ const media = Object.values(response?.content || {})[0];
117
+ const name = context.schemaName(media?.schema);
118
+ return `<div class="expect-row"><span class="code ${statusTone(code)}">${esc(code)}</span><span lang="en">${response?.description ? inline(String(response.description).replace(/\s*\n\s*/g, ' ')) : esc(statusNames.get(Number(code)) || '')}</span><span class="spacer"></span>${name
119
+ ? `<a class="type-link" href="#model/${encodeURIComponent(name.replace(/\[\]$/, ''))}" data-model="${esc(name.replace(/\[\]$/, ''))}">${esc(name)}</a>`
120
+ : `<span class="faint">${esc(t('res.noBody'))}</span>`}</div>`;
121
+ }).join('')}</div>`;
122
+ }
123
+
124
+ /** What each tab will show before anything has run, and how to fill it. */
125
+ export function beforeRun(tab, context) {
126
+ const { readOnly, canPreview, unavailable } = context;
127
+ // An operation marked preview: false says why in the body, and keeps Preview's step, marked off.
128
+ const offBody = unavailable && (unavailable.stores.length
129
+ ? t('res.before.response.previewOff', { stores: storeNames(unavailable.stores) })
130
+ : t('res.before.response.previewOffNoStore'));
131
+ const offStep = unavailable ? `<li class="step-off">${icon('flask-off', true)}<span>${esc(t('res.step.previewOff'))}</span><span class="spacer"></span>${unavailable.stores.map(store => `<span class="step-tag">${storeMark(store)}${esc(storeName(store))}</span>`).join('')}</li>` : '';
132
+ if (tab === 'Response') return stateBlock({
133
+ glyph: 'braces', title: esc(t('res.before.response.title')),
134
+ body: esc(offBody || t(readOnly ? 'res.before.response.readOnly' : canPreview ? 'res.before.response.body' : 'res.before.response.noPreview')),
135
+ extra: `<ol class="steps">
136
+ ${context.fillable ? `<li>${icon('wand', true)}${esc(t('shortcut.autofill-required'))}${shortcutHint('autofill-required')}</li>` : ''}
137
+ ${canPreview ? `<li>${icon('flask', true)}${esc(t('res.step.preview'))}${shortcutHint('preview')}</li>` : offStep}
138
+ <li>${icon('send', true)}${esc(t(readOnly ? 'res.step.sendReadOnly' : 'res.step.send'))}${shortcutHint(readOnly ? 'send-read-only' : 'send')}</li>
139
+ </ol>${documentedResponses(context)}`,
140
+ });
141
+ const spec = {
142
+ Database: ['db', readOnly ? 'res.before.database.readOnly' : canPreview ? 'res.before.database.body' : 'res.before.database.noPreview', [['plus', '30%', '12%'], ['edit', '42%', '18%']]],
143
+ 'Side effects': ['mail', canPreview ? 'res.before.effects.body' : 'res.before.effects.noPreview', [['mail', '38%', '14%'], ['globe', '52%', '20%'], ['clock', '30%', '16%']]],
144
+ Logs: ['list', 'res.before.logs.body', [['info', '64%', '8%'], ['db', '48%', '8%'], ['info', '56%', '8%']]],
145
+ Headers: ['list', 'res.before.headers.body', [['hash', '28%', '40%'], ['hash', '22%', '34%']]],
146
+ }[tab];
147
+ return stateBlock({
148
+ glyph: spec[0], title: esc(t('res.before.' + tab + '.title')), body: esc(t(spec[1])),
149
+ extra: ghostRows(spec[2]), actions: [runButton(context)],
150
+ });
151
+ }
152
+
153
+ /** Send without a trace: say what isn't captured, and how to capture it. */
154
+ export function notCaptured(tab, context) {
155
+ const turnOn = context.traceAvailable
156
+ ? `<button type="button" class="btn btn-sm" data-action="traced-on">${esc(t('res.tracedOn'))}</button>` : '';
157
+ const actions = [context.canPreview ? previewButton() : '', turnOn].filter(Boolean);
158
+ const why = context.traceAvailable ? esc(t('res.tracedWhy')) : '';
159
+ if (tab === 'Database') return stateBlock({ glyph: 'db', title: esc(t('res.notCaptured.database')), body: esc(t(context.traceAvailable ? 'res.notCaptured.databaseBody' : 'res.notCaptured.databaseNoTrace')), actions, why });
160
+ if (tab === 'Side effects') return stateBlock({ glyph: 'mail', title: esc(t('res.notCaptured.effects')), body: esc(t(context.traceAvailable ? 'res.notCaptured.effectsBody' : 'res.notCaptured.effectsNoTrace')), actions });
161
+ return stateBlock({ glyph: 'list', title: esc(t('res.notCaptured.logs')), body: esc(t(context.traceAvailable ? 'res.notCaptured.logsBody' : 'res.notCaptured.logsNoTrace')), actions });
162
+ }
163
+
164
+ /** A tab with nothing in it after a captured run. */
165
+ export function zeroState(tab, result) {
166
+ const status = result.status;
167
+ if (tab === 'Database') return stateBlock({ glyph: 'db', title: esc(t('res.zero.database')), body: esc(rejectedEarly(result) ? t('res.zero.databaseRejected', { status }) : t('res.zero.databaseBody')) });
168
+ if (tab === 'Side effects') return stateBlock({ glyph: 'check', title: esc(t('res.zero.effects')), body: esc(rejectedEarly(result) ? t('res.zero.effectsRejected') : t('res.zero.effectsBody')) });
169
+ if (tab === 'Logs') return stateBlock({ glyph: 'list', title: esc(t('res.zero.logs')), body: esc(t('res.zero.logsBody')) });
170
+ return stateBlock({ glyph: 'list', title: esc(t('res.zero.headers')), body: esc(t('res.zero.headersBody')) });
171
+ }
172
+
173
+ /** A 401 explains what happened and offers sign-in and retry, instead of a bare empty body. */
174
+ export function unauthorized(result, context) {
175
+ const challenge = header(result, 'www-authenticate');
176
+ const schemes = context.schemes?.length ? context.schemes.map(name => `<code>${esc(name)}</code>`).join(', ') : '';
177
+ return `<div class="problem" role="alert">
178
+ <div class="problem-head">${icon('lock')}<div><h3>${esc(t('res.unauthorized.title'))}</h3><p>${th(schemes ? 'res.unauthorized.body' : 'res.unauthorized.bodyNoScheme', { op: `<span lang="en">${esc(context.op?.title || '')}</span>`, schemes })}</p></div></div>
179
+ ${context.canSignIn ? `<div class="actions"><button type="button" class="btn btn-primary" data-action="signin-retry" ${shortcutAttrs('signin')}>${icon('log-in', true)}${esc(t('res.unauthorized.signIn'))} ${shortcutHint('signin')}</button></div>` : ''}
180
+ <dl class="facts problem-facts"><dt>${esc(t('res.unauthorized.bodyLabel'))}</dt><dd class="plain">${esc(result.raw ? t('res.unauthorized.bodySize', { size: formatBytes(result.size) }) : t('res.unauthorized.empty', { size: formatBytes(0) }))}</dd>${challenge ? `<dt>WWW-Authenticate</dt><dd>${esc(challenge)}</dd>` : ''}<dt>${esc(t('res.unauthorized.retry'))}</dt><dd class="plain">${th('res.unauthorized.retryBody', { op: `<span lang="en">${esc(context.op?.title || '')}</span>` })}</dd></dl>
181
+ </div>`;
182
+ }
183
+
184
+ /** Nothing came back: the API may be down. The request stays as it was. */
185
+ export const networkError = result => stateBlock({
186
+ glyph: 'wifi-off', tone: 'danger', title: esc(t('res.network.title')), role: 'alert',
187
+ body: th('res.network.body', { origin: `<code class="ltr">${esc(result.origin || result.host)}</code>` }),
188
+ why: esc(t('res.network.why')),
189
+ actions: [
190
+ `<button type="button" class="btn btn-primary btn-sm" data-action="retry-request">${icon('refresh', true)}${esc(t('res.tryAgain'))}</button>`,
191
+ `<button type="button" class="btn btn-ghost btn-sm copy" data-action="copy-failed-curl">${icon('copy', true, 'i-idle')}${icon('check', true, 'i-done')}<span class="copy-label"><span>${esc(t('res.copyCurl'))}</span><span aria-hidden="true">${esc(t('copy.copied'))}</span></span></button>`,
192
+ ],
193
+ });
194
+
195
+ /** The request couldn't be prepared or the preview wasn't acknowledged. */
196
+ export const requestError = result => stateBlock({
197
+ glyph: 'alert', tone: 'danger', title: esc(t('res.error.title')), role: 'alert',
198
+ body: esc(result.error), why: esc(t('res.error.why')),
199
+ });
200
+
201
+ /**
202
+ * Skeletons that mirror the final layout of each tab while a request runs. `blocked`: this
203
+ * operation's last Preview was stopped by the write guard, so the Response tab waits in the shape
204
+ * of the blocked state instead of the JSON viewer.
205
+ */
206
+ export function loadingBody(tab, preview, { blocked = false } = {}) {
207
+ if (blocked && tab === 'Response') return blockedSkeleton();
208
+ const sk = (width, height = '0.7rem', extra = '') => `<span class="sk" style="display:block;inline-size:${width};block-size:${height};${extra}"></span>`;
209
+ if (tab === 'Database' && preview) return `<div class="result-body" aria-hidden="true">${sk('100%', '3.25rem', 'border-radius:var(--r-lg)')}
210
+ ${[5, 2].map(rows => `<div class="table-change"><div class="tc-head">${sk('4.5rem', '1.25rem')}${sk('7rem', '0.8rem')}</div><div class="kv">${Array.from({ length: rows }, (_, i) => `<div>${sk(`${40 + (i * 7) % 30}%`)}</div><div>${sk(`${50 + (i * 11) % 40}%`)}</div>`).join('')}</div></div>`).join('')}</div>`;
211
+ return `<div class="result-body" aria-hidden="true"><div class="viewer"><div class="viewer-bar">${sk('11rem', '1.6rem')}</div><div class="code-view">${[30, 62, 40, 48, 36, 70, 74, 55, 30].map((width, index) =>
212
+ `<div class="ln"><span class="no">${formatNumber(index + 1)}</span><span></span><span class="src" style="--d:${index ? 1 : 0}">${sk(width + '%')}</span></div>`).join('')}</div></div></div>`;
213
+ }
@@ -0,0 +1,371 @@
1
+ // Runs requests and renders the result pane. All five tabs always exist; each shows captured
2
+ // data, a zero state, or why nothing was captured (mock: results.js). Clipboard problems are
3
+ // reported where the copy happened and never replace the pane.
4
+ import { esc, tab as tabButton } from './components.js';
5
+ import { dereference, execute, RequestTransportError, transportRequest } from './api.js';
6
+ import {
7
+ RESULT_TABS, beforeRun, captured, errorHeader, idleHeader, loadingBody, networkError, networkHeader,
8
+ notCaptured, rejectedEarly, requestError, responseHeader, resultBar, resultCounts, resultTabLabel, runningHeader,
9
+ unauthorized, zeroState,
10
+ } from './result-states.js';
11
+ import { blockedHeader, blockedMarkup, blockedTab, bindBlocked } from './result-blocked.js';
12
+ import { previewUnavailable as unavailableEntry, storeName } from './stores.js';
13
+ import { bindDatabase, databaseMarkup } from './result-database.js';
14
+ import { bindMatch, bindResponseViewer, matchButton, responseMarkup } from './response-viewer.js';
15
+ import { captureMarkup, bindCapturePane } from './result-capture.js';
16
+ import { formatRequest } from './snippets.js';
17
+ import { copyText } from './copy.js';
18
+ import { formatDuration, formatNumber, t } from './i18n.js';
19
+ import { actionBar, confirmation as confirmationBar, isReadOnly, previewDock, runningStatus } from './action-bar.js';
20
+ import { tracedSendEnabled } from './settings.js';
21
+ import { isPublic, primarySchemes } from './security.js';
22
+ import { noteSunsetHeader } from './deprecation.js';
23
+
24
+ const CREDENTIAL = /authorization|cookie|password|passwd|secret|token|api[-_]?key/i;
25
+
26
+ /** Execute requests and render the result pane. */
27
+ export function createResults({
28
+ state, basePath, $, readRequest, sensitiveNames, renderOperation, issues, onFollowUp, selectView,
29
+ schemaName = () => '', fillable = () => false, onCompleted = () => {},
30
+ }) {
31
+ let active;
32
+ let confirmation;
33
+ let restoreProgress;
34
+
35
+ function previewAvailable() {
36
+ return !!state.op && !isReadOnly(state.op) && (state.cap.previewOperations || []).some(operation =>
37
+ operation.method.toUpperCase() === state.op.method && operation.path === state.op.path);
38
+ }
39
+
40
+ /** The operation's preview: false mark from discovery, unless it is read-only anyway. */
41
+ const unavailable = () => isReadOnly(state.op) ? undefined : unavailableEntry(state.op, state.cap);
42
+
43
+ /** Facts the result states need to explain themselves. */
44
+ function context() {
45
+ const canPreview = previewAvailable();
46
+ return {
47
+ op: state.op, document: state.doc, readOnly: isReadOnly(state.op), canPreview, fillable: fillable(),
48
+ unavailable: unavailable(), capabilities: state.cap, traced: tracedSendEnabled(state.cap),
49
+ traceAvailable: state.cap.observedSend === true && canPreview, schemaName,
50
+ canSignIn: (state.cap.authProviders || []).length > 0,
51
+ schemes: state.op ? primarySchemes(state.op, state.doc).map(item => item.name) : [],
52
+ };
53
+ }
54
+
55
+ /**
56
+ * The action bar and, for an operation marked preview: false, the reason docked above it. After
57
+ * a Preview the write guard stopped, the status says so until the next run.
58
+ */
59
+ function renderBar() {
60
+ const bar = $('.actionbar');
61
+ const entry = unavailable();
62
+ const dock = $('[data-preview-dock]');
63
+ if (dock) {
64
+ dock.hidden = !entry;
65
+ dock.innerHTML = previewDock(entry);
66
+ }
67
+ const blocked = state.result?.blocked && state.result.operation === state.op ? storeName(state.result.blocked.store) : undefined;
68
+ if (bar && !confirmation) bar.innerHTML = actionBar(state.op, previewAvailable(), { unavailable: entry, blocked });
69
+ }
70
+
71
+ /** Preview pressed (or ⌘↵) on an operation marked preview: false: point at the reason instead. */
72
+ function nudgeDock() {
73
+ const dock = $('[data-preview-dock]');
74
+ if (!dock || dock.hidden) return false;
75
+ dock.classList.remove('is-nudged');
76
+ void dock.offsetWidth;
77
+ dock.classList.add('is-nudged');
78
+ dock.focus?.({ preventScroll: false });
79
+ return true;
80
+ }
81
+
82
+ function showProgress(preview) {
83
+ const button = $(`.actionbar [data-action="${preview ? 'preview' : 'send'}"]`);
84
+ const status = $('.actionbar .status');
85
+ const savedStatus = status?.innerHTML;
86
+ const glyph = button?.querySelector('svg');
87
+ const spinner = document.createElement('span');
88
+ spinner.className = 'spinner';
89
+ spinner.setAttribute('aria-hidden', 'true');
90
+ glyph?.replaceWith(spinner);
91
+ button?.setAttribute('aria-busy', 'true');
92
+ if (status) status.innerHTML = runningStatus(preview, state.cap.identity?.name);
93
+ restoreProgress = () => {
94
+ if (glyph) spinner.replaceWith(glyph);
95
+ button?.removeAttribute('aria-busy');
96
+ if (status) status.innerHTML = savedStatus;
97
+ restoreProgress = undefined;
98
+ };
99
+ }
100
+
101
+ function cancelConfirmation() {
102
+ if (!confirmation) return;
103
+ confirmation = undefined;
104
+ renderBar();
105
+ }
106
+
107
+ function askForConfirmation(request) {
108
+ const bar = $('.actionbar');
109
+ confirmation = { request, operation: state.op, documentUrl: state.documentUrl };
110
+ bar.innerHTML = confirmationBar(request.method, state.op.path, unavailable()?.stores ?? []);
111
+ setView('request');
112
+ bar.querySelector('[data-action="cancel-confirm"]').focus();
113
+ }
114
+
115
+ function setView(view) {
116
+ if (selectView) selectView(view);
117
+ else $('.workspace').dataset.view = view === 'response' ? 'result' : view;
118
+ }
119
+
120
+ function cancel() {
121
+ cancelConfirmation();
122
+ active?.abort();
123
+ active = undefined;
124
+ restoreProgress?.();
125
+ if ($('#result')) {
126
+ $('.response').removeAttribute('aria-busy');
127
+ document.querySelectorAll('.actionbar [data-action="send"], .actionbar [data-action="preview"]').forEach(button => { button.disabled = false; });
128
+ renderResult();
129
+ }
130
+ }
131
+
132
+ function containsCredential(value, names) {
133
+ if (!value || typeof value !== 'object') return false;
134
+ if (typeof File !== 'undefined' && value instanceof File) return true;
135
+ return Object.entries(value).some(([key, item]) => CREDENTIAL.test(key) ||
136
+ names.has(key.toLowerCase().replace(/^(header|query|cookie|path):/, '')) || containsCredential(item, names));
137
+ }
138
+
139
+ function canStoreHistory(op, body, params, headers) {
140
+ const names = new Set(sensitiveNames().map(name => name.toLowerCase()));
141
+ function sensitiveSchema(schema, seen = new Set()) {
142
+ if (!schema || typeof schema !== 'object' || seen.has(schema)) return false;
143
+ seen.add(schema);
144
+ if (schema.writeOnly || schema.format === 'password') return true;
145
+ if (schema.$ref && sensitiveSchema(dereference(schema, state.doc), seen)) return true;
146
+ return Object.values(schema).some(value => sensitiveSchema(value, seen));
147
+ }
148
+ return !/\b(auth|login|password|token|credentials)\b/i.test(op.path) &&
149
+ !sensitiveSchema(op.operation.requestBody) && !sensitiveSchema(op.parameters) &&
150
+ !containsCredential(body, names) && !containsCredential(params, names) &&
151
+ !headers.some(row => CREDENTIAL.test(row.name) || names.has(row.name.toLowerCase()));
152
+ }
153
+
154
+ function showValidationErrors(body) {
155
+ if (!body?.errors || typeof body.errors !== 'object' || Array.isArray(body.errors)) return;
156
+ const errors = Object.entries(body.errors).flatMap(([path, messages]) =>
157
+ (Array.isArray(messages) ? messages : [messages]).map(message => ({ path, message: String(message) })));
158
+ if (!errors.length) return;
159
+ if (state.tab === 'JSON') {
160
+ state.tab = 'Form';
161
+ renderOperation();
162
+ }
163
+ issues?.show(errors, { fromServer: true });
164
+ }
165
+
166
+ /** A request that couldn't be prepared or acknowledged. Shown in the Response tab only. */
167
+ function showError(error) {
168
+ state.result = { error: error.message };
169
+ state.resultTab = 'Response';
170
+ renderResult();
171
+ setView('response');
172
+ }
173
+
174
+ async function copyFailedRequest(button) {
175
+ if (!state.result?.network) return;
176
+ const request = state.result.wireRequest || transportRequest(readRequest(), state.result.preview, basePath);
177
+ await copyText(formatRequest('curl', request, sensitiveNames()), { button, what: t('copy.what.curl'), notice: button?.closest('.actions') });
178
+ }
179
+
180
+ async function copyCurl(button) {
181
+ if (!state.result?.wireRequest) return;
182
+ await copyText(formatRequest('curl', state.result.wireRequest, sensitiveNames()), { button, what: t('copy.what.curl') });
183
+ }
184
+
185
+ async function run(preview, confirmed = false) {
186
+ if (active) return;
187
+ let controller;
188
+ let started;
189
+ let target;
190
+ try {
191
+ let request;
192
+ if (confirmed) {
193
+ if (!confirmation || confirmation.operation !== state.op || confirmation.documentUrl !== state.documentUrl) return;
194
+ request = confirmation.request;
195
+ cancelConfirmation();
196
+ } else {
197
+ cancelConfirmation();
198
+ request = readRequest();
199
+ }
200
+ if (preview && unavailable() && nudgeDock()) return;
201
+ if (preview && !previewAvailable()) throw new Error(t('res.previewUnavailable'));
202
+ if (!preview && !isReadOnly(state.op) && !confirmed) {
203
+ issues?.clear();
204
+ askForConfirmation(request);
205
+ return;
206
+ }
207
+ const operation = state.op;
208
+ const documentUrl = state.documentUrl;
209
+ const recordHistory = canStoreHistory(operation, state.body, state.paramValues || {}, state.headers || []);
210
+ const body = recordHistory ? structuredClone(state.body) : undefined;
211
+ const params = recordHistory ? structuredClone(state.paramValues || {}) : undefined;
212
+ const draftHeaders = recordHistory ? structuredClone(state.headers || []) : undefined;
213
+ controller = new AbortController();
214
+ started = performance.now();
215
+ target = new URL(request.url);
216
+ active = controller;
217
+ issues?.clear();
218
+ const buttons = document.querySelectorAll('.actionbar [data-action="send"], .actionbar [data-action="preview"]');
219
+ buttons.forEach(button => { button.disabled = true; });
220
+ showProgress(preview);
221
+ $('.response').setAttribute('aria-busy', 'true');
222
+ state.running = { preview };
223
+ renderResult();
224
+ const elapsed = $('[data-elapsed]');
225
+ const timer = setInterval(() => {
226
+ if (elapsed) elapsed.textContent = formatDuration(performance.now() - started);
227
+ }, 250);
228
+ try {
229
+ const observedSend = !preview && previewAvailable() && tracedSendEnabled(state.cap);
230
+ const result = await execute(request, preview, basePath, controller.signal, { observedSend });
231
+ if (active !== controller || state.op !== operation || state.documentUrl !== documentUrl) return;
232
+ state.running = undefined;
233
+ state.result = result;
234
+ result.finishedAt = Date.now();
235
+ result.operation = operation;
236
+ // A blocked Preview's loading state mirrors the blocked result the next time it runs.
237
+ if (preview) state.blockedOps = { ...state.blockedOps, [`${operation.method} ${operation.path}`]: !!result.blocked };
238
+ result.requestHeaders = redactRequestHeaders(result.requestHeaders, sensitiveNames());
239
+ // A Sunset header (RFC 8594) dates a deprecated operation whose spec has no x-sunset.
240
+ noteSunsetHeader(operation, result.headers);
241
+ if (result.status < 400 && result.body && typeof result.body === 'object' && !Array.isArray(result.body))
242
+ state.lastResponse = { path: operation.path, body: result.body };
243
+ // Real responses feed the examples on model pages and in Docs.
244
+ if (result.status < 400 && result.body && typeof result.body === 'object') {
245
+ state.samples = [result.body, ...(state.samples || [])].slice(0, 20);
246
+ }
247
+ restoreProgress?.();
248
+ if (result.status >= 400) showValidationErrors(result.body);
249
+ if (state.resultTab !== 'Response' && !captured(result) && ['Database', 'Side effects', 'Logs'].includes(state.resultTab) && !rejectedEarly(result))
250
+ state.resultTab = 'Response';
251
+ else if (preview && result.status < 400 && result.changes?.length) state.resultTab = 'Database';
252
+ if (recordHistory) state.history.unshift({ op: operation, body, params, headers: draftHeaders, preview, when: Date.now(), status: result.status });
253
+ state.history.length = Math.min(state.history.length, 50);
254
+ $('.response').removeAttribute('aria-busy');
255
+ renderResult();
256
+ if (result.blocked || preview) renderBar();
257
+ setView('response');
258
+ onCompleted(result, { preview, operation });
259
+ } finally {
260
+ clearInterval(timer);
261
+ if (active === controller) {
262
+ active = undefined;
263
+ state.running = undefined;
264
+ restoreProgress?.();
265
+ buttons.forEach(button => { button.disabled = false; });
266
+ $('.response')?.removeAttribute('aria-busy');
267
+ }
268
+ }
269
+ } catch (error) {
270
+ state.running = undefined;
271
+ if (error.validation) {
272
+ setView('request');
273
+ issues?.show(error.issues ?? error.message.split('\n').map(message => ({ message })), { expand: true });
274
+ } else if (error instanceof RequestTransportError && !controller.signal.aborted) {
275
+ state.result = {
276
+ network: true, error: error.message, preview, host: target.host, origin: target.origin,
277
+ wireRequest: error.wireRequest, seconds: (performance.now() - started) / 1000,
278
+ };
279
+ state.resultTab = 'Response';
280
+ renderResult();
281
+ setView('response');
282
+ } else if (error.name !== 'AbortError' && (!controller || !controller.signal.aborted)) showError(error);
283
+ }
284
+ }
285
+
286
+ function renderTabs(result) {
287
+ const counts = state.running ? resultCounts(null) : resultCounts(result);
288
+ $('.response .tabs').innerHTML = RESULT_TABS.map((tab, index) => tabButton(resultTabLabel(tab), {
289
+ selected: tab === state.resultTab, count: counts[index], id: `result-tab-${tab.replaceAll(' ', '-')}`,
290
+ controls: 'result', shortcut: 'result-tab-' + index, data: `data-result-tab="${tab}"`,
291
+ })).join('');
292
+ $('.response .tabs [aria-selected="true"]')?.scrollIntoView?.({ block: 'nearest', inline: 'nearest' });
293
+ }
294
+
295
+ /** The content of the selected tab for the current result. */
296
+ function tabContent(tab, result, ctx) {
297
+ if (!result) return beforeRun(tab, ctx);
298
+ if (result.network) return tab === 'Response' ? networkError(result) : beforeRun(tab, ctx);
299
+ if (result.error) return tab === 'Response' ? requestError(result) : beforeRun(tab, ctx);
300
+ if (result.blocked && tab !== 'Headers') return tab === 'Response' ? blockedMarkup(result, ctx) : blockedTab(tab, result, ctx);
301
+ const viewContext = {
302
+ document: state.doc, operation: state.op, operations: state.ops, basePath, onFollowUp, capabilities: state.cap,
303
+ };
304
+ if (tab === 'Response') {
305
+ const problem = result.status === 401 ? unauthorized(result, ctx) : '';
306
+ return problem && !result.raw ? problem : problem + responseMarkup(result, viewContext);
307
+ }
308
+ if (tab === 'Headers') return captureMarkup(tab, result, viewContext);
309
+ if (!captured(result)) return rejectedEarly(result) && tab !== 'Logs' ? zeroState(tab, result) : notCaptured(tab, ctx);
310
+ if (tab === 'Database') return result.changes?.length || result.changesTruncated ? databaseMarkup(result, state.cap) : zeroState(tab, result);
311
+ const items = tab === 'Logs' ? result.logs : result.effects;
312
+ return items?.length ? captureMarkup(tab, result, viewContext) : zeroState(tab, result);
313
+ }
314
+
315
+ function renderResult() {
316
+ const result = state.result;
317
+ const head = $('.resp-head');
318
+ if (state.running) head.innerHTML = runningHeader(state.running.preview, state.cap.identity?.name);
319
+ else if (result?.network) head.innerHTML = networkHeader(result);
320
+ else if (result?.error) head.innerHTML = errorHeader();
321
+ else if (result?.blocked) head.innerHTML = blockedHeader(result);
322
+ else {
323
+ // The schema match sits in the status line, after status, time and size (mock 100).
324
+ const viewContext = { document: state.doc, operation: state.op, operations: state.ops, basePath, onFollowUp, capabilities: state.cap };
325
+ head.innerHTML = result ? responseHeader(result, { match: result.raw || result.body !== undefined ? matchButton(result, viewContext) : '' }) : idleHeader();
326
+ if (result) bindMatch(head, result, viewContext);
327
+ }
328
+ renderTabs(result);
329
+ const bar = $('.result-bar');
330
+ if (bar) bar.innerHTML = resultBar(result, { running: !!state.running, identity: state.cap.identity?.name });
331
+ const panel = $('#result');
332
+ const tab = state.resultTab;
333
+ const wasBlocked = !!state.op && !!state.blockedOps?.[`${state.op.method} ${state.op.path}`];
334
+ if (state.running) panel.innerHTML = loadingBody(tab, state.running.preview, { blocked: state.running.preview && wasBlocked }) + `<span class="sr-only">${esc(t('res.loading'))}</span>`;
335
+ else {
336
+ panel.innerHTML = `<div class="result-body">${tabContent(tab, result, context())}</div>`;
337
+ const container = panel.querySelector('.result-body');
338
+ const viewContext = { document: state.doc, operation: state.op, operations: state.ops, basePath, onFollowUp, capabilities: state.cap };
339
+ if (result?.blocked && tab === 'Response') bindBlocked(container, result, context());
340
+ else if (result?.blocked && tab !== 'Headers') { /* A designed state with no captured data to bind. */ }
341
+ else if (result && !result.error && tab === 'Response') bindResponseViewer(container, result, viewContext);
342
+ else if (result && !result.error && tab === 'Database' && captured(result) && result.changes?.length) bindDatabase(container, result);
343
+ else if (result && !result.error && showsCapture(tab, result)) bindCapturePane(container, tab, result, viewContext);
344
+ }
345
+ panel.scrollTop = 0;
346
+ panel.setAttribute('aria-labelledby', `result-tab-${tab.replaceAll(' ', '-')}`);
347
+ const mobileResult = $('.mobile-switch [data-view="response"]');
348
+ if (mobileResult) mobileResult.textContent = result?.status
349
+ ? `${t('shell.result')} · ${formatNumber(result.status, { useGrouping: false })}` : t('shell.result');
350
+ }
351
+
352
+ return {
353
+ showError, copyFailedRequest, copyCurl, run, renderResult, renderBar, cancel, cancelConfirmation, previewAvailable,
354
+ get confirming() { return !!confirmation; },
355
+ requiresSignIn: () => !!state.op && !isPublic(state.op, state.doc),
356
+ };
357
+ }
358
+
359
+ /** True when the tab renders captured items that need their interactive bindings. */
360
+ function showsCapture(tab, result) {
361
+ if (tab === 'Headers') return true;
362
+ if (!captured(result)) return false;
363
+ return tab === 'Logs' ? !!result.logs?.length : tab === 'Side effects' ? !!result.effects?.length : false;
364
+ }
365
+
366
+ function redactRequestHeaders(headers, sensitiveNames) {
367
+ const custom = new Set(sensitiveNames.map(name => name.toLowerCase()));
368
+ return Object.fromEntries(Object.entries(headers).map(([name, value]) => [
369
+ name, custom.has(name.toLowerCase()) || CREDENTIAL.test(name) ? 'REDACTED' : value,
370
+ ]));
371
+ }