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,496 @@
1
+ // Schema-driven fields. Every field has the same four-part anatomy (mocks 76, 84, 87):
2
+ //
3
+ // label row name, "i" toggletip, "optional" … [Clear] type
4
+ // control input, select, radio group or lookup
5
+ // description the spec's description, flush with the control (always present, maybe empty,
6
+ // so paired fields on a subgrid keep their rows aligned)
7
+ // status line one reserved line: the constraints, what will be sent, or the character
8
+ // count. An error or "Generated: … Undo" replaces it, so nothing moves.
9
+ import { element, svg, title, typeDescription } from './dom.js';
10
+ import { scalarControl } from './controls.js';
11
+ import { selectControl, useRadio } from './select.js';
12
+ import { inferCurrency, inferLookup } from './infer.js';
13
+ import { shortcutAria, shortcutHintNode } from '../shortcuts.js';
14
+ import { formatNumber, formatRelativeDays, t, th } from '../i18n.js';
15
+ import { openGenerateMenu } from '../generate-menu.js';
16
+ import { randomValid } from '../generate.js';
17
+ import { displayNumber } from './controls.js';
18
+ import { esc } from '../components.js';
19
+ import { inline } from '../markdown.js';
20
+ import { enumDescriptions } from './select.js';
21
+
22
+ function variantName(raw, resolved, index) {
23
+ return resolved.title || raw.$ref?.split('/').at(-1) || `Option ${index + 1}`;
24
+ }
25
+
26
+ function discriminatorValue(schema, raw, resolved, index) {
27
+ const property = schema.discriminator?.propertyName;
28
+ const mapped = Object.entries(schema.discriminator?.mapping || {}).find(([, ref]) => ref === raw.$ref)?.[0];
29
+ const constraint = resolved.properties?.[property];
30
+ return mapped ?? constraint?.const ?? constraint?.enum?.[0] ?? raw.$ref?.split('/').at(-1) ?? String(index);
31
+ }
32
+
33
+ /** Pick a variant without discarding fields from the supplied value. */
34
+ export function selectedVariant(context, schema, path) {
35
+ const variants = schema.oneOf || schema.anyOf;
36
+ if (!variants?.length) return null;
37
+ const options = variants.map((raw, index) => {
38
+ const resolved = context.resolve(raw);
39
+ return { raw, resolved, name: variantName(raw, resolved, index), discriminator: discriminatorValue(schema, raw, resolved, index) };
40
+ });
41
+ const key = JSON.stringify(path);
42
+ const discriminator = schema.discriminator?.propertyName;
43
+ const value = context.get(path);
44
+ let index = context.variants.get(key);
45
+ if (index === undefined && discriminator && value && typeof value === 'object') {
46
+ index = options.findIndex(option => option.discriminator === value[discriminator]);
47
+ }
48
+ if (index === undefined || index < 0 || !options[index]) {
49
+ index = options.findIndex(option => (option.resolved.required || []).some(name => value?.[name] !== undefined));
50
+ }
51
+ if (index < 0 || index === undefined) index = 0;
52
+ return { options, index, discriminator };
53
+ }
54
+
55
+ function objectFields(context, schema, path, refs, depth) {
56
+ const fields = element('div', 'fields');
57
+ const entries = inferCurrency(context, Object.entries(schema.properties || {}).filter(([, child]) => !child.readOnly));
58
+ const paired = new Set(entries.map(([, child]) => child['x-currency-field']).filter(Boolean));
59
+ const eligible = entries.filter(([name]) => !paired.has(name));
60
+ const chips = element('div', 'optional-props');
61
+ chips.setAttribute('role', 'group');
62
+ chips.setAttribute('aria-label', t('field.addOptional'));
63
+ chips.append(element('span', 'lead-label', t('field.add')));
64
+ let rowName, rowCount = 0;
65
+ for (const [name, child] of eligible) {
66
+ const resolved = context.resolve(child);
67
+ const currencyName = child['x-currency-field'];
68
+ const currency = currencyName && schema.properties[currencyName];
69
+ const needed = schema.required?.includes(name);
70
+ const pinned = needed || schema.required?.includes(currencyName) || resolved['x-sendproof-visible'] === true;
71
+ const fieldPath = [...path, name];
72
+ const key = JSON.stringify(fieldPath);
73
+ const fieldLabel = resolved.title || title(name);
74
+ const current = context.get(fieldPath);
75
+ if (!pinned && current === undefined && !context.expanded.has(key)) {
76
+ const chip = element('button', 'prop-chip');
77
+ chip.type = 'button';
78
+ chip.dataset.optionalPath = key;
79
+ const type = typeDescription(resolved, context.kind(resolved));
80
+ chip.append(svg('plus'), element('span', 'sr-only', t('field.addNamed', { name: '' })), element('span', 'ltr', name), element('span', 't', type));
81
+ chip.addEventListener('click', () => {
82
+ context.expanded.add(key);
83
+ context.render(key);
84
+ });
85
+ chips.append(chip);
86
+ continue;
87
+ }
88
+ const options = currency ? { name: currencyName, schema: currency, required: schema.required?.includes(currencyName) } : undefined;
89
+ const field = renderField(context, child, fieldPath, name, needed, refs, depth + 1, options);
90
+ const group = resolved['x-sendproof-row'];
91
+ rowCount = group && group === rowName ? rowCount + 1 : 0;
92
+ rowName = group;
93
+ if (group && eligible.some(([other, candidate]) => other !== name && context.resolve(candidate)['x-sendproof-row'] === group)) {
94
+ field.classList.add('half');
95
+ if (rowCount === 0) field.classList.add('row-start');
96
+ }
97
+ if (!pinned) {
98
+ const remove = element('button', 'btn btn-ghost btn-icon btn-xs field-remove');
99
+ remove.type = 'button';
100
+ remove.setAttribute('aria-label', t('field.remove', { name: fieldLabel }));
101
+ remove.append(svg('x'));
102
+ remove.addEventListener('click', () => {
103
+ context.expanded.delete(key);
104
+ context.set(fieldPath, undefined);
105
+ context.render(key, true);
106
+ });
107
+ // Removing an added optional field sits at the end of its label row, beside the type.
108
+ (field.querySelector(':scope > .label > .end') || field).prepend(remove);
109
+ }
110
+ fields.append(field);
111
+ }
112
+ if (chips.children.length > 1) fields.append(chips);
113
+ return fields;
114
+ }
115
+
116
+ function arrayFields(context, schema, path, refs, depth, label) {
117
+ const list = element('div', 'list-input');
118
+ list.setAttribute('role', 'group');
119
+ list.setAttribute('aria-label', title(label));
120
+ const values = Array.isArray(context.get(path)) ? context.get(path) : [];
121
+ values.forEach((_, index) => {
122
+ const row = element('div', 'li');
123
+ const number = element('span', 'idx', String(index + 1));
124
+ number.setAttribute('aria-hidden', 'true');
125
+ row.append(number);
126
+ const item = renderField(context, schema.items || {}, [...path, index], t('field.item', { n: index + 1 }), true, refs, depth + 1);
127
+ const val = element('div', 'val');
128
+ val.append(item);
129
+ row.append(val);
130
+ const remove = element('button', 'btn btn-ghost btn-icon btn-xs');
131
+ remove.type = 'button';
132
+ remove.setAttribute('aria-label', t('field.removeLine', { n: index + 1 }));
133
+ remove.append(svg('x'));
134
+ remove.addEventListener('click', () => {
135
+ const updated = [...context.get(path)];
136
+ updated.splice(index, 1);
137
+ context.set(path, updated);
138
+ for (const key of context.parseErrors.keys()) {
139
+ const segments = JSON.parse(key);
140
+ if (path.every((part, index) => segments[index] === part) && segments[path.length] >= index)
141
+ context.parseErrors.delete(key);
142
+ }
143
+ context.render(JSON.stringify(path));
144
+ });
145
+ row.append(remove);
146
+ list.append(row);
147
+ });
148
+ const add = element('button', 'add');
149
+ add.type = 'button';
150
+ add.disabled = values.length >= (schema.maxItems ?? Infinity);
151
+ add.append(svg('plus'), element('span', '', t('field.addLine')), shortcutHintNode('add-row'));
152
+ add.setAttribute('aria-keyshortcuts', shortcutAria('add-row'));
153
+ add.dataset.shortcut = 'add-row';
154
+ add.addEventListener('click', () => {
155
+ context.set(path, [...values, undefined]);
156
+ context.render(JSON.stringify([...path, values.length]));
157
+ });
158
+ list.append(add);
159
+ return list;
160
+ }
161
+
162
+ function renderVariant(context, schema, path, refs, depth, selection) {
163
+ const container = element('div', 'fields');
164
+ const selector = selectControl({
165
+ id: `variant-${context.nextId()}`, label: t('field.variant'), required: true,
166
+ options: selection.options.map(option => ({ value: option.name, label: option.name })),
167
+ value: selection.options[selection.index].name,
168
+ onChange: name => {
169
+ const index = selection.options.findIndex(option => option.name === name);
170
+ if (index < 0) return;
171
+ context.variants.set(JSON.stringify(path), index);
172
+ if (selection.discriminator) {
173
+ const current = context.get(path);
174
+ const value = current && typeof current === 'object' && !Array.isArray(current) ? { ...current } : {};
175
+ value[selection.discriminator] = selection.options[index].discriminator;
176
+ context.set(path, value);
177
+ }
178
+ context.render();
179
+ },
180
+ });
181
+ container.append(selector);
182
+ const base = { ...schema };
183
+ delete base.oneOf;
184
+ delete base.anyOf;
185
+ const combined = context.resolve({ allOf: [base, selection.options[selection.index].raw] });
186
+ if (combined.properties) container.append(objectFields(context, combined, path, refs, depth));
187
+ else container.append(renderField(context, selection.options[selection.index].raw, path, selection.options[selection.index].name, false, refs, depth + 1));
188
+ return container;
189
+ }
190
+
191
+ /** The type at the end of the label row: the enum's model name, the format, or the type. */
192
+ function typeName(raw, schema, type) {
193
+ if (typeof schema['x-sendproof-type-label'] === 'string') return schema['x-sendproof-type-label'];
194
+ const ref = raw?.$ref?.startsWith('#/components/schemas/') ? decodeURIComponent(raw.$ref.split('/').at(-1)) : '';
195
+ if (schema.enum) return ref || 'enum';
196
+ if (type === 'array') return `${schema.items?.$ref ? decodeURIComponent(schema.items.$ref.split('/').at(-1)) : schema.items?.format || schema.items?.type || 'value'}[]`;
197
+ if (ref && type === 'object') return ref;
198
+ return schema.format || type;
199
+ }
200
+
201
+ /** What kind of control a schema gets, which decides the label element and the status line. */
202
+ function controlKind(schema, type) {
203
+ if (schema['x-lookup']) return 'lookup';
204
+ if (schema.enum) return useRadio(schema.enum.filter(value => value !== null)) ? 'radio' : 'select';
205
+ if (type === 'boolean') return 'radio';
206
+ if (schema.format === 'date') return 'date';
207
+ return 'input';
208
+ }
209
+
210
+ /** Render one schema node; recursive references fall back to editable JSON. */
211
+ export function renderField(context, raw, path, label, required, refs = new Set(), depth = 0, currency) {
212
+ const repeated = raw?.$ref && refs.has(raw.$ref);
213
+ const nextRefs = raw?.$ref ? new Set([...refs, raw.$ref]) : refs;
214
+ let schema = context.resolve(raw);
215
+ const lookup = inferLookup(context, schema, label);
216
+ if (lookup && !Object.hasOwn(schema, 'x-lookup')) schema = { ...schema, 'x-lookup': lookup };
217
+ const variant = !repeated && selectedVariant(context, schema, path);
218
+ const type = repeated || depth > 12 ? 'json' : context.kind(schema);
219
+ const custom = context.customRenderer(schema, path, label);
220
+ const structuredObject = type === 'object' && schema.properties && !schema.additionalProperties;
221
+ const objectVariant = variant && variant.options.every(option => context.kind(option.resolved) === 'object');
222
+ const flattened = context.flattenRoot && path.length === 0 && !custom && (structuredObject || objectVariant);
223
+ const field = element('div', flattened ? '' : 'field');
224
+ field.dataset.schemaPath = JSON.stringify(path);
225
+ const id = `schema-field-${context.nextId()}`;
226
+ const fieldLabel = schema.title || title(label);
227
+ const kind = custom || variant || type === 'object' || type === 'array' ? 'group' : controlKind(schema, type);
228
+ if (!flattened) field.dataset.kind = kind;
229
+ const labelNode = element('div', 'label');
230
+ // A <label for> only names real inputs; comboboxes and radio groups are named by aria-labelledby.
231
+ const labelText = element(['input', 'date'].includes(kind) || custom ? 'label' : 'span', 'name', fieldLabel);
232
+ labelText.id = `${id}-label`;
233
+ if (labelText.tagName === 'LABEL') labelText.htmlFor = id;
234
+ else labelText.addEventListener('click', () => field.querySelector(`[id="${id}"]`)?.focusControl?.());
235
+ labelText.lang = 'en';
236
+ labelNode.append(labelText);
237
+ // The "i" toggletip trigger explains the field from the spec (24 px target).
238
+ const info = element('button', 'info-btn');
239
+ info.type = 'button';
240
+ info.setAttribute('aria-label', t('field.about', { name: fieldLabel }));
241
+ info.setAttribute('aria-expanded', 'false');
242
+ info.setAttribute('aria-keyshortcuts', shortcutAria('field-info'));
243
+ info.dataset.shortcut = 'field-info';
244
+ info.append(svg('info'));
245
+ info.fieldInfo = { schema, label: fieldLabel, required, path, parameter: context.parameter, example: context.exampleAt?.(path),
246
+ currency: currency && { name: currency.name, values: context.resolve(currency.schema).enum } };
247
+ labelNode.append(info);
248
+ if (!required) labelNode.append(element('span', 'opt', t('field.optional')));
249
+ // The end of the label row: Clear (an optional choice that has a value), then the type.
250
+ const end = element('span', 'end');
251
+ const value = context.get(path);
252
+ if (!required && value !== undefined && ['radio', 'select', 'lookup', 'date'].includes(kind)) {
253
+ const clear = element('button', 'field-clear', t('field.clear'));
254
+ clear.type = 'button';
255
+ clear.setAttribute('aria-label', t('field.clearName', { name: fieldLabel }));
256
+ clear.addEventListener('click', () => {
257
+ context.set(path, undefined);
258
+ context.render(JSON.stringify(path));
259
+ });
260
+ end.append(clear);
261
+ }
262
+ const typeLabel = element('span', 'type', typeName(raw, schema, type));
263
+ typeLabel.title = typeDescription(schema, type);
264
+ end.append(typeLabel);
265
+ labelNode.append(end);
266
+ // The phone sheet of a select or lookup: the field's name and description as its title.
267
+ const sheet = { title: esc(fieldLabel), sub: schema.description ? inline(String(schema.description).replace(/\s*\n\s*/g, ' ')) : '' };
268
+ const controlField = { labelledBy: `${id}-label`, sheet, unsetHint: context.parameter?.in === 'query' ? t('field.anyHintQuery') : t('field.anyHint') };
269
+ if (!flattened) field.append(labelNode);
270
+ if (custom) {
271
+ const node = custom({ schema, path, name: label, value: context.get(path), setValue: value => context.set(path, value), document: context.document, id, required });
272
+ if (node) field.append(node);
273
+ } else if (variant) field.append(renderVariant(context, schema, path, nextRefs, depth, variant));
274
+ else if (type === 'object' && schema.properties && !schema.additionalProperties) field.append(objectFields(context, schema, path, nextRefs, depth));
275
+ else if (type === 'array') field.append(arrayFields(context, schema, path, nextRefs, depth, label));
276
+ else {
277
+ const control = scalarControl(context, schema, type, path, id, required, label, controlField);
278
+ if (currency && control.classList && kind === 'input') {
279
+ control.classList.add('control-split');
280
+ const amount = element('span', 'part');
281
+ while (control.firstChild) amount.append(control.firstChild);
282
+ const currencyPath = [...path.slice(0, -1), currency.name];
283
+ const currencySchema = context.resolve(currency.schema);
284
+ const values = currencySchema.enum;
285
+ let currencyControl;
286
+ if (values) {
287
+ // The currency starts from the spec's default or example instead of "Choose a value…".
288
+ if (context.get(currencyPath) === undefined) {
289
+ const preset = currencySchema.default ?? context.exampleAt?.(currencyPath);
290
+ if (values.includes(preset)) context.setQuietly(currencyPath, preset);
291
+ }
292
+ // A joined segment of the amount: the same select and listbox as any other enum.
293
+ const descriptions = enumDescriptions(currencySchema, context.resolve);
294
+ currencyControl = selectControl({
295
+ id: `${id}-currency`, segment: true, label: title(currency.name), required: currency.required, optional: !currency.required,
296
+ options: values.map(code => ({ value: code, label: String(code), description: descriptions[code] })), value: context.get(currencyPath),
297
+ sheet: { title: esc(title(currency.name)), sub: currencySchema.description ? inline(currencySchema.description) : '' },
298
+ onChange: code => context.set(currencyPath, code),
299
+ });
300
+ } else {
301
+ currencyControl = element('span', 'part');
302
+ const input = element('input');
303
+ input.id = `${id}-currency`;
304
+ input.value = context.get(currencyPath) ?? '';
305
+ input.setAttribute('aria-label', title(currency.name));
306
+ input.addEventListener('input', () => context.set(currencyPath, input.value || undefined));
307
+ currencyControl.append(input);
308
+ }
309
+ currencyControl.dataset.schemaPath = JSON.stringify(currencyPath);
310
+ control.append(amount, currencyControl);
311
+ }
312
+ const slot = control.querySelector?.('.slot');
313
+ if (slot && generatable(schema, type)) addWand(context, control, slot, schema, path, fieldLabel);
314
+ else if (['radio', 'select', 'lookup'].includes(kind)) addChoiceGenerator(context, control, schema, path);
315
+ field.append(control);
316
+ }
317
+ if (!flattened) addAssistance(field, schema, type, id, context, path, required);
318
+ return field;
319
+ }
320
+
321
+ /**
322
+ * ⌥G on a select, radio group or lookup: a random documented value (or a real record), with the
323
+ * same "Generated: … Undo" status line as the wand. ⌥⇧G opens the list to pick one.
324
+ */
325
+ function addChoiceGenerator(context, control, schema, path) {
326
+ control.dataset.generate = '';
327
+ control.generateNow = async () => {
328
+ if (schema['x-lookup']) {
329
+ const { getLookupOptions } = await import('./lookup-source.js');
330
+ try {
331
+ const options = await getLookupOptions(context, schema['x-lookup']);
332
+ const choices = options.filter(option => !Object.is(option.value, context.get(path)));
333
+ const pick = choices[Math.floor(Math.random() * choices.length)];
334
+ if (pick) context.generate(path, pick.value, context.actor ? t('gen.realRecordAs', { name: context.actor }) : t('gen.realRecord'));
335
+ } catch { /* The lookup's own error state explains the failure when it opens. */ }
336
+ return;
337
+ }
338
+ const values = (schema.enum || [true, false]).filter(value => value !== null && !Object.is(value, context.get(path)));
339
+ if (values.length) context.generate(path, values[Math.floor(Math.random() * values.length)], t('gen.enumPick'));
340
+ };
341
+ }
342
+
343
+ const generatable = (schema, type) => !schema['x-lookup'] && !schema.enum && ['string', 'number', 'integer'].includes(type) && schema.format !== 'binary' && schema.format !== 'password';
344
+
345
+ /** The Generate button in a control's status slot (mock 31): click opens the menu, ⌥G fills. */
346
+ function addWand(context, control, slot, schema, path, label) {
347
+ const key = JSON.stringify(path);
348
+ const generated = context.autofilled.get?.(key);
349
+ const wand = element('button', `slot wand${generated ? ' gen' : ''}`);
350
+ wand.type = 'button';
351
+ wand.setAttribute('aria-label', t('field.generate', { name: label }));
352
+ wand.setAttribute('aria-haspopup', 'menu');
353
+ wand.setAttribute('aria-expanded', 'false');
354
+ wand.setAttribute('aria-keyshortcuts', shortcutAria('generate', 'generate-menu'));
355
+ wand.dataset.shortcut = 'generate generate-menu';
356
+ wand.title = t('field.generateTip');
357
+ wand.append(svg('wand'));
358
+ slot.hidden = true;
359
+ slot.after(wand);
360
+ if (generated) control.classList.add('is-generated');
361
+ const apply = (option, source) => {
362
+ if (option.text !== undefined) {
363
+ const input = control.querySelector('input');
364
+ input.value = option.text;
365
+ input.dispatchEvent(new Event('input', { bubbles: true }));
366
+ context.markGenerated(path, source);
367
+ context.render(key);
368
+ } else context.generate(path, option.value, source);
369
+ };
370
+ wand.addEventListener('click', () => openGenerateMenu(wand, {
371
+ schema, label, current: context.get(path),
372
+ apply: option => apply(option, option.sub || t('gen.chosen')),
373
+ }));
374
+ wand.generateNow = () => {
375
+ const option = randomValid(schema, context.get(path));
376
+ if (option) apply({ value: option.value }, option.source);
377
+ };
378
+ }
379
+
380
+ /** A hint for every field, so the reserved assist line is never visually empty (mock 07). */
381
+ function typeHint(schema, type) {
382
+ if (schema.format === 'date') return t('hint.date');
383
+ if (schema.format === 'date-time') return t('hint.dateTime');
384
+ if (schema.format === 'email') return t('hint.email');
385
+ if (schema.format === 'uuid') return t('hint.uuid');
386
+ if (schema.format === 'uri' || schema.format === 'url') return t('hint.url');
387
+ if (type === 'integer') return schema.minimum !== undefined ? t('hint.integerMin', { min: schema.minimum }) : t('hint.integer');
388
+ if (type === 'number') return schema.minimum !== undefined ? t('hint.numberMin', { min: displayNumber(schema.minimum, schema) }) : t('hint.number');
389
+ if (type === 'boolean') return t('hint.boolean');
390
+ if (type === 'array') return schema.maxItems !== undefined ? t('hint.arrayMax', { n: schema.maxItems }) : t('hint.array');
391
+ if (schema.enum) return t('hint.enum');
392
+ if (schema.maxLength !== undefined) return t('hint.maxLength', { n: schema.maxLength });
393
+ if (type === 'json') return t('hint.json');
394
+ return t('hint.text');
395
+ }
396
+
397
+ /** Days from today to an ISO date, for "In 3 days". */
398
+ function daysFromToday(iso) {
399
+ const today = new Date();
400
+ const start = Date.UTC(today.getFullYear(), today.getMonth(), today.getDate());
401
+ return Math.round((Date.parse(iso + 'T00:00:00Z') - start) / 864e5);
402
+ }
403
+
404
+ /** How a value is sent, for the status line: status=Open in a query, "Normal" in a JSON body. */
405
+ function sentForm(context, value) {
406
+ const parameter = context.parameter;
407
+ if (parameter?.in === 'query' || parameter?.in === 'cookie') return `${parameter.name}=${value}`;
408
+ if (parameter) return String(value);
409
+ return JSON.stringify(value);
410
+ }
411
+
412
+ /**
413
+ * The status line's resting text (HTML): what will be sent, the constraints, or a type hint.
414
+ * Errors and "Generated" replace it; schema.js puts it back.
415
+ */
416
+ function statusHtml(field, schema, type, context, path, required) {
417
+ const value = context.get(path);
418
+ const kind = field.dataset.kind;
419
+ const optionalQuery = !required && context.parameter && context.parameter.in !== 'path';
420
+ if (kind === 'lookup') return field.querySelector('.control.lk')?.lookupStatus?.() ?? '';
421
+ if (kind === 'radio' || kind === 'select') {
422
+ if (value !== undefined) return required ? '' : th('field.sends', { value: `<code>${esc(sentForm(context, value))}</code>`, n: 0 });
423
+ return required ? esc(t('hint.enum')) : esc(t('field.notSent'));
424
+ }
425
+ const parts = [];
426
+ if (type === 'number' || type === 'integer') {
427
+ const show = number => displayNumber(number, schema);
428
+ if (schema.minimum !== undefined && schema.maximum !== undefined && Math.abs(schema.maximum) < 1e15) parts.push(esc(t('field.between', { min: show(schema.minimum), max: show(schema.maximum) })));
429
+ else if (schema.minimum !== undefined) parts.push(esc(t('field.atLeast', { min: show(schema.minimum) })));
430
+ else if (schema.maximum !== undefined && Math.abs(schema.maximum) < 1e15) parts.push(esc(t('field.atMost', { max: show(schema.maximum) })));
431
+ if (schema.default !== undefined) parts.push(th('field.defaultIs', { value: `<code>${esc(show(schema.default))}</code>` }));
432
+ } else if (type === 'string' && schema.maxLength != null && !schema.format) parts.push(esc(t('field.upTo', { n: schema.maxLength })));
433
+ if (schema.format === 'date' && typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value)) {
434
+ const relative = formatRelativeDays(daysFromToday(value));
435
+ parts.push(esc(relative.charAt(0).toUpperCase() + relative.slice(1)));
436
+ }
437
+ if (!parts.length && optionalQuery && value === undefined) parts.push(esc(t('field.notSent')));
438
+ return parts.length ? parts.join(' · ') : esc(typeHint(schema, type));
439
+ }
440
+
441
+ function addAssistance(field, schema, type, id, context, path, required) {
442
+ const value = context.get(path);
443
+ const key = JSON.stringify(path);
444
+ const input = field.querySelector(`[id="${id}"]`);
445
+ // The description has its own line, from the spec; it always exists so subgrid rows line up.
446
+ const description = element('p', 'f-desc');
447
+ description.id = `${id}-desc`;
448
+ if (schema.description) {
449
+ description.lang = 'en';
450
+ description.innerHTML = inline(String(schema.description).replace(/\s*\n\s*/g, ' '));
451
+ }
452
+ field.append(description);
453
+ const assist = element('div', 'assist');
454
+ assist.id = `${id}-assist`;
455
+ const status = element('span', 'assist-icon');
456
+ status.hidden = true;
457
+ status.append(svg('alert'));
458
+ const msg = element('span', 'msg');
459
+ const hint = element('span', 'field-hint');
460
+ hint.innerHTML = statusHtml(field, schema, type, context, path, required);
461
+ hint.dataset.base = hint.innerHTML;
462
+ const error = element('span', 'field-error');
463
+ error.hidden = true;
464
+ msg.append(hint, error);
465
+ assist.append(status, msg);
466
+ // Generated values say where they came from, with Undo (mock 32).
467
+ const generated = context.autofilled.get?.(key);
468
+ if (generated) {
469
+ assist.classList.add('is-generated');
470
+ status.replaceChildren(svg('wand'));
471
+ status.hidden = false;
472
+ status.dataset.generated = '';
473
+ hint.textContent = t('field.generated', { source: generated });
474
+ if (context.canUndo(path)) {
475
+ const undo = element('button', 'undo', t('field.undo'));
476
+ undo.type = 'button';
477
+ undo.title = t('field.undoTip');
478
+ undo.addEventListener('click', () => context.undo(path));
479
+ assist.append(undo);
480
+ }
481
+ }
482
+ if (type === 'string' && schema.maxLength != null && input?.tagName === 'INPUT') {
483
+ const count = element('span', 'count');
484
+ const update = () => { count.textContent = `${formatNumber([...input.value].length)} / ${formatNumber(schema.maxLength)}`; };
485
+ update();
486
+ input.addEventListener('input', update);
487
+ assist.append(count);
488
+ } else if (type === 'array' && schema.maxItems != null) {
489
+ assist.append(element('span', 'count', `${formatNumber(value?.length ?? 0)} / ${formatNumber(schema.maxItems)}`));
490
+ }
491
+ if (input) {
492
+ input.setAttribute('aria-describedby', `${schema.description ? description.id + ' ' : ''}${assist.id}`);
493
+ if (input.getAttribute('role') === 'group') input.setAttribute('aria-labelledby', `${id}-label`);
494
+ }
495
+ field.append(assist);
496
+ }