sendproof-core 0.1.0.alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (229) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE +21 -0
  3. data/README.md +55 -0
  4. data/lib/sendproof/assets.rb +70 -0
  5. data/lib/sendproof/attribution.rb +98 -0
  6. data/lib/sendproof/capture.rb +66 -0
  7. data/lib/sendproof/clock.rb +54 -0
  8. data/lib/sendproof/configuration.rb +241 -0
  9. data/lib/sendproof/data_store.rb +34 -0
  10. data/lib/sendproof/dynamodb/store.rb +183 -0
  11. data/lib/sendproof/dynamodb.rb +17 -0
  12. data/lib/sendproof/elasticsearch/store.rb +24 -0
  13. data/lib/sendproof/elasticsearch.rb +17 -0
  14. data/lib/sendproof/firestore/interceptor.rb +38 -0
  15. data/lib/sendproof/firestore/store.rb +150 -0
  16. data/lib/sendproof/firestore.rb +99 -0
  17. data/lib/sendproof/handler.rb +23 -0
  18. data/lib/sendproof/identity.rb +37 -0
  19. data/lib/sendproof/limits.rb +113 -0
  20. data/lib/sendproof/middleware.rb +68 -0
  21. data/lib/sendproof/mongo/engine.rb +692 -0
  22. data/lib/sendproof/mongo/guarded.rb +100 -0
  23. data/lib/sendproof/mongo/plain.rb +45 -0
  24. data/lib/sendproof/mongo/store.rb +54 -0
  25. data/lib/sendproof/mongo/subscriber.rb +21 -0
  26. data/lib/sendproof/mongo.rb +41 -0
  27. data/lib/sendproof/mongoid/store.rb +58 -0
  28. data/lib/sendproof/mongoid.rb +65 -0
  29. data/lib/sendproof/observed_request.rb +108 -0
  30. data/lib/sendproof/opensearch/store.rb +21 -0
  31. data/lib/sendproof/opensearch.rb +17 -0
  32. data/lib/sendproof/operation_matcher.rb +28 -0
  33. data/lib/sendproof/pool_hooks.rb +80 -0
  34. data/lib/sendproof/preview_request.rb +44 -0
  35. data/lib/sendproof/preview_transport.rb +331 -0
  36. data/lib/sendproof/protocol.rb +81 -0
  37. data/lib/sendproof/provider.rb +83 -0
  38. data/lib/sendproof/recorder.rb +298 -0
  39. data/lib/sendproof/redaction.rb +98 -0
  40. data/lib/sendproof/redis/commands.rb +76 -0
  41. data/lib/sendproof/redis/store.rb +205 -0
  42. data/lib/sendproof/redis.rb +18 -0
  43. data/lib/sendproof/search/middleware.rb +39 -0
  44. data/lib/sendproof/search/store.rb +213 -0
  45. data/lib/sendproof/search.rb +82 -0
  46. data/lib/sendproof/stores/classify.rb +346 -0
  47. data/lib/sendproof/stores/guard.rb +127 -0
  48. data/lib/sendproof/stores/tables.rb +1328 -0
  49. data/lib/sendproof/stores.rb +12 -0
  50. data/lib/sendproof/trace_store.rb +110 -0
  51. data/lib/sendproof/transaction_control.rb +187 -0
  52. data/lib/sendproof/ui/action-bar.js +91 -0
  53. data/lib/sendproof/ui/api.js +239 -0
  54. data/lib/sendproof/ui/app.css +848 -0
  55. data/lib/sendproof/ui/app.js +742 -0
  56. data/lib/sendproof/ui/autofill.js +137 -0
  57. data/lib/sendproof/ui/code-copy.js +71 -0
  58. data/lib/sendproof/ui/code-picker.js +149 -0
  59. data/lib/sendproof/ui/commands.js +197 -0
  60. data/lib/sendproof/ui/components.js +77 -0
  61. data/lib/sendproof/ui/context-bar.js +82 -0
  62. data/lib/sendproof/ui/copy.js +92 -0
  63. data/lib/sendproof/ui/coverage-popover.js +35 -0
  64. data/lib/sendproof/ui/crumb-fit.js +80 -0
  65. data/lib/sendproof/ui/deprecation.js +164 -0
  66. data/lib/sendproof/ui/display-settings.js +175 -0
  67. data/lib/sendproof/ui/doc-diff.js +209 -0
  68. data/lib/sendproof/ui/docs-view.js +347 -0
  69. data/lib/sendproof/ui/favicon.png +0 -0
  70. data/lib/sendproof/ui/favicon.svg +1 -0
  71. data/lib/sendproof/ui/field-help.js +52 -0
  72. data/lib/sendproof/ui/field-modules.js +23 -0
  73. data/lib/sendproof/ui/fields/controls.js +179 -0
  74. data/lib/sendproof/ui/fields/dom.js +36 -0
  75. data/lib/sendproof/ui/fields/infer.js +71 -0
  76. data/lib/sendproof/ui/fields/lookup-source.js +63 -0
  77. data/lib/sendproof/ui/fields/lookup.js +285 -0
  78. data/lib/sendproof/ui/fields/render.js +496 -0
  79. data/lib/sendproof/ui/fields/select.js +175 -0
  80. data/lib/sendproof/ui/fields/validate.js +363 -0
  81. data/lib/sendproof/ui/fields/validation-formats.js +164 -0
  82. data/lib/sendproof/ui/fields/validation-references.js +68 -0
  83. data/lib/sendproof/ui/fields/validation-values.js +137 -0
  84. data/lib/sendproof/ui/generate-menu.js +44 -0
  85. data/lib/sendproof/ui/generate.js +184 -0
  86. data/lib/sendproof/ui/header-editor.js +777 -0
  87. data/lib/sendproof/ui/headers.js +188 -0
  88. data/lib/sendproof/ui/highlight.js +257 -0
  89. data/lib/sendproof/ui/history-popover.js +24 -0
  90. data/lib/sendproof/ui/i18n.js +253 -0
  91. data/lib/sendproof/ui/icons.js +87 -0
  92. data/lib/sendproof/ui/index.html +70 -0
  93. data/lib/sendproof/ui/issues.js +187 -0
  94. data/lib/sendproof/ui/json-view.js +166 -0
  95. data/lib/sendproof/ui/lang-icons.js +62 -0
  96. data/lib/sendproof/ui/layout.js +262 -0
  97. data/lib/sendproof/ui/listbox.js +334 -0
  98. data/lib/sendproof/ui/locales/ar-capture.js +366 -0
  99. data/lib/sendproof/ui/locales/ar-stores.js +116 -0
  100. data/lib/sendproof/ui/locales/ar.js +561 -0
  101. data/lib/sendproof/ui/locales/cs-capture.js +442 -0
  102. data/lib/sendproof/ui/locales/cs-stores.js +116 -0
  103. data/lib/sendproof/ui/locales/cs.js +689 -0
  104. data/lib/sendproof/ui/locales/da-capture.js +347 -0
  105. data/lib/sendproof/ui/locales/da-stores.js +116 -0
  106. data/lib/sendproof/ui/locales/da.js +522 -0
  107. data/lib/sendproof/ui/locales/de-capture.js +347 -0
  108. data/lib/sendproof/ui/locales/de-stores.js +116 -0
  109. data/lib/sendproof/ui/locales/de.js +519 -0
  110. data/lib/sendproof/ui/locales/el-capture.js +347 -0
  111. data/lib/sendproof/ui/locales/el-stores.js +116 -0
  112. data/lib/sendproof/ui/locales/el.js +520 -0
  113. data/lib/sendproof/ui/locales/en-capture.js +349 -0
  114. data/lib/sendproof/ui/locales/en-stores.js +95 -0
  115. data/lib/sendproof/ui/locales/en.js +522 -0
  116. data/lib/sendproof/ui/locales/es-capture.js +353 -0
  117. data/lib/sendproof/ui/locales/es-stores.js +116 -0
  118. data/lib/sendproof/ui/locales/es.js +525 -0
  119. data/lib/sendproof/ui/locales/fa-capture.js +348 -0
  120. data/lib/sendproof/ui/locales/fa-stores.js +116 -0
  121. data/lib/sendproof/ui/locales/fa.js +521 -0
  122. data/lib/sendproof/ui/locales/fi-capture.js +347 -0
  123. data/lib/sendproof/ui/locales/fi-stores.js +116 -0
  124. data/lib/sendproof/ui/locales/fi.js +523 -0
  125. data/lib/sendproof/ui/locales/fr-capture.js +353 -0
  126. data/lib/sendproof/ui/locales/fr-stores.js +116 -0
  127. data/lib/sendproof/ui/locales/fr.js +525 -0
  128. data/lib/sendproof/ui/locales/he-capture.js +358 -0
  129. data/lib/sendproof/ui/locales/he-stores.js +116 -0
  130. data/lib/sendproof/ui/locales/he.js +529 -0
  131. data/lib/sendproof/ui/locales/hi-capture.js +348 -0
  132. data/lib/sendproof/ui/locales/hi-stores.js +116 -0
  133. data/lib/sendproof/ui/locales/hi.js +523 -0
  134. data/lib/sendproof/ui/locales/id-capture.js +347 -0
  135. data/lib/sendproof/ui/locales/id-stores.js +116 -0
  136. data/lib/sendproof/ui/locales/id.js +521 -0
  137. data/lib/sendproof/ui/locales/it-capture.js +361 -0
  138. data/lib/sendproof/ui/locales/it-stores.js +116 -0
  139. data/lib/sendproof/ui/locales/it.js +523 -0
  140. data/lib/sendproof/ui/locales/ja-capture.js +346 -0
  141. data/lib/sendproof/ui/locales/ja-stores.js +116 -0
  142. data/lib/sendproof/ui/locales/ja.js +521 -0
  143. data/lib/sendproof/ui/locales/ko-capture.js +346 -0
  144. data/lib/sendproof/ui/locales/ko-stores.js +116 -0
  145. data/lib/sendproof/ui/locales/ko.js +522 -0
  146. data/lib/sendproof/ui/locales/nb-capture.js +349 -0
  147. data/lib/sendproof/ui/locales/nb-stores.js +116 -0
  148. data/lib/sendproof/ui/locales/nb.js +521 -0
  149. data/lib/sendproof/ui/locales/nl-capture.js +355 -0
  150. data/lib/sendproof/ui/locales/nl-stores.js +116 -0
  151. data/lib/sendproof/ui/locales/nl.js +520 -0
  152. data/lib/sendproof/ui/locales/pl-capture.js +432 -0
  153. data/lib/sendproof/ui/locales/pl-stores.js +116 -0
  154. data/lib/sendproof/ui/locales/pl.js +528 -0
  155. data/lib/sendproof/ui/locales/pt-BR-capture.js +350 -0
  156. data/lib/sendproof/ui/locales/pt-BR-stores.js +116 -0
  157. data/lib/sendproof/ui/locales/pt-BR.js +523 -0
  158. data/lib/sendproof/ui/locales/pt-PT-capture.js +350 -0
  159. data/lib/sendproof/ui/locales/pt-PT-stores.js +116 -0
  160. data/lib/sendproof/ui/locales/pt-PT.js +523 -0
  161. data/lib/sendproof/ui/locales/ru-capture.js +437 -0
  162. data/lib/sendproof/ui/locales/ru-stores.js +116 -0
  163. data/lib/sendproof/ui/locales/ru.js +624 -0
  164. data/lib/sendproof/ui/locales/sv-capture.js +349 -0
  165. data/lib/sendproof/ui/locales/sv-stores.js +116 -0
  166. data/lib/sendproof/ui/locales/sv.js +518 -0
  167. data/lib/sendproof/ui/locales/th-capture.js +347 -0
  168. data/lib/sendproof/ui/locales/th-stores.js +116 -0
  169. data/lib/sendproof/ui/locales/th.js +521 -0
  170. data/lib/sendproof/ui/locales/tr-capture.js +348 -0
  171. data/lib/sendproof/ui/locales/tr-stores.js +116 -0
  172. data/lib/sendproof/ui/locales/tr.js +521 -0
  173. data/lib/sendproof/ui/locales/uk-capture.js +442 -0
  174. data/lib/sendproof/ui/locales/uk-stores.js +116 -0
  175. data/lib/sendproof/ui/locales/uk.js +630 -0
  176. data/lib/sendproof/ui/locales/vi-capture.js +346 -0
  177. data/lib/sendproof/ui/locales/vi-stores.js +116 -0
  178. data/lib/sendproof/ui/locales/vi.js +523 -0
  179. data/lib/sendproof/ui/locales/zh-Hans-capture.js +347 -0
  180. data/lib/sendproof/ui/locales/zh-Hans-stores.js +116 -0
  181. data/lib/sendproof/ui/locales/zh-Hans.js +523 -0
  182. data/lib/sendproof/ui/locales/zh-Hant-capture.js +346 -0
  183. data/lib/sendproof/ui/locales/zh-Hant-stores.js +116 -0
  184. data/lib/sendproof/ui/locales/zh-Hant.js +522 -0
  185. data/lib/sendproof/ui/manifest.json +866 -0
  186. data/lib/sendproof/ui/markdown.js +39 -0
  187. data/lib/sendproof/ui/model-view.js +182 -0
  188. data/lib/sendproof/ui/navigation.js +233 -0
  189. data/lib/sendproof/ui/operation-header.js +76 -0
  190. data/lib/sendproof/ui/operations.js +7 -0
  191. data/lib/sendproof/ui/overview-view.js +63 -0
  192. data/lib/sendproof/ui/personas.js +59 -0
  193. data/lib/sendproof/ui/popover.js +71 -0
  194. data/lib/sendproof/ui/preview-false.js +108 -0
  195. data/lib/sendproof/ui/request-editor.js +496 -0
  196. data/lib/sendproof/ui/response-metadata.js +354 -0
  197. data/lib/sendproof/ui/response-viewer.js +618 -0
  198. data/lib/sendproof/ui/result-blocked.js +155 -0
  199. data/lib/sendproof/ui/result-capture.js +25 -0
  200. data/lib/sendproof/ui/result-database.js +185 -0
  201. data/lib/sendproof/ui/result-effects.js +176 -0
  202. data/lib/sendproof/ui/result-headers.js +106 -0
  203. data/lib/sendproof/ui/result-logs.js +408 -0
  204. data/lib/sendproof/ui/result-states.js +213 -0
  205. data/lib/sendproof/ui/results.js +371 -0
  206. data/lib/sendproof/ui/router.js +118 -0
  207. data/lib/sendproof/ui/schema-model.js +336 -0
  208. data/lib/sendproof/ui/schema-tree.js +344 -0
  209. data/lib/sendproof/ui/schema.js +397 -0
  210. data/lib/sendproof/ui/security.js +31 -0
  211. data/lib/sendproof/ui/seeded-menu.js +69 -0
  212. data/lib/sendproof/ui/settings.js +93 -0
  213. data/lib/sendproof/ui/shortcuts-sheet.js +73 -0
  214. data/lib/sendproof/ui/shortcuts.js +190 -0
  215. data/lib/sendproof/ui/sidebar.js +289 -0
  216. data/lib/sendproof/ui/signin.js +259 -0
  217. data/lib/sendproof/ui/snippets.js +530 -0
  218. data/lib/sendproof/ui/store-marks.js +47 -0
  219. data/lib/sendproof/ui/stores.js +131 -0
  220. data/lib/sendproof/ui/styles.css +971 -0
  221. data/lib/sendproof/ui/toggletip.js +53 -0
  222. data/lib/sendproof/ui/uuid.js +10 -0
  223. data/lib/sendproof/ui/view.js +122 -0
  224. data/lib/sendproof/ui/views.css +653 -0
  225. data/lib/sendproof/version.rb +9 -0
  226. data/lib/sendproof/workbench.rb +102 -0
  227. data/lib/sendproof-core.rb +3 -0
  228. data/lib/sendproof.rb +121 -0
  229. metadata +292 -0
@@ -0,0 +1,23 @@
1
+ import { registerFieldRenderer } from './schema.js';
2
+
3
+ const installed = new Set();
4
+
5
+ /** The host configures executable modules. Schema documents only describe data. */
6
+ export async function loadFieldModules(paths = [], load = url => import(url)) {
7
+ for (const path of paths) {
8
+ const url = new URL(path, location.origin);
9
+ if (url.origin !== location.origin || !['http:', 'https:'].includes(url.protocol)) {
10
+ throw new Error('Field modules must be served by the API host.');
11
+ }
12
+ if (installed.has(url.href)) continue;
13
+ const { fieldRenderers } = await load(url.href);
14
+ if (!Array.isArray(fieldRenderers) || fieldRenderers.some(entry =>
15
+ typeof entry?.predicate !== 'function' || typeof entry?.render !== 'function')) {
16
+ throw new Error('Invalid fieldRenderers export in ' + url.pathname);
17
+ }
18
+ if (!installed.has(url.href)) {
19
+ for (const { predicate, render } of fieldRenderers) registerFieldRenderer(predicate, render);
20
+ installed.add(url.href);
21
+ }
22
+ }
23
+ }
@@ -0,0 +1,179 @@
1
+ import { element, svg } from './dom.js';
2
+ import { newUuid } from '../uuid.js';
3
+ import { lookupControl } from './lookup.js';
4
+ import { enumDescriptions, radioGroup, selectControl, useRadio } from './select.js';
5
+ import { matchesShortcut, shortcutAria } from '../shortcuts.js';
6
+ import { current, datePattern, nativeDigits, formatDate, formatDayMonthYear, formatNumber, formatWeekday, parseLocalDate, t } from '../i18n.js';
7
+
8
+ /** Decimals shown for a number field: from multipleOf, two for decimal formats, else as typed. */
9
+ export function shownDecimals(schema) {
10
+ if (typeof schema.multipleOf === 'number' && schema.multipleOf < 1) return (String(schema.multipleOf).split('.')[1] || '').length;
11
+ return schema.format === 'decimal' || /decimal/.test(schema['x-sendproof-type-label'] || '') ? 2 : undefined;
12
+ }
13
+
14
+ /** A number as this locale writes it in an input: 50,000.00 or 50.000,00. */
15
+ export function displayNumber(value, schema) {
16
+ if (typeof value !== 'number') return value ?? '';
17
+ const digits = shownDecimals(schema);
18
+ return formatNumber(value, digits === undefined ? { maximumFractionDigits: 20 } : { minimumFractionDigits: digits, maximumFractionDigits: digits });
19
+ }
20
+
21
+ /** Reads a number typed in this locale or in plain JSON form. Returns NaN when it isn't one. */
22
+ export function parseLocalNumber(text) {
23
+ const parts = new Intl.NumberFormat(current().locale).formatToParts(12345.6);
24
+ const group = parts.find(part => part.type === 'group')?.value ?? ',';
25
+ const decimal = parts.find(part => part.type === 'decimal')?.value ?? '.';
26
+ let value = nativeDigits(String(text).trim()).replace(/[\u00a0\u202f\s]/g, '');
27
+ if (!value) return NaN;
28
+ // A lone '.' in a comma-decimal locale is a decimal point unless it groups thousands.
29
+ const plainDecimal = decimal !== '.' && !value.includes(decimal) && /^[+-]?\d+\.\d+$/.test(value) && !/^[+-]?\d{1,3}\.\d{3}$/.test(value);
30
+ if (!plainDecimal) value = value.split(group).join('').replace(decimal, '.');
31
+ if (!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(value)) return NaN;
32
+ return Number(value);
33
+ }
34
+
35
+ /**
36
+ * An enum: a radio group when every value is visible at a glance (useRadio), else a select.
37
+ * `field` carries the label id, the sheet title and whether the field is optional.
38
+ */
39
+ export function enumControl(context, schema, path, id, required, field = {}) {
40
+ const descriptions = enumDescriptions(schema, context.resolve);
41
+ const options = schema.enum.filter(value => value !== null && typeof value !== 'object')
42
+ .map(value => ({ value, label: String(value), description: descriptions[String(value)] }));
43
+ // A choice re-renders its field, so the status line ("Sends status=Open") and Clear follow it.
44
+ const set = value => { context.set(path, value); context.render(JSON.stringify(path)); };
45
+ const common = { id, options, value: context.get(path), optional: !required, onChange: set, labelledBy: field.labelledBy, required };
46
+ if (useRadio(options.map(option => option.value))) return radioGroup(common);
47
+ return selectControl({ ...common, sheet: field.sheet, unsetHint: field.unsetHint, mono: ['number', 'integer'].includes(context.kind(schema)) });
48
+ }
49
+
50
+ /** The control for a scalar: lookup, enum, boolean, file or a text input. `field` is enumControl's. */
51
+ export function scalarControl(context, schema, type, path, id, required, label, field = {}) {
52
+ if (schema['x-lookup']) return lookupControl(context, schema['x-lookup'], schema, path, id, required, schema.title || label, field);
53
+ if (schema.enum) return enumControl(context, schema, path, id, required, field);
54
+ const control = element('div', 'control');
55
+ const slot = element('span', 'slot');
56
+ slot.setAttribute('aria-hidden', 'true');
57
+ if (schema.format === 'binary') {
58
+ const input = element('input');
59
+ input.id = id;
60
+ input.type = 'file';
61
+ if (required) input.setAttribute('aria-required', 'true');
62
+ input.addEventListener('change', () => {
63
+ context.set(path, input.files?.[0]);
64
+ });
65
+ control.append(input, slot);
66
+ const value = context.get(path);
67
+ if (value && typeof value.name === 'string') control.append(element('span', 'trail', value.name));
68
+ return control;
69
+ }
70
+ // Two short values: a radio group, like any short enum.
71
+ if (type === 'boolean') return radioGroup({ id, options: [true, false].map(value => ({ value, label: String(value) })), value: context.get(path), optional: !required, onChange: value => { context.set(path, value); context.render(JSON.stringify(path)); }, labelledBy: field.labelledBy, required });
72
+ const input = element(type === 'json' ? 'textarea' : 'input');
73
+ input.id = id;
74
+ if (required) input.setAttribute('aria-required', 'true');
75
+ if (type !== 'json') {
76
+ input.type = schema.format === 'password' ? 'password' : schema.format === 'date-time' ? 'datetime-local' : 'text';
77
+ if (type === 'integer' || type === 'number') input.inputMode = type === 'integer' ? 'numeric' : 'decimal';
78
+ }
79
+ if (schema.format === 'date') { input.placeholder = datePattern(); input.inputMode = 'numeric'; input.size = Math.max(datePattern().length, 10); }
80
+ if (schema.format === 'email') { input.placeholder = 'name@example.com'; input.inputMode = 'email'; }
81
+ // The placeholder shows the value the API would use: its default, else its minimum, else 0.
82
+ if (type === 'number' || type === 'integer') { const hint = schema.default ?? schema.minimum ?? 0; input.placeholder = displayNumber(hint, schema) || String(hint); input.className = 'num'; }
83
+ if (schema.format === 'uuid' || /id$/i.test(label)) input.classList.add('mono-val');
84
+ if (type === 'number') input.step = 'any';
85
+ if (schema.format === 'date-time') input.step = 'any';
86
+ const value = context.get(path);
87
+ if (type === 'json') input.value = value === undefined ? '' : JSON.stringify(value, null, 2);
88
+ else if (schema.format === 'date-time' && value) {
89
+ const date = new Date(value);
90
+ input.value = Number.isNaN(date.valueOf()) ? '' : new Date(date.valueOf() - date.getTimezoneOffset() * 60000).toISOString().slice(0, 19);
91
+ } else input.value = schema.format === 'date' ? dateDisplay(value) : type === 'number' || type === 'integer' ? displayNumber(value, schema) : value ?? '';
92
+ if (['date', 'date-time', 'email'].includes(schema.format)) {
93
+ const lead = element('span', 'lead');
94
+ lead.append(svg(schema.format === 'email' ? 'at' : 'calendar'));
95
+ control.append(lead);
96
+ }
97
+ input.addEventListener('input', () => {
98
+ const text = input.value;
99
+ const key = JSON.stringify(path);
100
+ const setError = (message, json = false) => {
101
+ if (message) context.parseErrors.set(key, { path: path.join('.'), message, json });
102
+ else context.parseErrors.delete(key);
103
+ };
104
+ if (type === 'json') {
105
+ try {
106
+ const parsed = text.trim() ? JSON.parse(text) : undefined;
107
+ setError();
108
+ context.set(path, parsed);
109
+ } catch {
110
+ setError(t('field.fixJson'), true);
111
+ context.validate?.(path);
112
+ }
113
+ } else if (type === 'number' || type === 'integer') {
114
+ const trimmed = text.trim();
115
+ const number = parseLocalNumber(trimmed);
116
+ setError(trimmed && !Number.isFinite(number)
117
+ ? (type === 'integer' ? t('field.wholeNumber', { example: formatNumber(1250) }) : t('field.number', { example: displayNumber(1250, { format: 'decimal' }) }))
118
+ : undefined);
119
+ // Keep an invalid draft as text so a tab switch cannot turn `g` into an
120
+ // empty value or JSON null before validation gets a chance to report it.
121
+ context.set(path, trimmed === '' ? undefined : Number.isFinite(number) ? number : text);
122
+ }
123
+ else if (schema.format === 'date') {
124
+ const parsed = parseLocalDate(text);
125
+ setError(parsed.invalid === 'day' ? t('field.noSuchDate', { date: formatDayMonthYear(parsed.year, parsed.month, parsed.day) })
126
+ : parsed.invalid ? t('field.dateFormat', { pattern: datePattern() }) : undefined);
127
+ context.set(path, parsed.iso ?? (text || undefined));
128
+ updateWeekday();
129
+ }
130
+ else if (schema.format === 'date-time') {
131
+ const date = new Date(text);
132
+ context.set(path, text ? (Number.isFinite(date.valueOf()) ? date.toISOString() : text) : undefined);
133
+ }
134
+ else context.set(path, text === '' && !required ? undefined : text);
135
+ });
136
+ // A date shows its weekday at the end, so weekends are easy to spot.
137
+ const weekday = schema.format === 'date' ? element('span', 'trail') : null;
138
+ function updateWeekday() {
139
+ if (!weekday) return;
140
+ const iso = context.get(path);
141
+ weekday.textContent = typeof iso === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(iso) ? formatWeekday(iso) : '';
142
+ }
143
+ if (schema.format === 'date') {
144
+ input.addEventListener('blur', () => { if (/^\d{4}-\d{2}-\d{2}$/.test(context.get(path) || '')) input.value = dateDisplay(context.get(path)); });
145
+ const shortcuts = ['date-today', 'date-tomorrow', 'date-yesterday'];
146
+ input.setAttribute('aria-keyshortcuts', shortcutAria(...shortcuts));
147
+ input.dataset.shortcut = shortcuts.join(' ');
148
+ input.addEventListener('keydown', event => {
149
+ const key = shortcuts.find(id => matchesShortcut(id, event));
150
+ if (!key) return;
151
+ event.preventDefault();
152
+ const current = context.get(path);
153
+ let date = key === 'date-today' || !current ? new Date() : new Date(current + 'T00:00:00');
154
+ if (!Number.isFinite(+date)) date = new Date();
155
+ date.setDate(date.getDate() + (key === 'date-tomorrow' ? 1 : key === 'date-yesterday' ? -1 : 0));
156
+ input.value = dateDisplay(`${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`);
157
+ input.dispatchEvent(new Event('input', { bubbles: true }));
158
+ });
159
+ }
160
+ control.append(input);
161
+ if (weekday) { updateWeekday(); control.append(weekday); }
162
+ control.append(slot);
163
+ if (/^idempotency[-_ ]?key$/i.test(label)) {
164
+ input.className = 'mono';
165
+ const regenerate = element('button', 'btn btn-ghost', t('field.regenerate'));
166
+ regenerate.type = 'button';
167
+ regenerate.addEventListener('click', () => {
168
+ const uuid = newUuid();
169
+ if (uuid) { input.value = uuid; context.set(path, uuid); }
170
+ });
171
+ control.append(regenerate);
172
+ }
173
+ return control;
174
+ }
175
+
176
+ /** An ISO date as this locale writes it in an input (23/11/2026, 23.11.2026); other text as is. */
177
+ function dateDisplay(value) {
178
+ return typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value) ? formatDate(value) : value ?? '';
179
+ }
@@ -0,0 +1,36 @@
1
+ /** DOM helpers shared by the schema field renderers. */
2
+ export function element(tag, className, text) {
3
+ const node = document.createElement(tag);
4
+ if (className) node.className = className;
5
+ if (text !== undefined) node.textContent = text;
6
+ return node;
7
+ }
8
+
9
+ export function title(name) {
10
+ return String(name).replace(/([a-z0-9])([A-Z])/g, '$1 $2')
11
+ .replace(/[_-]/g, ' ').replace(/^./, character => character.toUpperCase());
12
+ }
13
+
14
+ export function svg(icon) {
15
+ const graphic = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
16
+ graphic.setAttribute('class', 'i i-sm');
17
+ graphic.setAttribute('aria-hidden', 'true');
18
+ const use = document.createElementNS('http://www.w3.org/2000/svg', 'use');
19
+ use.setAttribute('href', `#i-${icon}`);
20
+ graphic.append(use);
21
+ return graphic;
22
+ }
23
+
24
+ export function typeDescription(schema, type) {
25
+ if (typeof schema['x-sendproof-type-label'] === 'string') return schema['x-sendproof-type-label'];
26
+ const parts = [type === 'array' && schema.items?.type ? schema.items.type + '[]' : schema.format || (schema.enum ? 'enum' : type)];
27
+ if (schema.minimum != null) parts.push(`${schema.exclusiveMinimum === true ? '>' : '≥'} ${schema.minimum}`);
28
+ if (schema.maximum != null && Math.abs(schema.maximum) < 1e15) parts.push(`${schema.exclusiveMaximum === true ? '<' : '≤'} ${schema.maximum}`);
29
+ if (typeof schema.exclusiveMinimum === 'number') parts.push(`> ${schema.exclusiveMinimum}`);
30
+ if (typeof schema.exclusiveMaximum === 'number') parts.push(`< ${schema.exclusiveMaximum}`);
31
+ if (schema.minLength != null) parts.push(`min ${schema.minLength}`);
32
+ if (schema.maxLength != null) parts.push(`max ${schema.maxLength}`);
33
+ if (schema.minItems != null) parts.push(`min ${schema.minItems}`);
34
+ if (schema.maxItems != null) parts.push(`max ${schema.maxItems}`);
35
+ return parts.join(' · ');
36
+ }
@@ -0,0 +1,71 @@
1
+ /** Conservative defaults derived only from the supplied OpenAPI document. */
2
+ function singular(segment) {
3
+ const word = segment.toLowerCase();
4
+ if (word.endsWith('ies') && word.length > 3) return `${word.slice(0, -3)}y`;
5
+ if (word.endsWith('s') && !word.endsWith('ss') && word.length > 1) return word.slice(0, -1);
6
+ return null;
7
+ }
8
+
9
+ function matchesProperty(name, collection) {
10
+ const stem = name.replace(/(?:_id|Id|ID)$/, '');
11
+ if (stem === name) return false;
12
+ const match = stem.slice(-collection.length);
13
+ const boundary = stem.length === collection.length || /[_-]/.test(stem.at(-collection.length - 1)) || /^[A-Z]/.test(match);
14
+ return boundary && match.toLowerCase() === collection;
15
+ }
16
+
17
+ /** Infer a lookup only when exactly one documented collection fits the field. */
18
+ export function inferLookup(context, schema, name) {
19
+ if (Object.hasOwn(schema, 'x-lookup') || schema.enum) return schema['x-lookup'];
20
+ const fieldType = context.kind(schema);
21
+ if (!['string', 'integer'].includes(fieldType)) return undefined;
22
+ const candidates = [];
23
+ const directCollection = context.operationPath?.endsWith('/{' + name + '}') ?
24
+ context.operationPath.slice(0, -name.length - 3) : undefined;
25
+ for (const [path, rawPath] of Object.entries(context.document.paths || {})) {
26
+ if (!path.startsWith('/') || /[{}?#]/.test(path)) continue;
27
+ const collection = singular(path.split('/').filter(Boolean).at(-1) || '');
28
+ if (path !== directCollection && (!collection || !matchesProperty(name, collection))) continue;
29
+ const pathItem = context.resolve(rawPath);
30
+ const operation = pathItem.get;
31
+ if (!operation) continue;
32
+ const parameters = [...(pathItem.parameters || []), ...(operation.parameters || [])]
33
+ .map(parameter => context.resolve(parameter));
34
+ if (parameters.some(parameter => parameter.required || parameter.in === 'path')) continue;
35
+ const search = parameters.find(parameter => parameter.in === 'query' && /^(search|q|query)$/i.test(parameter.name));
36
+ const options = [];
37
+ for (const [status, rawResponse] of Object.entries(operation.responses || {})) {
38
+ if (!/^2\d\d$/.test(status)) continue;
39
+ const response = context.resolve(rawResponse);
40
+ for (const [mediaType, media] of Object.entries(response.content || {})) {
41
+ if (!/^application\/(?:[^;]+\+)?json(?:;|$)/i.test(mediaType)) continue;
42
+ const array = context.resolve(media.schema);
43
+ if (context.kind(array) !== 'array') continue;
44
+ const item = context.resolve(array.items);
45
+ const properties = item.properties || {};
46
+ const idNames = Object.keys(properties).filter(key => key.toLowerCase() === 'id');
47
+ const labelNames = Object.keys(properties).filter(key => ['name', 'label'].includes(key.toLowerCase()));
48
+ if (idNames.length !== 1 || (labelNames.length !== 1 && path !== directCollection)) continue;
49
+ const valueField = idNames[0];
50
+ const labelField = labelNames[0] || (['reference', 'title', 'description'].find(key => properties[key])) || valueField;
51
+ if (context.kind(context.resolve(properties[valueField])) !== fieldType) continue;
52
+ if (labelField !== valueField && context.kind(context.resolve(properties[labelField])) !== 'string') continue;
53
+ options.push({ url: path, valueField, labelField, ...(search ? { searchParam: search.name } : {}) });
54
+ }
55
+ }
56
+ if (options.length === 1) candidates.push(options[0]);
57
+ else if (options.length > 1) return undefined;
58
+ }
59
+ return candidates.length === 1 ? candidates[0] : undefined;
60
+ }
61
+
62
+ /** Pair amount with currency only for one clearly named, type-compatible pair. */
63
+ export function inferCurrency(context, entries) {
64
+ const amounts = entries.filter(([name, schema]) => name.toLowerCase() === 'amount' && ['number', 'integer'].includes(context.kind(context.resolve(schema))));
65
+ const currencies = entries.filter(([name, schema]) => name.toLowerCase() === 'currency' && context.kind(context.resolve(schema)) === 'string');
66
+ if (amounts.length !== 1 || currencies.length !== 1) return entries;
67
+ if (entries.some(([, schema]) => Object.hasOwn(context.resolve(schema), 'x-currency-field'))) return entries;
68
+ const [amountName] = amounts[0];
69
+ const [currencyName] = currencies[0];
70
+ return entries.map(([name, schema]) => name === amountName ? [name, { ...context.resolve(schema), 'x-currency-field': currencyName }] : [name, schema]);
71
+ }
@@ -0,0 +1,63 @@
1
+ const read = (item, key) => item && Object.hasOwn(item, key) ? item[key] : undefined;
2
+
3
+ /** Resolve lookup URLs within the mounted application and use the current user's session. */
4
+ export function lookupSource(metadata, basePath) {
5
+ const base = '/' + basePath.replace(/^\/+|\/+$/g, '');
6
+ const prefix = base === '/' ? '' : base;
7
+ const origin = globalThis.location.origin;
8
+ const url = new URL(metadata.url, `${origin}${prefix}/`);
9
+ if (url.origin !== origin || !/^https?:$/.test(url.protocol)) throw new Error('Lookup URL must be same-origin.');
10
+ if (metadata.url.startsWith('/') && !metadata.url.startsWith('//') && prefix &&
11
+ url.pathname !== prefix && !url.pathname.startsWith(prefix + '/')) url.pathname = prefix + url.pathname;
12
+ return url;
13
+ }
14
+
15
+ export function lookupOption(metadata, item) {
16
+ if (item === null || typeof item !== 'object') return { value: item, label: String(item) };
17
+ const value = read(item, metadata.valueField || 'id');
18
+ if (value === undefined || value === null || typeof value === 'object') return undefined;
19
+ return {
20
+ value,
21
+ label: String(read(item, metadata.labelField || 'name') ?? value),
22
+ detail: read(item, metadata.detailField || 'detail'),
23
+ status: read(item, metadata.statusField || 'status'),
24
+ // A short code at the end of the row, such as the account's currency.
25
+ end: typeof read(item, metadata.endField || 'currency') === 'string' ? read(item, metadata.endField || 'currency') : undefined,
26
+ };
27
+ }
28
+
29
+ export async function getLookupOptions(context, metadata, query = '') {
30
+ if (Array.isArray(metadata.options)) return metadata.options.map(option => ({
31
+ value: option?.value ?? option,
32
+ label: String(option?.label ?? option?.value ?? option),
33
+ detail: option?.detail,
34
+ }));
35
+ if (!metadata.url) return [];
36
+ const url = lookupSource(metadata, context.basePath);
37
+ if (metadata.searchParam && query) url.searchParams.set(metadata.searchParam, query);
38
+ const key = url.href;
39
+ const cache = context.lookupCache;
40
+ let request = cache.get(key);
41
+ if (!request) {
42
+ request = (async () => {
43
+ const response = await fetch(key, { credentials: 'same-origin', redirect: 'error', headers: { Accept: 'application/json' } });
44
+ if (!response.ok) throw new Error(`Lookup couldn’t load (HTTP ${response.status}). Try again or paste an ID.`);
45
+ const data = await response.json();
46
+ const list = Array.isArray(data) ? data : read(data, metadata.itemsField || 'items');
47
+ if (!Array.isArray(list)) throw new Error('Lookup returned no list. Paste an ID to continue.');
48
+ return list.map(item => lookupOption(metadata, item)).filter(Boolean);
49
+ })();
50
+ cache.set(key, request);
51
+ request.catch(() => cache.delete(key));
52
+ }
53
+ return request;
54
+ }
55
+
56
+ export function fromLastResponse(last, metadata) {
57
+ if (!last || !metadata.url) return undefined;
58
+ let collection;
59
+ try { collection = new URL(metadata.url, 'https://example.invalid/').pathname; }
60
+ catch { return undefined; }
61
+ if (last.path !== collection && !last.path?.startsWith(collection.replace(/\/$/, '') + '/{')) return undefined;
62
+ return lookupOption(metadata, last.body);
63
+ }