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.
- checksums.yaml +7 -0
- data/LICENSE +21 -0
- data/README.md +55 -0
- data/lib/sendproof/assets.rb +70 -0
- data/lib/sendproof/attribution.rb +98 -0
- data/lib/sendproof/capture.rb +66 -0
- data/lib/sendproof/clock.rb +54 -0
- data/lib/sendproof/configuration.rb +241 -0
- data/lib/sendproof/data_store.rb +34 -0
- data/lib/sendproof/dynamodb/store.rb +183 -0
- data/lib/sendproof/dynamodb.rb +17 -0
- data/lib/sendproof/elasticsearch/store.rb +24 -0
- data/lib/sendproof/elasticsearch.rb +17 -0
- data/lib/sendproof/firestore/interceptor.rb +38 -0
- data/lib/sendproof/firestore/store.rb +150 -0
- data/lib/sendproof/firestore.rb +99 -0
- data/lib/sendproof/handler.rb +23 -0
- data/lib/sendproof/identity.rb +37 -0
- data/lib/sendproof/limits.rb +113 -0
- data/lib/sendproof/middleware.rb +68 -0
- data/lib/sendproof/mongo/engine.rb +692 -0
- data/lib/sendproof/mongo/guarded.rb +100 -0
- data/lib/sendproof/mongo/plain.rb +45 -0
- data/lib/sendproof/mongo/store.rb +54 -0
- data/lib/sendproof/mongo/subscriber.rb +21 -0
- data/lib/sendproof/mongo.rb +41 -0
- data/lib/sendproof/mongoid/store.rb +58 -0
- data/lib/sendproof/mongoid.rb +65 -0
- data/lib/sendproof/observed_request.rb +108 -0
- data/lib/sendproof/opensearch/store.rb +21 -0
- data/lib/sendproof/opensearch.rb +17 -0
- data/lib/sendproof/operation_matcher.rb +28 -0
- data/lib/sendproof/pool_hooks.rb +80 -0
- data/lib/sendproof/preview_request.rb +44 -0
- data/lib/sendproof/preview_transport.rb +331 -0
- data/lib/sendproof/protocol.rb +81 -0
- data/lib/sendproof/provider.rb +83 -0
- data/lib/sendproof/recorder.rb +298 -0
- data/lib/sendproof/redaction.rb +98 -0
- data/lib/sendproof/redis/commands.rb +76 -0
- data/lib/sendproof/redis/store.rb +205 -0
- data/lib/sendproof/redis.rb +18 -0
- data/lib/sendproof/search/middleware.rb +39 -0
- data/lib/sendproof/search/store.rb +213 -0
- data/lib/sendproof/search.rb +82 -0
- data/lib/sendproof/stores/classify.rb +346 -0
- data/lib/sendproof/stores/guard.rb +127 -0
- data/lib/sendproof/stores/tables.rb +1328 -0
- data/lib/sendproof/stores.rb +12 -0
- data/lib/sendproof/trace_store.rb +110 -0
- data/lib/sendproof/transaction_control.rb +187 -0
- data/lib/sendproof/ui/action-bar.js +91 -0
- data/lib/sendproof/ui/api.js +239 -0
- data/lib/sendproof/ui/app.css +848 -0
- data/lib/sendproof/ui/app.js +742 -0
- data/lib/sendproof/ui/autofill.js +137 -0
- data/lib/sendproof/ui/code-copy.js +71 -0
- data/lib/sendproof/ui/code-picker.js +149 -0
- data/lib/sendproof/ui/commands.js +197 -0
- data/lib/sendproof/ui/components.js +77 -0
- data/lib/sendproof/ui/context-bar.js +82 -0
- data/lib/sendproof/ui/copy.js +92 -0
- data/lib/sendproof/ui/coverage-popover.js +35 -0
- data/lib/sendproof/ui/crumb-fit.js +80 -0
- data/lib/sendproof/ui/deprecation.js +164 -0
- data/lib/sendproof/ui/display-settings.js +175 -0
- data/lib/sendproof/ui/doc-diff.js +209 -0
- data/lib/sendproof/ui/docs-view.js +347 -0
- data/lib/sendproof/ui/favicon.png +0 -0
- data/lib/sendproof/ui/favicon.svg +1 -0
- data/lib/sendproof/ui/field-help.js +52 -0
- data/lib/sendproof/ui/field-modules.js +23 -0
- data/lib/sendproof/ui/fields/controls.js +179 -0
- data/lib/sendproof/ui/fields/dom.js +36 -0
- data/lib/sendproof/ui/fields/infer.js +71 -0
- data/lib/sendproof/ui/fields/lookup-source.js +63 -0
- data/lib/sendproof/ui/fields/lookup.js +285 -0
- data/lib/sendproof/ui/fields/render.js +496 -0
- data/lib/sendproof/ui/fields/select.js +175 -0
- data/lib/sendproof/ui/fields/validate.js +363 -0
- data/lib/sendproof/ui/fields/validation-formats.js +164 -0
- data/lib/sendproof/ui/fields/validation-references.js +68 -0
- data/lib/sendproof/ui/fields/validation-values.js +137 -0
- data/lib/sendproof/ui/generate-menu.js +44 -0
- data/lib/sendproof/ui/generate.js +184 -0
- data/lib/sendproof/ui/header-editor.js +777 -0
- data/lib/sendproof/ui/headers.js +188 -0
- data/lib/sendproof/ui/highlight.js +257 -0
- data/lib/sendproof/ui/history-popover.js +24 -0
- data/lib/sendproof/ui/i18n.js +253 -0
- data/lib/sendproof/ui/icons.js +87 -0
- data/lib/sendproof/ui/index.html +70 -0
- data/lib/sendproof/ui/issues.js +187 -0
- data/lib/sendproof/ui/json-view.js +166 -0
- data/lib/sendproof/ui/lang-icons.js +62 -0
- data/lib/sendproof/ui/layout.js +262 -0
- data/lib/sendproof/ui/listbox.js +334 -0
- data/lib/sendproof/ui/locales/ar-capture.js +366 -0
- data/lib/sendproof/ui/locales/ar-stores.js +116 -0
- data/lib/sendproof/ui/locales/ar.js +561 -0
- data/lib/sendproof/ui/locales/cs-capture.js +442 -0
- data/lib/sendproof/ui/locales/cs-stores.js +116 -0
- data/lib/sendproof/ui/locales/cs.js +689 -0
- data/lib/sendproof/ui/locales/da-capture.js +347 -0
- data/lib/sendproof/ui/locales/da-stores.js +116 -0
- data/lib/sendproof/ui/locales/da.js +522 -0
- data/lib/sendproof/ui/locales/de-capture.js +347 -0
- data/lib/sendproof/ui/locales/de-stores.js +116 -0
- data/lib/sendproof/ui/locales/de.js +519 -0
- data/lib/sendproof/ui/locales/el-capture.js +347 -0
- data/lib/sendproof/ui/locales/el-stores.js +116 -0
- data/lib/sendproof/ui/locales/el.js +520 -0
- data/lib/sendproof/ui/locales/en-capture.js +349 -0
- data/lib/sendproof/ui/locales/en-stores.js +95 -0
- data/lib/sendproof/ui/locales/en.js +522 -0
- data/lib/sendproof/ui/locales/es-capture.js +353 -0
- data/lib/sendproof/ui/locales/es-stores.js +116 -0
- data/lib/sendproof/ui/locales/es.js +525 -0
- data/lib/sendproof/ui/locales/fa-capture.js +348 -0
- data/lib/sendproof/ui/locales/fa-stores.js +116 -0
- data/lib/sendproof/ui/locales/fa.js +521 -0
- data/lib/sendproof/ui/locales/fi-capture.js +347 -0
- data/lib/sendproof/ui/locales/fi-stores.js +116 -0
- data/lib/sendproof/ui/locales/fi.js +523 -0
- data/lib/sendproof/ui/locales/fr-capture.js +353 -0
- data/lib/sendproof/ui/locales/fr-stores.js +116 -0
- data/lib/sendproof/ui/locales/fr.js +525 -0
- data/lib/sendproof/ui/locales/he-capture.js +358 -0
- data/lib/sendproof/ui/locales/he-stores.js +116 -0
- data/lib/sendproof/ui/locales/he.js +529 -0
- data/lib/sendproof/ui/locales/hi-capture.js +348 -0
- data/lib/sendproof/ui/locales/hi-stores.js +116 -0
- data/lib/sendproof/ui/locales/hi.js +523 -0
- data/lib/sendproof/ui/locales/id-capture.js +347 -0
- data/lib/sendproof/ui/locales/id-stores.js +116 -0
- data/lib/sendproof/ui/locales/id.js +521 -0
- data/lib/sendproof/ui/locales/it-capture.js +361 -0
- data/lib/sendproof/ui/locales/it-stores.js +116 -0
- data/lib/sendproof/ui/locales/it.js +523 -0
- data/lib/sendproof/ui/locales/ja-capture.js +346 -0
- data/lib/sendproof/ui/locales/ja-stores.js +116 -0
- data/lib/sendproof/ui/locales/ja.js +521 -0
- data/lib/sendproof/ui/locales/ko-capture.js +346 -0
- data/lib/sendproof/ui/locales/ko-stores.js +116 -0
- data/lib/sendproof/ui/locales/ko.js +522 -0
- data/lib/sendproof/ui/locales/nb-capture.js +349 -0
- data/lib/sendproof/ui/locales/nb-stores.js +116 -0
- data/lib/sendproof/ui/locales/nb.js +521 -0
- data/lib/sendproof/ui/locales/nl-capture.js +355 -0
- data/lib/sendproof/ui/locales/nl-stores.js +116 -0
- data/lib/sendproof/ui/locales/nl.js +520 -0
- data/lib/sendproof/ui/locales/pl-capture.js +432 -0
- data/lib/sendproof/ui/locales/pl-stores.js +116 -0
- data/lib/sendproof/ui/locales/pl.js +528 -0
- data/lib/sendproof/ui/locales/pt-BR-capture.js +350 -0
- data/lib/sendproof/ui/locales/pt-BR-stores.js +116 -0
- data/lib/sendproof/ui/locales/pt-BR.js +523 -0
- data/lib/sendproof/ui/locales/pt-PT-capture.js +350 -0
- data/lib/sendproof/ui/locales/pt-PT-stores.js +116 -0
- data/lib/sendproof/ui/locales/pt-PT.js +523 -0
- data/lib/sendproof/ui/locales/ru-capture.js +437 -0
- data/lib/sendproof/ui/locales/ru-stores.js +116 -0
- data/lib/sendproof/ui/locales/ru.js +624 -0
- data/lib/sendproof/ui/locales/sv-capture.js +349 -0
- data/lib/sendproof/ui/locales/sv-stores.js +116 -0
- data/lib/sendproof/ui/locales/sv.js +518 -0
- data/lib/sendproof/ui/locales/th-capture.js +347 -0
- data/lib/sendproof/ui/locales/th-stores.js +116 -0
- data/lib/sendproof/ui/locales/th.js +521 -0
- data/lib/sendproof/ui/locales/tr-capture.js +348 -0
- data/lib/sendproof/ui/locales/tr-stores.js +116 -0
- data/lib/sendproof/ui/locales/tr.js +521 -0
- data/lib/sendproof/ui/locales/uk-capture.js +442 -0
- data/lib/sendproof/ui/locales/uk-stores.js +116 -0
- data/lib/sendproof/ui/locales/uk.js +630 -0
- data/lib/sendproof/ui/locales/vi-capture.js +346 -0
- data/lib/sendproof/ui/locales/vi-stores.js +116 -0
- data/lib/sendproof/ui/locales/vi.js +523 -0
- data/lib/sendproof/ui/locales/zh-Hans-capture.js +347 -0
- data/lib/sendproof/ui/locales/zh-Hans-stores.js +116 -0
- data/lib/sendproof/ui/locales/zh-Hans.js +523 -0
- data/lib/sendproof/ui/locales/zh-Hant-capture.js +346 -0
- data/lib/sendproof/ui/locales/zh-Hant-stores.js +116 -0
- data/lib/sendproof/ui/locales/zh-Hant.js +522 -0
- data/lib/sendproof/ui/manifest.json +866 -0
- data/lib/sendproof/ui/markdown.js +39 -0
- data/lib/sendproof/ui/model-view.js +182 -0
- data/lib/sendproof/ui/navigation.js +233 -0
- data/lib/sendproof/ui/operation-header.js +76 -0
- data/lib/sendproof/ui/operations.js +7 -0
- data/lib/sendproof/ui/overview-view.js +63 -0
- data/lib/sendproof/ui/personas.js +59 -0
- data/lib/sendproof/ui/popover.js +71 -0
- data/lib/sendproof/ui/preview-false.js +108 -0
- data/lib/sendproof/ui/request-editor.js +496 -0
- data/lib/sendproof/ui/response-metadata.js +354 -0
- data/lib/sendproof/ui/response-viewer.js +618 -0
- data/lib/sendproof/ui/result-blocked.js +155 -0
- data/lib/sendproof/ui/result-capture.js +25 -0
- data/lib/sendproof/ui/result-database.js +185 -0
- data/lib/sendproof/ui/result-effects.js +176 -0
- data/lib/sendproof/ui/result-headers.js +106 -0
- data/lib/sendproof/ui/result-logs.js +408 -0
- data/lib/sendproof/ui/result-states.js +213 -0
- data/lib/sendproof/ui/results.js +371 -0
- data/lib/sendproof/ui/router.js +118 -0
- data/lib/sendproof/ui/schema-model.js +336 -0
- data/lib/sendproof/ui/schema-tree.js +344 -0
- data/lib/sendproof/ui/schema.js +397 -0
- data/lib/sendproof/ui/security.js +31 -0
- data/lib/sendproof/ui/seeded-menu.js +69 -0
- data/lib/sendproof/ui/settings.js +93 -0
- data/lib/sendproof/ui/shortcuts-sheet.js +73 -0
- data/lib/sendproof/ui/shortcuts.js +190 -0
- data/lib/sendproof/ui/sidebar.js +289 -0
- data/lib/sendproof/ui/signin.js +259 -0
- data/lib/sendproof/ui/snippets.js +530 -0
- data/lib/sendproof/ui/store-marks.js +47 -0
- data/lib/sendproof/ui/stores.js +131 -0
- data/lib/sendproof/ui/styles.css +971 -0
- data/lib/sendproof/ui/toggletip.js +53 -0
- data/lib/sendproof/ui/uuid.js +10 -0
- data/lib/sendproof/ui/view.js +122 -0
- data/lib/sendproof/ui/views.css +653 -0
- data/lib/sendproof/version.rb +9 -0
- data/lib/sendproof/workbench.rb +102 -0
- data/lib/sendproof-core.rb +3 -0
- data/lib/sendproof.rb +121 -0
- metadata +292 -0
|
@@ -0,0 +1,618 @@
|
|
|
1
|
+
// The Response tab's viewer (mocks 100–106, 111, m22): follow-ups and timing, then one viewer
|
|
2
|
+
// with a one-line toolbar (Pretty, Raw, Table, Schema at the start; icon actions at the end) and
|
|
3
|
+
// a body that never wraps. Pretty keeps its line numbers and folds sticky while long lines scroll
|
|
4
|
+
// sideways; Raw is the bytes as received with an optional Wrap; Table is a real table with a
|
|
5
|
+
// sticky header, row numbers and name column; Schema is the attribute list in compact rows with
|
|
6
|
+
// a presence mark at each line's end. The schema match lives in the result's status line
|
|
7
|
+
// (matchButton), with a toggletip that lists every issue.
|
|
8
|
+
import { copyButton, copyTextButton, esc, icon, method } from './components.js';
|
|
9
|
+
import { bindTrees, propertyTree } from './schema-tree.js';
|
|
10
|
+
import { buildJsonLines, codeLine, largeNote, pathId, visibleLines } from './json-view.js';
|
|
11
|
+
import { copyText } from './copy.js';
|
|
12
|
+
import { formatBytes, formatDuration, formatNumber, t, th } from './i18n.js';
|
|
13
|
+
import { shortcutAttrs, shortcutHint } from './shortcuts.js';
|
|
14
|
+
import { closePopover, openPopover, openPopoverAt } from './popover.js';
|
|
15
|
+
import {
|
|
16
|
+
responseDefinition, responseFollowUps, responseMediaType, responseSchema, responseTimings,
|
|
17
|
+
} from './response-metadata.js';
|
|
18
|
+
|
|
19
|
+
const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
20
|
+
const own = (value, key) => Object.hasOwn(value, key) ? value[key] : undefined;
|
|
21
|
+
const token = (text, kind) => ({ text, kind });
|
|
22
|
+
const findAction = 'find-response';
|
|
23
|
+
const copyAction = 'copy-response';
|
|
24
|
+
const followAction = 'follow-response';
|
|
25
|
+
const bindings = new WeakMap();
|
|
26
|
+
|
|
27
|
+
function jsonContent(raw) {
|
|
28
|
+
const numbers = new WeakMap();
|
|
29
|
+
let rootNumber;
|
|
30
|
+
// Preserve the wire spelling of decimals and large numbers where the browser supplies it.
|
|
31
|
+
const body = JSON.parse(raw, function (key, value, context) {
|
|
32
|
+
rootNumber = typeof value === 'number' ? context?.source : undefined;
|
|
33
|
+
if (rootNumber !== undefined) {
|
|
34
|
+
if (!numbers.has(this)) numbers.set(this, new Map());
|
|
35
|
+
numbers.get(this).set(key, rootNumber);
|
|
36
|
+
}
|
|
37
|
+
return value;
|
|
38
|
+
});
|
|
39
|
+
return { body, raw, json: true, numbers, rootNumber };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function bodyContent(result) {
|
|
43
|
+
const mediaType = responseMediaType(result);
|
|
44
|
+
const body = result.body;
|
|
45
|
+
const jsonType = mediaType.endsWith('/json') || mediaType.endsWith('+json');
|
|
46
|
+
if (typeof result.raw === 'string') {
|
|
47
|
+
if (result.raw === '') return { mediaType };
|
|
48
|
+
if (jsonType || !mediaType) {
|
|
49
|
+
try { return { ...jsonContent(result.raw), mediaType }; }
|
|
50
|
+
catch { /* Malformed or non-JSON bodies remain inspectable as text. */ }
|
|
51
|
+
}
|
|
52
|
+
return { body: result.raw, raw: result.raw, json: false, malformed: jsonType, mediaType };
|
|
53
|
+
}
|
|
54
|
+
if (body === undefined || (body === null && (!jsonType || [204, 205, 304].includes(result.status))) || (body === '' && !jsonType)) {
|
|
55
|
+
return { mediaType };
|
|
56
|
+
}
|
|
57
|
+
const json = jsonType || typeof body !== 'string';
|
|
58
|
+
return { body, raw: json ? JSON.stringify(body, null, 2) : body, json, mediaType };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function titleOf(operation) {
|
|
62
|
+
return operation.title ?? operation.operation?.summary ?? operation.method + ' ' + operation.path;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function followUpMarkup(followUps) {
|
|
66
|
+
if (!followUps.length) return '';
|
|
67
|
+
const names = new Set(followUps.flatMap(item => item.paths.map(path => path.at(-1))));
|
|
68
|
+
const intro = names.size === 1 && [...names][0] !== undefined
|
|
69
|
+
? th('resp.useNameIn', { name: `<code>${esc([...names][0])}</code>` }) : esc(t('resp.useResultIn'));
|
|
70
|
+
const buttons = followUps.map(({ operation, name }, index) => {
|
|
71
|
+
const secured = operation.operation?.security?.some(item => Object.values(item).some(scopes => scopes.length));
|
|
72
|
+
const permission = secured ? `<span class="faint">${icon('lock', true)}<span class="sr-only">${esc(t('resp.needsPermission'))}</span></span>` : '';
|
|
73
|
+
return `<button type="button" class="chain" data-follow-up="${index}"${name ? ` title="${esc(name)}"` : ''} ${index === 0 ? shortcutAttrs(followAction) : ''}>${method(operation.method)}<span>${esc(titleOf(operation))}</span>${permission}${index === 0 ? shortcutHint(followAction) : ''}</button>`;
|
|
74
|
+
}).join('');
|
|
75
|
+
return `<div class="next-steps" role="group" aria-label="${esc(t('resp.useResult'))}"><span class="faint">${intro}</span>${buttons}</div>`;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function timingMarkup(result) {
|
|
79
|
+
const metrics = responseTimings(result);
|
|
80
|
+
if (!metrics.length) return '';
|
|
81
|
+
const total = metrics.reduce((sum, metric) => sum + metric.duration, 0);
|
|
82
|
+
const bar = total > 0 ? `<div class="timing-bar" aria-hidden="true">${metrics.filter(metric => metric.duration > 0).map(metric =>
|
|
83
|
+
`<span style="flex:${metric.duration};background:${metric.color}"></span>`).join('')}</div>` : '';
|
|
84
|
+
const legend = metrics.map(({ label, color, duration, description }) =>
|
|
85
|
+
`<span><i style="background:${color}" aria-hidden="true"></i>${esc(label)} ${esc(formatDuration(duration))}${description ? ' · ' + esc(description) : ''}</span>`).join('');
|
|
86
|
+
return `<div class="timing" role="group" aria-label="${esc(t('resp.timingTotal', { n: Math.round(total) }))}">${bar}<div class="timing-legend">${legend}</div></div>`;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function validationMarkup(result, body) {
|
|
90
|
+
if (!(result.status >= 400) || !object(body?.errors)) return '';
|
|
91
|
+
const fields = Object.keys(body.errors).length;
|
|
92
|
+
const detail = typeof body.detail === 'string' ? body.detail
|
|
93
|
+
: fields ? t('resp.fieldsNeedAttention', { n: fields }) : '';
|
|
94
|
+
return `<div class="effect">${icon('alert', true)}<div><div class="t">${esc(t('resp.validationProblem'))}</div>${detail ? `<div class="s">${esc(detail)}</div>` : ''}</div></div>`;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Keys whose values name a record; the first one present leads the table and stays in view. */
|
|
98
|
+
const LABEL_KEYS = ['name', 'title', 'label', 'displayName', 'reference', 'number'];
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* The Table view's model. A list (an array of objects, or a page object with one) is a table
|
|
102
|
+
* of its items, its columns in first-seen order with the record's label first; any other
|
|
103
|
+
* object is a Field / Value table.
|
|
104
|
+
*/
|
|
105
|
+
function tableRows(body, numbers, labelField) {
|
|
106
|
+
const text = (row, key) => {
|
|
107
|
+
const value = own(row, key);
|
|
108
|
+
if (value !== null && typeof value === 'object') return { nested: Array.isArray(value) ? t('resp.summary.items', { n: value.length }) : t('resp.summary.keys', { n: Object.keys(value).length }) };
|
|
109
|
+
if (value === null) return { text: 'null', null: true };
|
|
110
|
+
return { text: numbers?.get(row)?.get(key) ?? (typeof value === 'string' ? value : JSON.stringify(value) ?? '') , number: typeof value === 'number' };
|
|
111
|
+
};
|
|
112
|
+
const listKey = object(body) ? Object.keys(body).find(key => Array.isArray(body[key]) && body[key].length && body[key].every(object)) : undefined;
|
|
113
|
+
const items = Array.isArray(body) ? body : listKey !== undefined ? body[listKey] : undefined;
|
|
114
|
+
if (items?.length && items.every(object)) {
|
|
115
|
+
const columns = [...new Set(items.flatMap(Object.keys))];
|
|
116
|
+
const lead = [labelField, ...LABEL_KEYS].find(key => key && columns.includes(key));
|
|
117
|
+
if (lead) columns.splice(columns.indexOf(lead), 1), columns.unshift(lead);
|
|
118
|
+
const rows = items.map(row => columns.map(key => Object.hasOwn(row, key) ? text(row, key) : { text: '', missing: true }));
|
|
119
|
+
const numeric = new Set(columns.filter((key, column) => rows.every(row => row[column].number || row[column].null || row[column].missing)));
|
|
120
|
+
const pageOf = key => typeof own(body, key) === 'number' ? own(body, key) : undefined;
|
|
121
|
+
const page = object(body) ? { page: pageOf('page'), pages: pageOf('totalPages'), total: pageOf('totalItems') ?? pageOf('total') } : {};
|
|
122
|
+
return { list: true, path: listKey ?? '', headings: columns, rows, numeric, lead: !!lead, page, basePath: listKey !== undefined ? [listKey] : [] };
|
|
123
|
+
}
|
|
124
|
+
if (object(body) && Object.keys(body).length) {
|
|
125
|
+
return { list: false, headings: [t('resp.table.field'), t('resp.table.value')], rows: Object.keys(body).map(key => [{ text: key }, text(body, key)]), fields: true, numeric: new Set(), basePath: [] };
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function responseModel(result, context) {
|
|
130
|
+
const content = bodyContent(result);
|
|
131
|
+
const definition = responseDefinition(result, context);
|
|
132
|
+
const followUps = responseFollowUps(result, context, definition, content.body);
|
|
133
|
+
const pretty = content.json ? buildJsonLines(content) : undefined;
|
|
134
|
+
const table = content.json ? tableRows(content.body, content.numbers) : undefined;
|
|
135
|
+
const contentType = Object.entries(result.headers ?? {}).find(([name]) => name.toLowerCase() === 'content-type')?.[1] ?? (typeof result.headers?.get === 'function' ? result.headers.get('content-type') : undefined);
|
|
136
|
+
const rawLines = content.raw?.split(/\r\n|\n|\r/).map((text, index) => ({
|
|
137
|
+
id: 'raw-' + index, depth: 0, ancestors: [], tokens: [token(text)],
|
|
138
|
+
}));
|
|
139
|
+
const schema = !content.malformed && responseSchema(result, context, definition, content.body);
|
|
140
|
+
const firstLineFollowUps = new Map();
|
|
141
|
+
for (const [index, item] of followUps.entries()) {
|
|
142
|
+
for (const path of item.paths) {
|
|
143
|
+
const key = pathId(path);
|
|
144
|
+
if (!firstLineFollowUps.has(key)) firstLineFollowUps.set(key, index);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
return { ...content, followUps, pretty, table, rawLines, schema, firstLineFollowUps, contentType, lineIssues: schema && pretty ? issueLines(pretty.lines, schema) : undefined };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Pretty's issue marks (mock 101): each issue on the line of its value; a missing property on
|
|
152
|
+
* the line that opens its parent object.
|
|
153
|
+
*/
|
|
154
|
+
function issueLines(lines, check) {
|
|
155
|
+
const marks = new Map();
|
|
156
|
+
const ids = new Set(lines.map(line => line.id));
|
|
157
|
+
for (const issue of check.issues || []) {
|
|
158
|
+
const path = String(issue.path ?? '').split('.').filter(Boolean);
|
|
159
|
+
let id = pathId(path);
|
|
160
|
+
while (!ids.has(id) && path.length) { path.pop(); id = pathId(path); }
|
|
161
|
+
if (!marks.has(id)) marks.set(id, issue.message);
|
|
162
|
+
}
|
|
163
|
+
return marks;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function initialState(model) {
|
|
167
|
+
return {
|
|
168
|
+
mode: model.pretty ? 'pretty' : 'raw',
|
|
169
|
+
wrap: false,
|
|
170
|
+
folded: new Set(model.pretty?.initiallyFolded),
|
|
171
|
+
matches: [],
|
|
172
|
+
byLine: new Map(),
|
|
173
|
+
active: -1,
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function renderToken(text, kind) {
|
|
178
|
+
if (!kind) return esc(text);
|
|
179
|
+
return `<span class="${kind === 'folded' ? kind : 'tok-' + kind}">${esc(text)}</span>`;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function markedTokens(tokens, matches = [], active) {
|
|
183
|
+
let offset = 0;
|
|
184
|
+
let index = 0;
|
|
185
|
+
return tokens.map(({ text, kind }) => {
|
|
186
|
+
let html = '';
|
|
187
|
+
let start = 0;
|
|
188
|
+
const end = offset + text.length;
|
|
189
|
+
while (index < matches.length && matches[index].start < end) {
|
|
190
|
+
const match = matches[index];
|
|
191
|
+
const from = Math.max(start, match.start - offset);
|
|
192
|
+
const to = Math.min(text.length, match.end - offset);
|
|
193
|
+
if (to > from) {
|
|
194
|
+
html += renderToken(text.slice(start, from), kind);
|
|
195
|
+
html += `<mark${match.index === active ? ' class="is-current" data-current-match' : ''}>${renderToken(text.slice(from, to), kind)}</mark>`;
|
|
196
|
+
start = to;
|
|
197
|
+
}
|
|
198
|
+
if (match.end > end) break;
|
|
199
|
+
index++;
|
|
200
|
+
}
|
|
201
|
+
offset = end;
|
|
202
|
+
return html + renderToken(text.slice(start), kind);
|
|
203
|
+
}).join('');
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function tableMarkup(table, state) {
|
|
207
|
+
const cell = (id, value) => markedTokens([token(value)], state.byLine.get(id), state.active);
|
|
208
|
+
const classes = (name, column) => [table.numeric.has(name) ? 'num' : '', table.lead && column === 0 ? 'lead' : ''].filter(Boolean).join(' ');
|
|
209
|
+
const headings = table.headings.map((name, index) => `<th scope="col"${classes(name, index) ? ` class="${classes(name, index)}"` : ''}>${cell('heading-' + index, name)}</th>`).join('');
|
|
210
|
+
const rows = table.rows.map((row, index) => `<tr>${table.list ? `<th scope="row" class="idx">${formatNumber(index + 1)}</th>` : ''}${row.map((value, column) => {
|
|
211
|
+
const id = 'cell-' + index + '-' + column;
|
|
212
|
+
const path = table.list ? [...table.basePath, index, table.headings[column]] : [table.rows[index][0].text];
|
|
213
|
+
const html = value.nested !== undefined ? `<button type="button" class="obj" data-table-open="${esc(pathId(path))}">${esc(value.nested)}</button>`
|
|
214
|
+
: value.null ? `<span class="null">${cell(id, value.text)}</span>` : cell(id, value.text);
|
|
215
|
+
const cls = classes(table.headings[column], column);
|
|
216
|
+
return table.fields && column === 0 ? `<th scope="row">${html}</th>` : `<td${cls ? ` class="${cls}"` : ''}>${html}</td>`;
|
|
217
|
+
}).join('')}</tr>`).join('');
|
|
218
|
+
const label = table.list ? t('resp.table.of', { name: table.path || t('resp.body') }) : t('resp.tableLabel');
|
|
219
|
+
const foot = table.list
|
|
220
|
+
? `<span>${th('resp.table.foot', { n: table.rows.length, path: `<code>${esc(table.path || '[]')}</code>` })}${table.page.page !== undefined && table.page.pages !== undefined ? ` · ${esc(t('resp.table.page', { page: formatNumber(table.page.page), pages: formatNumber(table.page.pages), total: formatNumber(table.page.total ?? table.rows.length) }))}` : ''}</span>`
|
|
221
|
+
: `<span>${esc(t('resp.table.fields', { n: table.rows.length }))}</span>`;
|
|
222
|
+
const more = table.list ? `<button type="button" class="tbl-more" data-table-more title="${esc(t("resp.table.moreLabel", { n: formatNumber(table.headings.length) }))}" hidden>${esc(t('resp.table.more', { n: formatNumber(table.headings.length) }))}${icon('arrow-right', true)}</button>` : '';
|
|
223
|
+
return `<div class="tbl-wrap"><div class="tbl${table.fields ? ' is-kv' : ''}" role="region" tabindex="0" aria-label="${esc(label)}"><table><thead><tr>${table.list ? '<th scope="col" class="idx">#</th>' : ''}${headings}</tr></thead><tbody>${rows}</tbody></table></div></div>
|
|
224
|
+
<div class="vb-foot">${foot}<span class="spacer"></span>${more}</div>`;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function lineMarkup(model, line, number, folded, state) {
|
|
228
|
+
const note = state.mode === 'pretty' ? model.lineIssues?.get(line.id) : undefined;
|
|
229
|
+
const index = model.firstLineFollowUps.get(line.id);
|
|
230
|
+
const action = model.followUps[index];
|
|
231
|
+
const actions = line.copy === undefined && !action ? '' : `<span class="line-acts">
|
|
232
|
+
${line.copy !== undefined ? copyTextButton(t('code.copy'), { cls: 'btn-xs', data: `data-copy-line="${esc(line.id)}" aria-label="${esc(t('resp.copyLine', { n: formatNumber(number) }))}"` }) : ''}
|
|
233
|
+
${action ? `<button type="button" class="btn btn-xs" data-follow-up="${index}">${esc(t('resp.openIn', { title: titleOf(action.operation) }))}${index === 0 ? shortcutHint(followAction) : ''}</button>` : ''}
|
|
234
|
+
</span>`;
|
|
235
|
+
return codeLine(line, number, folded, markedTokens(folded ? line.folded : line.tokens, folded ? [] : state.byLine.get(line.id), state.active), actions, note ? { cls: 'is-issue', note } : {});
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* The Schema view (mock 30): the documented response schema, marking which top-level
|
|
240
|
+
* properties this response returned, with a link to the model page.
|
|
241
|
+
*/
|
|
242
|
+
/** The dotted paths a body returned, in the form the property tree uses: `items[].id`, `bankDetails.scheme`. */
|
|
243
|
+
export function presentPaths(value, prefix = '', paths = new Set()) {
|
|
244
|
+
if (Array.isArray(value)) value.forEach(item => presentPaths(item, prefix + '[]', paths));
|
|
245
|
+
else if (value && typeof value === 'object') {
|
|
246
|
+
for (const [key, child] of Object.entries(value)) {
|
|
247
|
+
const path = prefix ? `${prefix}.${key}` : key;
|
|
248
|
+
paths.add(path);
|
|
249
|
+
presentPaths(child, path, paths);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
return paths;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** The validator's dotted path (items.0.name) as the attribute list's path (items[].name). */
|
|
256
|
+
export const treePath = path => String(path ?? '').split('.').filter(Boolean).map(part => /^\d+$/.test(part) ? '[]' : part).join('.').replace(/\.\[\]/g, '[]');
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* The Schema view (mocks 102, 103): a one-line legend, then the documented schema in compact
|
|
260
|
+
* rows with a mark at each line's end (returned, not returned, doesn't match). Failing rows carry
|
|
261
|
+
* their reason; properties the schema doesn't document are listed as "Not in the schema".
|
|
262
|
+
*/
|
|
263
|
+
function schemaMarkup(model, document) {
|
|
264
|
+
const present = presentPaths(model.body);
|
|
265
|
+
const check = model.schema;
|
|
266
|
+
const issues = Object.fromEntries((check.issues || []).filter(issue => !issue.extra).map(issue => [treePath(issue.path), issue.message]));
|
|
267
|
+
const extra = (check.extra || []).map(item => ({ ...item, issue: t('match.extra', { model: check.name }) }));
|
|
268
|
+
const link = check.ref ? `<a class="type-link" href="#model/${encodeURIComponent(check.ref)}" data-model="${esc(check.ref)}">${esc(check.ref)} ${icon('arrow-right', true)}</a>` : '';
|
|
269
|
+
const legendMark = kind => `<span class="attr-mark is-${kind}" aria-hidden="true"></span>`;
|
|
270
|
+
return `<div class="schema-pane">
|
|
271
|
+
<div class="legend"><span>${legendMark('on')}${esc(t('resp.legend.on'))}</span><span>${legendMark('off')}${esc(t('resp.legend.off'))}</span>${check.matches ? '' : `<span>${legendMark('issue')}${esc(t('resp.legend.issue'))}</span>`}<span class="spacer"></span>${link}</div>
|
|
272
|
+
${propertyTree(check.raw, document, { id: 'rs', compact: true, present, issues, extra, label: check.name })}
|
|
273
|
+
</div>`;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
function viewerBody(model, state) {
|
|
277
|
+
if (state.mode === 'schema') return schemaMarkup(model, state.document);
|
|
278
|
+
if (state.mode === 'table') return tableMarkup(model.table, state);
|
|
279
|
+
const lines = state.mode === 'pretty' ? model.pretty.lines : model.rawLines;
|
|
280
|
+
const folded = id => state.folded.has(id);
|
|
281
|
+
const content = visibleLines(lines, state.folded).map((line, index) => lineMarkup(model, line, index + 1, folded(line.id), state)).join('');
|
|
282
|
+
const type = model.mediaType || (model.json ? 'application/json' : '');
|
|
283
|
+
const label = type ? t('resp.bodyType', { type }) : t('resp.body');
|
|
284
|
+
const note = state.mode === 'pretty' && model.pretty.large ? largeNote(model.raw.length, model.pretty.lines.length) : '';
|
|
285
|
+
// Raw is the bytes as received: one line for compact JSON, with Wrap as an option.
|
|
286
|
+
const foot = state.mode === 'raw' ? `<div class="vb-foot"><span>${th('resp.raw.foot', { n: model.rawLines.length, size: esc(formatBytes(new TextEncoder().encode(model.raw).length)), type: `<code>${esc(model.contentType || type || 'text/plain')}</code>` })}</span><span class="spacer"></span><span class="hint">${esc(t(state.wrap ? 'resp.raw.wrapped' : 'resp.raw.scroll'))}</span></div>` : '';
|
|
287
|
+
return `${note}<div class="vb-scroll" tabindex="0" role="region" aria-label="${esc(label)}"><div class="code-view${state.mode === 'raw' ? ' is-raw' : ''}${state.mode === 'raw' && state.wrap ? ' is-wrap' : ''}" role="group" aria-label="${esc(label)}">${content}</div></div>${foot}`;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** The Collapse all / Expand all button: a label that gives way to its icon in a narrow pane. */
|
|
291
|
+
const foldAllButton = (label, hidden) => `<button type="button" class="btn btn-ghost btn-xs vb-lbl" data-fold-all title="${esc(label)}" aria-label="${esc(label)}" ${shortcutAttrs('fold-all')}${hidden ? ' hidden' : ''}>${icon('chevrons-ud', true)}<span class="lbl" data-fold-all-label>${esc(label)}</span></button>`;
|
|
292
|
+
|
|
293
|
+
/** An icon button for the viewer bar; `label` is plain text and becomes the aria-label and tooltip. */
|
|
294
|
+
function control(action, symbol, label, extra = '') {
|
|
295
|
+
return `<button type="button" class="btn btn-ghost btn-icon btn-xs" aria-label="${esc(label)}" title="${esc(label)}" ${action ? `data-action="${action}" ${shortcutAttrs(action)}` : ''} ${extra}>${icon(symbol, true)}</button>`;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/** Render the response tab contents, including only features supported by this result. */
|
|
299
|
+
export function responseMarkup(result, context = {}) {
|
|
300
|
+
const model = responseModel(result, context);
|
|
301
|
+
const state = initialState(model);
|
|
302
|
+
const overview = followUpMarkup(model.followUps) + timingMarkup(result) + validationMarkup(result, model.body);
|
|
303
|
+
if (model.raw === undefined) return `<div class="response-viewer">${overview}<div class="viewer-empty faint">${esc(t('resp.noBody'))}</div></div>`;
|
|
304
|
+
state.document = context.document;
|
|
305
|
+
const modes = ['pretty', 'raw', 'table', 'schema'].filter(mode => mode === 'raw' || (mode === 'pretty' ? model.pretty : mode === 'table' ? model.table : model.schema?.raw && context.document));
|
|
306
|
+
const buttons = modes.map(mode => `<button type="button" data-response-mode="${mode}" aria-pressed="${mode === state.mode}">${esc(t('resp.mode.' + mode))}</button>`).join('');
|
|
307
|
+
const foldAllLabel = t(state.folded.size ? 'resp.expandAll' : 'resp.collapseAll');
|
|
308
|
+
// One toolbar line at every width: views at the start, icon actions at the end.
|
|
309
|
+
return `<div class="response-viewer">${overview}<div class="viewer v5-viewer">
|
|
310
|
+
<div class="viewer-bar vb">
|
|
311
|
+
<div class="segmented sm" role="group" aria-label="${esc(t('resp.bodyView'))}">${buttons}</div><span class="spacer"></span>
|
|
312
|
+
${foldAllButton(foldAllLabel, state.mode !== 'pretty' || !model.pretty?.branches.size)}
|
|
313
|
+
${control('', 'wrap', t('resp.wrap'), `data-wrap aria-pressed="false"${state.mode === 'raw' ? '' : ' hidden'} ${shortcutAttrs('wrap-lines')}`)}
|
|
314
|
+
${control(findAction, 'search', t('resp.search'), 'aria-expanded="false"')}
|
|
315
|
+
${copyButton(t('resp.copyBody'), { action: copyAction, shortcut: copyAction, size: 'btn-xs' })}
|
|
316
|
+
</div>
|
|
317
|
+
<div class="response-find" role="search" aria-label="${esc(t('resp.body'))}" hidden>
|
|
318
|
+
<label class="input-sm">${icon('search', true)}<input type="search" aria-label="${esc(t('resp.find'))}" placeholder="${esc(t('resp.find'))}" spellcheck="false"></label>
|
|
319
|
+
<span class="faint" data-match-count role="status"></span>
|
|
320
|
+
${control('', 'arrow-up', t('resp.prevMatch'), 'data-match-step="-1" disabled')}
|
|
321
|
+
${control('', 'arrow-down', t('resp.nextMatch'), 'data-match-step="1" disabled')}
|
|
322
|
+
${control('', 'x', t('resp.closeSearch'), 'data-close-response-find')}
|
|
323
|
+
</div>
|
|
324
|
+
<div class="vb-body" data-response-content data-mode="${state.mode}">${viewerBody(model, state)}</div>
|
|
325
|
+
</div></div>`;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* The schema match in the result's status line (mocks 100, 101): a quiet "✓ Matches schema", or
|
|
330
|
+
* an amber "⚠ 3 schema issues". Its toggletip says what was checked or lists each issue.
|
|
331
|
+
* Returns '' when the response has no documented schema to check against.
|
|
332
|
+
*/
|
|
333
|
+
export function matchButton(result, context = {}) {
|
|
334
|
+
const check = schemaCheck(result, context);
|
|
335
|
+
if (!check) return '';
|
|
336
|
+
const count = check.issues.length;
|
|
337
|
+
return check.matches
|
|
338
|
+
? `<button type="button" class="match" id="match-btn" data-match aria-haspopup="dialog" aria-expanded="false">${icon('circle-check', true)}<span class="full">${esc(t('match.ok'))}</span><span class="short" aria-hidden="true">${esc(t('resp.mode.schema'))}</span></button>`
|
|
339
|
+
: `<button type="button" class="match is-fail" id="match-btn" data-match aria-haspopup="dialog" aria-expanded="false">${icon('warn', true)}<span class="full">${esc(t('match.issues', { n: count }))}</span><span class="short" aria-hidden="true">${esc(formatNumber(count))}</span></button>`;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/** The documented schema and how the body compares with it, or undefined. */
|
|
343
|
+
export function schemaCheck(result, context = {}) {
|
|
344
|
+
const model = responseModel(result, context);
|
|
345
|
+
return model.schema?.raw && context.document ? model.schema : undefined;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/** The match toggletip's content. */
|
|
349
|
+
export function matchTip(result, context = {}) {
|
|
350
|
+
const check = schemaCheck(result, context);
|
|
351
|
+
if (!check) return '';
|
|
352
|
+
const model = check.ref ? `<a class="type-link" href="#model/${encodeURIComponent(check.ref)}" data-model="${esc(check.ref)}">${esc(check.ref)}</a>` : `<code>${esc(check.name)}</code>`;
|
|
353
|
+
const media = Object.entries(result.headers ?? {}).find(([name]) => name.toLowerCase() === 'content-type')?.[1]?.split(';')[0] ?? 'application/json';
|
|
354
|
+
const shown = check.issues.slice(0, 8);
|
|
355
|
+
const body = check.matches
|
|
356
|
+
? `<h3 id="match-h">${icon('circle-check', true)}${esc(t('match.okTitle'))}</h3>
|
|
357
|
+
<p>${th('match.okBody', { model, n: check.properties })}</p>
|
|
358
|
+
<dl class="facts"><dt>${esc(t('match.schema'))}</dt><dd><span class="ltr">${esc(String(result.status))} · ${esc(media)}</span> · ${model}</dd><dt>${esc(t('match.checked'))}</dt><dd class="plain">${esc(t('match.checks'))}</dd></dl>`
|
|
359
|
+
: `<h3 id="match-h">${icon('warn', true)}${esc(t('match.failTitle', { n: check.issues.length }))}</h3>
|
|
360
|
+
<p>${th('match.failBody', { model, status: `<span class="ltr">${esc(String(result.status))}</span>` })}</p>
|
|
361
|
+
<ul class="issue-list">${shown.map(issue => `<li><code>${esc(issue.path || '$')}</code><span>${esc(issue.message)}</span></li>`).join('')}</ul>
|
|
362
|
+
${check.issues.length > shown.length ? `<p class="faint">${esc(t('match.more', { n: check.issues.length - shown.length }))}</p>` : ''}
|
|
363
|
+
<p class="faint note">${esc(t('match.note'))}</p>`;
|
|
364
|
+
return `<div class="pop toggletip match-tip${check.matches ? '' : ' is-fail'}" role="dialog" aria-labelledby="match-h">
|
|
365
|
+
<div class="tt-body">${body}</div>
|
|
366
|
+
<div class="tt-foot"><button type="button" class="link" data-match-schema>${esc(t('match.showSchema'))}</button>${check.matches ? '' : `<button type="button" class="link" data-match-copy>${esc(t('match.copy'))}</button>`}<span class="spacer"></span>${shortcutHint('escape')}</div>
|
|
367
|
+
</div>`;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/** Wires the match button in the status line: its toggletip, Show in Schema view and Copy issues. */
|
|
371
|
+
export function bindMatch(head, result, context = {}) {
|
|
372
|
+
const button = head?.querySelector('[data-match]');
|
|
373
|
+
if (!button) return;
|
|
374
|
+
button.addEventListener('click', () => {
|
|
375
|
+
if (openPopover()?.anchor === button) { closePopover(); return; }
|
|
376
|
+
const pop = openPopoverAt(button, matchTip(result, context), { gap: 10, arrow: true, kind: 'toggletip', focus: false });
|
|
377
|
+
pop.addEventListener('click', event => {
|
|
378
|
+
if (event.target.closest('[data-match-schema]')) {
|
|
379
|
+
closePopover();
|
|
380
|
+
document.querySelector('.response-viewer')?.setMode?.('schema');
|
|
381
|
+
} else if (event.target.closest('[data-match-copy]')) {
|
|
382
|
+
const check = schemaCheck(result, context);
|
|
383
|
+
void copyText(check.issues.map(issue => `${issue.path || '$'}: ${issue.message}`).join('\n'), { button: event.target.closest('[data-match-copy]'), what: t('match.what') });
|
|
384
|
+
}
|
|
385
|
+
});
|
|
386
|
+
});
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
function searchLines(model, mode) {
|
|
390
|
+
if (mode === 'table') return [
|
|
391
|
+
...model.table.headings.map((text, index) => ({ id: 'heading-' + index, tokens: [token(text)] })),
|
|
392
|
+
...model.table.rows.flatMap((row, index) => row.map((cell, column) => ({ id: 'cell-' + index + '-' + column, tokens: [token(cell.text ?? '')] }))),
|
|
393
|
+
];
|
|
394
|
+
return mode === 'pretty' ? model.pretty.lines : model.rawLines;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
function searchBody(model, state, query) {
|
|
398
|
+
state.matches = [];
|
|
399
|
+
state.byLine.clear();
|
|
400
|
+
state.active = -1;
|
|
401
|
+
if (!query) return;
|
|
402
|
+
// The Schema view searches its attribute names once they're drawn (markSchema).
|
|
403
|
+
if (state.mode === 'schema') { state.active = 0; return; }
|
|
404
|
+
const pattern = new RegExp(query.replace(/[.*+?^$(){}|[\]\\]/g, '\\$&'), 'giu');
|
|
405
|
+
for (const line of searchLines(model, state.mode)) {
|
|
406
|
+
const text = line.tokens.map(part => part.text).join('');
|
|
407
|
+
const matches = Array.from(text.matchAll(pattern), match => {
|
|
408
|
+
const found = { line, start: match.index, end: match.index + match[0].length, index: state.matches.length };
|
|
409
|
+
state.matches.push(found);
|
|
410
|
+
return found;
|
|
411
|
+
});
|
|
412
|
+
if (matches.length) state.byLine.set(line.id, matches);
|
|
413
|
+
}
|
|
414
|
+
if (state.matches.length) state.active = 0;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/** Attach a result-scoped viewer. A fresh render resets its view, folds and search. */
|
|
418
|
+
export function bindResponseViewer(container, result, context = {}) {
|
|
419
|
+
const root = container.matches('.response-viewer') ? container : container.querySelector('.response-viewer');
|
|
420
|
+
if (!root) return;
|
|
421
|
+
bindings.get(root)?.abort();
|
|
422
|
+
const binding = new AbortController();
|
|
423
|
+
bindings.set(root, binding);
|
|
424
|
+
const { signal } = binding;
|
|
425
|
+
const model = responseModel(result, context);
|
|
426
|
+
const state = initialState(model);
|
|
427
|
+
state.document = context.document;
|
|
428
|
+
const content = root.querySelector('[data-response-content]');
|
|
429
|
+
const search = root.querySelector('.response-find');
|
|
430
|
+
const input = search?.querySelector('input');
|
|
431
|
+
const find = root.querySelector('[data-action="find-response"]');
|
|
432
|
+
const all = root.querySelector('[data-fold-all]');
|
|
433
|
+
const copies = new Map(model.pretty?.lines.map(line => [line.id, line.copy]));
|
|
434
|
+
bindTrees(root);
|
|
435
|
+
|
|
436
|
+
function render(reveal = false) {
|
|
437
|
+
const current = reveal && state.matches[state.active]?.line;
|
|
438
|
+
if (current) {
|
|
439
|
+
for (const ancestor of current.ancestors ?? []) state.folded.delete(ancestor);
|
|
440
|
+
state.folded.delete(current.id);
|
|
441
|
+
}
|
|
442
|
+
content.innerHTML = viewerBody(model, state);
|
|
443
|
+
if (content.dataset) content.dataset.mode = state.mode;
|
|
444
|
+
if (state.mode === 'schema' && input?.value) markSchema(input.value);
|
|
445
|
+
const wrap = root.querySelector('[data-wrap]');
|
|
446
|
+
if (wrap) { wrap.hidden = state.mode !== 'raw'; wrap.setAttribute('aria-pressed', String(state.wrap)); }
|
|
447
|
+
if (state.mode === 'table') watchTable();
|
|
448
|
+
if (state.mode === 'schema') bindTrees(root);
|
|
449
|
+
for (const button of root.querySelectorAll('[data-response-mode]')) {
|
|
450
|
+
button.setAttribute('aria-pressed', String(button.dataset.responseMode === state.mode));
|
|
451
|
+
}
|
|
452
|
+
all.hidden = state.mode !== 'pretty' || !model.pretty?.branches.size;
|
|
453
|
+
const foldLabel = t(state.folded.size ? 'resp.expandAll' : 'resp.collapseAll');
|
|
454
|
+
all.querySelector('[data-fold-all-label]').textContent = foldLabel;
|
|
455
|
+
all.setAttribute?.('aria-label', foldLabel);
|
|
456
|
+
all.title = foldLabel;
|
|
457
|
+
search.querySelector('[data-match-count]').textContent = input.value
|
|
458
|
+
? state.matches.length ? t('resp.matchCount', { current: formatNumber(state.active + 1), total: formatNumber(state.matches.length) }) : t('resp.noMatches')
|
|
459
|
+
: '';
|
|
460
|
+
for (const button of search.querySelectorAll('[data-match-step]')) button.disabled = !state.matches.length;
|
|
461
|
+
if (reveal) content.querySelector('[data-current-match]')?.scrollIntoView({ block: 'nearest', inline: 'nearest' });
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
function closeSearch() {
|
|
465
|
+
search.hidden = true;
|
|
466
|
+
find.setAttribute('aria-expanded', 'false');
|
|
467
|
+
input.value = '';
|
|
468
|
+
searchBody(model, state, '');
|
|
469
|
+
render();
|
|
470
|
+
find.focus();
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
function moveMatch(step) {
|
|
474
|
+
if (!state.matches.length) return;
|
|
475
|
+
state.active = (state.active + step + state.matches.length) % state.matches.length;
|
|
476
|
+
render(true);
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
/** Copies through the shared helper. If the clipboard is blocked, the body text is selected and a notice appears above it. */
|
|
480
|
+
function copy(value, button, what, select = content.querySelector('.code-view, .response-table')) {
|
|
481
|
+
return copyText(value, { button, what, select, notice: content });
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/**
|
|
485
|
+
* Table: an edge fade while columns remain off to the side, a shadow on the sticky name column
|
|
486
|
+
* once scrolled, and the "15 columns, scroll" button while there is more to see.
|
|
487
|
+
*/
|
|
488
|
+
function watchTable() {
|
|
489
|
+
const region = content.querySelector?.('.tbl');
|
|
490
|
+
if (!region) return;
|
|
491
|
+
const update = () => {
|
|
492
|
+
const max = region.scrollWidth - region.clientWidth;
|
|
493
|
+
const x = Math.abs(region.scrollLeft);
|
|
494
|
+
region.parentElement.classList.toggle('more-end', x < max - 1);
|
|
495
|
+
region.parentElement.classList.toggle('is-scrolled', x > 0);
|
|
496
|
+
const more = content.querySelector('[data-table-more]');
|
|
497
|
+
if (more) more.hidden = max <= 1;
|
|
498
|
+
};
|
|
499
|
+
region.addEventListener('scroll', update, { passive: true, signal });
|
|
500
|
+
new ResizeObserver(update).observe(region);
|
|
501
|
+
update();
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/** Search in the Schema view: marks the attribute names that contain the query. */
|
|
505
|
+
function markSchema(query) {
|
|
506
|
+
const pattern = new RegExp(query.replace(/[.*+?^$(){}|[\]\\]/g, '\\$&'), 'giu');
|
|
507
|
+
const names = [...(content.querySelectorAll?.('.attr-name') ?? [])];
|
|
508
|
+
for (let pass = 0; pass < 2; pass++) {
|
|
509
|
+
let count = 0;
|
|
510
|
+
state.matches = [];
|
|
511
|
+
for (const node of names) {
|
|
512
|
+
const text = node.textContent;
|
|
513
|
+
let html = '';
|
|
514
|
+
let last = 0;
|
|
515
|
+
for (const match of text.matchAll(pattern)) {
|
|
516
|
+
const index = count++;
|
|
517
|
+
state.matches.push({ index });
|
|
518
|
+
html += `${esc(text.slice(last, match.index))}<mark${index === state.active ? ' class="is-current" data-current-match' : ''}>${esc(match[0])}</mark>`;
|
|
519
|
+
last = match.index + match[0].length;
|
|
520
|
+
}
|
|
521
|
+
if (last) node.innerHTML = html + esc(text.slice(last));
|
|
522
|
+
}
|
|
523
|
+
if (state.active < state.matches.length) break;
|
|
524
|
+
state.active = state.matches.length ? 0 : -1;
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
/** Switches the body view (the match toggletip's "Show in Schema view" calls this too). */
|
|
529
|
+
function setMode(mode) {
|
|
530
|
+
if (!root.querySelector(`[data-response-mode="${mode}"]`)) return;
|
|
531
|
+
state.mode = mode;
|
|
532
|
+
searchBody(model, state, input?.value ?? '');
|
|
533
|
+
render(Boolean(input?.value));
|
|
534
|
+
root.querySelector(`[data-response-mode="${mode}"]`)?.focus?.();
|
|
535
|
+
}
|
|
536
|
+
root.setMode = setMode;
|
|
537
|
+
|
|
538
|
+
root.addEventListener('click', event => {
|
|
539
|
+
// On touch screens a tap on a line reveals that line's actions (copy, open in).
|
|
540
|
+
const tapped = event.target.closest?.('.ln');
|
|
541
|
+
if (tapped && !event.target.closest('button') && globalThis.matchMedia?.('(pointer: coarse)').matches) {
|
|
542
|
+
const open = tapped.classList.contains('is-active');
|
|
543
|
+
for (const line of root.querySelectorAll('.ln.is-active')) line.classList.remove('is-active');
|
|
544
|
+
if (!open) tapped.classList.add('is-active');
|
|
545
|
+
}
|
|
546
|
+
const button = event.target.closest('button');
|
|
547
|
+
if (!button || !root.contains(button)) return;
|
|
548
|
+
const { dataset } = button;
|
|
549
|
+
if (dataset.followUp !== undefined) {
|
|
550
|
+
const followUp = model.followUps[Number(dataset.followUp)];
|
|
551
|
+
if (followUp) context.onFollowUp(followUp.operation, structuredClone(followUp.values));
|
|
552
|
+
} else if (dataset.action === copyAction) {
|
|
553
|
+
event.stopPropagation();
|
|
554
|
+
void copy(model.raw, button, t('copy.what.body'));
|
|
555
|
+
} else if (dataset.copyLine !== undefined) {
|
|
556
|
+
const { value, source } = copies.get(dataset.copyLine);
|
|
557
|
+
void copy(source ?? (typeof value === 'string' ? value : JSON.stringify(value, null, 2)), button, t('copy.what.line'),
|
|
558
|
+
button.closest('.ln')?.querySelector('.src'));
|
|
559
|
+
} else if (dataset.action === findAction) {
|
|
560
|
+
search.hidden = false;
|
|
561
|
+
find.setAttribute('aria-expanded', 'true');
|
|
562
|
+
input.focus();
|
|
563
|
+
input.select();
|
|
564
|
+
} else if (dataset.closeResponseFind !== undefined) {
|
|
565
|
+
closeSearch();
|
|
566
|
+
} else if (dataset.matchStep) {
|
|
567
|
+
moveMatch(Number(dataset.matchStep));
|
|
568
|
+
} else if (dataset.responseMode && dataset.responseMode !== state.mode) {
|
|
569
|
+
state.mode = dataset.responseMode;
|
|
570
|
+
searchBody(model, state, input.value);
|
|
571
|
+
render(Boolean(input.value));
|
|
572
|
+
} else if (dataset.wrap !== undefined) {
|
|
573
|
+
state.wrap = !state.wrap;
|
|
574
|
+
render();
|
|
575
|
+
} else if (dataset.tableMore !== undefined) {
|
|
576
|
+
const region = content.querySelector('.tbl');
|
|
577
|
+
const rtl = getComputedStyle(region).direction === 'rtl';
|
|
578
|
+
region.scrollBy({ left: (rtl ? -1 : 1) * region.clientWidth * 0.8, behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth' });
|
|
579
|
+
} else if (dataset.tableOpen) {
|
|
580
|
+
// "3 keys" opens Pretty at that value, unfolded.
|
|
581
|
+
const line = model.pretty?.lines.find(item => item.id === dataset.tableOpen);
|
|
582
|
+
if (!line) return;
|
|
583
|
+
for (const ancestor of line.ancestors) state.folded.delete(ancestor);
|
|
584
|
+
state.folded.delete(line.id);
|
|
585
|
+
state.mode = 'pretty';
|
|
586
|
+
render();
|
|
587
|
+
content.querySelector(`[data-fold-line="${CSS.escape(line.id)}"]`)?.scrollIntoView({ block: 'nearest' });
|
|
588
|
+
} else if (dataset.foldLine !== undefined) {
|
|
589
|
+
const id = dataset.foldLine;
|
|
590
|
+
if (state.folded.has(id)) state.folded.delete(id);
|
|
591
|
+
else state.folded.add(id);
|
|
592
|
+
render();
|
|
593
|
+
for (const fold of content.querySelectorAll('[data-fold-line]')) {
|
|
594
|
+
if (fold.dataset.foldLine === id) fold.focus({ preventScroll: true });
|
|
595
|
+
}
|
|
596
|
+
} else if (dataset.foldAll !== undefined) {
|
|
597
|
+
// Anything collapsed means the next click opens everything; otherwise it closes everything.
|
|
598
|
+
state.folded = state.folded.size ? new Set() : new Set(model.pretty.branches);
|
|
599
|
+
render();
|
|
600
|
+
}
|
|
601
|
+
}, { signal });
|
|
602
|
+
|
|
603
|
+
input?.addEventListener('input', () => {
|
|
604
|
+
searchBody(model, state, input.value);
|
|
605
|
+
render(true);
|
|
606
|
+
}, { signal });
|
|
607
|
+
search?.addEventListener('keydown', event => {
|
|
608
|
+
if (event.key === 'Escape') {
|
|
609
|
+
event.preventDefault();
|
|
610
|
+
event.stopPropagation();
|
|
611
|
+
closeSearch();
|
|
612
|
+
} else if (event.target === input && event.key === 'Enter') {
|
|
613
|
+
event.preventDefault();
|
|
614
|
+
event.stopPropagation();
|
|
615
|
+
moveMatch(event.shiftKey ? -1 : 1);
|
|
616
|
+
}
|
|
617
|
+
}, { signal });
|
|
618
|
+
}
|