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,164 @@
|
|
|
1
|
+
// Formats with request-side checks. Custom formats are treated as annotations.
|
|
2
|
+
import { t } from '../i18n.js';
|
|
3
|
+
|
|
4
|
+
const datePattern = /^\d{4}-\d{2}-\d{2}$/;
|
|
5
|
+
const timePattern = /^(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:z|([+-])(\d{2}):(\d{2}))$/i;
|
|
6
|
+
const pointerPattern = /^(?:\/(?:[^~/]|~[01])*)*$/;
|
|
7
|
+
const relativePointerPattern = /^(?:0|[1-9]\d*)(?:#|(?:\/(?:[^~/]|~[01])*)*)$/;
|
|
8
|
+
const hostnamePattern = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i;
|
|
9
|
+
const emailLocalPattern = /^(?:[a-z0-9!#$%&'*+/=?^_{}|~-]+(?:\.[a-z0-9!#$%&'*+/=?^_{}|~-]+)*|"(?:[^"\\\r\n]|\\[ -~])*")$/i;
|
|
10
|
+
|
|
11
|
+
function isDate(value) {
|
|
12
|
+
if (!datePattern.test(value)) return false;
|
|
13
|
+
const date = new Date(value + 'T00:00:00Z');
|
|
14
|
+
return Number.isFinite(date.valueOf()) && date.toISOString().slice(0, 10) === value;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function isTime(value, date) {
|
|
18
|
+
const match = timePattern.exec(value);
|
|
19
|
+
if (!match) return false;
|
|
20
|
+
const [, hours, minutes, seconds, sign, zoneHours = '0', zoneMinutes = '0'] = match;
|
|
21
|
+
if (+hours > 23 || +minutes > 59 || +seconds > 60 || +zoneHours > 23 || +zoneMinutes > 59) return false;
|
|
22
|
+
if (+seconds < 60) return true;
|
|
23
|
+
const offset = (sign === '-' ? -1 : 1) * (+zoneHours * 60 + +zoneMinutes);
|
|
24
|
+
const utcMinute = +hours * 60 + +minutes - offset;
|
|
25
|
+
if ((utcMinute + 1440) % 1440 !== 1439) return false;
|
|
26
|
+
if (!date) return true;
|
|
27
|
+
const nextDay = new Date(date + 'T00:00:00Z');
|
|
28
|
+
nextDay.setUTCDate(nextDay.getUTCDate() + 1 + Math.floor(utcMinute / 1440));
|
|
29
|
+
return nextDay.getUTCDate() === 1;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function isDateTime(value) {
|
|
33
|
+
const [date, time, ...rest] = value.split(/t/i);
|
|
34
|
+
return time !== undefined && rest.length === 0 && isDate(date) && isTime(time, date);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function isIPv4(value) {
|
|
38
|
+
const parts = value.split('.');
|
|
39
|
+
return parts.length === 4 && parts.every(part => /^(?:0|[1-9]\d{0,2})$/.test(part) && +part <= 255);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function isIPv6(value) {
|
|
43
|
+
if (!/^[a-f0-9:.]+$/i.test(value) || !value.includes(':')) return false;
|
|
44
|
+
try {
|
|
45
|
+
return Boolean(new URL('http://[' + value + ']').hostname);
|
|
46
|
+
} catch {
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function isHostname(value) {
|
|
52
|
+
const name = value.endsWith('.') ? value.slice(0, -1) : value;
|
|
53
|
+
return name.length <= 253 && name.split('.').every(label => hostnamePattern.test(label));
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function isInternationalHostname(value) {
|
|
57
|
+
if (/^[\x00-\x7f]*$/.test(value)) return isHostname(value);
|
|
58
|
+
if (/[\s:/?#@[\]\\%]/u.test(value)) return false;
|
|
59
|
+
const labels = value.normalize('NFKC').replace(/[。。.]/gu, '.');
|
|
60
|
+
if (/(?:^|\.)-|-($|\.)/u.test(labels)) return false;
|
|
61
|
+
try {
|
|
62
|
+
return isHostname(new URL('http://' + value).hostname);
|
|
63
|
+
} catch {
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function isEmail(value, international = false) {
|
|
69
|
+
const separator = value.lastIndexOf('@');
|
|
70
|
+
const local = value.slice(0, separator);
|
|
71
|
+
const host = value.slice(separator + 1);
|
|
72
|
+
const normalizedLocal = international ? local.replace(/[^\x00-\x7f\s]/gu, 'a') : local;
|
|
73
|
+
if (separator <= 0 || local.length > 64 || !emailLocalPattern.test(normalizedLocal)) return false;
|
|
74
|
+
if (!international && /[^\x00-\x7f]/.test(local)) return false;
|
|
75
|
+
if (host.startsWith('[') && host.endsWith(']')) {
|
|
76
|
+
const address = host.slice(1, -1);
|
|
77
|
+
return /^ipv6:/i.test(address) ? isIPv6(address.slice(5)) : isIPv4(address);
|
|
78
|
+
}
|
|
79
|
+
return !host.endsWith('.') && (international ? isInternationalHostname(host) : isHostname(host));
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function isUri(value, relative, international = false) {
|
|
83
|
+
if (/\s|%(?![a-f0-9]{2})|[\x00-\x1f\x7f]/i.test(value)) return false;
|
|
84
|
+
if (!international && /[^\x21-\x7e]/.test(value)) return false;
|
|
85
|
+
if (/[<>"{}|\\^\x60]/.test(value)) return false;
|
|
86
|
+
|
|
87
|
+
const match = /^(?:([a-z][a-z0-9+.-]*):)?(?:\/\/([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#([^#]*))?$/i.exec(value);
|
|
88
|
+
if (!match) return false;
|
|
89
|
+
const [, scheme, authority, path, query = '', fragment = ''] = match;
|
|
90
|
+
const requiresHost = /^(?:https?|wss?|ftp)$/i.test(scheme ?? '');
|
|
91
|
+
if (!scheme && (!relative || (authority === undefined && path.split('/')[0].includes(':')))) return false;
|
|
92
|
+
if (/[[\]]/.test(path + query + fragment)) return false;
|
|
93
|
+
if (authority === undefined) return !requiresHost;
|
|
94
|
+
|
|
95
|
+
const parts = /^(?:([^@[\]]*)@)?(\[[^\]]+\]|[^:[\]@]*)(?::\d*)?$/.exec(authority);
|
|
96
|
+
if (!parts) return false;
|
|
97
|
+
const host = parts[2];
|
|
98
|
+
if (!host.startsWith('[')) return !requiresHost || host.length > 0;
|
|
99
|
+
const address = host.slice(1, -1);
|
|
100
|
+
return isIPv6(address) || /^v[0-9a-f]+\.[a-z0-9._~!$&'()*+,;=:-]+$/i.test(address);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function isUrl(value) {
|
|
104
|
+
if (!isUri(value, false)) return false;
|
|
105
|
+
try {
|
|
106
|
+
return Boolean(new URL(value).href);
|
|
107
|
+
} catch {
|
|
108
|
+
return false;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function isUriTemplate(value) {
|
|
113
|
+
const variable = /^(?:[a-z0-9_]|%[0-9a-f]{2})+(?:\.(?:[a-z0-9_]|%[0-9a-f]{2})+)*(?:\*|:[1-9]\d{0,3})?$/i;
|
|
114
|
+
const literal = /[\s<>"{}|\\^\x60]|%(?![a-f0-9]{2})/i;
|
|
115
|
+
const remainder = value.replace(/\{([+#./;?&]?)([^{}]+)\}/g, (expression, _operator, variables) =>
|
|
116
|
+
variables.split(',').every(name => variable.test(name)) ? '' : expression);
|
|
117
|
+
return !literal.test(remainder);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function isDuration(value) {
|
|
121
|
+
// RFC 3339 durations allow weeks alone or ordered date and time components.
|
|
122
|
+
return /^P\d+W$/.test(value) ||
|
|
123
|
+
/^P(?=\d|T)(?:\d+Y)?(?:\d+M)?(?:\d+D)?(?:T(?=\d)(?:\d+H)?(?:\d+M)?(?:\d+S)?)?$/.test(value);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function isRegex(value) {
|
|
127
|
+
try {
|
|
128
|
+
new RegExp(value, 'u');
|
|
129
|
+
return true;
|
|
130
|
+
} catch {
|
|
131
|
+
return false;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// Each check is [test, message key]. Messages live in ui/locales/en-capture.js under valid.format.*.
|
|
136
|
+
const checks = new Map([
|
|
137
|
+
['email', [isEmail, 'valid.format.email']],
|
|
138
|
+
['idn-email', [value => isEmail(value, true), 'valid.format.email']],
|
|
139
|
+
['date', [isDate, 'valid.format.date']],
|
|
140
|
+
['time', [isTime, 'valid.format.time']],
|
|
141
|
+
['date-time', [isDateTime, 'valid.format.dateTime']],
|
|
142
|
+
['duration', [isDuration, 'valid.format.duration']],
|
|
143
|
+
['uuid', [value => /^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/i.test(value), 'valid.format.uuid']],
|
|
144
|
+
['hostname', [isHostname, 'valid.format.hostname']],
|
|
145
|
+
['idn-hostname', [isInternationalHostname, 'valid.format.hostname']],
|
|
146
|
+
['ipv4', [isIPv4, 'valid.format.ipv4']],
|
|
147
|
+
['ipv6', [isIPv6, 'valid.format.ipv6']],
|
|
148
|
+
['url', [isUrl, 'valid.format.url']],
|
|
149
|
+
['uri', [value => isUri(value, false), 'valid.format.uri']],
|
|
150
|
+
['uri-reference', [value => isUri(value, true), 'valid.format.uriReference']],
|
|
151
|
+
['iri', [value => isUri(value, false, true), 'valid.format.iri']],
|
|
152
|
+
['iri-reference', [value => isUri(value, true, true), 'valid.format.iriReference']],
|
|
153
|
+
['uri-template', [isUriTemplate, 'valid.format.uriTemplate']],
|
|
154
|
+
['json-pointer', [value => pointerPattern.test(value), 'valid.format.jsonPointer']],
|
|
155
|
+
['relative-json-pointer', [value => relativePointerPattern.test(value), 'valid.format.relativeJsonPointer']],
|
|
156
|
+
['regex', [isRegex, 'valid.format.regex']],
|
|
157
|
+
['byte', [value => /^(?:[a-z0-9+/]{4})*(?:[a-z0-9+/]{2}==|[a-z0-9+/]{3}=)?$/i.test(value), 'valid.format.byte']],
|
|
158
|
+
]);
|
|
159
|
+
|
|
160
|
+
/** The message for a value that breaks its `format`, or undefined when it passes or the format is unchecked. */
|
|
161
|
+
export function formatError(format, value) {
|
|
162
|
+
const check = checks.get(format);
|
|
163
|
+
return check && !check[0](value) ? t(check[1], { example: '/items/{id}' }) : undefined;
|
|
164
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
function pointerTarget(root, fragment) {
|
|
2
|
+
let target = root;
|
|
3
|
+
for (const part of fragment.slice(1).split('/')) {
|
|
4
|
+
const key = part.replace(/~1/g, '/').replace(/~0/g, '~');
|
|
5
|
+
if (target == null || !Object.hasOwn(target, key)) return;
|
|
6
|
+
target = target[key];
|
|
7
|
+
}
|
|
8
|
+
return target;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
const schemaMaps = ['$defs', 'definitions', 'properties', 'patternProperties', 'dependentSchemas', 'dependencies'];
|
|
12
|
+
const schemaLists = ['allOf', 'anyOf', 'oneOf', 'prefixItems'];
|
|
13
|
+
const subschemas = [
|
|
14
|
+
'not', 'if', 'then', 'else', 'items', 'contains', 'additionalItems', 'unevaluatedItems',
|
|
15
|
+
'additionalProperties', 'unevaluatedProperties', 'propertyNames',
|
|
16
|
+
];
|
|
17
|
+
|
|
18
|
+
function anchorTarget(schema, fragment, visited = new Set()) {
|
|
19
|
+
if (!schema || typeof schema !== 'object' || visited.has(schema)) return;
|
|
20
|
+
visited.add(schema);
|
|
21
|
+
if (schema.$anchor === fragment) return schema;
|
|
22
|
+
if (Array.isArray(schema)) {
|
|
23
|
+
for (const child of schema) {
|
|
24
|
+
const found = anchorTarget(child, fragment, visited);
|
|
25
|
+
if (found) return found;
|
|
26
|
+
}
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const children = [
|
|
31
|
+
...schemaMaps.flatMap(key => Object.values(schema[key] ?? {})),
|
|
32
|
+
...schemaLists.flatMap(key => schema[key] ?? []),
|
|
33
|
+
...subschemas.map(key => schema[key]),
|
|
34
|
+
];
|
|
35
|
+
for (const child of children) {
|
|
36
|
+
const found = anchorTarget(child, fragment, visited);
|
|
37
|
+
if (found) return found;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Resolve references supplied with the schema or OpenAPI document. */
|
|
42
|
+
export function createReferenceResolver(document, schema) {
|
|
43
|
+
const cache = new Map();
|
|
44
|
+
return ref => {
|
|
45
|
+
if (typeof ref !== 'string' || !ref.startsWith('#')) return;
|
|
46
|
+
if (!cache.has(ref)) {
|
|
47
|
+
let target;
|
|
48
|
+
try {
|
|
49
|
+
const fragment = decodeURIComponent(ref.slice(1));
|
|
50
|
+
if (!fragment) target = document?.openapi ? document : schema;
|
|
51
|
+
else if (fragment.startsWith('/')) target = pointerTarget(document, fragment) ?? pointerTarget(schema, fragment);
|
|
52
|
+
else {
|
|
53
|
+
target = anchorTarget(schema, fragment) ?? anchorTarget(document, fragment);
|
|
54
|
+
if (!target) {
|
|
55
|
+
for (const component of Object.values(document?.components?.schemas ?? {})) {
|
|
56
|
+
target = anchorTarget(component, fragment);
|
|
57
|
+
if (target) break;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
} catch {
|
|
62
|
+
// Invalid URI fragments are unresolved references.
|
|
63
|
+
}
|
|
64
|
+
cache.set(ref, target);
|
|
65
|
+
}
|
|
66
|
+
return cache.get(ref);
|
|
67
|
+
};
|
|
68
|
+
}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { formatList, t } from '../i18n.js';
|
|
2
|
+
import { formatError } from './validation-formats.js';
|
|
3
|
+
|
|
4
|
+
export const isFile = value => typeof Blob !== 'undefined' && value instanceof Blob;
|
|
5
|
+
export const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value) && !isFile(value);
|
|
6
|
+
export const isNumber = value => typeof value === 'number' && Number.isFinite(value);
|
|
7
|
+
|
|
8
|
+
const typeChecks = new Map([
|
|
9
|
+
['null', value => value === null],
|
|
10
|
+
['boolean', value => typeof value === 'boolean'],
|
|
11
|
+
['object', isObject],
|
|
12
|
+
['array', Array.isArray],
|
|
13
|
+
['number', isNumber],
|
|
14
|
+
['integer', Number.isInteger],
|
|
15
|
+
['string', (value, schema) => typeof value === 'string' || (schema.format === 'binary' && isFile(value))],
|
|
16
|
+
]);
|
|
17
|
+
|
|
18
|
+
// Messages live in ui/locales/en-capture.js as valid.type.<type>.
|
|
19
|
+
const typeMessages = new Set(['null', 'boolean', 'object', 'array', 'number', 'integer', 'string']);
|
|
20
|
+
|
|
21
|
+
/** The message for a value of the wrong type, or undefined when its type fits the schema. */
|
|
22
|
+
export function typeError(schema, value, allowNullable) {
|
|
23
|
+
if (schema.type === undefined) return;
|
|
24
|
+
const types = Array.isArray(schema.type) ? schema.type : [schema.type];
|
|
25
|
+
if (value === null && allowNullable && schema.nullable === true && typeof schema.type === 'string') return;
|
|
26
|
+
if (types.some(type => !typeChecks.has(type) || typeChecks.get(type)(value, schema))) return;
|
|
27
|
+
if (value === null) return t('valid.type.nullValue');
|
|
28
|
+
if (schema.format === 'binary' && types.includes('string') && types.length === 1) return t('valid.type.file');
|
|
29
|
+
return types.length === 1 && typeMessages.has(types[0])
|
|
30
|
+
? t('valid.type.' + types[0])
|
|
31
|
+
: t('valid.type.oneOf', { types: formatList(types, 'unit') });
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function compilePattern(pattern) {
|
|
35
|
+
if (typeof pattern !== 'string') return;
|
|
36
|
+
try {
|
|
37
|
+
return new RegExp(pattern, 'u');
|
|
38
|
+
} catch {
|
|
39
|
+
// A malformed schema pattern cannot give the user a reliable constraint.
|
|
40
|
+
return undefined;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function displayValue(value) {
|
|
45
|
+
const text = JSON.stringify(value) ?? String(value);
|
|
46
|
+
return text.length > 48 ? text.slice(0, 47) + '…' : text;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Produce comparable keys for JSON values, with File identity preserved for uploads. */
|
|
50
|
+
export function createValueKey() {
|
|
51
|
+
const files = new WeakMap();
|
|
52
|
+
let nextFile = 0;
|
|
53
|
+
|
|
54
|
+
function key(value) {
|
|
55
|
+
if (isFile(value)) {
|
|
56
|
+
if (!files.has(value)) files.set(value, ++nextFile);
|
|
57
|
+
return 'file:' + files.get(value);
|
|
58
|
+
}
|
|
59
|
+
if (Array.isArray(value)) return '[' + Array.from(value, key).join(',') + ']';
|
|
60
|
+
if (isObject(value)) {
|
|
61
|
+
return '{' + Object.keys(value).sort().map(name =>
|
|
62
|
+
JSON.stringify(name) + ':' + key(value[name])).join(',') + '}';
|
|
63
|
+
}
|
|
64
|
+
// JSON.stringify treats both positive and negative zero as the same number.
|
|
65
|
+
return JSON.stringify(value) ?? 'undefined';
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
return key;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function decimalParts(value) {
|
|
72
|
+
const [mantissa, exponent = '0'] = String(value).split('e');
|
|
73
|
+
const [whole, fraction = ''] = mantissa.split('.');
|
|
74
|
+
return [BigInt(whole + fraction), +exponent - fraction.length];
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function isMultipleOf(value, step) {
|
|
78
|
+
// Use the decimal representation sent in JSON to avoid floating-point remainder artifacts.
|
|
79
|
+
const [coefficient, scale] = decimalParts(value);
|
|
80
|
+
const [divisor, divisorScale] = decimalParts(step);
|
|
81
|
+
const commonScale = Math.min(scale, divisorScale);
|
|
82
|
+
return coefficient * 10n ** BigInt(scale - commonScale) %
|
|
83
|
+
(divisor * 10n ** BigInt(divisorScale - commonScale)) === 0n;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Reports a count outside its bounds. `unit` is 'property', 'item', 'character' or 'contains'
|
|
88
|
+
* and picks the plural message valid.atLeast.<unit> / valid.atMost.<unit>; `vars` fills extra
|
|
89
|
+
* placeholders such as {expected}.
|
|
90
|
+
*/
|
|
91
|
+
export function validateRange(value, minimum, maximum, unit, add, vars = {}) {
|
|
92
|
+
if (typeof minimum === 'number' && value < minimum) add(t('valid.atLeast.' + unit, { ...vars, n: minimum }));
|
|
93
|
+
if (typeof maximum === 'number' && value > maximum) add(t('valid.atMost.' + unit, { ...vars, n: maximum }));
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Checks a number against minimum, maximum, multipleOf and the integer and float formats. */
|
|
97
|
+
export function validateNumber(schema, value, add) {
|
|
98
|
+
const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf } = schema;
|
|
99
|
+
// Bounds come from the spec and are shown as written, so the user can type exactly that.
|
|
100
|
+
if (typeof minimum === 'number' && (value < minimum || (exclusiveMinimum === true && value === minimum))) {
|
|
101
|
+
add(t(exclusiveMinimum === true ? 'valid.number.greaterThan' : 'valid.number.atLeast', { n: minimum }));
|
|
102
|
+
}
|
|
103
|
+
if (typeof maximum === 'number' && (value > maximum || (exclusiveMaximum === true && value === maximum))) {
|
|
104
|
+
add(t(exclusiveMaximum === true ? 'valid.number.lessThan' : 'valid.number.atMost', { n: maximum }));
|
|
105
|
+
}
|
|
106
|
+
if (typeof exclusiveMinimum === 'number' && value <= exclusiveMinimum) add(t('valid.number.greaterThan', { n: exclusiveMinimum }));
|
|
107
|
+
if (typeof exclusiveMaximum === 'number' && value >= exclusiveMaximum) add(t('valid.number.lessThan', { n: exclusiveMaximum }));
|
|
108
|
+
if (isNumber(multipleOf) && multipleOf > 0 && !isMultipleOf(value, multipleOf)) {
|
|
109
|
+
add(t('valid.number.multipleOf', { n: multipleOf }));
|
|
110
|
+
}
|
|
111
|
+
if (schema.format === 'int32' && (!Number.isInteger(value) || value < -2147483648 || value > 2147483647)) {
|
|
112
|
+
add(t('valid.number.int32'));
|
|
113
|
+
}
|
|
114
|
+
if (schema.format === 'int64' && (!Number.isInteger(value) || BigInt(value) < -(2n ** 63n) || BigInt(value) >= 2n ** 63n)) {
|
|
115
|
+
add(t('valid.number.int64'));
|
|
116
|
+
}
|
|
117
|
+
if (schema.format === 'float' && !Number.isFinite(Math.fround(value))) add(t('valid.number.float'));
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Checks a string's length, format and pattern. */
|
|
121
|
+
export function validateString(schema, value, add) {
|
|
122
|
+
if (schema.minLength !== undefined || schema.maxLength !== undefined) {
|
|
123
|
+
validateRange([...value].length, schema.minLength, schema.maxLength, 'character', add, { current: [...value].length });
|
|
124
|
+
}
|
|
125
|
+
const message = formatError(schema.format, value);
|
|
126
|
+
if (message) add(message);
|
|
127
|
+
const pattern = compilePattern(schema.pattern);
|
|
128
|
+
if (!message && pattern && !pattern.test(value)) {
|
|
129
|
+
const decimal = ['decimal', 'double', 'float'].includes(schema.format) ||
|
|
130
|
+
(Array.isArray(schema.type) && schema.type.includes('number')) ||
|
|
131
|
+
schema.pattern.includes('(?:0|[1-9]');
|
|
132
|
+
const example = schema.example ?? schema.examples?.[0];
|
|
133
|
+
// A spec description of the pattern is shown as written; it is the API's own wording.
|
|
134
|
+
add(decimal ? t('valid.type.number') : schema.description ||
|
|
135
|
+
(typeof example === 'string' ? t('valid.pattern.example', { example: displayValue(example) }) : t('valid.pattern.generic')));
|
|
136
|
+
}
|
|
137
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// The Generate menu opened from a field's wand (mock 31, m06): valid values within the schema's
|
|
2
|
+
// constraints, then invalid values to test the API's errors. ↑↓ pick, ↵ use, Esc closes.
|
|
3
|
+
import { esc, icon } from './components.js';
|
|
4
|
+
import { t } from './i18n.js';
|
|
5
|
+
import { generateOptions } from './generate.js';
|
|
6
|
+
import { shortcutHint } from './shortcuts.js';
|
|
7
|
+
import { closePopover, openPopoverAt } from './popover.js';
|
|
8
|
+
|
|
9
|
+
/** Opens the menu under a field's control. `apply(option)` puts the chosen value in the field. */
|
|
10
|
+
export function openGenerateMenu(button, { schema, label, current, apply }) {
|
|
11
|
+
const { valid, invalid, rule } = generateOptions(schema, current);
|
|
12
|
+
const options = [...valid, ...invalid];
|
|
13
|
+
const row = (option, index) => `<button type="button" class="opt-row${index === 0 ? ' is-active' : ''}" role="menuitem" tabindex="-1" data-option="${index}" style="inline-size:100%;border:0;background-color:transparent;text-align:start;font:inherit">
|
|
14
|
+
<span class="stack"><span class="main num"${option.text === undefined ? ' lang="en"' : ''}>${esc(option.main)}</span>${option.sub ? `<span class="sub">${esc(option.sub)}</span>` : ''}</span>${index === 0 ? `<span class="end">${shortcutHint('generate')}</span>` : ''}</button>`;
|
|
15
|
+
const anchor = button.closest('.control') || button;
|
|
16
|
+
const pop = openPopoverAt(anchor, `<div class="pop gen-menu" id="gen-menu" role="menu" aria-label="${esc(t('gen.menuLabel', { name: label }))}">
|
|
17
|
+
<div class="pop-group"><div class="pop-label">${esc(rule ? t('gen.validRule', { rule }) : t('gen.valid'))}</div>${valid.map((option, index) => row(option, index)).join('')}</div>
|
|
18
|
+
${invalid.length ? `<div class="pop-group"><div class="pop-label">${icon('alert', true)}${esc(t('gen.invalid'))}</div>${invalid.map((option, index) => row(option, valid.length + index)).join('')}</div>` : ''}
|
|
19
|
+
<div class="pop-foot"><span>${shortcutHint('updown')} ${esc(t('gen.pick'))}</span><span>${shortcutHint('enter')} ${esc(t('gen.use'))}</span><span class="spacer"></span><span>${shortcutHint('escape')}</span></div>
|
|
20
|
+
</div>`, { align: 'start', focus: false, kind: 'generate', onClose: () => button.classList.remove('is-active') });
|
|
21
|
+
button.classList.add('is-active');
|
|
22
|
+
button.setAttribute('aria-expanded', 'true');
|
|
23
|
+
const items = [...pop.querySelectorAll('[role="menuitem"]')];
|
|
24
|
+
const focus = index => {
|
|
25
|
+
items.forEach((item, i) => item.classList.toggle('is-active', i === index));
|
|
26
|
+
items[index]?.focus();
|
|
27
|
+
};
|
|
28
|
+
focus(0);
|
|
29
|
+
pop.addEventListener('keydown', event => {
|
|
30
|
+
const index = items.indexOf(document.activeElement);
|
|
31
|
+
const keys = { ArrowDown: index + 1, ArrowUp: index - 1, Home: 0, End: items.length - 1 };
|
|
32
|
+
if (event.key in keys) {
|
|
33
|
+
event.preventDefault();
|
|
34
|
+
focus((keys[event.key] + items.length) % items.length);
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
pop.addEventListener('click', event => {
|
|
38
|
+
const item = event.target.closest('[data-option]');
|
|
39
|
+
if (!item) return;
|
|
40
|
+
closePopover();
|
|
41
|
+
apply(options[Number(item.dataset.option)]);
|
|
42
|
+
button.focus();
|
|
43
|
+
});
|
|
44
|
+
}
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
// Values for the per-field Generate button (mocks 31, 32, m06). Valid values are random within
|
|
2
|
+
// the schema's constraints; invalid ones deliberately break one rule so the API's errors can be
|
|
3
|
+
// tested. Every option says what it is, so a generated value is never mistaken for real data.
|
|
4
|
+
import { newUuid } from './uuid.js';
|
|
5
|
+
import { formatDecimal, t } from './i18n.js';
|
|
6
|
+
|
|
7
|
+
const pick = list => list[Math.floor(random() * list.length)];
|
|
8
|
+
/** A uniformly random number in [0, 1) from the platform's secure generator when available. */
|
|
9
|
+
function random() {
|
|
10
|
+
const array = new Uint32Array(1);
|
|
11
|
+
globalThis.crypto?.getRandomValues?.(array);
|
|
12
|
+
return array[0] ? array[0] / 2 ** 32 : Math.random();
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const FIRST = ['ada', 'ben', 'cara', 'dev', 'elif', 'farah', 'goran', 'hana', 'ivan', 'jun', 'kemi', 'lior', 'maya', 'noor', 'oscar'];
|
|
16
|
+
const LAST = ['lovelace', 'okafor', 'novak', 'silva', 'tanaka', 'haddad', 'kowalski', 'moreau', 'ivanova', 'osei', 'park', 'reyes'];
|
|
17
|
+
const WORDS = ['freight', 'invoice', 'quarterly', 'supplier', 'payroll', 'refund', 'licence', 'deposit', 'retainer', 'shipment', 'services', 'rental', 'consulting', 'materials'];
|
|
18
|
+
|
|
19
|
+
const typeOf = schema => (Array.isArray(schema.type) ? schema.type.find(item => item !== 'null') : schema.type) || (schema.properties ? 'object' : schema.items ? 'array' : 'string');
|
|
20
|
+
|
|
21
|
+
/** Decimal places implied by multipleOf or a decimal format. */
|
|
22
|
+
function decimalsOf(schema, integer) {
|
|
23
|
+
if (integer) return 0;
|
|
24
|
+
if (typeof schema.multipleOf === 'number') return Math.max(0, (String(schema.multipleOf).split('.')[1] || '').length);
|
|
25
|
+
return 2;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function numberRange(schema, integer) {
|
|
29
|
+
const step = integer ? 1 : 10 ** -decimalsOf(schema, integer);
|
|
30
|
+
const low = typeof schema.exclusiveMinimum === 'number' ? schema.exclusiveMinimum + step
|
|
31
|
+
: schema.minimum !== undefined ? schema.minimum + (schema.exclusiveMinimum === true ? step : 0) : integer ? 1 : 1;
|
|
32
|
+
const high = typeof schema.exclusiveMaximum === 'number' ? schema.exclusiveMaximum - step
|
|
33
|
+
: schema.maximum !== undefined ? schema.maximum - (schema.exclusiveMaximum === true ? step : 0) : Infinity;
|
|
34
|
+
// Huge documented maximums (such as .NET's decimal range) still give everyday values.
|
|
35
|
+
const everyday = Math.max(low * 100, low + (integer ? 100 : 10000));
|
|
36
|
+
return { low, high: Math.min(high, everyday), max: high, step };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const round = (value, decimals) => Number(value.toFixed(decimals));
|
|
40
|
+
|
|
41
|
+
function randomNumber(schema, integer) {
|
|
42
|
+
const { low, high, step } = numberRange(schema, integer);
|
|
43
|
+
const decimals = decimalsOf(schema, integer);
|
|
44
|
+
const steps = Math.max(0, Math.floor((high - low) / step));
|
|
45
|
+
return round(low + Math.floor(random() * (steps + 1)) * step, decimals);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The next weekday at least `from` days ahead, as ISO yyyy-mm-dd. */
|
|
49
|
+
export function businessDay(from = 1 + Math.floor(random() * 21)) {
|
|
50
|
+
const date = new Date();
|
|
51
|
+
date.setUTCHours(0, 0, 0, 0);
|
|
52
|
+
date.setUTCDate(date.getUTCDate() + from);
|
|
53
|
+
while ([0, 6].includes(date.getUTCDay())) date.setUTCDate(date.getUTCDate() + 1);
|
|
54
|
+
return date.toISOString().slice(0, 10);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function words(min = 0, max = 40) {
|
|
58
|
+
const target = Math.min(max, Math.max(min, Math.min(24, max)));
|
|
59
|
+
let text = '';
|
|
60
|
+
while (text.length < Math.max(min, Math.min(target, 12))) text = (text ? text + ' ' : '') + pick(WORDS);
|
|
61
|
+
text = text.charAt(0).toUpperCase() + text.slice(1);
|
|
62
|
+
return text.length > max ? text.slice(0, max).trimEnd() : text.padEnd(min, 'x');
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** A string matching simple patterns made of character classes, quantifiers and literals. */
|
|
66
|
+
function fromPattern(pattern) {
|
|
67
|
+
const source = String(pattern).replace(/^\^|\$$/g, '');
|
|
68
|
+
const classes = { '\\d': '0123456789', '[A-Z]': 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', '[a-z]': 'abcdefghijklmnopqrstuvwxyz', '[0-9]': '0123456789', '[A-Z0-9]': 'ABCDEFGHJKLMNPQRSTUVWXYZ0123456789', '[a-zA-Z]': 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' };
|
|
69
|
+
const token = /(\\d|\[[^\]]+\]|\\.|[^\\[{])(\{(\d+)(?:,(\d*))?\}|[+*?])?/g;
|
|
70
|
+
let out = '';
|
|
71
|
+
for (const match of source.matchAll(token)) {
|
|
72
|
+
const [, atom, quantifier, min, max] = match;
|
|
73
|
+
const set = classes[atom] ?? (atom.startsWith('\\') ? atom.slice(1) : atom.startsWith('[') ? null : atom);
|
|
74
|
+
if (set === null || /[()|]/.test(atom)) return null;
|
|
75
|
+
const count = quantifier === '?' ? 0 : quantifier === '*' ? 1 : quantifier === '+' ? 2 : min ? Number(min) + (max ? Math.floor(random() * (Number(max || min) - Number(min) + 1)) : 0) : 1;
|
|
76
|
+
for (let i = 0; i < count; i++) out += set.length > 1 ? pick([...set]) : set;
|
|
77
|
+
}
|
|
78
|
+
try { return new RegExp(pattern).test(out) ? out : null; } catch { return null; }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** One random valid value and its short description, or undefined when nothing fits. */
|
|
82
|
+
export function randomValid(schema, current) {
|
|
83
|
+
const type = typeOf(schema);
|
|
84
|
+
if (schema.const !== undefined) return { value: schema.const, source: t('gen.const') };
|
|
85
|
+
if (schema.enum?.length) {
|
|
86
|
+
const others = schema.enum.filter(value => !Object.is(value, current));
|
|
87
|
+
return { value: pick(others.length ? others : schema.enum), source: t('gen.enumPick') };
|
|
88
|
+
}
|
|
89
|
+
if (type === 'integer' || type === 'number') return { value: randomNumber(schema, type === 'integer'), source: t('gen.inRange') };
|
|
90
|
+
if (type === 'boolean') return { value: current === undefined ? true : !current, source: t('gen.toggled') };
|
|
91
|
+
if (type !== 'string') return undefined;
|
|
92
|
+
switch (schema.format) {
|
|
93
|
+
case 'uuid': return { value: newUuid(), source: t('gen.uuid') };
|
|
94
|
+
case 'date': return { value: businessDay(), source: t('gen.businessDay') };
|
|
95
|
+
case 'date-time': return { value: new Date(Date.now() + Math.round((random() - 0.5) * 14 * 864e5)).toISOString().replace(/\.\d+Z$/, 'Z'), source: t('gen.nearNow') };
|
|
96
|
+
case 'email': return { value: `${pick(FIRST)}.${pick(LAST)}@example.test`, source: t('gen.email') };
|
|
97
|
+
case 'uri': case 'url': return { value: `https://example.test/${pick(WORDS)}/${Math.floor(random() * 1000)}`, source: t('gen.url') };
|
|
98
|
+
case 'password': return { value: `${pick(WORDS)}-${Math.floor(random() * 9000 + 1000)}-${pick(WORDS).toUpperCase()}!`, source: t('gen.password') };
|
|
99
|
+
default: break;
|
|
100
|
+
}
|
|
101
|
+
if (schema.pattern) {
|
|
102
|
+
const value = fromPattern(schema.pattern);
|
|
103
|
+
if (value) return { value, source: t('gen.pattern') };
|
|
104
|
+
}
|
|
105
|
+
return { value: words(schema.minLength ?? 0, schema.maxLength ?? 40), source: t('gen.words') };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* The Generate menu for a field: valid options first, then deliberately invalid ones.
|
|
110
|
+
* Each option is { value, main, sub }. `text` is what goes into the input when the value is
|
|
111
|
+
* not a plain JSON value (such as "abc" in a number field).
|
|
112
|
+
*/
|
|
113
|
+
export function generateOptions(schema, current) {
|
|
114
|
+
const type = typeOf(schema);
|
|
115
|
+
const valid = [];
|
|
116
|
+
const invalid = [];
|
|
117
|
+
const integer = type === 'integer';
|
|
118
|
+
if (type === 'integer' || type === 'number') {
|
|
119
|
+
const { low, high } = numberRange(schema, integer);
|
|
120
|
+
const decimals = decimalsOf(schema, integer);
|
|
121
|
+
const show = value => integer ? String(value) : formatDecimal(value, decimals);
|
|
122
|
+
const randomValue = randomNumber(schema, integer);
|
|
123
|
+
valid.push({ value: randomValue, main: show(randomValue), sub: t('gen.random') });
|
|
124
|
+
valid.push({ value: round(low, decimals), main: show(low), sub: t('gen.minimum') });
|
|
125
|
+
const roundNumber = Math.min(high, Math.max(low, 1000));
|
|
126
|
+
if (roundNumber !== low) valid.push({ value: roundNumber, main: show(roundNumber), sub: t('gen.round') });
|
|
127
|
+
if (schema.minimum !== undefined || schema.exclusiveMinimum !== undefined) {
|
|
128
|
+
const below = round(low > 0 ? 0 : low - 1, decimals);
|
|
129
|
+
invalid.push({ value: below, main: show(below), sub: t('gen.belowMinimum') });
|
|
130
|
+
}
|
|
131
|
+
if ((schema.maximum !== undefined || schema.exclusiveMaximum !== undefined) && numberRange(schema, integer).max < 1e15) {
|
|
132
|
+
const above = round(numberRange(schema, integer).max + 1, decimals);
|
|
133
|
+
invalid.push({ value: above, main: show(above), sub: t('gen.aboveMaximum') });
|
|
134
|
+
}
|
|
135
|
+
if (!integer && decimals < 6) invalid.push({ text: `10.${'0'.repeat(decimals)}5`, main: `10.${'0'.repeat(decimals)}5`, sub: t('gen.tooManyDecimals') });
|
|
136
|
+
if (integer) invalid.push({ text: '1.5', main: '1.5', sub: t('gen.notWhole') });
|
|
137
|
+
invalid.push({ text: 'abc', main: 'abc', sub: t('gen.notNumber') });
|
|
138
|
+
} else if (schema.enum?.length) {
|
|
139
|
+
for (const value of schema.enum.filter(item => !Object.is(item, current)).slice(0, 4)) valid.push({ value, main: String(value), sub: t('gen.member') });
|
|
140
|
+
invalid.push({ value: 'NotAValue', main: 'NotAValue', sub: t('gen.outsideEnum') });
|
|
141
|
+
} else if (type === 'boolean') {
|
|
142
|
+
valid.push({ value: true, main: 'true', sub: '' }, { value: false, main: 'false', sub: '' });
|
|
143
|
+
} else if (type === 'string') {
|
|
144
|
+
const first = randomValid(schema, current);
|
|
145
|
+
valid.push({ value: first.value, main: String(first.value), sub: first.source });
|
|
146
|
+
if (schema.format === 'uuid') {
|
|
147
|
+
invalid.push({ value: newUuid(), main: t('gen.unknownId'), sub: t('gen.unknownIdBody') });
|
|
148
|
+
invalid.push({ value: 'not-a-uuid', main: 'not-a-uuid', sub: t('gen.badFormat') });
|
|
149
|
+
} else if (schema.format === 'date') {
|
|
150
|
+
valid.push({ value: businessDay(1), main: businessDay(1), sub: t('gen.nextBusinessDay') });
|
|
151
|
+
invalid.push({ value: `${new Date().getUTCFullYear()}-02-31`, main: `${new Date().getUTCFullYear()}-02-31`, sub: t('gen.noSuchDay') });
|
|
152
|
+
const past = new Date(Date.now() - 864e5 * 7).toISOString().slice(0, 10);
|
|
153
|
+
invalid.push({ value: past, main: past, sub: t('gen.past') });
|
|
154
|
+
} else if (schema.format === 'email') {
|
|
155
|
+
valid.push({ value: `${pick(FIRST)}.${pick(LAST)}@example.test`, main: `${pick(FIRST)}.${pick(LAST)}@example.test`, sub: t('gen.email') });
|
|
156
|
+
invalid.push({ value: 'not-an-email', main: 'not-an-email', sub: t('gen.badFormat') });
|
|
157
|
+
} else if (schema.format === 'date-time') {
|
|
158
|
+
invalid.push({ value: 'tomorrow', main: 'tomorrow', sub: t('gen.badFormat') });
|
|
159
|
+
} else {
|
|
160
|
+
if (schema.maxLength !== undefined) {
|
|
161
|
+
const longest = words(schema.maxLength, schema.maxLength);
|
|
162
|
+
valid.push({ value: longest, main: longest, sub: t('gen.longest', { n: schema.maxLength }) });
|
|
163
|
+
invalid.push({ value: longest + 'x', main: t('gen.oneOver', { n: schema.maxLength + 1 }), sub: t('gen.tooLong') });
|
|
164
|
+
}
|
|
165
|
+
if (schema.pattern) invalid.push({ value: '!' + first.value, main: '!' + first.value, sub: t('gen.breaksPattern') });
|
|
166
|
+
if (schema.minLength) invalid.push({ value: 'x'.repeat(schema.minLength - 1), main: t('gen.oneUnder', { n: schema.minLength - 1 }), sub: t('gen.tooShort') });
|
|
167
|
+
}
|
|
168
|
+
if (!schema.minLength || schema.minLength > 0) invalid.push({ value: '', main: t('gen.empty'), sub: t('gen.emptyBody') });
|
|
169
|
+
}
|
|
170
|
+
return { valid, invalid, rule: ruleSummary(schema, type) };
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** "within 0.01 and up to 2 decimals": the constraints the valid group respects. */
|
|
174
|
+
function ruleSummary(schema, type) {
|
|
175
|
+
const parts = [];
|
|
176
|
+
if (type === 'number' || type === 'integer') {
|
|
177
|
+
if (schema.minimum !== undefined && schema.maximum !== undefined && schema.maximum < 1e15) parts.push(t('gen.between', { min: schema.minimum, max: schema.maximum }));
|
|
178
|
+
else if (schema.minimum !== undefined) parts.push(t('gen.atLeast', { min: schema.minimum }));
|
|
179
|
+
else if (schema.maximum !== undefined) parts.push(t('gen.atMost', { max: schema.maximum }));
|
|
180
|
+
if (type === 'number') parts.push(t('gen.decimals', { n: decimalsOf(schema, false) }));
|
|
181
|
+
} else if (schema.maxLength !== undefined) parts.push(t('gen.maxChars', { n: schema.maxLength }));
|
|
182
|
+
else if (schema.format) parts.push(schema.format);
|
|
183
|
+
return parts.join(' · ');
|
|
184
|
+
}
|