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,188 @@
1
+ import { formatNumber, t } from "./i18n.js";
2
+ import { newUuid } from "./uuid.js";
3
+
4
+ /** HTTP header names use the RFC 9110 token grammar. */
5
+ export const HEADER_NAME_PATTERN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
6
+
7
+ const variablePattern = /\{\{\s*([^{}]*?)\s*\}\}/g;
8
+ const sampleUuid = "00000000-0000-4000-8000-000000000000";
9
+ let nextHeaderId = 1;
10
+
11
+ /** Create a stable, editable custom-header row. */
12
+ export function createHeaderRow(name = "", value = "", enabled = true) {
13
+ return { id: `custom-header-${nextHeaderId++}`, name: String(name), value: String(value), enabled };
14
+ }
15
+
16
+ function objectRows(value) {
17
+ if (!value || Array.isArray(value) || typeof value !== "object") return [];
18
+ return Object.entries(value).map(([name, headerValue]) => createHeaderRow(name, headerValue));
19
+ }
20
+
21
+ /** Normalize the persisted value, including the old JSON-object representation. */
22
+ export function normalizeHeaderRows(value) {
23
+ if (typeof value === "string") {
24
+ if (!value.trim()) return [];
25
+ try {
26
+ return objectRows(JSON.parse(value));
27
+ } catch {
28
+ return [];
29
+ }
30
+ }
31
+ if (Array.isArray(value)) {
32
+ for (const row of value) {
33
+ const serial = Number(/^custom-header-(\d+)$/.exec(row?.id)?.[1]);
34
+ if (Number.isSafeInteger(serial) && serial < Number.MAX_SAFE_INTEGER) {
35
+ nextHeaderId = Math.max(nextHeaderId, serial + 1);
36
+ }
37
+ }
38
+ if (value.every((row) => row && typeof row.id === "string" && typeof row.name === "string" && typeof row.value === "string")) return value;
39
+ return value.map((row) => ({
40
+ id: row?.id || `custom-header-${nextHeaderId++}`,
41
+ name: String(row?.name ?? ""),
42
+ value: String(row?.value ?? ""),
43
+ enabled: row?.enabled !== false,
44
+ }));
45
+ }
46
+ return objectRows(value);
47
+ }
48
+
49
+ function error(row, message, field = "name") {
50
+ return { id: row.id, field, message };
51
+ }
52
+
53
+ /** Share the token syntax between the display, validation, and request preparation. */
54
+ export function headerVariables(value) {
55
+ return [...String(value ?? "").matchAll(variablePattern)];
56
+ }
57
+
58
+ function resolveHeaderValue(value, { uuid, now, lastId }) {
59
+ return value.replace(variablePattern, (_, name) => {
60
+ if (name === "now") return now;
61
+ if (name === "uuid") {
62
+ const id = uuid();
63
+ if (id) return id;
64
+ throw new Error(t("kv.err.uuidUnavailable", { token: "{{uuid}}" }));
65
+ }
66
+ if (name === "last.id") {
67
+ if ((typeof lastId === "string" && lastId.trim()) || Number.isFinite(lastId)) return String(lastId);
68
+ throw new Error(t("kv.err.lastId", { token: "{{last.id}}" }));
69
+ }
70
+ throw new Error(t("kv.err.unknownVariable", { name: `{{${name}}}`, uuid: "{{uuid}}", now: "{{now}}", last: "{{last.id}}" }));
71
+ });
72
+ }
73
+
74
+ /**
75
+ * Validate and resolve enabled rows together. By default, inspection uses a
76
+ * representative UUID so typing and live validation leave the draft intact.
77
+ */
78
+ export function inspectHeaderRows(rows, { uuid = () => sampleUuid, now = new Date().toISOString(), lastId } = {}) {
79
+ const errors = [];
80
+ const names = new Map();
81
+ const enabled = [];
82
+ for (const row of rows) {
83
+ if (row?.enabled === false) continue;
84
+ const name = String(row?.name ?? "").trim();
85
+ const rawValue = String(row?.value ?? "");
86
+ let value = rawValue;
87
+ if (!name) {
88
+ errors.push(error(row, t("kv.err.nameRequired")));
89
+ continue;
90
+ }
91
+ if (!HEADER_NAME_PATTERN.test(name)) {
92
+ const fixed = headerNameFix(name);
93
+ errors.push(error(row, fixed ? t("kv.err.nameSpaces", { fixed }) : t("kv.err.nameToken")));
94
+ }
95
+ try {
96
+ value = resolveHeaderValue(value, { uuid, now, lastId });
97
+ } catch (failure) {
98
+ errors.push(error(row, failure.message, "value"));
99
+ }
100
+ if (/[\r\n]/.test(rawValue) || /[\r\n]/.test(value)) {
101
+ errors.push(error(row, t("kv.err.lineBreak"), "value"));
102
+ } else if (/[\x00-\x08\x0a-\x1f\x7f\u0100-\uffff]/.test(value)) {
103
+ errors.push(error(row, t("kv.err.valueChars"), "value"));
104
+ }
105
+ const key = name.toLowerCase();
106
+ const first = names.get(key);
107
+ if (first) {
108
+ errors.push(error(row, t("kv.err.duplicate", { first })));
109
+ } else {
110
+ names.set(key, name);
111
+ }
112
+ enabled.push({ ...row, name, value });
113
+ }
114
+ return { valid: errors.length === 0, errors, rows: enabled };
115
+ }
116
+
117
+ /** Validate the active header set against HTTP syntax and variable availability. */
118
+ export function validateHeaderRows(rows, context) {
119
+ const { valid, errors } = inspectHeaderRows(rows, context);
120
+ return { valid, errors };
121
+ }
122
+
123
+ export function headerNameFix(name) {
124
+ const fixed = name.trim().replace(/\s+/g, "-");
125
+ return fixed !== name.trim() && HEADER_NAME_PATTERN.test(fixed) ? fixed : undefined;
126
+ }
127
+
128
+ /** Keep values edited in the headers view compatible with declared schemas. */
129
+ export function coerceHeaderValue(value, schema = {}) {
130
+ const text = String(value ?? "");
131
+ if (!text) return undefined;
132
+ if (schema.enum) {
133
+ const match = schema.enum.find((choice) => String(choice) === text);
134
+ if (match !== undefined) return match;
135
+ }
136
+ const type = Array.isArray(schema.type)
137
+ ? schema.type.find((item) => item !== "null")
138
+ : schema.type;
139
+ if (type === "integer" || type === "number") {
140
+ const number = Number(text);
141
+ return Number.isNaN(number) ? text : number;
142
+ }
143
+ if (type === "boolean") {
144
+ if (text === "true") return true;
145
+ if (text === "false") return false;
146
+ }
147
+ if (type === "object" || type === "array") {
148
+ try { return JSON.parse(text); } catch { return text; }
149
+ }
150
+ return text;
151
+ }
152
+
153
+ /** Convert validated custom rows to the object accepted by the request API. */
154
+ export function headerRowsToObject(rows, context) {
155
+ const validation = inspectHeaderRows(rows, { uuid: newUuid, ...context });
156
+ if (!validation.valid) {
157
+ const error = new Error(validation.errors.map(({ message }) => message).join("\n"));
158
+ error.validation = true;
159
+ error.headerErrors = validation.errors;
160
+ throw error;
161
+ }
162
+ return Object.fromEntries(validation.rows.map(({ name, value }) => [name, value]));
163
+ }
164
+
165
+ /** Retain disabled rows in bulk edit with a reversible comment prefix. */
166
+ export function formatHeaderLines(rows) {
167
+ return rows.map(row => `${row.enabled === false ? "# " : ""}${row.name}: ${row.value}`).join("\n");
168
+ }
169
+
170
+ export function parseHeaderLines(text, previous = []) {
171
+ const rows = [];
172
+ const errors = [];
173
+ for (const [index, line] of text.split(/\r?\n/).entries()) {
174
+ if (!line.trim()) continue;
175
+ const enabled = !line.startsWith("# ");
176
+ const entry = enabled ? line : line.slice(2);
177
+ const colon = entry.indexOf(":");
178
+ if (colon === -1) {
179
+ errors.push(t("kv.err.noColon", { n: formatNumber(index + 1) }));
180
+ continue;
181
+ }
182
+ const name = entry.slice(0, colon).trim();
183
+ const value = entry.slice(colon + 1).replace(/^ /, "");
184
+ const id = previous[rows.length]?.id ?? createHeaderRow().id;
185
+ rows.push({ id, name, value, enabled });
186
+ }
187
+ return { rows, errors };
188
+ }
@@ -0,0 +1,257 @@
1
+ // Syntax colouring for JSON and for the request samples in every language we export.
2
+ //
3
+ // A sample is plain text in, HTML out: the text is cut into tokens by a small per-language lexer
4
+ // and each token becomes `<span class="tok-KIND">` (classes live in views.css and app.css, with
5
+ // light and dark colours that meet WCAG AA). Every piece of text goes through esc(), so nothing a
6
+ // request contains can become markup. There is no parser: a lexer is an ordered list of sticky
7
+ // regular expressions, and the first rule that matches at the current position wins. Text no rule
8
+ // claims (spaces, an unterminated quote) passes through uncoloured.
9
+ //
10
+ // Token kinds
11
+ // k JSON/object key s string (any quoting form, incl. raw, verbatim, heredoc)
12
+ // n number b literal: true, false, null, None, nil ...
13
+ // p punctuation kw keyword
14
+ // c comment f function or method call, command, cmdlet
15
+ // fl shell flag (-X) u URL inside a string
16
+ // v variable ($name) t type or class name (Capitalised identifier)
17
+ //
18
+ // A string whose content is a JSON document (a --data-raw body, a Python r"""...""", a Rust
19
+ // r#"..."#, a PHP nowdoc, a PowerShell here-string, ...) is not painted as one green block: its
20
+ // delimiters stay string-coloured and the JSON inside is coloured like the response viewer does.
21
+ import { esc } from './components.js';
22
+
23
+ // ---------------------------------------------------------------------------------------------
24
+ // JSON
25
+ // ---------------------------------------------------------------------------------------------
26
+
27
+ const TOKEN = /("(?:\\.|[^"\\])*")(\s*:)?|(-?\b\d+(?:\.\d+)?(?:[eE][+-]?\d+)?\b)|\b(true|false|null)\b|([{}[\],])/g;
28
+ // The same, for JSON written inside a string that escapes its backslashes (a Java text block):
29
+ // there a JSON \" appears as \\" and a JSON backslash as four, so an escape is two backslashes and a character.
30
+ const DOUBLED_TOKEN = /("(?:\\\\[\s\S]|[^"\\])*")(\s*:)?|(-?\b\d+(?:\.\d+)?(?:[eE][+-]?\d+)?\b)|\b(true|false|null)\b|([{}[\],])/g;
31
+
32
+ /**
33
+ * Colours JSON text (or JSON inside a snippet). The input is plain text; the output is HTML.
34
+ * `doubled` reads JSON whose backslashes are doubled, as inside a Java text block.
35
+ */
36
+ export function highlightJson(text, { doubled = false } = {}) {
37
+ let out = '';
38
+ let last = 0;
39
+ for (const match of String(text).matchAll(doubled ? DOUBLED_TOKEN : TOKEN)) {
40
+ out += esc(text.slice(last, match.index));
41
+ const [whole, string, colon, number, literal, punctuation] = match;
42
+ if (string) out += colon ? `<span class="tok-k">${esc(string)}</span><span class="tok-p">${esc(colon)}</span>` : `<span class="tok-s">${esc(string)}</span>`;
43
+ else if (number) out += `<span class="tok-n">${esc(number)}</span>`;
44
+ else if (literal) out += `<span class="tok-b">${literal}</span>`;
45
+ else out += `<span class="tok-p">${esc(punctuation)}</span>`;
46
+ last = match.index + whole.length;
47
+ }
48
+ return out + esc(String(text).slice(last));
49
+ }
50
+
51
+ // ---------------------------------------------------------------------------------------------
52
+ // Building blocks for the lexers
53
+ // ---------------------------------------------------------------------------------------------
54
+
55
+ const span = (kind, text) => text ? `<span class="tok-${kind}">${esc(text)}</span>` : '';
56
+
57
+ /** A rule: a sticky regex plus a function turning its match into HTML. */
58
+ const rule = (pattern, emit) => ({ re: new RegExp(pattern.source, pattern.flags.replace('y', '') + 'y'), emit });
59
+ /** A rule that paints the whole match one kind. */
60
+ const simple = (pattern, kind) => rule(pattern, match => span(kind, match[0]));
61
+
62
+ const URL_IN_TEXT = /https?:\/\/[^\s"'`\\)]+/g;
63
+
64
+ /** Splits text into plain and URL pieces so a URL inside a string gets its own colour. */
65
+ function withUrls(text, kind) {
66
+ let html = '';
67
+ let last = 0;
68
+ for (const match of text.matchAll(URL_IN_TEXT)) {
69
+ html += span(kind, text.slice(last, match.index)) + span('u', match[0]);
70
+ last = match.index + match[0].length;
71
+ }
72
+ return html + span(kind, text.slice(last));
73
+ }
74
+
75
+ const looksLikeJson = text => {
76
+ if (!/^\s*[[{]/.test(text) || !/[\]}]\s*$/.test(text)) return false;
77
+ try { JSON.parse(text); return true; } catch { return false; }
78
+ };
79
+
80
+ /**
81
+ * A string rule. `groups` names the capture groups holding the opening delimiter, the content
82
+ * and the closing delimiter (1, 2, 3 unless the pattern says otherwise). With `keys`, a string
83
+ * that is followed by a colon is an object key, as in a JavaScript or Python dictionary literal.
84
+ * `unescape` turns the content into the text it stands for, only to decide whether it is JSON;
85
+ * `doubled` colours that JSON with doubled backslashes (see highlightJson).
86
+ */
87
+ function string(pattern, { open = 1, content = 2, close = 3, keys = false, unescape, doubled = false } = {}) {
88
+ return rule(pattern, match => {
89
+ const [whole, before, inner, after] = [match[0], match[open], match[content], match[close]];
90
+ if (keys && /^\s*:/.test(match.input.slice(match.index + whole.length, match.index + whole.length + 16))) return span('k', whole);
91
+ if (looksLikeJson(unescape ? unescape(inner) : inner)) return span('s', before) + highlightJson(inner, { doubled }) + span('s', after);
92
+ return withUrls(whole, 's');
93
+ });
94
+ }
95
+
96
+ /**
97
+ * A heredoc (Ruby `<<~'JSON'`, PHP `<<<'JSON'`): the tag, whatever else is on that line
98
+ * (`.chomp`, which is lexed like code), the body, then the closing line. Groups: 1 tag, 4 rest of
99
+ * the tag's line, 5 body.
100
+ */
101
+ const heredoc = pattern => rule(pattern, (match, lex) => {
102
+ const [whole, tag, , , rest, body] = match;
103
+ const head = tag.length + rest.length + 1;
104
+ const closing = whole.slice(head + body.length + 1);
105
+ return span('s', tag) + tokenize(rest, lex) + '\n' + (looksLikeJson(body) ? highlightJson(body) : span('s', body)) + '\n' + span('s', closing);
106
+ });
107
+
108
+ const doubleQuoted = (keys = false) => string(/(")((?:\\[\s\S]|[^"\\])*)(")/, { keys });
109
+ const singleQuoted = (keys = false) => string(/(')((?:\\[\s\S]|[^'\\])*)(')/, { keys });
110
+ const lineComment = prefix => simple(new RegExp(`${prefix}.*`), 'c');
111
+ const blockComment = simple(/\/\*[\s\S]*?\*\//, 'c');
112
+ const number = simple(/0[xX][\da-fA-F_]+|\d[\d_]*(?:\.\d+)?(?:[eE][+-]?\d+)?/, 'n');
113
+ const punctuation = simple(/[{}()[\],;:.<>=+\-?!&|@\\~^%]+/, 'p');
114
+
115
+ /** An identifier: a keyword, a literal, a call, a Capitalised type, or plain text. */
116
+ const identifier = rule(/[A-Za-z_$][\w$]*/, (match, lex) => {
117
+ const word = match[0];
118
+ const next = match.input.slice(match.index + word.length, match.index + word.length + 2);
119
+ if (lex.keywords.has(word)) return span('kw', word);
120
+ if (lex.literals.has(word)) return span('b', word);
121
+ if (lex.builtins.has(word) || /^!?\(/.test(next)) return span('f', word);
122
+ if (/^[A-Z]/.test(word) && /[a-z]/.test(word)) return span('t', word);
123
+ return esc(word);
124
+ });
125
+
126
+ const words = text => new Set(text.split(' ').filter(Boolean));
127
+
128
+ /** A lexer: its rules in priority order, plus the word lists the identifier rule consults. */
129
+ const defineLexer = ({ rules, keywords = '', literals = '', builtins = '' }) => ({
130
+ rules: [...rules, number, identifier, punctuation], keywords: words(keywords), literals: words(literals), builtins: words(builtins),
131
+ });
132
+
133
+ const cStyleComments = [lineComment('//'), blockComment];
134
+ const hashComment = rule(/(?<![^\s])#.*/, match => span('c', match[0]));
135
+ const backtickString = string(/(`)((?:\\[\s\S]|[^`\\])*)(`)/);
136
+
137
+ // ---------------------------------------------------------------------------------------------
138
+ // The lexers
139
+ // ---------------------------------------------------------------------------------------------
140
+
141
+ const LEXERS = {
142
+ // cURL: single quotes are verbatim, so a JSON body is one multi-line string.
143
+ bash: defineLexer({
144
+ rules: [hashComment, string(/(')((?:[^']|'\\'')*)(')/, { unescape: text => text.replaceAll("'\\''", "'") }), doubleQuoted(), simple(/(?<=\s)--?[A-Za-z][\w-]*/, 'fl'), simple(/\$\{?\w+\}?/, 'v')],
145
+ builtins: 'curl echo',
146
+ }),
147
+ javascript: defineLexer({
148
+ rules: [...cStyleComments, doubleQuoted(true), singleQuoted(true), backtickString],
149
+ keywords: 'const let var await async function return if else new import from export class of typeof',
150
+ literals: 'true false null undefined',
151
+ }),
152
+ python: defineLexer({
153
+ rules: [hashComment,
154
+ string(/([rRbBfFuU]{0,2}""")([\s\S]*?)(""")/), string(/([rRbBfFuU]{0,2}''')([\s\S]*?)(''')/),
155
+ string(/([rRbBfFuU]{0,2}")((?:\\[\s\S]|[^"\\\n])*)(")/, { keys: true }), string(/([rRbBfFuU]{0,2}')((?:\\[\s\S]|[^'\\\n])*)(')/, { keys: true })],
156
+ keywords: 'import from as def return if elif else with await async class for in not and or is lambda pass try except raise while',
157
+ literals: 'True False None',
158
+ }),
159
+ csharp: defineLexer({
160
+ rules: [...cStyleComments,
161
+ string(/("{3,})([\s\S]*?)(\1)/), string(/(@\$?"|\$@")((?:""|[^"])*)(")/), string(/(\$?")((?:\\[\s\S]|[^"\\\n])*)(")/), singleQuoted()],
162
+ keywords: 'using var new await async public static void class return if else namespace string int bool object foreach in',
163
+ literals: 'true false null',
164
+ }),
165
+ go: defineLexer({
166
+ rules: [...cStyleComments, string(/(`)([^`]*)(`)/), doubleQuoted(), singleQuoted()],
167
+ keywords: 'package import func return if else defer var const type struct for range go select switch case',
168
+ literals: 'true false nil',
169
+ }),
170
+ java: defineLexer({
171
+ rules: [...cStyleComments, string(/(""")((?:\\[\s\S]|(?!""")[\s\S])*)(""")/, { unescape: text => text.replace(/\\([\\"])/g, '$1'), doubled: true }), doubleQuoted(), singleQuoted()],
172
+ keywords: 'import public private class static void throws new final return if else try catch throw extends implements package',
173
+ literals: 'true false null',
174
+ }),
175
+ kotlin: defineLexer({
176
+ rules: [...cStyleComments, string(/(""")([\s\S]*?)(""")/), doubleQuoted(), singleQuoted()],
177
+ keywords: 'import fun val var return if else class object suspend package for in when',
178
+ literals: 'true false null',
179
+ }),
180
+ php: defineLexer({
181
+ rules: [...cStyleComments, hashComment, simple(/<\?php|\?>/, 'kw'),
182
+ heredoc(/(<<<(['"]?)(\w+)\2)([^\n]*)\n([\s\S]*?)\n[ \t]*\3\b/), singleQuoted(), doubleQuoted(), simple(/\$\w+/, 'v')],
183
+ keywords: 'use new echo require require_once return if else foreach function class namespace',
184
+ literals: 'true false null',
185
+ }),
186
+ ruby: defineLexer({
187
+ rules: [hashComment, heredoc(/(<<[~-]?(['"]?)(\w+)\2)([^\n]*)\n([\s\S]*?)\n[ \t]*\3\b/), doubleQuoted(), singleQuoted(), simple(/@\w+/, 'v')],
188
+ keywords: 'require def end do if elsif else class module unless begin rescue return',
189
+ literals: 'true false nil',
190
+ builtins: 'puts print p',
191
+ }),
192
+ rust: defineLexer({
193
+ rules: [...cStyleComments, string(/(r(#*)")([\s\S]*?)("\2)/, { open: 1, content: 3, close: 4 }), doubleQuoted()],
194
+ keywords: 'use fn let mut pub struct impl match return if else for in mod const static',
195
+ literals: 'true false',
196
+ }),
197
+ powershell: defineLexer({
198
+ rules: [simple(/<#[\s\S]*?#>/, 'c'), hashComment,
199
+ string(/(@')(\r?\n[\s\S]*?\r?\n)('@)/), string(/(@")(\r?\n[\s\S]*?\r?\n)("@)/),
200
+ string(/(')((?:''|[^'])*)(')/), string(/(")((?:`[\s\S]|""|[^"`])*)(")/),
201
+ rule(/\$(?:true|false|null)\b/i, match => span('b', match[0])), simple(/\$\{[^}]*\}|\$\w+/, 'v'),
202
+ simple(/(?<=^[ \t]*)[A-Za-z]+(?=[ \t]*=)/m, 'k'), simple(/[A-Za-z]+-[A-Za-z]+(?![\w-])/, 'f'), simple(/(?<![\w])-[A-Za-z]\w*/, 'fl')],
203
+ keywords: 'if else elseif foreach function param return',
204
+ }),
205
+ };
206
+
207
+ /** Cuts source into tokens with a lexer and returns HTML. */
208
+ function tokenize(source, lex) {
209
+ let html = '';
210
+ let plain = '';
211
+ let position = 0;
212
+ scan: while (position < source.length) {
213
+ for (const { re, emit } of lex.rules) {
214
+ re.lastIndex = position;
215
+ const match = re.exec(source);
216
+ if (!match || !match[0]) continue;
217
+ html += esc(plain);
218
+ plain = '';
219
+ html += emit(match, lex);
220
+ position += match[0].length;
221
+ continue scan;
222
+ }
223
+ plain += source[position++];
224
+ }
225
+ return html + esc(plain);
226
+ }
227
+
228
+ /**
229
+ * The .http format: request line, header lines, then a body. Names are keys, the URL is
230
+ * highlighted as one, and a JSON body is coloured like the response viewer does.
231
+ */
232
+ function highlightHttp(text) {
233
+ const [head, ...rest] = text.split('\n\n');
234
+ const lines = head.split('\n').map((line, index) => {
235
+ if (index === 0) {
236
+ const request = /^(\S+)(\s+)(\S+)(.*)$/.exec(line);
237
+ return request ? span('kw', request[1]) + esc(request[2]) + span('u', request[3]) + esc(request[4]) : esc(line);
238
+ }
239
+ const header = /^([^:\s]+)(:)(.*)$/.exec(line);
240
+ return header ? span('k', header[1]) + span('p', header[2]) + span('s', header[3]) : esc(line);
241
+ });
242
+ const body = rest.join('\n\n');
243
+ return lines.join('\n') + (rest.length ? '\n\n' + (looksLikeJson(body) ? highlightJson(body) : esc(body)) : '');
244
+ }
245
+
246
+ /**
247
+ * Colours a request snippet. `lexerId` is the format's lexer (bash, javascript, python, csharp,
248
+ * go, java, kotlin, php, ruby, rust, powershell or http). Without one only the JSON body found in
249
+ * the text is coloured, which is how snippets were shown before they had grammars.
250
+ */
251
+ export function highlightSnippet(text, lexerId) {
252
+ const source = String(text);
253
+ if (lexerId === 'http') return highlightHttp(source);
254
+ if (Object.hasOwn(LEXERS, lexerId ?? '')) return tokenize(source, LEXERS[lexerId]);
255
+ const start = source.search(/[{[]\s*\n|[{[]"|[{[]\s*$/m);
256
+ return start < 0 ? esc(source) : esc(source.slice(0, start)) + highlightJson(source.slice(start));
257
+ }
@@ -0,0 +1,24 @@
1
+ // History (mock 35): every Preview and Send of this session with its inputs, kept in this
2
+ // browser only. A row replays the request into its operation without running it.
3
+ import { esc, icon, method, stateBlock } from './components.js';
4
+ import { formatTime, t } from './i18n.js';
5
+ import { shortcutHint } from './shortcuts.js';
6
+ import { closePopover, openPopoverAt } from './popover.js';
7
+
8
+ export function openHistory(anchor, { state, replay }) {
9
+ const rows = state.history;
10
+ const list = rows.length ? `<div class="pop-group" role="list">${rows.map((entry, index) => `
11
+ <button type="button" class="opt-row" role="listitem" data-history="${index}" style="inline-size:100%;border:0;background:none;text-align:start;font:inherit">
12
+ ${method(entry.op.method)}<span class="stack"><span class="main" lang="en">${esc(entry.op.title)}</span><span class="sub">${esc(t(entry.preview ? 'res.preview' : 'res.sent'))} · <bdi class="ltr">${esc(entry.status ?? '')}</bdi> · ${esc(formatTime(entry.when))}</span></span>
13
+ <span class="end">${icon('history', true)}${esc(t('history.replay'))}</span>
14
+ </button>`).join('')}</div>`
15
+ : stateBlock({ glyph: 'history', compact: true, title: esc(t('history.emptyTitle')), body: esc(t('history.emptyBody')), why: esc(t('history.local')) });
16
+ const pop = openPopoverAt(anchor, `<div class="pop hist-pop" role="dialog" aria-labelledby="history-title">
17
+ <div class="pop-head"><span id="history-title">${esc(t('shell.history'))}</span><span class="spacer"></span>${shortcutHint('history')}</div>${list}</div>`, { align: 'end', kind: 'history' });
18
+ pop.addEventListener('click', event => {
19
+ const row = event.target.closest('[data-history]');
20
+ if (!row) return;
21
+ closePopover();
22
+ replay(rows[Number(row.dataset.history)]);
23
+ });
24
+ }