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,285 @@
1
+ // The ID lookup (mocks 81, 85, m24): a select whose options are real records from the API
2
+ // (x-lookup). The control shows the chosen record's name with its detail in mono; the popover
3
+ // is the shared listbox (ui/listbox.js) with search by name, detail or ID, "From your last
4
+ // request" first, every record with a quiet tag for a non-default status, then "Paste an ID"
5
+ // (⌘V) and "Random UUID" (to test 404). The source of the options lives in the popover's footer
6
+ // on one line: GET /api/v2/accounts · as Ada Admin · 25, with Refresh.
7
+ //
8
+ // Loading, empty, error and signed-out states mirror the loaded layout; paste works in all of them.
9
+ import { element, svg, title } from './dom.js';
10
+ import { fromLastResponse, getLookupOptions } from './lookup-source.js';
11
+ import { newUuid } from '../uuid.js';
12
+ import { matchesShortcut, shortcutAria, shortcutHint } from '../shortcuts.js';
13
+ import { esc, icon } from '../components.js';
14
+ import { formatNumber, t, th } from '../i18n.js';
15
+ import { closeListbox, openListbox } from '../listbox.js';
16
+
17
+ /** "account" from an x-lookup URL such as /api/v2/accounts?pageSize=100. */
18
+ export function lookupNoun(url) {
19
+ const segment = String(url ?? '').split('?')[0].split('/').filter(Boolean).at(-1) ?? '';
20
+ if (!/^[a-z][a-z-]*$/i.test(segment)) return '';
21
+ const word = segment.endsWith('ies') ? segment.slice(0, -3) + 'y' : segment.endsWith('s') && !segment.endsWith('ss') ? segment.slice(0, -1) : segment;
22
+ return word.replace(/-/g, ' ').replace(/([a-z])([A-Z])/g, '$1 $2').toLowerCase();
23
+ }
24
+
25
+ /** The chip glyph for a record: a currency symbol when it has one, else its first letter. */
26
+ function glyph(option) {
27
+ const currency = typeof option.end === 'string' && /^[A-Z]{3}$/.test(option.end) ? option.end : undefined;
28
+ if (currency) {
29
+ try { return new Intl.NumberFormat('en', { style: 'currency', currency, currencyDisplay: 'narrowSymbol' }).formatToParts(0).find(part => part.type === 'currency')?.value || option.label.charAt(0); }
30
+ catch { /* An unknown code keeps the first letter. */ }
31
+ }
32
+ return String(option.label).charAt(0).toUpperCase();
33
+ }
34
+
35
+ /**
36
+ * Records already loaded, by lookup URL, for the session: a re-rendered field (after a pick, a
37
+ * tab switch or a carried-over value) names its record at once instead of flashing the raw ID.
38
+ */
39
+ const known = new Map();
40
+
41
+ /** A shortened ID for the status line: e25dbc9d…e3dd. */
42
+ const shortId = value => { const text = String(value); return text.length > 14 ? `${text.slice(0, 8)}…${text.slice(-4)}` : text; };
43
+
44
+ /**
45
+ * The lookup control. `field` carries the label id and the phone sheet's title.
46
+ * Returns the `.control` element (role="combobox").
47
+ */
48
+ export function lookupControl(context, metadata, schema, path, id, required, label, field = {}) {
49
+ const control = element('div', 'control sel lk');
50
+ control.id = id;
51
+ control.tabIndex = 0;
52
+ control.setAttribute('role', 'combobox');
53
+ control.setAttribute('aria-haspopup', 'listbox');
54
+ control.setAttribute('aria-expanded', 'false');
55
+ if (field.labelledBy) control.setAttribute('aria-labelledby', field.labelledBy);
56
+ if (required) control.setAttribute('aria-required', 'true');
57
+ const shortcuts = ['lookup-open', 'lookup-preview', 'lookup-paste', ...(schema.format === 'uuid' ? ['autofill-ids'] : [])];
58
+ control.setAttribute('aria-keyshortcuts', shortcutAria(...shortcuts));
59
+ control.dataset.shortcut = shortcuts.join(' ');
60
+ const picked = element('span', 'picked');
61
+ const slot = element('span', 'slot');
62
+ slot.setAttribute('aria-hidden', 'true');
63
+ const trigger = element('span', 'sel-trigger');
64
+ trigger.setAttribute('aria-hidden', 'true');
65
+ trigger.append(svg('chevron-down'));
66
+ control.append(picked, slot, trigger);
67
+
68
+ const noun = lookupNoun(metadata.url) || title(label).toLowerCase().replace(/ id$/, '');
69
+ const placeholder = t('lookup.choose', { name: noun, article: /^[aeiou]/.test(noun) ? 'an' : 'a' });
70
+ const last = fromLastResponse(context.lastResponse, metadata);
71
+ const signedOut = context.signedIn === false && !!metadata.url;
72
+ const cacheKey = `${context.basePath}|${metadata.url}`;
73
+ let options = (metadata.url && known.get(cacheKey)) || [];
74
+ let state = signedOut ? 'signedout' : metadata.url && !known.has(cacheKey) ? 'idle' : 'ok';
75
+ let loadError = { status: '' };
76
+ let generation = 0;
77
+ let searchTimer;
78
+ let box;
79
+
80
+ const currentOption = () => options.find(option => Object.is(option.value, context.get(path))) ||
81
+ (last && Object.is(last.value, context.get(path)) ? last : undefined);
82
+
83
+ /** The control's face: the record's chip, name and detail, or the placeholder. */
84
+ function renderSelection() {
85
+ const value = context.get(path);
86
+ const current = currentOption();
87
+ picked.replaceChildren();
88
+ control.classList.toggle('has-pick', value !== undefined);
89
+ if (value === undefined) { picked.append(element('span', 'placeholder', placeholder)); return; }
90
+ // Until the records arrive, a placeholder in the record's shape, not the raw ID.
91
+ if (!current && ['idle', 'loading'].includes(state)) {
92
+ const chip = element('span', 'sk sk-box');
93
+ const line = element('span', 'sk sk-line');
94
+ line.style.inlineSize = '10rem';
95
+ picked.append(chip, line);
96
+ picked.setAttribute('aria-busy', 'true');
97
+ return;
98
+ }
99
+ picked.removeAttribute('aria-busy');
100
+ const text = String(current?.label ?? value);
101
+ const chip = element('span', 'chip-ico', current ? glyph(current) : text.charAt(0).toUpperCase());
102
+ chip.setAttribute('aria-hidden', 'true');
103
+ const main = element('span', 'main', text);
104
+ main.lang = 'en';
105
+ picked.append(chip, main);
106
+ if (current?.detail !== undefined) picked.append(element('span', 'sub', String(current.detail)));
107
+ else if (!current) main.classList.add('mono-val');
108
+ }
109
+
110
+ /** The record noun's plural as the group label: "Accounts · 25". */
111
+ const groupLabel = n => `${esc(title(String(metadata.url ?? '').split('?')[0].split('/').filter(Boolean).at(-1) || t('lookup.optionsTitle')))} · ${esc(formatNumber(n))}`;
112
+
113
+ function items() {
114
+ const list = [];
115
+ if (last?.value !== undefined && last.value !== null) list.push({ ...row(last), group: esc(t('lookup.lastResponse')) });
116
+ const rest = options.filter(option => !Object.is(option.value, last?.value));
117
+ list.push(...rest.map(option => ({ ...row(option), group: groupLabel(options.length) })));
118
+ list.push({ command: 'paste', icon: 'copy', label: t('lookup.paste'), end: shortcutHint('lookup-paste') });
119
+ if (schema.format === 'uuid') list.push({ command: 'uuid', icon: 'refresh', label: t('lookup.random'), description: t('lookup.randomBody') });
120
+ return list;
121
+ }
122
+ function row(option) {
123
+ const end = [option.status && !/^(open|active|enabled)$/i.test(String(option.status)) ? `<span class="tag">${esc(option.status)}</span>` : '', option.end ? esc(option.end) : ''].join('');
124
+ return { value: option.value, label: String(option.label), detail: option.detail !== undefined ? String(option.detail) : undefined, keywords: [String(option.value)], glyph: glyph(option), end, valueLang: 'en' };
125
+ }
126
+
127
+ /** The state rows above the commands, in the same shape as the loaded list. */
128
+ function before() {
129
+ if (state === 'loading' || state === 'idle') {
130
+ const widths = [[52, 70], [64, 62], [44, 74], [58, 66], [48, 70]];
131
+ return `<li class="lb-group" role="presentation"><span class="spinner" aria-hidden="true"></span>${esc(t('lookup.loading'))}</li>${widths.map(([a, b]) =>
132
+ `<li class="lb-sk" aria-hidden="true"><span class="sk sk-box"></span><span class="stack"><span class="sk sk-line" style="inline-size:${a}%"></span><span class="sk sk-line thin" style="inline-size:${b}%"></span></span><span class="sk sk-line" style="inline-size:2rem"></span></li>`).join('')}`;
133
+ }
134
+ if (state === 'empty') {
135
+ // The operation that creates a record of this kind, when the spec has one: POST to the same collection.
136
+ const create = context.document?.paths?.[String(metadata.url).split('?')[0]]?.post;
137
+ const action = create?.operationId ? `<a class="btn btn-sm" href="#op/${encodeURIComponent(create.operationId)}">${icon('plus', true)}<span lang="en">${esc(create.summary || create.operationId)}</span></a>` : '';
138
+ return `<li class="lb-state" role="presentation"><strong>${icon('db', true)}${esc(context.actor ? t('lookup.emptyTitle', { name: context.actor }) : t('lookup.emptyTitlePlain'))}</strong><p>${esc(t('lookup.emptyBody'))}</p>${action}</li>`;
139
+ }
140
+ if (state === 'error') return `<li class="lb-state is-error" role="presentation"><strong>${icon('alert', true)}${esc(t('lookup.errorTitle'))}</strong><p>${loadError.status ? th('lookup.errorBody', { request: `<code>GET ${esc(metadata.url)}</code>`, status: esc(loadError.status) }) : esc(loadError.message)}</p><button type="button" class="btn btn-sm" data-lookup-retry>${icon('refresh', true)}${esc(t('lookup.retry'))}</button></li>`;
141
+ if (state === 'signedout') return `<li class="lb-state" role="presentation"><strong>${icon('lock', true)}${esc(t('lookup.outTitle'))}</strong><p>${esc(t('lookup.outBody'))}</p>${context.onSignIn ? `<button type="button" class="btn btn-sm btn-primary" data-lookup-signin>${icon('log-in', true)}${esc(t('shell.signIn'))}</button>` : ''}</li>`;
142
+ return '';
143
+ }
144
+
145
+ /** The footer: where the options come from, as whom, how many, and Refresh. */
146
+ function source() {
147
+ if (!metadata.url) return '';
148
+ const [route, query] = String(metadata.url).split(/(?=\?)/);
149
+ const meta = { ok: context.actor ? `<span class="who">· ${esc(t('lookup.as', { name: context.actor }))}</span> · ${esc(formatNumber(options.length))}` : `· ${esc(formatNumber(options.length))}`,
150
+ loading: `· ${esc(t('lookup.metaLoading'))}`, idle: `· ${esc(t('lookup.metaLoading'))}`, empty: context.actor ? `<span class="who">· ${esc(t('lookup.as', { name: context.actor }))}</span> · ${esc(formatNumber(0))}` : `· ${esc(formatNumber(0))}`,
151
+ error: `· ${esc(t('lookup.metaError', { code: loadError.status || '?' }))}`, signedout: `· ${esc(t('lookup.metaOut'))}` }[state];
152
+ const glyphName = state === 'error' ? 'alert' : state === 'signedout' ? 'lock' : 'db';
153
+ return `<div class="lb-src">${icon(glyphName, true)}<code class="src-q ltr" title="${esc(`GET ${metadata.url}`)}"><span>GET ${esc(route)}</span>${query ? `<span class="qs">${esc(query)}</span>` : ''}</code><span class="meta">${meta}</span><span class="spacer"></span><button type="button" class="btn btn-ghost btn-icon btn-xs" data-lookup-refresh aria-label="${esc(t('lookup.refresh'))}" title="${esc(t('lookup.refresh'))}">${icon('refresh', true)}</button></div>`;
154
+ }
155
+
156
+ async function load(query = '', force = false) {
157
+ if (!metadata.url && !Array.isArray(metadata.options)) return;
158
+ if (signedOut) return;
159
+ const ticket = ++generation;
160
+ if (force) { context.lookupCache.clear?.(); known.delete(cacheKey); }
161
+ if (state === 'ok' && !force && !query && options.length) return;
162
+ state = 'loading';
163
+ refresh();
164
+ try {
165
+ const loaded = await getLookupOptions(context, metadata, query);
166
+ if (ticket !== generation) return;
167
+ options = loaded;
168
+ if (!query && metadata.url) known.set(cacheKey, loaded);
169
+ state = loaded.length || query ? 'ok' : 'empty';
170
+ } catch (error) {
171
+ if (ticket !== generation) return;
172
+ loadError = { status: /HTTP (\d+)/.exec(error.message)?.[1] ?? '', message: error.message };
173
+ state = 'error';
174
+ }
175
+ refresh();
176
+ renderSelection();
177
+ // The status line counts the records once they're known (unless an error has taken it over).
178
+ const hint = control.closest?.('.field')?.querySelector(':scope > .assist:not(.is-error):not(.is-generated) .field-hint');
179
+ if (hint) { hint.innerHTML = control.lookupStatus(); hint.dataset.base = hint.innerHTML; }
180
+ }
181
+
182
+ function refresh() {
183
+ box?.update(items(), { before: before(), after: source() });
184
+ }
185
+
186
+ function pick(value, preview = false) {
187
+ context.set(path, value);
188
+ context.render(JSON.stringify(path));
189
+ if (preview) context.onLookupPreview?.();
190
+ }
191
+
192
+ async function command(item) {
193
+ if (item.command === 'paste') {
194
+ try { paste(await navigator.clipboard.readText()); }
195
+ catch { control.title = t('lookup.pasteHelp'); }
196
+ } else if (item.command === 'uuid') pick(newUuid());
197
+ }
198
+
199
+ function paste(raw) {
200
+ const text = String(raw ?? '').trim();
201
+ if (!text) return;
202
+ closeListbox();
203
+ pick(context.kind(schema) === 'integer' && /^-?\d+$/.test(text) ? Number(text) : text);
204
+ }
205
+
206
+ function show() {
207
+ box = openListbox(control, {
208
+ label: t('lookup.options', { name: title(label) }), className: 'lk-pop',
209
+ items: items(), value: context.get(path), search: true,
210
+ // "Search by name, IBAN or ID": a short field name is an acronym; a longer one reads as words.
211
+ searchLabel: metadata.detailField ? t('lookup.searchBy', { detail: metadata.detailField.length <= 4 ? metadata.detailField.toUpperCase() : title(metadata.detailField).toLowerCase() }) : t('lookup.searchPlain'),
212
+ before: before(), after: source(), sheet: field.sheet,
213
+ onPick: item => item.command ? command(item) : pick(item.value),
214
+ onKey: (event, { item }) => {
215
+ if (matchesShortcut('lookup-preview', event) && item && !item.command) { closeListbox(true); pick(item.value, true); return true; }
216
+ if (matchesShortcut('autofill-ids', event) && schema.format === 'uuid') { closeListbox(true); pick(newUuid()); return true; }
217
+ return false;
218
+ },
219
+ onSearch: query => {
220
+ if (!metadata.searchParam) return;
221
+ clearTimeout(searchTimer);
222
+ searchTimer = setTimeout(() => load(query), 200);
223
+ },
224
+ onClose: () => clearTimeout(searchTimer),
225
+ });
226
+ const search = box.pop.querySelector('.lb-search input');
227
+ // Paste works in every state: an ID pasted into the search box is used as the value.
228
+ search?.addEventListener('paste', event => {
229
+ const text = event.clipboardData?.getData('text/plain')?.trim();
230
+ if (!text || options.some(option => String(option.label).toLowerCase().includes(text.toLowerCase()))) return;
231
+ event.preventDefault();
232
+ paste(text);
233
+ });
234
+ box.pop.addEventListener('click', event => {
235
+ if (event.target.closest('[data-lookup-refresh]')) load('', true);
236
+ else if (event.target.closest('[data-lookup-retry]')) load('', true);
237
+ else if (event.target.closest('[data-lookup-signin]')) { closeListbox(); context.onSignIn?.(); }
238
+ else if (event.target.closest('a[href^="#op/"]')) closeListbox();
239
+ });
240
+ if (state === 'idle' || state === 'error') load('');
241
+ }
242
+
243
+ control.addEventListener('click', () => {
244
+ if (control.getAttribute('aria-expanded') === 'true') closeListbox(true);
245
+ else show();
246
+ });
247
+ control.addEventListener('paste', event => {
248
+ const text = event.clipboardData?.getData('text/plain');
249
+ if (!text) return;
250
+ event.preventDefault();
251
+ paste(text);
252
+ });
253
+ control.addEventListener('keydown', event => {
254
+ if (control.getAttribute('aria-expanded') === 'true') return;
255
+ if (matchesShortcut('autofill-ids', event) && schema.format === 'uuid') pick(newUuid());
256
+ else if ((event.key === 'Delete' || event.key === 'Backspace') && context.get(path) !== undefined) pick(undefined);
257
+ else if (matchesShortcut('lookup-open', event) || ['ArrowDown', 'ArrowUp', 'Enter', ' '].includes(event.key)) show();
258
+ else if (event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) {
259
+ show();
260
+ const search = box?.pop.querySelector('.lb-search input');
261
+ if (search) { search.value = event.key; search.dispatchEvent(new Event('input')); }
262
+ } else return;
263
+ event.preventDefault();
264
+ event.stopPropagation();
265
+ });
266
+ control.focusControl = () => control.focus();
267
+ control.openOptions = () => { if (control.getAttribute('aria-expanded') !== 'true') show(); };
268
+ /** Chooses a record (or any ID) as if it had been picked from the list. */
269
+ control.choose = value => pick(value);
270
+ /** What the status line says about this lookup: "Sends e25dbc9d…e3dd" or how many it offers. */
271
+ control.lookupStatus = () => {
272
+ const value = context.get(path);
273
+ if (value !== undefined) return th('field.sends', { value: `<code>${esc(shortId(value))}</code>` });
274
+ if (signedOut) return esc(t('lookup.outTitle'));
275
+ if (state === 'error') return esc(loadError.status ? t('lookup.errorTitle') : loadError.message || t('lookup.errorTitle'));
276
+ if (state === 'ok' && options.length) return esc(context.actor ? t('lookup.countAs', { n: options.length, name: context.actor }) : t('lookup.count', { n: options.length }));
277
+ return esc(t('lookup.hint'));
278
+ };
279
+ renderSelection();
280
+ // Load right away (the request is cached per URL): the control names the chosen record and the
281
+ // status line says how many records there are to choose from.
282
+ if (!signedOut && metadata.url) queueMicrotask(() => load(''));
283
+ else if (Array.isArray(metadata.options)) load('');
284
+ return control;
285
+ }