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,496 @@
|
|
|
1
|
+
// The request pane (mock: request.js): operation header, the request tabs (Body, Params,
|
|
2
|
+
// Headers, Auth, Code), the forms inside them, Autofill and per-field generation, and turning
|
|
3
|
+
// the drafts into a prepared request.
|
|
4
|
+
import { createSchemaForm, resolveSchema, validateSchemaValue } from './schema.js';
|
|
5
|
+
import { dereference, encodeRequestBody, makeRequest } from './api.js';
|
|
6
|
+
import { copyTextButton, esc, icon, inlineNote, tab as tabButton } from './components.js';
|
|
7
|
+
import { snippetFormats, formatRequest } from './snippets.js';
|
|
8
|
+
import { newUuid } from './uuid.js';
|
|
9
|
+
import { createHeaderEditor } from './header-editor.js';
|
|
10
|
+
import { autofillContext, fillDraft, showAutofillMenu } from './autofill.js';
|
|
11
|
+
import { shortcutAttrs, shortcutHint, shortcutLong } from './shortcuts.js';
|
|
12
|
+
import { t, th } from './i18n.js';
|
|
13
|
+
import { operationHeader } from './operation-header.js';
|
|
14
|
+
import { isPublic, primarySchemes, scopeText } from './security.js';
|
|
15
|
+
import { copyText } from './copy.js';
|
|
16
|
+
import { highlightSnippet } from './highlight.js';
|
|
17
|
+
import { bindCodePicker, codePicker, getCodeFormat } from './code-picker.js';
|
|
18
|
+
import { schemaName } from './schema-model.js';
|
|
19
|
+
import { describeField } from './field-help.js';
|
|
20
|
+
import { setToggletipContent } from './toggletip.js';
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Where a sample writes the redacted Cookie value, in every language: `Cookie: REDACTED` (cURL),
|
|
24
|
+
* `"Cookie": "REDACTED"` (JavaScript, Python), `"Cookie", "REDACTED"` (C#, Go, Java, Kotlin, Rust),
|
|
25
|
+
* `'Cookie' => 'REDACTED'` (PHP), `["Cookie"] = "REDACTED"` (Ruby), `'Cookie' = 'REDACTED'` (PowerShell).
|
|
26
|
+
*/
|
|
27
|
+
const COOKIE_VALUE = /(Cookie['"]?\s*(?:=>|[:=,]|\]\s*=)\s*['"]?)REDACTED/;
|
|
28
|
+
const bodyMode = tab => tab === 'Form' || tab === 'JSON';
|
|
29
|
+
/** Query parameters that cut and order a page rather than filter it. */
|
|
30
|
+
const PAGING = ['page', 'pagenumber', 'pageindex', 'pagesize', 'perpage', 'per_page', 'limit', 'offset', 'cursor', 'after', 'before', 'sort', 'sortby', 'order', 'orderby'];
|
|
31
|
+
const isPaging = name => PAGING.includes(String(name).toLowerCase());
|
|
32
|
+
const pagingRank = name => PAGING.indexOf(String(name).toLowerCase());
|
|
33
|
+
const TAB_LABELS = { Body: 'tab.body', Params: 'tab.params', Headers: 'tab.headers', Auth: 'tab.auth', Code: 'tab.code' };
|
|
34
|
+
|
|
35
|
+
/** Select an inline OpenAPI example, including a locally referenced Example Object. */
|
|
36
|
+
export function requestExample(source, document) {
|
|
37
|
+
if (source && Object.hasOwn(source, 'example')) return source.example;
|
|
38
|
+
for (const raw of Object.values(source?.examples || {})) {
|
|
39
|
+
const example = dereference(raw, document);
|
|
40
|
+
if (example && Object.hasOwn(example, 'value')) return example.value;
|
|
41
|
+
}
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Own request editor rendering and conversion into a prepared request. */
|
|
46
|
+
export function createRequestEditor({ state, basePath, $, onLookupPreview, onHeadersChange, sensitiveNames = () => [], onFilled = () => {} }) {
|
|
47
|
+
let includeCookie = true;
|
|
48
|
+
|
|
49
|
+
function validationError(issues) {
|
|
50
|
+
const error = new Error(issues.map(issue => `${issue.path}: ${issue.message}`).join('\n'));
|
|
51
|
+
error.validation = true;
|
|
52
|
+
error.issues = issues;
|
|
53
|
+
return error;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const withPrefix = (issue, prefix) => ({
|
|
57
|
+
path: prefix ? (issue.path ? `${prefix}.${issue.path}` : prefix) : issue.path || '$',
|
|
58
|
+
message: issue.message,
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
function parameterSchema(parameter) {
|
|
62
|
+
if (parameter.schema != null) return parameter.schema;
|
|
63
|
+
return Object.values(parameter.content || {})[0]?.schema;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function validateValue(schema, value, required, prefix) {
|
|
67
|
+
if (schema == null) return [];
|
|
68
|
+
return validateSchemaValue({ schema, value, document: state.doc, required }).map(issue => withPrefix(issue, prefix));
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const isIdempotencyKey = parameter => parameter.in === 'header' && parameter.name?.toLowerCase() === 'idempotency-key';
|
|
72
|
+
|
|
73
|
+
function requestMedia() {
|
|
74
|
+
const body = dereference(state.op?.operation.requestBody, state.doc);
|
|
75
|
+
const content = body?.content || {};
|
|
76
|
+
const type = Object.hasOwn(content, 'application/json') ? 'application/json' : Object.keys(content)[0];
|
|
77
|
+
return { body, media: content[type], type };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const headerEditor = createHeaderEditor({
|
|
81
|
+
state, $, parameterSchema, getMediaType: () => requestMedia().type,
|
|
82
|
+
onChange: () => { updateHeaderCount(); onHeadersChange?.(); },
|
|
83
|
+
});
|
|
84
|
+
function updateHeaderCount() {
|
|
85
|
+
const badge = $('[data-request-tab="Headers"] .n');
|
|
86
|
+
if (badge) badge.textContent = String(headerEditor.count());
|
|
87
|
+
}
|
|
88
|
+
let autofillUndo;
|
|
89
|
+
let fillGeneration = 0;
|
|
90
|
+
|
|
91
|
+
async function fillSample(mode = 'all') {
|
|
92
|
+
if (!state.op) return;
|
|
93
|
+
const operation = state.op;
|
|
94
|
+
const ticket = ++fillGeneration;
|
|
95
|
+
const before = { body: state.body, json: state.json, paramValues: { ...state.paramValues }, headers: structuredClone(state.headers || []), autofilled: state.autofilled };
|
|
96
|
+
const focused = globalThis.document?.activeElement;
|
|
97
|
+
const announcement = $('[data-request-announcement]');
|
|
98
|
+
const say = text => { if (announcement) announcement.textContent = text; };
|
|
99
|
+
if (mode === 'undo') {
|
|
100
|
+
if (!autofillUndo || autofillUndo.operation !== operation) return;
|
|
101
|
+
Object.assign(state, autofillUndo.before);
|
|
102
|
+
autofillUndo = undefined;
|
|
103
|
+
state.canUndoAutofill = false;
|
|
104
|
+
renderOperation();
|
|
105
|
+
onFilled(0);
|
|
106
|
+
say(t('fill.undone'));
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
let draft = before.body;
|
|
110
|
+
if (before.json !== undefined && !['clear', 'reuse'].includes(mode)) {
|
|
111
|
+
try { draft = before.json.trim() ? JSON.parse(before.json) : undefined; }
|
|
112
|
+
catch { say(t('fill.fixJson')); return; }
|
|
113
|
+
}
|
|
114
|
+
const next = { body: draft, paramValues: { ...before.paramValues }, headers: before.headers };
|
|
115
|
+
const filled = new Map();
|
|
116
|
+
if (mode === 'clear') {
|
|
117
|
+
next.body = undefined;
|
|
118
|
+
next.paramValues = {};
|
|
119
|
+
next.headers = [];
|
|
120
|
+
} else if (mode === 'reuse') {
|
|
121
|
+
const entry = state.history?.find(item => item.op === operation);
|
|
122
|
+
if (!entry) return;
|
|
123
|
+
next.body = structuredClone(entry.body);
|
|
124
|
+
next.paramValues = structuredClone(entry.params || {});
|
|
125
|
+
next.headers = structuredClone(entry.headers || []);
|
|
126
|
+
} else {
|
|
127
|
+
const { media } = requestMedia();
|
|
128
|
+
const regenerate = mode === 'ids';
|
|
129
|
+
const all = mode === 'all';
|
|
130
|
+
const context = autofillContext(state.doc, basePath, operation.path, state.lastResponse, state.lookupCache ??= new Map(), filled, state.cap?.identity?.name);
|
|
131
|
+
say(t('fill.filling'));
|
|
132
|
+
const body = media && fillDraft(media.schema, draft, requestExample(media, state.doc), context, { all, regenerate });
|
|
133
|
+
await Promise.all(operation.parameters.map(async parameter => {
|
|
134
|
+
const key = `${parameter.in}:${parameter.name}`;
|
|
135
|
+
if (isIdempotencyKey(parameter)) {
|
|
136
|
+
if (regenerate) next.paramValues[key] = newUuid();
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
if (!all && !regenerate && !parameter.required) return;
|
|
140
|
+
const schema = parameterSchema(parameter) ?? {};
|
|
141
|
+
const value = await fillDraft(schema, next.paramValues[key], requestExample(parameter, state.doc),
|
|
142
|
+
{ ...context, filled: new Map() }, { all, regenerate }, [parameter.name]);
|
|
143
|
+
if (value !== undefined) next.paramValues[key] = value;
|
|
144
|
+
}));
|
|
145
|
+
if (body) next.body = await body;
|
|
146
|
+
if (operation !== state.op || ticket !== fillGeneration || state.body !== before.body || state.json !== before.json ||
|
|
147
|
+
Object.keys({ ...state.paramValues, ...before.paramValues }).some(key => state.paramValues?.[key] !== before.paramValues[key])) return;
|
|
148
|
+
}
|
|
149
|
+
autofillUndo = { operation, before };
|
|
150
|
+
state.canUndoAutofill = true;
|
|
151
|
+
Object.assign(state, next, { json: undefined, autofilled: filled });
|
|
152
|
+
renderOperation();
|
|
153
|
+
if (focused?.matches?.('[data-action="sample"]')) $('.request-tools [data-action="sample"]')?.focus();
|
|
154
|
+
onFilled(['required', 'all'].includes(mode) ? filled.size : 0);
|
|
155
|
+
say(mode === 'clear' ? t('fill.cleared') : mode === 'reuse' ? t('fill.restored') : t('fill.done', { n: filled.size }));
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function autofill(anchor, after = () => {}) {
|
|
159
|
+
const { media } = requestMedia();
|
|
160
|
+
const schema = media?.schema;
|
|
161
|
+
const rendered = JSON.stringify(resolveSchema(schema, state.doc));
|
|
162
|
+
const canRegenerate = state.op.parameters.some(isIdempotencyKey) ||
|
|
163
|
+
JSON.stringify([schema, state.doc.components?.schemas]).includes('"uuid"');
|
|
164
|
+
showAutofillMenu(anchor, {
|
|
165
|
+
history: state.history?.find(item => item.op === state.op),
|
|
166
|
+
canRegenerate,
|
|
167
|
+
optionalCount: countOptional(),
|
|
168
|
+
lookupActor: rendered.includes('"x-lookup"') ? state.cap?.identity?.name : undefined,
|
|
169
|
+
onSelect: async mode => { await fillSample(mode); after(); },
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function countOptional() {
|
|
174
|
+
const schema = resolveSchema(requestMedia().media?.schema, state.doc);
|
|
175
|
+
return Object.keys(schema.properties || {}).filter(name => !schema.required?.includes(name) && !resolveSchema(schema.properties[name], state.doc).readOnly).length;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Number of inputs Autofill could fill: body properties and non-header parameters. */
|
|
179
|
+
function fieldCount() {
|
|
180
|
+
const schema = resolveSchema(requestMedia().media?.schema, state.doc);
|
|
181
|
+
return Object.keys(schema.properties || {}).length + (state.op?.parameters || []).filter(p => p.in !== 'header').length;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function tabs() {
|
|
185
|
+
const params = state.op.parameters.map(p => dereference(p, state.doc)).filter(p => p?.name);
|
|
186
|
+
const { media } = requestMedia();
|
|
187
|
+
// Query parameters split into what filters and how the page is cut and ordered (mock 76),
|
|
188
|
+
// when the operation has paging parameters at all.
|
|
189
|
+
const paging = params.some(p => p.in === 'query' && isPaging(p.name));
|
|
190
|
+
const sections = [['path', 'req.path'], ...(paging ? [['query', 'req.filter', p => !isPaging(p.name)], ['paging', 'req.paging', p => isPaging(p.name)]] : [['query', 'req.query']]), ['cookie', 'req.cookies']]
|
|
191
|
+
.map(([location, label, test = () => true]) => [location, label, p => (location === 'paging' ? p.in === 'query' : p.in === location) && test(p)])
|
|
192
|
+
.filter(([, , test]) => params.some(test));
|
|
193
|
+
const signIn = state.cap?.identity || state.cap?.authProviders?.length || !isPublic(state.op, state.doc);
|
|
194
|
+
return {
|
|
195
|
+
params, media, sections,
|
|
196
|
+
list: [...(media ? ['Body'] : []), ...(sections.length ? ['Params'] : []), 'Headers', ...(signIn ? ['Auth'] : []), 'Code'],
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function renderTabs(list, current, params) {
|
|
201
|
+
const counts = { Params: params.filter(p => p.in !== 'header').length, Headers: headerEditor.count() };
|
|
202
|
+
$('.request-tabs').innerHTML = list.map((name, index) => tabButton(t(TAB_LABELS[name]), {
|
|
203
|
+
selected: name === current, count: counts[name], id: `request-tab-${name}`, controls: 'editor',
|
|
204
|
+
shortcut: 'request-tab-' + index, data: `data-request-tab="${name}"`, flagSlot: ['Body', 'Params', 'Headers'].includes(name),
|
|
205
|
+
})).join('');
|
|
206
|
+
const tools = $('.request-tools');
|
|
207
|
+
if (tools) tools.innerHTML = ['Body', 'Params'].includes(current) && fieldCount()
|
|
208
|
+
? `<button type="button" class="btn btn-ghost btn-sm" id="autofill" data-action="sample" aria-label="${esc(t('req.autofill'))}" aria-haspopup="menu" aria-controls="autofill-menu" aria-expanded="false" title="${esc(t('shortcut.autofill-required') + ' · ' + shortcutLong('autofill-required'))}" ${shortcutAttrs('autofill-required')}>${icon('wand', true)}<span class="lbl">${esc(t('req.autofill'))}</span>${icon('chevron-down', true)}</button>`
|
|
209
|
+
: '';
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** The Body section heading: schema link and the Form/JSON switch. */
|
|
213
|
+
function bodyHeading(media, json) {
|
|
214
|
+
const name = schemaName(media?.schema, state.doc);
|
|
215
|
+
const switcher = media?.schema ? `<div class="segmented" role="group" aria-label="${esc(t('req.bodyEditor'))}" ${shortcutAttrs('editor-mode')}>
|
|
216
|
+
<button type="button" data-body-mode="Form" aria-pressed="${!json}">${esc(t('req.form'))}</button>
|
|
217
|
+
<button type="button" data-body-mode="JSON" aria-pressed="${json}">${esc(t('req.json'))}</button></div>` : '';
|
|
218
|
+
return `<div class="section-label"><span id="body-legend">${esc(t('req.body'))} ${name ? `<a class="schema-link" href="#model/${encodeURIComponent(name.replace(/\[\]$/, ''))}" data-model="${esc(name.replace(/\[\]$/, ''))}" title="${esc(t('req.openModel', { name }))}">${esc(name)}</a>` : ''}</span><span class="rule" aria-hidden="true"></span>${switcher}</div>`;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function renderOperation() {
|
|
222
|
+
state.forms.forEach(form => form.destroy());
|
|
223
|
+
state.forms = [];
|
|
224
|
+
state.bodyForm = null;
|
|
225
|
+
if (!state.op) {
|
|
226
|
+
$('#operation').innerHTML = `<div class="op-head"><h1 class="op-title" id="op-title">${esc(t('req.noOperations'))}</h1><p class="op-desc">${esc(t('req.noOperationsBody'))}</p></div>`;
|
|
227
|
+
$('#editor').innerHTML = '';
|
|
228
|
+
$('.request-tabs').innerHTML = '';
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
state.paramValues ||= {};
|
|
232
|
+
for (const parameter of state.op.parameters) {
|
|
233
|
+
const key = 'header:' + parameter.name;
|
|
234
|
+
if (isIdempotencyKey(parameter) && !Object.hasOwn(state.paramValues, key)) state.paramValues[key] = newUuid();
|
|
235
|
+
}
|
|
236
|
+
$('#operation').innerHTML = operationHeader(state.op, {
|
|
237
|
+
base: (globalThis.location?.origin || '') + basePath.replace(/\/$/, ''), document: state.doc,
|
|
238
|
+
signedIn: !!state.cap?.identity?.name, canSignIn: !!state.cap?.authProviders?.length, ops: state.ops,
|
|
239
|
+
});
|
|
240
|
+
const { params, media, sections, list } = tabs();
|
|
241
|
+
let tab = bodyMode(state.tab) ? 'Body' : state.tab;
|
|
242
|
+
if (!list.includes(tab)) {
|
|
243
|
+
tab = list[0];
|
|
244
|
+
state.tab = tab === 'Body' ? (media.schema ? 'Form' : 'JSON') : tab;
|
|
245
|
+
}
|
|
246
|
+
if (tab === 'Body' && !media.schema) state.tab = 'JSON';
|
|
247
|
+
renderTabs(list, tab, params);
|
|
248
|
+
const editor = $('#editor');
|
|
249
|
+
editor.setAttribute('aria-labelledby', `request-tab-${tab}`);
|
|
250
|
+
if (state.tab === 'JSON') {
|
|
251
|
+
editor.innerHTML = `<fieldset aria-labelledby="body-legend">${bodyHeading(media, true)}<div class="field"><label class="sr-only" for="json">${esc(t('req.jsonLabel'))}</label><textarea class="code" id="json" aria-describedby="json-assist" spellcheck="false">${esc(state.json ?? (state.body === undefined ? '' : JSON.stringify(state.body, null, 2)))}</textarea>
|
|
252
|
+
<div class="assist" id="json-assist"><span class="assist-icon" hidden>${icon('alert', true)}</span><span class="msg"><span class="field-hint">${esc(t('req.jsonHint'))}</span><span class="field-error" hidden></span></span></div></div></fieldset>`;
|
|
253
|
+
$('#json').addEventListener('input', event => { state.json = event.target.value; updateHeaderCount(); });
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
if (state.tab === 'Headers') { headerEditor.render(); return; }
|
|
257
|
+
if (state.tab === 'Auth') { editor.innerHTML = authMarkup(); return; }
|
|
258
|
+
if (state.tab === 'Code') { renderCode(editor); return; }
|
|
259
|
+
if (tab === 'Params') editor.innerHTML = sections.map(([location, label]) =>
|
|
260
|
+
`<fieldset><legend class="section-label">${esc(t(label))}<span class="rule" aria-hidden="true"></span></legend><div class="fields" id="parameters-${location}"></div></fieldset>`).join('');
|
|
261
|
+
else editor.innerHTML = `<fieldset aria-labelledby="body-legend">${bodyHeading(media, false)}<p class="form-note">${esc(t('req.requiredNote'))}</p><div id="body-form"></div></fieldset>`;
|
|
262
|
+
const shared = {
|
|
263
|
+
document: state.doc, basePath: basePath.replace(/\/$/, ''), lastResponse: state.lastResponse,
|
|
264
|
+
lookupCache: state.lookupCache ??= new Map(), onLookupPreview, autofilled: state.autofilled,
|
|
265
|
+
actor: state.cap?.identity?.name, signedIn: !!state.cap?.identity?.name,
|
|
266
|
+
// A signed-out lookup offers Sign in: the same flow as the top bar's button.
|
|
267
|
+
onSignIn: state.cap?.authProviders?.length ? () => globalThis.document.querySelector('.topbar [data-action="signin"]')?.click() : undefined,
|
|
268
|
+
};
|
|
269
|
+
const sectionOf = p => sections.find(([, , test]) => test(p))?.[0];
|
|
270
|
+
const ordered = tab === 'Params' ? params.filter(p => p.in !== 'header') : [];
|
|
271
|
+
// Page, then page size, then sort: the order people read a paging control in.
|
|
272
|
+
ordered.sort((a, b) => (isPaging(a.name) ? pagingRank(a.name) : -1) - (isPaging(b.name) ? pagingRank(b.name) : -1));
|
|
273
|
+
for (const p of ordered) {
|
|
274
|
+
const section = $(`#parameters-${sectionOf(p)}`);
|
|
275
|
+
if (!section) continue;
|
|
276
|
+
const holder = globalThis.document.createElement('div');
|
|
277
|
+
holder.className = 'param-holder';
|
|
278
|
+
holder.dataset.parameterName = p.name;
|
|
279
|
+
holder.innerHTML = '<div></div>';
|
|
280
|
+
section.append(holder);
|
|
281
|
+
const schema = parameterSchema(p);
|
|
282
|
+
const form = createSchemaForm({
|
|
283
|
+
...shared, container: holder.lastElementChild, name: p.name, required: p.required,
|
|
284
|
+
// The parameter's own description says what it does here; the schema's is the fallback.
|
|
285
|
+
schema: typeof schema === 'boolean' ? schema : { ...(schema || { type: 'string' }), title: schema?.title || p.name, description: p.description || resolveSchema(schema, state.doc).description },
|
|
286
|
+
operationPath: p.in === 'path' ? state.op.path : undefined, value: state.paramValues?.[`${p.in}:${p.name}`], parameter: p,
|
|
287
|
+
onChange: value => { state.paramValues ||= {}; state.paramValues[`${p.in}:${p.name}`] = value; },
|
|
288
|
+
});
|
|
289
|
+
form.parameter = p;
|
|
290
|
+
state.forms.push(form);
|
|
291
|
+
}
|
|
292
|
+
if (tab === 'Params') pairShortFields(editor);
|
|
293
|
+
if (tab === 'Body' && media?.schema) {
|
|
294
|
+
state.bodyForm = createSchemaForm({
|
|
295
|
+
...shared, container: $('#body-form'), schema: media.schema, flattenRoot: true, value: state.body,
|
|
296
|
+
required: requestMedia().body.required,
|
|
297
|
+
example: requestExample(media, state.doc) ?? resolveSchema(media.schema, state.doc).examples?.[0] ?? resolveSchema(media.schema, state.doc).example,
|
|
298
|
+
onChange: value => { state.body = value; state.json = undefined; updateHeaderCount(); },
|
|
299
|
+
});
|
|
300
|
+
state.forms.push(state.bodyForm);
|
|
301
|
+
state.body = state.bodyForm.getValue();
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* Two short controls in a row share it (page and page size, type and currency): selects and
|
|
307
|
+
* numbers, paired with the next one. A lone short field keeps the full width.
|
|
308
|
+
*/
|
|
309
|
+
function pairShortFields(editor) {
|
|
310
|
+
for (const section of editor.querySelectorAll('.fields')) {
|
|
311
|
+
const fields = [...section.querySelectorAll(':scope > .param-holder > div > .field')];
|
|
312
|
+
const short = field => field.dataset.kind === 'select' || !!field.querySelector(':scope > .control > input.num');
|
|
313
|
+
for (let index = 0; index < fields.length - 1; index++) {
|
|
314
|
+
// The pairing lives on the holders, which survive a field re-rendering itself.
|
|
315
|
+
if (short(fields[index]) && short(fields[index + 1])) {
|
|
316
|
+
fields[index].closest('.param-holder').dataset.half = 'start';
|
|
317
|
+
fields[index + 1].closest('.param-holder').dataset.half = 'end';
|
|
318
|
+
index++;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/** The Auth tab: what this operation needs, from its security requirements, and whether you meet it. */
|
|
325
|
+
function authMarkup() {
|
|
326
|
+
const identity = state.cap?.identity;
|
|
327
|
+
const signedIn = !!identity?.name;
|
|
328
|
+
const providers = state.cap?.authProviders || [];
|
|
329
|
+
if (isPublic(state.op, state.doc)) return `<section><h3 class="section-label">${esc(t('auth.requirements'))}<span class="rule" aria-hidden="true"></span></h3>
|
|
330
|
+
<div class="req-list"><div class="req"><span class="req-ico">${icon('globe', true)}</span><div class="grow"><div class="t">${esc(t('docs.public'))}</div><div class="s">${esc(t('auth.publicBody'))}</div></div>${signedIn ? `<span class="tag tag-ok">${icon('check')}${esc(identity.name)}</span>` : ''}</div></div></section>`;
|
|
331
|
+
const schemes = primarySchemes(state.op, state.doc);
|
|
332
|
+
const scopes = scopeText(state.op, state.doc) ? [scopeText(state.op, state.doc)] : [];
|
|
333
|
+
const label = scheme => t('auth.scheme.' + (scheme.type === 'apiKey' && scheme.in === 'cookie' ? 'cookie' : scheme.type || 'other'));
|
|
334
|
+
const rows = [
|
|
335
|
+
...schemes.map(item => `<div class="req"><span class="req-ico">${icon('lock', true)}</span><div class="grow"><div class="t">${esc(label(item.scheme))} <span class="tag tag-mono">${esc(item.name)}</span></div><div class="s">${item.scheme.description ? `<span lang="en">${esc(item.scheme.description)}</span>` : esc(t('auth.sessionBody'))}</div></div>
|
|
336
|
+
${signedIn ? `<span class="tag tag-ok">${icon('check')}${esc(identity.name)}</span>` : `<span class="tag tag-warn">${esc(t('auth.notSignedIn'))}</span>`}</div>`),
|
|
337
|
+
...scopes.map(scope => `<div class="req"><span class="req-ico">${icon('shield', true)}</span><div class="grow"><div class="t">${esc(t('auth.permission'))} <span class="tag tag-mono">${esc(scope)}</span></div><div class="s">${esc(t('auth.permissionBody'))}</div></div>
|
|
338
|
+
<span class="tag">${esc(t(signedIn ? 'auth.checkedOnSend' : 'auth.unknown'))}</span></div>`),
|
|
339
|
+
];
|
|
340
|
+
if (!rows.length) rows.push(`<div class="req"><span class="req-ico">${icon('lock', true)}</span><div class="grow"><div class="t">${esc(t('auth.signInNeeded'))}</div><div class="s">${esc(t('auth.sessionBody'))}</div></div>${signedIn ? `<span class="tag tag-ok">${icon('check')}${esc(identity.name)}</span>` : `<span class="tag tag-warn">${esc(t('auth.notSignedIn'))}</span>`}</div>`);
|
|
341
|
+
const personas = providers.some(provider => /persona/i.test(provider.kind || ''));
|
|
342
|
+
return `<section class="auth-req"><h3 class="section-label">${esc(t('auth.requirements'))}<span class="rule" aria-hidden="true"></span></h3>
|
|
343
|
+
<div class="req-list">${rows.join('')}</div>
|
|
344
|
+
${providers.length ? `<div class="actions" style="display:flex;flex-wrap:wrap;gap:0.5rem;margin-block-start:1rem">
|
|
345
|
+
<button type="button" class="btn ${signedIn ? '' : 'btn-primary'}" data-action="signin" ${shortcutAttrs('signin')}>${icon(signedIn ? 'user' : 'log-in', true)}${esc(t(signedIn ? 'shortcut.signin' : 'shell.signIn'))} ${shortcutHint('signin')}</button>
|
|
346
|
+
${!signedIn && personas ? `<button type="button" class="btn" data-action="signin">${esc(t('auth.seeded'))}</button>` : ''}</div>` : ''}
|
|
347
|
+
</section>`;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/** Builds the request without validation, using typed placeholders for missing values. */
|
|
351
|
+
function draftRequest() {
|
|
352
|
+
const placeholders = [];
|
|
353
|
+
const token = label => { placeholders.push(label); return `zzph${placeholders.length - 1}zz`; };
|
|
354
|
+
let issues = [];
|
|
355
|
+
try { return { request: readRequest(), placeholders }; }
|
|
356
|
+
catch (error) { if (!error.validation) throw error; issues = error.issues || []; }
|
|
357
|
+
const clone = value => value === undefined ? undefined : structuredClone(value);
|
|
358
|
+
let body = clone(state.json !== undefined ? safeJson(state.json) : state.body);
|
|
359
|
+
const params = { ...(state.paramValues || {}) };
|
|
360
|
+
for (const issue of issues) {
|
|
361
|
+
if (issue.tab === 'Headers') continue;
|
|
362
|
+
const parts = String(issue.path || '').replace(/^\$\.?/, '').split('.').filter(Boolean);
|
|
363
|
+
if (issue.tab === 'Params') {
|
|
364
|
+
const parameter = state.op.parameters.find(p => p.name === parts[0]);
|
|
365
|
+
if (parameter) params[`${parameter.in}:${parameter.name}`] = token(`${parameter.name}: ${typeLabel(parameterSchema(parameter))}`);
|
|
366
|
+
continue;
|
|
367
|
+
}
|
|
368
|
+
if (!parts.length) continue;
|
|
369
|
+
body = body && typeof body === 'object' ? body : {};
|
|
370
|
+
let node = body;
|
|
371
|
+
let schema = resolveSchema(requestMedia().media?.schema, state.doc);
|
|
372
|
+
for (const [index, part] of parts.entries()) {
|
|
373
|
+
schema = resolveSchema(schema.properties?.[part] ?? schema.items ?? {}, state.doc);
|
|
374
|
+
if (index === parts.length - 1) node[part] = token(`${part}: ${typeLabel(schema)}`);
|
|
375
|
+
else node = node[part] = node[part] && typeof node[part] === 'object' ? node[part] : {};
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
const headers = headerEditor.values();
|
|
379
|
+
const parameters = state.op.parameters.map(p => dereference(p, state.doc)).filter(p => p?.name && p.in !== 'header')
|
|
380
|
+
.map(p => ({ ...p, value: params[`${p.in}:${p.name}`] ?? (p.in === 'path' ? token(`${p.name}: ${typeLabel(parameterSchema(p))}`) : undefined) }));
|
|
381
|
+
parameters.push(...headerEditor.parameters());
|
|
382
|
+
const { type } = requestMedia();
|
|
383
|
+
return { request: makeRequest(state.op, parameters, encodeRequestBody(body, type, headers), headers, basePath), placeholders };
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
const safeJson = text => { try { return text.trim() ? JSON.parse(text) : undefined; } catch { return undefined; } };
|
|
387
|
+
function typeLabel(raw) {
|
|
388
|
+
const schema = resolveSchema(raw, state.doc);
|
|
389
|
+
const type = Array.isArray(schema.type) ? schema.type.find(item => item !== 'null') : schema.type;
|
|
390
|
+
const parts = [schema.format || type || 'value'];
|
|
391
|
+
if (schema.minimum !== undefined) parts.push(`≥ ${schema.minimum}`);
|
|
392
|
+
if (schema.maxLength !== undefined) parts.push(`≤ ${schema.maxLength}`);
|
|
393
|
+
return parts.join(' ');
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/** The Code tab: always a snippet. Missing values become typed placeholders. */
|
|
397
|
+
function renderCode(editor) {
|
|
398
|
+
// The remembered language is shared with the Docs sample card.
|
|
399
|
+
const codeFormat = getCodeFormat();
|
|
400
|
+
const format = snippetFormats.find(item => item.id === codeFormat);
|
|
401
|
+
let snippet = '';
|
|
402
|
+
let missing = 0;
|
|
403
|
+
let failure = '';
|
|
404
|
+
try {
|
|
405
|
+
const { request, placeholders } = draftRequest();
|
|
406
|
+
missing = placeholders.length;
|
|
407
|
+
const cookieScheme = !isPublic(state.op, state.doc);
|
|
408
|
+
const withCookie = includeCookie && cookieScheme ? { ...request, headers: new Headers(request.headers) } : request;
|
|
409
|
+
if (withCookie !== request) withCookie.headers.set('Cookie', 'session');
|
|
410
|
+
// The session cookie is HttpOnly, so the snippet shows a placeholder where it goes.
|
|
411
|
+
const cookieToken = withCookie !== request ? `zzph${placeholders.push(t('code.cookiePlaceholder')) - 1}zz` : '';
|
|
412
|
+
const text = formatRequest(codeFormat, withCookie, sensitiveNames()).replace(COOKIE_VALUE, `$1${cookieToken}`);
|
|
413
|
+
snippet = highlightSnippet(text, format.lexer).replace(/(?:"|'|")?zzph(\d+)zz(?:"|")?/g, (match, index) =>
|
|
414
|
+
`<span class="ph" title="${esc(t('code.fillToReplace'))}"><${esc(placeholders[Number(index)])}></span>`);
|
|
415
|
+
} catch (error) {
|
|
416
|
+
failure = error.message;
|
|
417
|
+
}
|
|
418
|
+
editor.innerHTML = `<div class="code-tools">
|
|
419
|
+
${codePicker({ id: 'editor-code-picker', value: codeFormat })}
|
|
420
|
+
<span class="spacer"></span>
|
|
421
|
+
${!isPublic(state.op, state.doc) ? `<label class="switch-row"><button type="button" class="switch${includeCookie ? ' on' : ''}" role="switch" aria-checked="${includeCookie}" data-code-cookie aria-labelledby="code-cookie-label"></button><span id="code-cookie-label">${esc(t('code.includeCookie'))}</span></label>` : ''}
|
|
422
|
+
</div>
|
|
423
|
+
${missing && !failure ? inlineNote(th('code.missing', { n: missing - (includeCookie && !isPublic(state.op, state.doc) ? 1 : 0) }), { extra: `<button type="button" class="btn btn-ghost btn-xs" data-fill-required ${shortcutAttrs('autofill-required')}>${esc(t('code.fillRequired'))} ${shortcutHint('autofill-required')}</button>` }) : ''}
|
|
424
|
+
<div class="viewer">
|
|
425
|
+
<div class="viewer-bar"><span class="faint ltr" style="font-size:var(--fs-sm);padding-inline-start:0.35rem">${esc(format.label)} · ${esc(t(missing ? 'code.withPlaceholders' : 'code.ready'))}</span><span class="spacer"></span>
|
|
426
|
+
${copyTextButton(t('code.copy'), { action: 'copy-code', cls: 'btn-sm btn-ghost' })}</div>
|
|
427
|
+
<pre class="code-block ltr" id="snippet" tabindex="0" aria-label="${esc(t('code.snippetLabel', { language: format.label }))}">${failure ? esc(failure) : snippet}</pre>
|
|
428
|
+
</div>`;
|
|
429
|
+
// The picker stores the choice and re-renders; it returns focus to the (new) trigger itself.
|
|
430
|
+
bindCodePicker(editor, { onChange: () => renderCode(editor) });
|
|
431
|
+
editor.querySelector('[data-code-cookie]')?.addEventListener('click', () => {
|
|
432
|
+
includeCookie = !includeCookie;
|
|
433
|
+
renderCode(editor);
|
|
434
|
+
editor.querySelector('[data-code-cookie]')?.focus();
|
|
435
|
+
});
|
|
436
|
+
editor.querySelector('[data-fill-required]')?.addEventListener('click', async () => { await fillSample('required'); });
|
|
437
|
+
editor.querySelector('[data-action="copy-code"]').addEventListener('click', event => {
|
|
438
|
+
event.stopPropagation();
|
|
439
|
+
const pre = editor.querySelector('#snippet');
|
|
440
|
+
copyText(pre.textContent, { button: event.currentTarget, what: t('copy.what.snippet'), select: pre, notice: pre });
|
|
441
|
+
});
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
function readRequest() {
|
|
445
|
+
if (!state.op) throw new Error(t('req.chooseOperation'));
|
|
446
|
+
const issues = [];
|
|
447
|
+
if (state.json !== undefined) {
|
|
448
|
+
try { state.body = state.json.trim() ? JSON.parse(state.json) : undefined; }
|
|
449
|
+
catch { throw validationError([{ path: '$', message: t('req.fixJsonThen') }]); }
|
|
450
|
+
}
|
|
451
|
+
for (const form of state.forms) {
|
|
452
|
+
const prefix = form.parameter?.name || '';
|
|
453
|
+
issues.push(...form.validate().errors.map(issue => ({ ...withPrefix(issue, prefix), ...(prefix ? { tab: 'Params' } : {}) })));
|
|
454
|
+
}
|
|
455
|
+
if (state.bodyForm) state.body = state.bodyForm.getValue();
|
|
456
|
+
else if (state.tab !== 'Form' || state.forms.length === 0) {
|
|
457
|
+
const { body, media } = requestMedia();
|
|
458
|
+
issues.push(...validateValue(media?.schema, state.body, body?.required, ''));
|
|
459
|
+
}
|
|
460
|
+
const parameterForms = new Map(state.forms.filter(form => form.parameter).map(form => [`${form.parameter.in}:${form.parameter.name}`, form]));
|
|
461
|
+
for (const raw of state.op.parameters || []) {
|
|
462
|
+
const parameter = dereference(raw, state.doc);
|
|
463
|
+
if (!parameter?.name || parameter.in === 'header') continue;
|
|
464
|
+
const key = `${parameter.in}:${parameter.name}`;
|
|
465
|
+
if (!parameterForms.has(key)) issues.push(...validateValue(parameterSchema(parameter), state.paramValues?.[key], parameter.required, parameter.name).map(issue => ({ ...issue, tab: 'Params' })));
|
|
466
|
+
}
|
|
467
|
+
issues.push(...headerEditor.issues().map(issue => ({ ...issue, tab: 'Headers' })));
|
|
468
|
+
if (issues.length) throw validationError(issues);
|
|
469
|
+
for (const form of state.forms) if (form.parameter) {
|
|
470
|
+
state.paramValues ||= {};
|
|
471
|
+
state.paramValues[`${form.parameter.in}:${form.parameter.name}`] = form.getValue();
|
|
472
|
+
}
|
|
473
|
+
const headers = headerEditor.values();
|
|
474
|
+
const parameters = state.op.parameters.map(p => dereference(p, state.doc)).filter(p => p?.name && p.in !== 'header')
|
|
475
|
+
.map(p => ({ ...p, value: state.paramValues?.[`${p.in}:${p.name}`] }));
|
|
476
|
+
parameters.push(...headerEditor.parameters());
|
|
477
|
+
const { type } = requestMedia();
|
|
478
|
+
return makeRequest(state.op, parameters, encodeRequestBody(state.body, type, headers), headers, basePath);
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/** ⌥G generates a value for the focused field; ⌥⇧G opens its Generate menu. */
|
|
482
|
+
function generateField(target, menu) {
|
|
483
|
+
const field = target?.closest?.('.field');
|
|
484
|
+
const button = field?.querySelector('.slot.wand, [data-generate]');
|
|
485
|
+
if (!button) return false;
|
|
486
|
+
if (menu) button.click();
|
|
487
|
+
else button.generateNow?.();
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
setToggletipContent(button => describeField(button, { state, requestMedia }));
|
|
491
|
+
|
|
492
|
+
return {
|
|
493
|
+
renderOperation, readRequest, fillSample, autofill, generateField, fieldCount,
|
|
494
|
+
addHeader: headerEditor.add, removeHeader: headerEditor.remove, showBulkHeaders: headerEditor.showBulk, toggleHeader: headerEditor.toggleRow,
|
|
495
|
+
};
|
|
496
|
+
}
|