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,397 @@
|
|
|
1
|
+
import { renderField } from './fields/render.js';
|
|
2
|
+
import { validateSchema } from './fields/validate.js';
|
|
3
|
+
import { newUuid } from './uuid.js';
|
|
4
|
+
import { unwrapNull } from './schema-model.js';
|
|
5
|
+
|
|
6
|
+
// Schema-driven controls for OpenAPI request bodies and parameters.
|
|
7
|
+
const renderers = [];
|
|
8
|
+
let nextId = 0;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Register a renderer for a schema. The predicate receives (schema, {path, name}).
|
|
12
|
+
* The renderer receives {schema, path, name, value, setValue, document, id, required}
|
|
13
|
+
* and returns a DOM node. Last registration wins; the returned function unregisters it.
|
|
14
|
+
*
|
|
15
|
+
* Built-in extensions: x-lookup accepts {url, valueField, labelField, detailField}
|
|
16
|
+
* or {options: [{value, label, detail}]}. URL lookups are same-origin credentialed GETs
|
|
17
|
+
* returning an array. x-currency-field names a sibling property paired with a number.
|
|
18
|
+
*/
|
|
19
|
+
export function registerFieldRenderer(predicate, render) {
|
|
20
|
+
const entry = { predicate, render };
|
|
21
|
+
renderers.unshift(entry);
|
|
22
|
+
return () => {
|
|
23
|
+
const index = renderers.indexOf(entry);
|
|
24
|
+
if (index >= 0) renderers.splice(index, 1);
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* A `oneOf`/`anyOf` that offers `null` next to real options is how OpenAPI 3.1 writes "optional":
|
|
30
|
+
* ASP.NET emits `oneOf: [{type: null}, {$ref}]` for a nullable body or property. That is one schema
|
|
31
|
+
* that may also be null, not a choice between alternatives, so the null option is dropped (and
|
|
32
|
+
* `nullable: true` set, which validation honours) and a single remaining option is merged in.
|
|
33
|
+
* Without this the form showed a "Value · json" field and an "Option 1" select for the wrapper.
|
|
34
|
+
*/
|
|
35
|
+
function collapseNullOption(schema, document, seen) {
|
|
36
|
+
for (const key of ['oneOf', 'anyOf']) {
|
|
37
|
+
if (!Array.isArray(schema[key])) continue;
|
|
38
|
+
const { schema: rest, nullable } = unwrapNull(schema);
|
|
39
|
+
if (!nullable || rest === schema) continue;
|
|
40
|
+
const merged = rest[key] ? rest : resolveSchema(rest, document, seen);
|
|
41
|
+
return { ...merged, nullable: true };
|
|
42
|
+
}
|
|
43
|
+
return schema;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Resolve local JSON pointers; unresolved and recursive references remain usable as JSON. */
|
|
47
|
+
export function resolveSchema(schema, document = {}, seen = new Set()) {
|
|
48
|
+
if (!schema || typeof schema !== 'object') return {};
|
|
49
|
+
if (schema.$ref) {
|
|
50
|
+
const ref = schema.$ref;
|
|
51
|
+
if (!ref.startsWith('#/') || seen.has(ref)) return { ...schema, 'x-unresolved': true };
|
|
52
|
+
const target = ref.slice(2).split('/').reduce((node, part) => node?.[part.replace(/~1/g, '/').replace(/~0/g, '~')], document);
|
|
53
|
+
if (!target) return { ...schema, 'x-unresolved': true };
|
|
54
|
+
const siblings = { ...schema };
|
|
55
|
+
delete siblings.$ref;
|
|
56
|
+
return { ...resolveSchema(target, document, new Set([...seen, ref])), ...siblings };
|
|
57
|
+
}
|
|
58
|
+
if (Array.isArray(schema.allOf)) {
|
|
59
|
+
const merged = { ...schema };
|
|
60
|
+
delete merged.allOf;
|
|
61
|
+
for (const part of schema.allOf) {
|
|
62
|
+
const resolved = resolveSchema(part, document, seen);
|
|
63
|
+
Object.assign(merged, resolved, {
|
|
64
|
+
properties: { ...merged.properties, ...resolved.properties },
|
|
65
|
+
required: [...new Set([...(merged.required || []), ...(resolved.required || [])])]
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
return merged;
|
|
69
|
+
}
|
|
70
|
+
return collapseNullOption(schema, document, seen);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function kind(schema) {
|
|
74
|
+
if (schema['x-unresolved'] || schema.oneOf || schema.anyOf) return 'json';
|
|
75
|
+
const type = Array.isArray(schema.type) ? schema.type.find(item => item !== 'null') : schema.type;
|
|
76
|
+
return type || (schema.properties ? 'object' : schema.items ? 'array' : 'json');
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function sampleNumber(schema, integer) {
|
|
80
|
+
const exclusiveMin = typeof schema.exclusiveMinimum === 'number' ? schema.exclusiveMinimum : schema.exclusiveMinimum === true ? schema.minimum : undefined;
|
|
81
|
+
const exclusiveMax = typeof schema.exclusiveMaximum === 'number' ? schema.exclusiveMaximum : schema.exclusiveMaximum === true ? schema.maximum : undefined;
|
|
82
|
+
const min = exclusiveMin ?? schema.minimum ?? -Infinity;
|
|
83
|
+
const max = exclusiveMax ?? schema.maximum ?? Infinity;
|
|
84
|
+
if (integer) {
|
|
85
|
+
const lower = exclusiveMin === undefined ? Math.ceil(min) : Math.floor(min) + 1;
|
|
86
|
+
const upper = exclusiveMax === undefined ? Math.floor(max) : Math.ceil(max) - 1;
|
|
87
|
+
return Math.max(lower, Math.min(0, upper));
|
|
88
|
+
}
|
|
89
|
+
const step = 0.01;
|
|
90
|
+
let value = Math.max(min, Math.min(0, max));
|
|
91
|
+
if (exclusiveMin !== undefined && value <= exclusiveMin) value = min + step;
|
|
92
|
+
if (exclusiveMax !== undefined && value >= exclusiveMax) value = max - step;
|
|
93
|
+
if (min < max && (value < min || value > max || (exclusiveMin !== undefined && value <= min) || (exclusiveMax !== undefined && value >= max))) {
|
|
94
|
+
value = min + (max - min) / 2;
|
|
95
|
+
}
|
|
96
|
+
return value;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Build a sample from schema metadata, never from application-specific data. */
|
|
100
|
+
export function sampleValue(schema, document = {}, refs = new Set(), depth = 0) {
|
|
101
|
+
if (depth > 12) return null;
|
|
102
|
+
if (schema?.$ref) {
|
|
103
|
+
if (refs.has(schema.$ref)) return null;
|
|
104
|
+
refs = new Set([...refs, schema.$ref]);
|
|
105
|
+
}
|
|
106
|
+
schema = resolveSchema(schema, document);
|
|
107
|
+
if (schema.example !== undefined) return structuredClone(schema.example);
|
|
108
|
+
if (Array.isArray(schema.examples) && schema.examples.length) return structuredClone(schema.examples[0]);
|
|
109
|
+
if (schema.default !== undefined) return structuredClone(schema.default);
|
|
110
|
+
if (schema.const !== undefined) return structuredClone(schema.const);
|
|
111
|
+
if (schema.enum?.length) return schema.enum[0];
|
|
112
|
+
const variants = schema.oneOf || schema.anyOf;
|
|
113
|
+
if (variants?.length) {
|
|
114
|
+
const base = { ...schema };
|
|
115
|
+
delete base.oneOf;
|
|
116
|
+
delete base.anyOf;
|
|
117
|
+
const merged = resolveSchema({ allOf: [base, variants[0]] }, document);
|
|
118
|
+
const result = sampleValue(merged, document, refs, depth + 1);
|
|
119
|
+
if (schema.discriminator?.propertyName && result && typeof result === 'object' && !Array.isArray(result)) {
|
|
120
|
+
const property = schema.discriminator.propertyName;
|
|
121
|
+
const mapped = Object.entries(schema.discriminator.mapping || {}).find(([, ref]) => ref === variants[0].$ref)?.[0];
|
|
122
|
+
result[property] ??= mapped ?? variants[0].$ref?.split('/').at(-1);
|
|
123
|
+
}
|
|
124
|
+
return result;
|
|
125
|
+
}
|
|
126
|
+
switch (kind(schema)) {
|
|
127
|
+
case 'object':
|
|
128
|
+
return Object.fromEntries(Object.entries(schema.properties || {})
|
|
129
|
+
.filter(([, property]) => !property.readOnly)
|
|
130
|
+
.map(([name, property]) => [name, sampleValue(property, document, refs, depth + 1)]));
|
|
131
|
+
case 'array':
|
|
132
|
+
return Array.from({ length: Math.min(schema.minItems || 1, schema.maxItems ?? Infinity, 10) },
|
|
133
|
+
() => sampleValue(schema.items || {}, document, refs, depth + 1));
|
|
134
|
+
case 'integer': return sampleNumber(schema, true);
|
|
135
|
+
case 'number': return sampleNumber(schema, false);
|
|
136
|
+
case 'boolean': return false;
|
|
137
|
+
case 'string':
|
|
138
|
+
if (schema.format === 'date') return new Date().toISOString().slice(0, 10);
|
|
139
|
+
if (schema.format === 'date-time') return new Date().toISOString();
|
|
140
|
+
if (schema.format === 'uuid') return newUuid() || '00000000-0000-4000-8000-000000000000';
|
|
141
|
+
if (schema.format === 'binary') return undefined; // Browsers require a user-selected file.
|
|
142
|
+
{
|
|
143
|
+
const examples = {
|
|
144
|
+
email: 'person@example.com', uri: 'https://example.com/resource',
|
|
145
|
+
url: 'https://example.com/resource', hostname: 'example.com',
|
|
146
|
+
ipv4: '192.0.2.1', ipv6: '2001:db8::1', time: '12:00:00Z',
|
|
147
|
+
duration: 'PT1H', password: 'Example123!', byte: 'ZXhhbXBsZQ==',
|
|
148
|
+
};
|
|
149
|
+
const example = examples[schema.format] ?? 'value';
|
|
150
|
+
return example.padEnd(schema.minLength || 0, 'x').slice(0, schema.maxLength);
|
|
151
|
+
}
|
|
152
|
+
default: return null;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// Files are immutable and must remain File instances when handed to FormData.
|
|
157
|
+
function copy(value) {
|
|
158
|
+
if (typeof Blob !== 'undefined' && value instanceof Blob) return value;
|
|
159
|
+
if (Array.isArray(value)) return value.map(copy);
|
|
160
|
+
if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, copy(item)]));
|
|
161
|
+
return value;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Validate a value without mounting controls, for raw JSON request bodies. */
|
|
165
|
+
export function validateSchemaValue({ schema, value, document = {}, required = false }) {
|
|
166
|
+
let current = value;
|
|
167
|
+
const context = {
|
|
168
|
+
document,
|
|
169
|
+
parseErrors: new Map(),
|
|
170
|
+
variants: new Map(),
|
|
171
|
+
resolve: raw => resolveSchema(raw, document),
|
|
172
|
+
kind,
|
|
173
|
+
get: path => path.reduce((item, key) => item?.[key], current)
|
|
174
|
+
};
|
|
175
|
+
return validateSchema(context, schema, current, required);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Mount a typed form. onChange receives JSON-compatible values and binary File values.
|
|
179
|
+
* basePath is the application's URL path base (for example, /tenant), not /sendproof.
|
|
180
|
+
* flattenRoot removes the decorative label for a structured object at the root.
|
|
181
|
+
*/
|
|
182
|
+
export function createSchemaForm({ container, schema, document: spec = {}, value, onChange = () => {},
|
|
183
|
+
name = 'Value', required = false, basePath = '', flattenRoot = false,
|
|
184
|
+
lookupCache = new Map(), operationPath, lastResponse, onLookupPreview, autofilled = new Map(),
|
|
185
|
+
example, parameter, actor, signedIn = true, onSignIn,
|
|
186
|
+
}) {
|
|
187
|
+
// Earlier callers passed a Set of filled paths; generated sources are labelled in a Map.
|
|
188
|
+
if (!(autofilled instanceof Map)) autofilled = new Map([...autofilled].map(key => [key, '']));
|
|
189
|
+
const previous = new Map();
|
|
190
|
+
let current = copy(value);
|
|
191
|
+
let errors = [];
|
|
192
|
+
let formApi;
|
|
193
|
+
let submitted = false;
|
|
194
|
+
const touched = new Set();
|
|
195
|
+
const parseErrors = new Map();
|
|
196
|
+
const expanded = new Set();
|
|
197
|
+
const variants = new Map();
|
|
198
|
+
|
|
199
|
+
function get(path) {
|
|
200
|
+
return path.reduce((value, key) => value != null && Object.hasOwn(value, key) ? value[key] : undefined, current);
|
|
201
|
+
}
|
|
202
|
+
/** A typed edit replaces a generated value: its "Generated" note and Undo go away. */
|
|
203
|
+
function clearGenerated(key) {
|
|
204
|
+
previous.delete(key);
|
|
205
|
+
const field = [...container.querySelectorAll('[data-schema-path]')].find(node => node.dataset.schemaPath === key);
|
|
206
|
+
if (!field) return;
|
|
207
|
+
const assist = field.querySelector(':scope > .assist');
|
|
208
|
+
const hint = assist?.querySelector('.field-hint');
|
|
209
|
+
if (hint && hint.dataset.base !== undefined) hint.innerHTML = hint.dataset.base;
|
|
210
|
+
const icon = assist?.querySelector('.assist-icon[data-generated]');
|
|
211
|
+
if (icon) { icon.removeAttribute('data-generated'); icon.hidden = !assist.classList.contains('is-error'); }
|
|
212
|
+
assist?.classList.remove('is-generated');
|
|
213
|
+
assist?.querySelector('.undo')?.remove();
|
|
214
|
+
field.querySelector('.control.is-generated')?.classList.remove('is-generated');
|
|
215
|
+
field.querySelector('.slot.wand.gen')?.classList.remove('gen');
|
|
216
|
+
}
|
|
217
|
+
let generating = false;
|
|
218
|
+
function set(path, value) {
|
|
219
|
+
const key = JSON.stringify(path);
|
|
220
|
+
if (autofilled.delete(key) && !generating) clearGenerated(key);
|
|
221
|
+
if (!path.length) current = value;
|
|
222
|
+
else {
|
|
223
|
+
if (current === undefined || current === null || typeof current !== 'object') current = typeof path[0] === 'number' ? [] : {};
|
|
224
|
+
let target = current;
|
|
225
|
+
for (let i = 0; i < path.length - 1; i++) {
|
|
226
|
+
const key = path[i];
|
|
227
|
+
if (!Object.hasOwn(target, key) || !target[key] || typeof target[key] !== 'object')
|
|
228
|
+
Object.defineProperty(target, key, { value: typeof path[i + 1] === 'number' ? [] : {}, enumerable: true, configurable: true, writable: true });
|
|
229
|
+
target = target[key];
|
|
230
|
+
}
|
|
231
|
+
if (value === undefined && !Array.isArray(target)) delete target[path.at(-1)];
|
|
232
|
+
else Object.defineProperty(target, path.at(-1), { value, enumerable: true, configurable: true, writable: true });
|
|
233
|
+
}
|
|
234
|
+
onChange(copy(current));
|
|
235
|
+
formApi?.validate(path);
|
|
236
|
+
}
|
|
237
|
+
/** Sets a value without counting it as an edit, for defaults taken from the spec. */
|
|
238
|
+
function setQuietly(path, value) {
|
|
239
|
+
let target = current && typeof current === 'object' ? current : (current = {});
|
|
240
|
+
for (const key of path.slice(0, -1)) target = target[key] ??= {};
|
|
241
|
+
target[path.at(-1)] = value;
|
|
242
|
+
onChange(copy(current));
|
|
243
|
+
}
|
|
244
|
+
const context = {
|
|
245
|
+
document: spec,
|
|
246
|
+
basePath,
|
|
247
|
+
flattenRoot,
|
|
248
|
+
expanded,
|
|
249
|
+
variants,
|
|
250
|
+
lookupCache,
|
|
251
|
+
operationPath,
|
|
252
|
+
lastResponse,
|
|
253
|
+
onLookupPreview,
|
|
254
|
+
autofilled,
|
|
255
|
+
parseErrors,
|
|
256
|
+
parameter,
|
|
257
|
+
actor,
|
|
258
|
+
signedIn,
|
|
259
|
+
onSignIn,
|
|
260
|
+
get,
|
|
261
|
+
set,
|
|
262
|
+
setQuietly,
|
|
263
|
+
exampleAt: path => path.reduce((value, key) => value?.[key], example),
|
|
264
|
+
/** Puts a generated value in a field, remembering the old value for Undo. */
|
|
265
|
+
generate(path, value, source) {
|
|
266
|
+
const key = JSON.stringify(path);
|
|
267
|
+
if (!previous.has(key)) previous.set(key, get(path));
|
|
268
|
+
generating = true;
|
|
269
|
+
try { set(path, value); } finally { generating = false; }
|
|
270
|
+
autofilled.set(key, source);
|
|
271
|
+
render(key);
|
|
272
|
+
},
|
|
273
|
+
markGenerated(path, source) {
|
|
274
|
+
const key = JSON.stringify(path);
|
|
275
|
+
autofilled.set(key, source);
|
|
276
|
+
},
|
|
277
|
+
canUndo: path => previous.has(JSON.stringify(path)),
|
|
278
|
+
undo(path) {
|
|
279
|
+
const key = JSON.stringify(path);
|
|
280
|
+
if (!previous.has(key)) return;
|
|
281
|
+
const value = previous.get(key);
|
|
282
|
+
previous.delete(key);
|
|
283
|
+
parseErrors.delete(key);
|
|
284
|
+
generating = true;
|
|
285
|
+
try { set(path, value); } finally { generating = false; }
|
|
286
|
+
render(key);
|
|
287
|
+
},
|
|
288
|
+
resolve: raw => resolveSchema(raw, spec),
|
|
289
|
+
kind,
|
|
290
|
+
sample: raw => sampleValue(raw, spec),
|
|
291
|
+
validate: path => formApi?.validate(path),
|
|
292
|
+
nextId: () => ++nextId,
|
|
293
|
+
customRenderer: (resolved, path, label) =>
|
|
294
|
+
renderers.find(entry => entry.predicate(resolved, { path, name: label }))?.render,
|
|
295
|
+
render
|
|
296
|
+
};
|
|
297
|
+
|
|
298
|
+
function render(focusKey, removed = false) {
|
|
299
|
+
container.replaceChildren(renderField(context, schema, [], name, required));
|
|
300
|
+
if (submitted) formApi?.validate();
|
|
301
|
+
if (focusKey) {
|
|
302
|
+
const target = [...container.querySelectorAll(removed ? '[data-optional-path]' : '[data-schema-path]')]
|
|
303
|
+
.find(node => (removed ? node.dataset.optionalPath : node.dataset.schemaPath) === focusKey);
|
|
304
|
+
// Focus the field's own control, not the "i" button in its label row.
|
|
305
|
+
(removed ? target : target?.querySelector('input, textarea, [role="combobox"], [role="radio"][tabindex="0"]') ?? target?.querySelector('.control button'))?.focus?.();
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
function fieldControl(field) {
|
|
309
|
+
const direct = [...(field.children || [])].find(child => child.classList?.contains?.('control'));
|
|
310
|
+
if (direct) return direct;
|
|
311
|
+
for (const child of field.children || []) {
|
|
312
|
+
const nested = child.querySelector?.(':scope > .control');
|
|
313
|
+
if (nested) return nested;
|
|
314
|
+
}
|
|
315
|
+
return null;
|
|
316
|
+
}
|
|
317
|
+
render();
|
|
318
|
+
formApi = {
|
|
319
|
+
getValue: () => copy(current),
|
|
320
|
+
setValue(value) {
|
|
321
|
+
current = copy(value);
|
|
322
|
+
parseErrors.clear();
|
|
323
|
+
variants.clear();
|
|
324
|
+
render();
|
|
325
|
+
},
|
|
326
|
+
validate(changedPath) {
|
|
327
|
+
if (changedPath) touched.add(JSON.stringify(changedPath));
|
|
328
|
+
else submitted = true;
|
|
329
|
+
errors = validateSchema(context, schema, current, required);
|
|
330
|
+
for (const field of container.querySelectorAll('[data-schema-path]')) {
|
|
331
|
+
if (!submitted && !touched.has(field.dataset.schemaPath)) continue;
|
|
332
|
+
const path = JSON.parse(field.dataset.schemaPath).join('.');
|
|
333
|
+
const error = errors.find(entry => entry.path === path);
|
|
334
|
+
// Lookup controls wrap their actual .control one level deeper. Only
|
|
335
|
+
// inspect direct descendants so an object field cannot clear a nested
|
|
336
|
+
// field's invalid border while its own error state is being updated.
|
|
337
|
+
const control = fieldControl(field);
|
|
338
|
+
const candidate = field.querySelector('input,textarea,[role="combobox"],[role="radiogroup"],[role="group"]:not(.optional-props)');
|
|
339
|
+
const input = candidate?.closest('[data-schema-path]') === field ? candidate : null;
|
|
340
|
+
setFieldIssue(field, input, error?.message, control);
|
|
341
|
+
}
|
|
342
|
+
return { valid: errors.length === 0, errors: errors.map(({ path, message }) => ({ path, message })) };
|
|
343
|
+
},
|
|
344
|
+
hasParseErrors: () => [...parseErrors.values()].some(error => error.json),
|
|
345
|
+
fillSample() {
|
|
346
|
+
current = sampleValue(schema, spec);
|
|
347
|
+
parseErrors.clear();
|
|
348
|
+
variants.clear();
|
|
349
|
+
render();
|
|
350
|
+
onChange(copy(current));
|
|
351
|
+
return copy(current);
|
|
352
|
+
},
|
|
353
|
+
destroy() { container.replaceChildren(); }
|
|
354
|
+
};
|
|
355
|
+
return formApi;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/** Reuse the field's reserved assistance and status slots for local or API errors. */
|
|
359
|
+
export function setFieldIssue(field, input, message, control) {
|
|
360
|
+
const assist = field.querySelector(':scope > .assist');
|
|
361
|
+
if (assist) {
|
|
362
|
+
const invalid = !!message;
|
|
363
|
+
const error = assist.querySelector('.field-error');
|
|
364
|
+
const icon = assist.querySelector('.assist-icon');
|
|
365
|
+
const hint = assist.querySelector('.field-hint');
|
|
366
|
+
const generated = icon?.hasAttribute('data-generated');
|
|
367
|
+
if (hint) hint.hidden = invalid;
|
|
368
|
+
error.hidden = !invalid;
|
|
369
|
+
if (icon) {
|
|
370
|
+
icon.hidden = !invalid && !generated;
|
|
371
|
+
icon.innerHTML = `<svg class="i i-sm" aria-hidden="true"><use href="#i-${invalid ? 'alert' : 'wand'}"/></svg>`;
|
|
372
|
+
}
|
|
373
|
+
error.textContent = message || '';
|
|
374
|
+
error.title = message || '';
|
|
375
|
+
assist.classList.toggle('is-error', invalid);
|
|
376
|
+
assist.classList.toggle('is-generated', !invalid && generated);
|
|
377
|
+
assist.querySelector('.undo')?.toggleAttribute('hidden', invalid);
|
|
378
|
+
// The description stays in the accessible description; the status line follows it.
|
|
379
|
+
const description = field.querySelector(':scope > .f-desc');
|
|
380
|
+
input?.setAttribute('aria-describedby', `${description?.childNodes.length ? description.id + ' ' : ''}${assist.id}`);
|
|
381
|
+
}
|
|
382
|
+
if (input && message) input.setAttribute('aria-invalid', 'true');
|
|
383
|
+
else input?.removeAttribute('aria-invalid');
|
|
384
|
+
control ??= input?.closest('.control');
|
|
385
|
+
control?.classList.toggle('is-invalid', !!message);
|
|
386
|
+
// A radio group has no single control: its options take the danger border.
|
|
387
|
+
field.querySelector(':scope > .rg')?.classList.toggle('is-invalid', !!message);
|
|
388
|
+
// The status slot shows the error icon; the Generate button shares its place.
|
|
389
|
+
const slot = control?.querySelector('.slot:not(.wand)');
|
|
390
|
+
const wand = control?.querySelector('.slot.wand');
|
|
391
|
+
if (slot) {
|
|
392
|
+
slot.classList.toggle('err', !!message);
|
|
393
|
+
slot.innerHTML = message ? '<svg class="i i-sm" aria-hidden="true"><use href="#i-alert"/></svg>' : '';
|
|
394
|
+
slot.hidden = !message && !!wand;
|
|
395
|
+
}
|
|
396
|
+
if (wand) wand.hidden = !!message;
|
|
397
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// What an operation needs before it can run, read from its OpenAPI security requirements.
|
|
2
|
+
import { dereference } from './api.js';
|
|
3
|
+
import { formatList } from './i18n.js';
|
|
4
|
+
|
|
5
|
+
/** The effective requirement list: the operation's own, else the document default. */
|
|
6
|
+
export function securityRequirements(op, document) {
|
|
7
|
+
const raw = op?.operation?.security ?? document?.security ?? [];
|
|
8
|
+
return raw.map(requirement => Object.entries(requirement || {}).map(([name, scopes]) => ({
|
|
9
|
+
name, scopes: Array.isArray(scopes) ? scopes : [],
|
|
10
|
+
scheme: dereference(document?.components?.securitySchemes?.[name], document) || {},
|
|
11
|
+
})));
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** True when the operation can be called without signing in. */
|
|
15
|
+
export function isPublic(op, document) {
|
|
16
|
+
const requirements = securityRequirements(op, document);
|
|
17
|
+
return !requirements.length || requirements.some(alternative => !alternative.length);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Every scope the operation names, across its alternatives. */
|
|
21
|
+
export const requiredScopes = (op, document) =>
|
|
22
|
+
[...new Set(securityRequirements(op, document).flatMap(alternative => alternative.flatMap(item => item.scopes)))];
|
|
23
|
+
|
|
24
|
+
/** The schemes of the first alternative, which is what the UI explains. */
|
|
25
|
+
export const primarySchemes = (op, document) => securityRequirements(op, document)[0] || [];
|
|
26
|
+
|
|
27
|
+
/** Scopes or roles as people read them: alternatives joined with "or", e.g. "admin or payments.approve". */
|
|
28
|
+
export function scopeText(op, document) {
|
|
29
|
+
const alternatives = securityRequirements(op, document).map(alternative => alternative.flatMap(item => item.scopes)).filter(scopes => scopes.length);
|
|
30
|
+
return alternatives.length ? formatList(alternatives.map(scopes => scopes.join(' + ')), 'disjunction') : '';
|
|
31
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// The "Seeded account" menu of the signed-out notice: sign in as one of the API's seeded users
|
|
2
|
+
// in a click, without leaving the page. The accounts come from the same `personas` provider the
|
|
3
|
+
// sign-in page uses; the menu is arrow-key navigable and Esc closes it.
|
|
4
|
+
import { esc, icon } from './components.js';
|
|
5
|
+
import { t } from './i18n.js';
|
|
6
|
+
import { closePopover, openPopoverAt } from './popover.js';
|
|
7
|
+
import { isPersonaRefusal, personasProvider } from './personas.js';
|
|
8
|
+
|
|
9
|
+
const initials = name => String(name || '?').trim().split(/\s+/).slice(0, 2).map(part => part[0]).join('').toUpperCase() || '?';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Opens the menu under `button`. `onSignedIn()` runs after the API accepted the sign-in; failures
|
|
13
|
+
* are shown inside the menu and nothing else changes.
|
|
14
|
+
*/
|
|
15
|
+
export async function openSeededMenu(button, { capabilities, onSignedIn }) {
|
|
16
|
+
const provider = personasProvider(capabilities);
|
|
17
|
+
if (!provider) return;
|
|
18
|
+
const pop = openPopoverAt(button, `<div class="pop seeded-pop" role="menu" aria-label="${esc(t('auth.out.seeded'))}">
|
|
19
|
+
<div class="pop-group"><div class="pop-label">${esc(t('signin.seeded'))}</div><div data-seeded-list role="none"><div class="opt-row" role="status"><span class="faint">${esc(t('signin.loadingAccounts'))}</span></div></div></div>
|
|
20
|
+
</div>`, { align: 'start', focus: false, kind: 'seeded', onClose: () => button.setAttribute('aria-expanded', 'false') });
|
|
21
|
+
const list = pop.querySelector('[data-seeded-list]');
|
|
22
|
+
let users;
|
|
23
|
+
try {
|
|
24
|
+
const response = await fetch(provider.url, { credentials: 'include', redirect: 'error' });
|
|
25
|
+
if (isPersonaRefusal(response.status)) {
|
|
26
|
+
// The host does not offer seeded accounts to this caller: drop the option, show no error.
|
|
27
|
+
closePopover();
|
|
28
|
+
button.hidden = true;
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
if (!response.ok) throw new Error(t('signin.accountsStatus', { status: response.status }));
|
|
32
|
+
users = await response.json();
|
|
33
|
+
if (!Array.isArray(users)) throw new Error(t('signin.accountsInvalid'));
|
|
34
|
+
} catch (failure) {
|
|
35
|
+
list.innerHTML = `<div class="opt-row" role="alert"><span style="color:var(--danger)">${esc(failure.message)}</span></div>`;
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
list.innerHTML = users.map((user, index) => {
|
|
39
|
+
const roles = (Array.isArray(user.roles) ? user.roles : user.role ? [user.role] : []).join(', ');
|
|
40
|
+
return `<button type="button" class="opt-row" role="menuitem" tabindex="-1" data-seeded="${index}" style="inline-size:100%;border:0;background:none;text-align:start;font:inherit">
|
|
41
|
+
<span class="avatar" aria-hidden="true">${esc(initials(user.name || user.email))}</span>
|
|
42
|
+
<span class="stack"><span class="main">${esc(user.name || user.email || '')}${roles ? ` <span class="tag tag-mono">${esc(roles)}</span>` : ''}</span><span class="sub ltr">${esc(user.email || '')}</span></span></button>`;
|
|
43
|
+
}).join('') || `<div class="opt-row"><span class="faint">${esc(t('signin.noAccounts'))}</span></div>`;
|
|
44
|
+
const items = [...list.querySelectorAll('[role="menuitem"]')];
|
|
45
|
+
items[0]?.focus();
|
|
46
|
+
pop.addEventListener('keydown', event => {
|
|
47
|
+
const index = items.indexOf(document.activeElement);
|
|
48
|
+
const keys = { ArrowDown: index + 1, ArrowUp: index - 1, Home: 0, End: items.length - 1 };
|
|
49
|
+
if (event.key in keys && items.length) {
|
|
50
|
+
event.preventDefault();
|
|
51
|
+
items[(keys[event.key] + items.length) % items.length].focus();
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
pop.addEventListener('click', async event => {
|
|
55
|
+
const item = event.target.closest('[data-seeded]');
|
|
56
|
+
const user = item && users[Number(item.dataset.seeded)];
|
|
57
|
+
if (!user?.email) return;
|
|
58
|
+
item.setAttribute('aria-busy', 'true');
|
|
59
|
+
try {
|
|
60
|
+
const response = await fetch(`${provider.url.replace(/\/$/, '')}/${encodeURIComponent(user.email)}`, { method: 'POST', credentials: 'include', redirect: 'error' });
|
|
61
|
+
if (!response.ok) throw new Error(t('signin.failedStatus', { status: response.status }));
|
|
62
|
+
closePopover();
|
|
63
|
+
onSignedIn();
|
|
64
|
+
} catch (failure) {
|
|
65
|
+
item.removeAttribute('aria-busy');
|
|
66
|
+
list.insertAdjacentHTML('afterbegin', `<div class="opt-row" role="alert">${icon('alert', true)}<span style="color:var(--danger)">${esc(failure.message)}</span></div>`);
|
|
67
|
+
}
|
|
68
|
+
});
|
|
69
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// User preferences that live in this browser only: density, theme, language, digits and traced
|
|
2
|
+
// Send. applySettings() writes them to <html> so the stylesheet and i18n follow.
|
|
3
|
+
import { configure, current, detectPlatform, LANGUAGES, matchLanguage, runButtonWidths } from './i18n.js';
|
|
4
|
+
|
|
5
|
+
const STORAGE_KEY = 'sendproof-settings';
|
|
6
|
+
const DENSITIES = ['compact', 'default', 'comfortable'];
|
|
7
|
+
const THEMES = ['system', 'light', 'dark'];
|
|
8
|
+
|
|
9
|
+
/** Settings with defaults filled in. tracedSend is null until the user chooses. */
|
|
10
|
+
export function loadSettings(storage = globalThis.localStorage, preferences = globalThis.navigator?.languages) {
|
|
11
|
+
let saved = {};
|
|
12
|
+
try { saved = JSON.parse(storage?.getItem(STORAGE_KEY) || '{}') || {}; } catch { /* Ignore an unreadable value. */ }
|
|
13
|
+
// Earlier versions stored only the theme.
|
|
14
|
+
const legacyTheme = (() => { try { return storage?.getItem('sendproof-theme'); } catch { return null; } })();
|
|
15
|
+
return {
|
|
16
|
+
density: DENSITIES.includes(saved.density) ? saved.density : 'default',
|
|
17
|
+
theme: THEMES.includes(saved.theme) ? saved.theme : ['light', 'dark'].includes(legacyTheme) ? legacyTheme : 'system',
|
|
18
|
+
language: LANGUAGES.some(language => language.id === saved.language) ? saved.language : matchLanguage(preferences || []),
|
|
19
|
+
digits: saved.digits === 'arab' ? 'arab' : 'latn',
|
|
20
|
+
tracedSend: typeof saved.tracedSend === 'boolean' ? saved.tracedSend : null,
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
let settings = loadSettings();
|
|
25
|
+
const listeners = new Set();
|
|
26
|
+
|
|
27
|
+
export const getSettings = () => settings;
|
|
28
|
+
|
|
29
|
+
/** Merges a change, stores it and re-applies every setting. */
|
|
30
|
+
export function updateSettings(change, storage = globalThis.localStorage) {
|
|
31
|
+
settings = { ...settings, ...change };
|
|
32
|
+
try { storage?.setItem(STORAGE_KEY, JSON.stringify(settings)); } catch { /* Private mode can refuse storage. */ }
|
|
33
|
+
applySettings();
|
|
34
|
+
listeners.forEach(listener => listener(settings, change));
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Calls back after every change. Returns an unsubscribe function. */
|
|
38
|
+
export function onSettingsChange(listener) {
|
|
39
|
+
listeners.add(listener);
|
|
40
|
+
return () => listeners.delete(listener);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Traced Send is on by default in Development and off elsewhere, unless the user chose. */
|
|
44
|
+
export function tracedSendEnabled(capabilities) {
|
|
45
|
+
if (capabilities?.observedSend !== true) return false;
|
|
46
|
+
return settings.tracedSend ?? /^development$/i.test(capabilities.environment || '');
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const darkQuery = () => globalThis.matchMedia?.('(prefers-color-scheme: dark)');
|
|
50
|
+
|
|
51
|
+
/** The theme actually shown: System follows the operating system. */
|
|
52
|
+
export const resolvedTheme = () => settings.theme === 'system' ? (darkQuery()?.matches ? 'dark' : 'light') : settings.theme;
|
|
53
|
+
|
|
54
|
+
/** Writes density, theme, language, direction, platform and run-button widths to <html>. */
|
|
55
|
+
export function applySettings(root = globalThis.document?.documentElement) {
|
|
56
|
+
configure({ language: settings.language, digits: settings.digits, platform: detectPlatform() });
|
|
57
|
+
if (!root) return;
|
|
58
|
+
const { dir, platform } = current();
|
|
59
|
+
if (settings.density === 'default') delete root.dataset.density;
|
|
60
|
+
else root.dataset.density = settings.density;
|
|
61
|
+
root.dataset.theme = resolvedTheme();
|
|
62
|
+
root.dataset.platform = platform;
|
|
63
|
+
root.lang = settings.language;
|
|
64
|
+
root.dir = dir;
|
|
65
|
+
loadScriptFont(settings.language, root.ownerDocument);
|
|
66
|
+
const widths = runButtonWidths();
|
|
67
|
+
root.style.setProperty('--w-preview', widths.preview);
|
|
68
|
+
root.style.setProperty('--w-send', widths.send);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Faces for scripts Geist doesn't cover, loaded only for the active language: Noto Sans JP, KR,
|
|
73
|
+
* SC and TC for CJK, Hebrew, Devanagari and Thai (Arabic and Persian use IBM Plex Sans Arabic,
|
|
74
|
+
* which styles.css loads with Geist). The stylesheet's :lang() rules put the face after Geist.
|
|
75
|
+
*/
|
|
76
|
+
const SCRIPT_FONTS = {
|
|
77
|
+
ja: 'Noto+Sans+JP', ko: 'Noto+Sans+KR', 'zh-Hans': 'Noto+Sans+SC', 'zh-Hant': 'Noto+Sans+TC',
|
|
78
|
+
he: 'Noto+Sans+Hebrew', hi: 'Noto+Sans+Devanagari', th: 'Noto+Sans+Thai',
|
|
79
|
+
};
|
|
80
|
+
function loadScriptFont(language, document) {
|
|
81
|
+
const catalogue = LANGUAGES.find(item => item.id === language)?.catalogue;
|
|
82
|
+
const family = SCRIPT_FONTS[catalogue];
|
|
83
|
+
if (!family || !document?.head || document.querySelector(`link[data-script-font="${family}"]`)) return;
|
|
84
|
+
const link = document.createElement('link');
|
|
85
|
+
link.rel = 'stylesheet';
|
|
86
|
+
link.href = `https://fonts.googleapis.com/css2?family=${family}:wght@400;500;600&display=swap`;
|
|
87
|
+
link.dataset.scriptFont = family;
|
|
88
|
+
document.head.append(link);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
darkQuery()?.addEventListener?.('change', () => {
|
|
92
|
+
if (settings.theme === 'system') applySettings();
|
|
93
|
+
});
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// The keyboard shortcut sheet (?), built from the shortcut registry (mock 55). Search filters
|
|
2
|
+
// every registered shortcut; without a query it shows the curated overview below.
|
|
3
|
+
import { esc, icon } from './components.js';
|
|
4
|
+
import { t } from './i18n.js';
|
|
5
|
+
import { matchesShortcut, shortcutHint, shortcutLabel, shortcutLong, SHORTCUTS } from './shortcuts.js';
|
|
6
|
+
|
|
7
|
+
const sections = ['General', 'Navigate', 'Request', 'Fields', 'Headers & lists', 'Result'];
|
|
8
|
+
// [label key or shortcut id, ...shortcut ids]. A label key starts with "sheet.".
|
|
9
|
+
const overview = [
|
|
10
|
+
[['palette'], ['shortcuts'], ['display'], ['sidebar'], ['theme'], ['history'], ['signin']],
|
|
11
|
+
[['filter'], ['sheet.nextPrevious', 'next', 'previous'], ['sheet.sidebarTabs', 'sidebar-operations', 'sidebar-models'], ['docs'],
|
|
12
|
+
['request-tab-range'], ['result-tab-range'], ['model-back']],
|
|
13
|
+
[['preview'], ['send'], ['autofill-required'], ['editor-mode'], ['issue-next'], ['copy-url']],
|
|
14
|
+
[['generate'], ['generate-menu'], ['field-info'], ['lookup-open'], ['autofill-ids'], ['autofill-undo']],
|
|
15
|
+
[['add-row'], ['remove-row'], ['toggle-header'], ['bulk-edit']],
|
|
16
|
+
[['copy-curl'], ['copy-response'], ['follow-response'], ['sheet.changes', 'change-next', 'change-prev'], ['escape']],
|
|
17
|
+
];
|
|
18
|
+
|
|
19
|
+
const row = (label, ids) => `<div class="sc-row"><span>${esc(label)}</span><span class="sc-keys">${ids.map(id => shortcutHint(id)).join('<span class="then" aria-hidden="true">/</span>')}</span></div>`;
|
|
20
|
+
|
|
21
|
+
/** Opens the shortcut sheet and keeps keyboard focus within it. */
|
|
22
|
+
export function showShortcuts(overlay) {
|
|
23
|
+
const opener = document.activeElement?.closest('.palette') ? document.querySelector('.search-trigger') : document.activeElement;
|
|
24
|
+
const app = document.querySelector('.app');
|
|
25
|
+
overlay.innerHTML = `<div class="scrim shortcuts-scrim">
|
|
26
|
+
<section class="dialog" role="dialog" aria-modal="true" aria-labelledby="sc-title">
|
|
27
|
+
<div class="dialog-head">
|
|
28
|
+
<h2 id="sc-title">${esc(t('sheet.title'))}</h2>
|
|
29
|
+
<label class="input-sm">${icon('search', true)}<span class="sr-only">${esc(t('sheet.search'))}</span><input placeholder="${esc(t('sheet.search'))}" type="search"></label>
|
|
30
|
+
<span class="spacer"></span><span class="faint desktop-only" style="font-size:var(--fs-sm)">${esc(t('sheet.note', { example: shortcutLong('send') }))}</span>
|
|
31
|
+
<button type="button" class="btn btn-ghost btn-icon btn-sm" aria-label="${esc(t('sheet.close'))}">${icon('x', true)}</button>
|
|
32
|
+
</div>
|
|
33
|
+
<div class="dialog-body"></div>
|
|
34
|
+
</section></div>`;
|
|
35
|
+
const dialog = overlay.querySelector('.dialog');
|
|
36
|
+
const input = overlay.querySelector('input');
|
|
37
|
+
const dismiss = overlay.querySelector('.dialog-head button');
|
|
38
|
+
const body = overlay.querySelector('.dialog-body');
|
|
39
|
+
const all = Object.entries(SHORTCUTS).filter(([, definition]) => definition.group && (definition.chord || definition.sequence));
|
|
40
|
+
if (app) app.inert = true;
|
|
41
|
+
|
|
42
|
+
function render() {
|
|
43
|
+
const query = input.value.trim().toLowerCase();
|
|
44
|
+
body.innerHTML = sections.map((section, index) => {
|
|
45
|
+
const rows = query
|
|
46
|
+
? all.filter(([id, definition]) => definition.group === section && shortcutLabel(id).toLowerCase().includes(query)).map(([id]) => row(shortcutLabel(id), [id]))
|
|
47
|
+
: overview[index].map(([first, ...rest]) => first.startsWith('sheet.') ? row(t(first), rest) : row(shortcutLabel(first), [first]));
|
|
48
|
+
return rows.length ? `<section class="sc-group" aria-label="${esc(t('sheet.group.' + section))}"><h3>${esc(t('sheet.group.' + section))}</h3>${rows.join('')}</section>` : '';
|
|
49
|
+
}).join('') || `<p class="faint" role="status">${esc(t('sheet.none'))}</p>`;
|
|
50
|
+
}
|
|
51
|
+
function close() {
|
|
52
|
+
overlay.innerHTML = '';
|
|
53
|
+
if (app) app.inert = false;
|
|
54
|
+
opener?.focus();
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
dialog.addEventListener('keydown', event => {
|
|
58
|
+
if (matchesShortcut('escape', event)) {
|
|
59
|
+
event.preventDefault(); event.stopPropagation(); close();
|
|
60
|
+
} else if (event.key === 'Tab' && !event.shiftKey && document.activeElement === dismiss) {
|
|
61
|
+
event.preventDefault(); input.focus();
|
|
62
|
+
} else if (event.key === 'Tab' && event.shiftKey && document.activeElement === input) {
|
|
63
|
+
event.preventDefault(); dismiss.focus();
|
|
64
|
+
}
|
|
65
|
+
});
|
|
66
|
+
dismiss.addEventListener('click', close);
|
|
67
|
+
overlay.querySelector('.scrim').addEventListener('click', event => {
|
|
68
|
+
if (event.target === event.currentTarget) close();
|
|
69
|
+
});
|
|
70
|
+
input.addEventListener('input', render);
|
|
71
|
+
render();
|
|
72
|
+
input.focus();
|
|
73
|
+
}
|