@parcha/agentrun-serve 0.1.0-beta.55 → 0.1.0-beta.57

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 (296) hide show
  1. package/CHANGELOG.md +261 -0
  2. package/README.md +228 -45
  3. package/dist/acp-package.d.ts +2 -0
  4. package/dist/adapters.d.ts +18 -5
  5. package/dist/adapters.js +23 -9
  6. package/dist/agent-package.d.ts +3 -3
  7. package/dist/agent-package.js +17 -8
  8. package/dist/answer-json.d.ts +6 -2
  9. package/dist/answer-json.js +22 -4
  10. package/dist/api-keys.d.ts +76 -0
  11. package/dist/api-keys.js +217 -0
  12. package/dist/api-only.d.ts +17 -5
  13. package/dist/api-only.js +36 -8
  14. package/dist/browser-hold.d.ts +23 -0
  15. package/dist/browser-hold.js +48 -0
  16. package/dist/browser-person.d.ts +3 -0
  17. package/dist/browser-person.js +4 -1
  18. package/dist/calendar/tools.js +3 -2
  19. package/dist/chatgpt-plan.d.ts +28 -3
  20. package/dist/chatgpt-plan.js +182 -21
  21. package/dist/claude-login.d.ts +101 -14
  22. package/dist/claude-login.js +232 -49
  23. package/dist/claude-sign-in.d.ts +46 -0
  24. package/dist/claude-sign-in.js +93 -0
  25. package/dist/cli.js +63 -6
  26. package/dist/composio-made.d.ts +4 -0
  27. package/dist/composio-made.js +4 -0
  28. package/dist/composio-preset.d.ts +43 -2
  29. package/dist/composio-preset.js +92 -4
  30. package/dist/computer-held-routes.d.ts +5 -4
  31. package/dist/computer-held-routes.js +29 -8
  32. package/dist/computer-held.d.ts +6 -1
  33. package/dist/computer-held.js +14 -0
  34. package/dist/computer-record.js +4 -2
  35. package/dist/computer-viewer.js +4 -1
  36. package/dist/console/assets/{backend-D5EmB4N3.js → backend-DVhHzJX2.js} +19 -19
  37. package/dist/console/assets/index-Bwn1oTem.css +1 -0
  38. package/dist/console/assets/index-okP-y8PK.js +747 -0
  39. package/dist/console/index.html +2 -2
  40. package/dist/decisions.d.ts +1 -1
  41. package/dist/decisions.js +1 -1
  42. package/dist/docker-host-addresses.d.ts +22 -11
  43. package/dist/docker-host-addresses.js +38 -26
  44. package/dist/env-switch.d.ts +10 -0
  45. package/dist/env-switch.js +33 -2
  46. package/dist/errors.d.ts +1 -0
  47. package/dist/errors.js +2 -0
  48. package/dist/fal-price.d.ts +58 -20
  49. package/dist/fal-price.js +341 -82
  50. package/dist/handed-values.d.ts +43 -1
  51. package/dist/handed-values.js +119 -2
  52. package/dist/harness-archive.d.ts +13 -10
  53. package/dist/harness-archive.js +60 -34
  54. package/dist/harness-check.d.ts +3 -1
  55. package/dist/harness-check.js +25 -46
  56. package/dist/harness-keys.d.ts +73 -27
  57. package/dist/harness-keys.js +194 -61
  58. package/dist/harness-recipe-entry.d.ts +8 -7
  59. package/dist/harness-recipe-entry.js +21 -32
  60. package/dist/harness-recipe.d.ts +38 -25
  61. package/dist/harness-recipe.js +49 -36
  62. package/dist/harness-sign-in.js +12 -23
  63. package/dist/harness-table.d.ts +10 -3
  64. package/dist/harness-table.js +26 -21
  65. package/dist/harness.d.ts +1 -0
  66. package/dist/harness.js +17 -5
  67. package/dist/host-check.d.ts +4 -0
  68. package/dist/host-check.js +4 -0
  69. package/dist/hosted-search.d.ts +1 -1
  70. package/dist/hosted-search.js +1 -2
  71. package/dist/import-worker.d.ts +4 -2
  72. package/dist/import-worker.js +9 -2
  73. package/dist/in-flight.d.ts +26 -0
  74. package/dist/in-flight.js +52 -0
  75. package/dist/key-refusal.d.ts +26 -5
  76. package/dist/key-refusal.js +313 -37
  77. package/dist/learn/secrets.d.ts +31 -11
  78. package/dist/learn/secrets.js +152 -191
  79. package/dist/learning-cost.d.ts +6 -3
  80. package/dist/learning-cost.js +4 -2
  81. package/dist/link-check.js +1 -1
  82. package/dist/llms.txt +2 -2
  83. package/dist/marketplace.d.ts +77 -0
  84. package/dist/marketplace.js +224 -0
  85. package/dist/mcp-api-only-origins.d.ts +30 -0
  86. package/dist/mcp-api-only-origins.js +57 -0
  87. package/dist/mcp-gateway.d.ts +7 -5
  88. package/dist/mcp-gateway.js +9 -12
  89. package/dist/mcp-secret-writes.js +5 -3
  90. package/dist/mcp-servers-store.d.ts +28 -6
  91. package/dist/mcp-servers-store.js +53 -4
  92. package/dist/media-duration.d.ts +3 -0
  93. package/dist/media-duration.js +90 -9
  94. package/dist/model-form.d.ts +5 -4
  95. package/dist/model-form.js +11 -7
  96. package/dist/model.d.ts +5 -2
  97. package/dist/model.js +9 -5
  98. package/dist/ollama-provider.d.ts +7 -1
  99. package/dist/ollama-provider.js +14 -2
  100. package/dist/openapi.d.ts +3 -3
  101. package/dist/openapi.js +245 -42
  102. package/dist/otel/genai.d.ts +65 -0
  103. package/dist/otel/genai.js +116 -0
  104. package/dist/otel/tracer.d.ts +55 -0
  105. package/dist/otel/tracer.js +308 -0
  106. package/dist/page.d.ts +2 -0
  107. package/dist/page.js +3 -1
  108. package/dist/paid-calls.d.ts +1 -32
  109. package/dist/paid-calls.js +4 -39
  110. package/dist/place-offers.d.ts +14 -6
  111. package/dist/place-offers.js +26 -13
  112. package/dist/provider.d.ts +9 -0
  113. package/dist/provider.js +50 -3
  114. package/dist/redact/match.d.ts +101 -0
  115. package/dist/redact/match.js +1152 -0
  116. package/dist/refusal-words.d.ts +11 -0
  117. package/dist/refusal-words.js +11 -0
  118. package/dist/run-census.d.ts +67 -0
  119. package/dist/run-census.js +240 -0
  120. package/dist/run-computer.d.ts +6 -3
  121. package/dist/run-computer.js +4 -1
  122. package/dist/run-cut.d.ts +15 -6
  123. package/dist/run-cut.js +30 -9
  124. package/dist/run-files.d.ts +3 -0
  125. package/dist/run-files.js +3 -0
  126. package/dist/run-launch.d.ts +12 -1
  127. package/dist/run-launch.js +9 -10
  128. package/dist/run-learning-served.d.ts +2 -0
  129. package/dist/run-model-key.d.ts +8 -0
  130. package/dist/run-model-key.js +31 -1
  131. package/dist/run-reads-over-store.d.ts +24 -6
  132. package/dist/run-reads-over-store.js +67 -23
  133. package/dist/run-recordings.d.ts +5 -1
  134. package/dist/run-recordings.js +39 -14
  135. package/dist/run-timeline-served.d.ts +3 -1
  136. package/dist/run-timeline-served.js +4 -4
  137. package/dist/run-usage.d.ts +1 -0
  138. package/dist/runnable.d.ts +10 -1
  139. package/dist/runnable.js +20 -8
  140. package/dist/runner/adapter-loop.d.ts +14 -0
  141. package/dist/runner/adapter-loop.js +56 -11
  142. package/dist/runner/adapter-run-spec.d.ts +45 -8
  143. package/dist/runner/adapter-run-spec.js +154 -29
  144. package/dist/runner/adapters/pi.js +25 -3
  145. package/dist/runner/beside.js +11 -6
  146. package/dist/runner/big-writes.js +1 -10
  147. package/dist/runner/claim-secrets.d.ts +18 -3
  148. package/dist/runner/claim-secrets.js +35 -6
  149. package/dist/runner/cli-run-spec.d.ts +6 -0
  150. package/dist/runner/cli-run-spec.js +85 -36
  151. package/dist/runner/computer-journal.d.ts +9 -1
  152. package/dist/runner/computer-journal.js +26 -0
  153. package/dist/runner/conformance/harness.js +1 -1
  154. package/dist/runner/feedback-round.js +3 -0
  155. package/dist/runner/harness-loops.d.ts +6 -5
  156. package/dist/runner/harness-loops.js +7 -7
  157. package/dist/runner/held.d.ts +11 -5
  158. package/dist/runner/journal-kinds.d.ts +5 -0
  159. package/dist/runner/journal-kinds.js +5 -0
  160. package/dist/runner/loop-contract.d.ts +4 -0
  161. package/dist/runner/main.js +15 -6
  162. package/dist/runner/mcp-claim.js +30 -3
  163. package/dist/runner/mcp-run.d.ts +12 -0
  164. package/dist/runner/mcp-run.js +12 -5
  165. package/dist/runner/model-route.d.ts +17 -0
  166. package/dist/runner/model-route.js +120 -2
  167. package/dist/runner/presence.d.ts +4 -3
  168. package/dist/runner/presence.js +4 -2
  169. package/dist/runner/run-child-host.d.ts +5 -0
  170. package/dist/runner/run-child-host.js +71 -30
  171. package/dist/runner/run-child.js +5 -2
  172. package/dist/runner/runner.d.ts +18 -3
  173. package/dist/runner/runner.js +162 -36
  174. package/dist/runner/store-port.d.ts +1 -1
  175. package/dist/runner/store-secrets.d.ts +6 -0
  176. package/dist/runner/store-secrets.js +49 -7
  177. package/dist/runner/subagent.js +4 -40
  178. package/dist/runner/workflow-first.d.ts +11 -4
  179. package/dist/runner/workflow-first.js +14 -8
  180. package/dist/runner/workflow-spec.js +3 -2
  181. package/dist/runs-over-store.d.ts +15 -6
  182. package/dist/runs-over-store.js +33 -21
  183. package/dist/scrub-command.d.ts +73 -0
  184. package/dist/scrub-command.js +307 -0
  185. package/dist/secret-cut.d.ts +73 -0
  186. package/dist/secret-cut.js +291 -4
  187. package/dist/secret-rules.d.ts +143 -0
  188. package/dist/secret-rules.js +2564 -0
  189. package/dist/secrets.d.ts +7 -0
  190. package/dist/secrets.js +20 -0
  191. package/dist/server-keys.d.ts +20 -0
  192. package/dist/server-keys.js +25 -6
  193. package/dist/server.d.ts +57 -13
  194. package/dist/server.js +371 -113
  195. package/dist/skills/agentrun-serve/SKILL.md +4 -0
  196. package/dist/store/dialect.d.ts +3 -0
  197. package/dist/store/dialect.js +1 -0
  198. package/dist/store/index.d.ts +1 -1
  199. package/dist/store/index.js +1 -1
  200. package/dist/store/journal/storage.js +1 -1
  201. package/dist/store/postgres/dialect.js +3 -0
  202. package/dist/store/postgres/migrations/0027_run_launch_census.sql +31 -0
  203. package/dist/store/schema.d.ts +6 -0
  204. package/dist/store/schema.js +11 -1
  205. package/dist/store/seal.d.ts +6 -1
  206. package/dist/store/seal.js +5 -3
  207. package/dist/store/sqlite/run-launch.d.ts +9 -1
  208. package/dist/store/sqlite/run-launch.js +24 -13
  209. package/dist/store/sqlite/run-patch.d.ts +1 -1
  210. package/dist/store/sqlite/run-patch.js +13 -4
  211. package/dist/store/sqlite/store.js +76 -16
  212. package/dist/store/store.d.ts +53 -3
  213. package/dist/store/store.js +27 -0
  214. package/dist/store-reads/learning.d.ts +6 -3
  215. package/dist/store-reads/learning.js +22 -7
  216. package/dist/store-view.d.ts +3 -0
  217. package/dist/store-view.js +4 -4
  218. package/dist/suggestions.js +3 -2
  219. package/dist/template-eval.d.ts +22 -11
  220. package/dist/template-eval.js +124 -41
  221. package/dist/template-import.d.ts +10 -0
  222. package/dist/template-import.js +16 -7
  223. package/dist/templates.d.ts +10 -2
  224. package/dist/templates.js +28 -8
  225. package/dist/timeline/index.d.ts +1 -1
  226. package/dist/timeline/index.js +1 -1
  227. package/dist/timeline/labels.d.ts +6 -4
  228. package/dist/timeline/labels.js +18 -6
  229. package/dist/timeline/timeline.d.ts +17 -7
  230. package/dist/timeline/timeline.js +28 -14
  231. package/dist/timeline/util.js +1 -1
  232. package/dist/timeline/web-calls.d.ts +26 -9
  233. package/dist/timeline/web-calls.js +124 -37
  234. package/dist/tool-gate.d.ts +42 -3
  235. package/dist/tool-gate.js +69 -6
  236. package/dist/tool-keys-store.d.ts +2 -4
  237. package/dist/tool-keys-store.js +5 -21
  238. package/dist/tool-keys.d.ts +2 -2
  239. package/dist/tool-keys.js +2 -2
  240. package/dist/tool-list.js +1 -1
  241. package/dist/tool-plane.d.ts +2 -2
  242. package/dist/tool-plane.js +35 -33
  243. package/dist/tools.js +13 -7
  244. package/dist/trigger-targets.d.ts +4 -0
  245. package/dist/trigger-targets.js +9 -2
  246. package/dist/triggers.d.ts +67 -4
  247. package/dist/triggers.js +171 -22
  248. package/dist/until.d.ts +3 -0
  249. package/dist/until.js +11 -0
  250. package/dist/validate.js +1 -1
  251. package/dist/web-fake.d.ts +1 -3
  252. package/dist/web-fake.js +7 -18
  253. package/dist/web-fetch.d.ts +6 -72
  254. package/dist/web-fetch.js +11 -265
  255. package/dist/web-run.d.ts +31 -0
  256. package/dist/web-run.js +90 -0
  257. package/dist/web-save.d.ts +6 -4
  258. package/dist/web-save.js +9 -12
  259. package/dist/web-search.d.ts +9 -127
  260. package/dist/web-search.js +23 -259
  261. package/dist/wires.d.ts +13 -0
  262. package/dist/wires.js +11 -0
  263. package/dist/workflow-run.d.ts +5 -4
  264. package/dist/workflow-run.js +5 -4
  265. package/dist/workspace/computer-deps.d.ts +3 -1
  266. package/dist/workspace/computer-deps.js +12 -4
  267. package/dist/workspace/computer-for-claim.d.ts +19 -2
  268. package/dist/workspace/computer-for-claim.js +101 -13
  269. package/dist/workspace/computer-janitor.d.ts +15 -7
  270. package/dist/workspace/computer-janitor.js +33 -8
  271. package/dist/workspace/computer-kept.d.ts +55 -4
  272. package/dist/workspace/computer-kept.js +129 -8
  273. package/dist/workspace/index.d.ts +1 -1
  274. package/dist/workspace/index.js +1 -1
  275. package/dist/workspace/kind-skills.d.ts +4 -0
  276. package/dist/workspace/kind-skills.js +9 -0
  277. package/dist/workspace/run-end-computers.d.ts +5 -1
  278. package/dist/workspace/run-end-computers.js +27 -1
  279. package/dist/workspace/synced-folder.js +3 -4
  280. package/dist/wrapped.d.ts +65 -0
  281. package/dist/wrapped.js +77 -0
  282. package/package.json +17 -11
  283. package/skills/agentrun-serve/SKILL.md +4 -0
  284. package/templates/README.md +38 -15
  285. package/dist/console/assets/index-DUYLaqiR.js +0 -746
  286. package/dist/console/assets/index-DYhU4adm.css +0 -1
  287. package/dist/exa-keyless.d.ts +0 -34
  288. package/dist/exa-keyless.js +0 -118
  289. package/dist/firecrawl-keyless.d.ts +0 -41
  290. package/dist/firecrawl-keyless.js +0 -152
  291. package/dist/keyless-mcp.d.ts +0 -36
  292. package/dist/keyless-mcp.js +0 -127
  293. package/dist/text-urls.d.ts +0 -38
  294. package/dist/text-urls.js +0 -170
  295. package/dist/web-fetch-direct.d.ts +0 -119
  296. package/dist/web-fetch-direct.js +0 -190
@@ -0,0 +1,1152 @@
1
+ // The one matcher served text is redacted with (learn/secrets.ts redactSecrets and redactLearned run on it): the secret
2
+ // and bank shapes as scanners, the held values' forms found as they stand, and the whole-text check over the views a
3
+ // value can hide in (whitespace gone, NFKC, percent-decoded, folded). Nothing here reads attacker text with a
4
+ // backtracking regex: each shape is a prefix found with indexOf, then runs of a character class read forward, and a
5
+ // start inside a run already read is not read again. So a text costs time in proportion to its length, whatever it
6
+ // repeats. The few bank shapes that stay regexes are tried only at their words, each reading a bounded head and one
7
+ // run of digits.
8
+ //
9
+ // The whole-text check reads the text as it came, never the text after its cut: a cut can hide part of a held value
10
+ // (a credential parameter's value cut in place, the rest of the held value past a line break), and the rest would then
11
+ // read as no value at all. A held value found in a view is cut only when every character the view read of it comes
12
+ // from text a cut covers; otherwise the text is withheld whole.
13
+ /** The characters the redaction pipeline has visited in this process: the text each prefix search passes over, each
14
+ * run read, each guard read back (the shape scanners); each form, hex, folded and plain needle's search, and the text
15
+ * it passes over (find); each view built (its special characters found, its blanks, its decoders' reads, its non-ASCII
16
+ * stretches squeezed, each cut its cover passes), lowered and flattened; each covered stretch a find in a view is
17
+ * checked against (inside); the finds merged and the text cut; and
18
+ * key-refusal.ts's reads of a text in pieces. A test sets it to 0, redacts, and reads it: a stage that read again from
19
+ * the start at each find would count the text once per find. */
20
+ export const scanned = { chars: 0 };
21
+ // ---- Character classes, as the regexes they replace wrote them.
22
+ /** JavaScript's \s. */
23
+ function isSpace(code) {
24
+ if (code < 128)
25
+ return code === 32 || (code >= 9 && code <= 13);
26
+ return code === 0xa0 || code === 0x1680 || (code >= 0x2000 && code <= 0x200a) || code === 0x2028 || code === 0x2029 || code === 0x202f || code === 0x205f || code === 0x3000 || code === 0xfeff;
27
+ }
28
+ const UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
29
+ const LOWER = "abcdefghijklmnopqrstuvwxyz";
30
+ const DIGIT = "0123456789";
31
+ const ALNUM = UPPER + LOWER + DIGIT;
32
+ const tableOf = (chars) => {
33
+ const table = new Uint8Array(128);
34
+ for (const char of chars)
35
+ table[char.charCodeAt(0)] = 1;
36
+ return table;
37
+ };
38
+ /** The ASCII characters `chars`. */
39
+ const only = (chars) => {
40
+ const table = tableOf(chars);
41
+ return (code) => code < 128 && table[code] === 1;
42
+ };
43
+ /** Any character but whitespace and `chars`. */
44
+ const allBut = (chars) => {
45
+ const table = tableOf(chars);
46
+ return (code) => (code < 128 ? table[code] === 0 : true) && !isSpace(code);
47
+ };
48
+ const WORD = only(`${ALNUM}_`);
49
+ const ALNUM_CLASS = only(ALNUM);
50
+ const PART = only(`${ALNUM}_-`);
51
+ const isDigit = (code) => code >= 48 && code <= 57;
52
+ // ---- Reading.
53
+ /** Where the run of `cls` starting at `from` ends. */
54
+ function run(text, from, cls) {
55
+ let at = from;
56
+ while (at < text.length && cls(text.charCodeAt(at)))
57
+ at++;
58
+ scanned.chars += at - from + 1;
59
+ return at;
60
+ }
61
+ /** Whether `count` characters of `cls` start at `from`. */
62
+ function fixed(text, from, count, cls) {
63
+ let at = from;
64
+ while (at < text.length && at - from < count && cls(text.charCodeAt(at)))
65
+ at++;
66
+ scanned.chars += at - from + 1;
67
+ return at - from === count;
68
+ }
69
+ /** The next place `prefix` stands in `hay` at or after `from`. */
70
+ function seek(hay, prefix, from) {
71
+ const at = hay.indexOf(prefix, from);
72
+ scanned.chars += (at < 0 ? hay.length : at + prefix.length) - from;
73
+ return at < 0 ? Number.POSITIVE_INFINITY : at;
74
+ }
75
+ /** Where `needle` next stands in `hay` at or after `from`, or -1: a needle's search, counted as seek counts a prefix's. */
76
+ function find(hay, needle, from) {
77
+ const at = hay.indexOf(needle, from);
78
+ scanned.chars += Math.max(0, (at < 0 ? hay.length : at + needle.length) - from);
79
+ return at;
80
+ }
81
+ /** `text` with A-Z lowered and nothing else changed, so each offset is the same in both. */
82
+ export const asciiLower = (text) => text.replace(/[A-Z]+/g, (upper) => upper.toLowerCase());
83
+ const none = (next) => ({ start: -1, end: -1, next });
84
+ /** A prefix, then a run of `cls` of at least `min` characters to the end of that run. */
85
+ const prefixRun = (kind, prefixes, cls, min, guard) => ({
86
+ kind,
87
+ prefixes,
88
+ scan(text, at, prefix) {
89
+ if (guard && !guard(text, at))
90
+ return none(at + 1);
91
+ const from = at + prefix.length;
92
+ const end = run(text, from, cls);
93
+ const next = end - (prefix.length - 1);
94
+ return end - from >= min ? { start: at, end, next } : none(next);
95
+ },
96
+ });
97
+ /** A prefix, then exactly `count` characters of `cls`. */
98
+ const prefixFixed = (kind, prefixes, cls, count) => ({
99
+ kind,
100
+ prefixes,
101
+ scan: (text, at, prefix) => (fixed(text, at + prefix.length, count, cls) ? { start: at, end: at + prefix.length + count, next: at + 1 } : none(at + 1)),
102
+ });
103
+ const PRIVATE_KEY_TYPE = only(` ${UPPER}${DIGIT}`);
104
+ /** Where a private key block's armor line at `at` ends, past its closing "-----", or -1. Its opening ("-----BEGIN" or
105
+ * "-----END", `head` characters) is already read; then its key type (RSA, EC, OPENSSH, ENCRYPTED, an armored key's
106
+ * "PGP ... BLOCK"), at most 64 characters each side of "PRIVATE KEY", then "-----". It reads at most 140 characters,
107
+ * and 11 at each place "PRIVATE KEY" may stand. */
108
+ function armorEnd(text, at, head) {
109
+ const from = at + head;
110
+ let end = from;
111
+ while (end < text.length && end - from < 140 && PRIVATE_KEY_TYPE(text.charCodeAt(end)))
112
+ end++;
113
+ scanned.chars += end - from + 1;
114
+ const length = end - from;
115
+ if (length >= 140 || !text.startsWith("-----", end))
116
+ return -1;
117
+ for (let i = Math.max(0, length - 75); i <= Math.min(64, length - 11); i++) {
118
+ scanned.chars += 11;
119
+ if (text.startsWith("PRIVATE KEY", from + i))
120
+ return end + 5;
121
+ }
122
+ return -1;
123
+ }
124
+ /** The most characters between a key's header and its END line, and the most base64 characters on a body line. */
125
+ const KEY_BODY_MAX = 16384;
126
+ /** The most lines of a key's body read when no END line is in reach. */
127
+ const KEY_LINES = 1024;
128
+ /** The most characters of a legacy PEM's or armored key's header line after its colon. */
129
+ const KEY_HEADER_MAX = 256;
130
+ const KEY_BASE64 = only(`${ALNUM}+=`);
131
+ /** A header line's text: any character but a line break, a backslash, a quote or a "<". */
132
+ const KEY_HEADER_TEXT = (code) => code !== 10 && code !== 13 && code !== 92 && code !== 34 && code !== 39 && code !== 60;
133
+ const KEY_HEADER_WORDS = ["Proc-Type:", "DEK-Info:", "Version:", "Comment:"];
134
+ /** How many backslashes stand at `at`, at most 9 read: an escape takes 1 to 8 (a string four deep); 9 is too many. */
135
+ function backslashes(text, at) {
136
+ let end = at;
137
+ while (end < text.length && end - at < 9 && text.charCodeAt(end) === 92)
138
+ end++;
139
+ scanned.chars += end - at + 1;
140
+ return end - at;
141
+ }
142
+ /** Where an escape at `at` of one of `chars`, after 1 to 8 backslashes, ends, or -1. */
143
+ function escapeEnd(text, at, chars) {
144
+ const count = backslashes(text, at);
145
+ const ok = count >= 1 && count <= 8 && at + count < text.length && chars.includes(text[at + count]);
146
+ return ok ? at + count + 1 : -1;
147
+ }
148
+ /** Where each spelling of a line break at `at` ends, in the order the key's reading tries them: CRLF, then CR alone;
149
+ * LF; an escaped CR followed by an escaped LF, then the CR alone; an escaped LF. */
150
+ function keyBreaks(text, at) {
151
+ if (at >= text.length)
152
+ return [];
153
+ scanned.chars += 2;
154
+ const code = text.charCodeAt(at);
155
+ if (code === 13)
156
+ return text.charCodeAt(at + 1) === 10 ? [at + 2, at + 1] : [at + 1];
157
+ if (code === 10)
158
+ return [at + 1];
159
+ if (code !== 92)
160
+ return [];
161
+ const count = backslashes(text, at);
162
+ if (count > 8)
163
+ return [];
164
+ const after = text[at + count];
165
+ if (after === "n")
166
+ return [at + count + 1];
167
+ if (after !== "r")
168
+ return [];
169
+ const lf = escapeEnd(text, at + count + 1, "n");
170
+ return lf >= 0 ? [lf, at + count + 1] : [at + count + 1];
171
+ }
172
+ /** Where the blanks at `at` end: spaces, tabs and escaped tabs. */
173
+ function keyBlanks(text, at) {
174
+ let end = at;
175
+ for (;;) {
176
+ const code = text.charCodeAt(end);
177
+ scanned.chars += 1;
178
+ if (code === 32 || code === 9)
179
+ end++;
180
+ else if (code !== 92)
181
+ return end;
182
+ else {
183
+ const tab = escapeEnd(text, end, "t");
184
+ if (tab < 0)
185
+ return end;
186
+ end = tab;
187
+ }
188
+ }
189
+ }
190
+ /** Where the base64 at `at` ends: at most KEY_BODY_MAX of its characters, each a letter, a digit, "+", "=" or a "/"
191
+ * (maybe escaped, "\/"). */
192
+ function keyBase64(text, at) {
193
+ let end = at;
194
+ for (let count = 0; count < KEY_BODY_MAX; count++) {
195
+ const code = text.charCodeAt(end);
196
+ scanned.chars += 1;
197
+ if (KEY_BASE64(code) || code === 47)
198
+ end++;
199
+ else if (code !== 92)
200
+ return end;
201
+ else {
202
+ const slash = escapeEnd(text, end, "/");
203
+ if (slash < 0)
204
+ return end;
205
+ end = slash;
206
+ }
207
+ }
208
+ return end;
209
+ }
210
+ /** Where a legacy PEM's or armored key's header line at `at` ends ("Proc-Type:", "DEK-Info:", "Version:" or "Comment:",
211
+ * then at most KEY_HEADER_MAX characters of its text), or -1. */
212
+ function keyHeaderLine(text, at) {
213
+ for (const word of KEY_HEADER_WORDS) {
214
+ scanned.chars += word.length;
215
+ if (!text.startsWith(word, at))
216
+ continue;
217
+ const from = at + word.length;
218
+ let end = from;
219
+ while (end < text.length && end - from < KEY_HEADER_MAX && KEY_HEADER_TEXT(text.charCodeAt(end)))
220
+ end++;
221
+ scanned.chars += end - from + 1;
222
+ return end;
223
+ }
224
+ return -1;
225
+ }
226
+ /** Whether a body line may end at `at`: a line break or a closing quote (either maybe escaped), a tag's "<", the text's
227
+ * end. */
228
+ function keyLineEnds(text, at) {
229
+ if (at >= text.length)
230
+ return true;
231
+ scanned.chars += 1;
232
+ const code = text.charCodeAt(at);
233
+ if (code === 10 || code === 13 || code === 34 || code === 39 || code === 60)
234
+ return true;
235
+ return code === 92 && escapeEnd(text, at, `rn"'`) >= 0;
236
+ }
237
+ /** Where a body line at `at` ends, or -1: blanks, then base64, or a header line, or nothing, then blanks, at a place a
238
+ * line may end. Each is tried in that order and the first that ends at such a place is the line. */
239
+ function keyLine(text, at) {
240
+ const start = keyBlanks(text, at);
241
+ const base64 = keyBase64(text, start);
242
+ if (base64 > start) {
243
+ const end = keyBlanks(text, base64);
244
+ if (keyLineEnds(text, end))
245
+ return end;
246
+ }
247
+ const header = keyHeaderLine(text, start);
248
+ if (header >= 0) {
249
+ const end = keyBlanks(text, header);
250
+ if (keyLineEnds(text, end))
251
+ return end;
252
+ }
253
+ return keyLineEnds(text, start) ? start : -1;
254
+ }
255
+ /** Where a line break at `at` and the body line after it end, the break's spellings tried in order, or -1. */
256
+ function keyNextLine(text, at) {
257
+ for (const start of keyBreaks(text, at)) {
258
+ const end = keyLine(text, start);
259
+ if (end >= 0)
260
+ return end;
261
+ }
262
+ return -1;
263
+ }
264
+ /** Where the END line of a block whose header ends at `header` ends, or -1: the first "-----" after the header, at most
265
+ * KEY_BODY_MAX characters on, must start one. The search stops at that "-----", so a reading from one header never
266
+ * passes the next header's dashes. */
267
+ function keyEndLine(text, header) {
268
+ const dashes = find(text, "-----", header);
269
+ if (dashes < 0 || dashes - header > KEY_BODY_MAX)
270
+ return -1;
271
+ scanned.chars += 3;
272
+ return text.startsWith("-----END", dashes) ? armorEnd(text, dashes, 8) : -1;
273
+ }
274
+ /** Where the body lines after a header that ends at `header` end, or -1 when not even an empty line stands there: a
275
+ * first line (after a line break, or glued to the header), then at most KEY_LINES - 1 more, each after a line break,
276
+ * as long as one follows. */
277
+ function keyBodyLines(text, header) {
278
+ let end = keyNextLine(text, header);
279
+ if (end < 0)
280
+ end = keyLine(text, header);
281
+ for (let lines = 1; end >= 0 && lines < KEY_LINES; lines++) {
282
+ const next = keyNextLine(text, end);
283
+ if (next < 0)
284
+ break;
285
+ end = next;
286
+ }
287
+ return end;
288
+ }
289
+ /** A private key block, whole: its BEGIN line through its body to its END line, the key itself, not its header alone (a
290
+ * cut read serves a run's whole file). Ported from #3617's rule, one regex there, read here by hand with every
291
+ * character counted.
292
+ * - With its END line within KEY_BODY_MAX characters, all between is cut, whatever wraps the body's lines (a code
293
+ * string literal on each, a "#" or ">" before each, an XML or HTML line break, an escape, an armored key's headers):
294
+ * the body is any character but a "-" that starts "-----", so the END line can only start at the first "-----"
295
+ * after the header, and the reading from one header stops there.
296
+ * - With no END line in reach (a key cut short, one past the bound, one the edge of a window key-refusal.ts reads
297
+ * crosses), it is cut through its body's lines: the first maybe glued to its header, at most KEY_LINES in all. A
298
+ * line break is LF, CRLF or CR, or one escaped in a quoted string ("\n", "\r\n", "\\n" in a string within a string:
299
+ * at most 8 backslashes, four strings deep). A line is blanks (a space, a tab, or an escaped tab), then base64 of at
300
+ * most KEY_BODY_MAX characters (its slashes maybe escaped, "\/"), or a legacy PEM's or armored key's header
301
+ * (Proc-Type, DEK-Info, Version, Comment) of at most KEY_HEADER_MAX after its colon, or nothing (a blank line), then
302
+ * blanks; it ends at a line break or a closing quote (either maybe escaped), an XML or HTML tag's "<", or the text's
303
+ * end. Text after the body that is no such line (prose, a field) stays.
304
+ * - A header with not even an empty line after it (prose on its line, another header glued to it) is cut alone, as
305
+ * the header shape before this one cut it.
306
+ * A block read whole or through its lines reads on from its end: a "-----BEGIN" inside it can only stand in a header
307
+ * line's text, already cut. Each part is bounded, a line break's spellings try the line after it at most three times,
308
+ * and the search for the END line stops at the next "-----": the reading stays linear. */
309
+ const PRIVATE_KEY = {
310
+ kind: "private key block",
311
+ prefixes: ["-----BEGIN"],
312
+ scan(text, at) {
313
+ const header = armorEnd(text, at, 10);
314
+ if (header < 0)
315
+ return none(at + 1);
316
+ const whole = keyEndLine(text, header);
317
+ if (whole >= 0)
318
+ return { start: at, end: whole, next: whole };
319
+ const lines = keyBodyLines(text, header);
320
+ return lines >= 0 ? { start: at, end: lines, next: lines } : { start: at, end: header, next: at + 1 };
321
+ },
322
+ };
323
+ /** Where the private key block whose "-----BEGIN" stands at `at` ends, past its END line, or -1: no key's header there,
324
+ * or no END line in reach, as PRIVATE_KEY reads it whole. key-refusal.ts reads it so that no piece of an answer ends
325
+ * inside a block. Whether any "-----" stands within KEY_BODY_MAX of the header is read back from there first (the
326
+ * header's own closing dashes stop that read), so a header with none after it reads no further. */
327
+ export function privateKeyEnd(text, at) {
328
+ if (!text.startsWith("-----BEGIN", at))
329
+ return -1;
330
+ const header = armorEnd(text, at, 10);
331
+ if (header < 0)
332
+ return -1;
333
+ const reach = Math.min(text.length, header + KEY_BODY_MAX);
334
+ const last = text.lastIndexOf("-----", reach);
335
+ scanned.chars += reach - Math.max(last, header - 5);
336
+ return last < header ? -1 : keyEndLine(text, header);
337
+ }
338
+ /** A JWT: three base64url parts, the first two JSON objects ("eyJ"), each 8 characters or more after it. It starts at
339
+ * the first "eyJ" of a run of a part's characters, wherever that run starts ("token-eyJ…", "x9eyJ…"): a later "eyJ" in
340
+ * the same run reaches the same "." with fewer characters. Whether an "eyJ" is the first is read back to the "eyJ"
341
+ * before it or the run's start, so the reads back add up to one pass. A scan that fails reads on past the part it
342
+ * failed in: a start in an earlier part reads the same parts and fails there too. One that matched reads on from its
343
+ * second part, as a match starting there can run past this one into a fourth. */
344
+ const JWT = {
345
+ kind: "JWT",
346
+ prefixes: ["eyJ"],
347
+ scan(text, at) {
348
+ let back = at - 1;
349
+ while (back >= 0 && PART(text.charCodeAt(back))) {
350
+ if (back >= 2 && text.startsWith("eyJ", back - 2)) {
351
+ scanned.chars += at - back;
352
+ return none(at + 1);
353
+ }
354
+ back--;
355
+ }
356
+ scanned.chars += at - back;
357
+ const first = run(text, at + 3, PART);
358
+ if (first - (at + 3) < 8 || text[first] !== ".")
359
+ return none(first - 2);
360
+ if (!text.startsWith("eyJ", first + 1))
361
+ return none(first + 1);
362
+ const second = run(text, first + 4, PART);
363
+ if (second - (first + 4) < 8 || text[second] !== ".")
364
+ return none(second - 2);
365
+ const third = run(text, second + 1, PART);
366
+ if (third - (second + 1) < 8)
367
+ return none(third - 2);
368
+ return { start: at, end: third, next: first + 1 };
369
+ },
370
+ };
371
+ const WEBHOOK_BODY = only(`${ALNUM}+/`);
372
+ /** A Standard Webhooks signing secret: `whsec_` and base64, this server's or any other's. Its run's class has no "_",
373
+ * so the run can take the next secret's "whsec" and stop at its "_": that secret starts in this run's last characters. */
374
+ const WEBHOOK_SECRET = {
375
+ kind: "webhook signing secret",
376
+ prefixes: ["whsec_"],
377
+ scan(text, at) {
378
+ const from = at + 6;
379
+ const body = run(text, from, WEBHOOK_BODY);
380
+ if (body - from < 24)
381
+ return none(body - 5);
382
+ let end = body;
383
+ while (end < body + 2 && text[end] === "=")
384
+ end++;
385
+ return { start: at, end, next: body - 5 };
386
+ },
387
+ };
388
+ const URL_USER = allBut("/?#@:");
389
+ const URL_PASS = allBut("/?#@");
390
+ const SED_HOST = only(`${ALNUM}._~-`);
391
+ const SED_TARGET = only(`${ALNUM}.-`);
392
+ const isBlank = (char) => char === " " || char === "\t";
393
+ /** Whether the URL password at `at` ("://"), ending at `end`, is the capture pattern of a complete single-quoted sed
394
+ * search expression: `sed -n 's|https://<host or [^:]*>:\([^@]*\)@<host>|\1|p'`, opened at the text's start, after
395
+ * whitespace, ";" or "(". The "@" inside "[^@]" is regex syntax, not a password's end. A bracketed password or a bare
396
+ * URL is never one. Read back from the "://" over the expression's head and forward over its tail, each once. */
397
+ function inSedCapture(text, at, end) {
398
+ let head = text.startsWith("https", at - 5) ? at - 5 : text.startsWith("http", at - 4) ? at - 4 : -1;
399
+ if (head < 0 || !text.startsWith("'s|", head - 3))
400
+ return false;
401
+ head -= 3;
402
+ let blanks = head;
403
+ while (blanks > 0 && isBlank(text[blanks - 1]))
404
+ blanks--;
405
+ if (blanks === head || !text.startsWith("-n", blanks - 2))
406
+ return false;
407
+ const flag = blanks - 2;
408
+ blanks = flag;
409
+ while (blanks > 0 && isBlank(text[blanks - 1]))
410
+ blanks--;
411
+ scanned.chars += at - blanks;
412
+ if (blanks === flag || !text.startsWith("sed", blanks - 3))
413
+ return false;
414
+ const sed = blanks - 3;
415
+ if (sed > 0 && !(isSpace(text.charCodeAt(sed - 1)) || text[sed - 1] === ";" || text[sed - 1] === "("))
416
+ return false;
417
+ let tail = at + 3;
418
+ if (text.startsWith("[^:]*", tail))
419
+ tail += 5;
420
+ else {
421
+ const host = run(text, tail, SED_HOST);
422
+ if (host === tail)
423
+ return false;
424
+ tail = host;
425
+ }
426
+ if (!text.startsWith(":\\([^@]*\\)@", tail))
427
+ return false;
428
+ const target = run(text, tail + 11, SED_TARGET);
429
+ if (target === tail + 11 || !text.startsWith("|\\1|p'", target))
430
+ return false;
431
+ return end <= target + 6;
432
+ }
433
+ /** A URL with a user and password: "://", a user, ":", a password, then "@". An authority that stops at a "/" may stop
434
+ * at the next URL's "://", so a failed scan reads on from two characters before where it stopped. */
435
+ const URL_PASSWORD = {
436
+ kind: "URL with a password",
437
+ prefixes: ["://"],
438
+ scan(text, at) {
439
+ const user = run(text, at + 3, URL_USER);
440
+ if (user === at + 3 || text[user] !== ":")
441
+ return none(user - 2);
442
+ const password = run(text, user + 1, URL_PASS);
443
+ if (text[password] !== "@")
444
+ return none(password - 2);
445
+ return inSedCapture(text, at, password + 1) ? none(password - 2) : { start: at, end: password + 1, next: password - 2 };
446
+ },
447
+ };
448
+ const BEARER_TOKEN_CLASS = only(`${ALNUM}._~+/-`);
449
+ /** The token after a `Bearer` scheme (RFC 6750's characters), in any case: twenty characters or more with a digit among
450
+ * them, so a word after "bearer" ("bearer authentication/authorization"), a placeholder (`<token>`, `$TOKEN`,
451
+ * `YOUR_API_KEY`) and a challenge's parameter (`Bearer realm="x"`) are none. The token alone is the match: the scheme
452
+ * before it stays, so a reader still sees a header was there. The scheme is at most three blanks before the token. A
453
+ * token can hold the word "bearer" and then a blank and another token, so the next scheme is looked for from this
454
+ * token's start: each token is still read once. */
455
+ const BEARER_TOKEN = {
456
+ kind: "bearer token",
457
+ prefixes: ["bearer"],
458
+ ci: true,
459
+ scan(text, at) {
460
+ if (at > 0 && WORD(text.charCodeAt(at - 1)))
461
+ return none(at + 1);
462
+ let token = at + 6;
463
+ while (token < text.length && token - (at + 6) < 4 && isSpace(text.charCodeAt(token)))
464
+ token++;
465
+ scanned.chars += token - at - 5;
466
+ const blanks = token - (at + 6);
467
+ if (blanks < 1 || blanks > 3)
468
+ return none(at + 1);
469
+ let end = token;
470
+ let digit = false;
471
+ for (; end < text.length; end++) {
472
+ const code = text.charCodeAt(end);
473
+ if (!BEARER_TOKEN_CLASS(code))
474
+ break;
475
+ digit ||= isDigit(code);
476
+ }
477
+ scanned.chars += end - token + 1;
478
+ if (end - token < 20 || !digit)
479
+ return none(token);
480
+ const body = end;
481
+ while (end < body + 2 && text[end] === "=")
482
+ end++;
483
+ return { start: token, end, next: token };
484
+ },
485
+ };
486
+ /** Each name a credential parameter goes by, as written after "?" or "&" and lowered; and each key, lowered, of a held
487
+ * JSON value whose string is held as itself (learn/secrets.ts heldFields). */
488
+ export const CREDENTIAL_NAMES = new Set([
489
+ ...["api", "access", "auth", "id", "refresh", "client"].flatMap((head) => {
490
+ const tail = head === "api" ? "key" : head === "client" ? "secret" : "token";
491
+ return [`${head}${tail}`, `${head}_${tail}`, `${head}-${tail}`];
492
+ }),
493
+ "x-amz-signature", "x-amz-security-token", "x-goog-signature", "token", "secret", "password", "passwd", "signature", "sig",
494
+ ]);
495
+ const NAME_CHAR = only(`${UPPER}${LOWER}_-`);
496
+ const URL_VALUE = allBut("&#\"'`<>\\[]");
497
+ /** The value of a URL parameter named like a credential, after `?` or `&`: sixteen characters or more, to the next
498
+ * separator. The name is the whole parameter's (`token`, never `page_token`), and the value alone is the match, so the
499
+ * name stays. A signed URL's signature is one: whoever holds the URL holds what it grants. No bracket is a value's
500
+ * character (a URL writes one percent-encoded), so a value already cut to "[redacted]" is never read as one. A value
501
+ * may hold "?" and "=", so a parameter of the same name inside it ends where it ends: the next start is looked for past
502
+ * it. */
503
+ const URL_CREDENTIAL = {
504
+ kind: "URL parameter named like a credential",
505
+ prefixes: ["?", "&"],
506
+ scan(text, at) {
507
+ let name = at + 1;
508
+ while (name < text.length && name - at <= 21 && NAME_CHAR(text.charCodeAt(name)))
509
+ name++;
510
+ scanned.chars += name - at;
511
+ if (text[name] !== "=" || !CREDENTIAL_NAMES.has(text.slice(at + 1, name).toLowerCase()))
512
+ return none(at + 1);
513
+ const end = run(text, name + 1, URL_VALUE);
514
+ return end - (name + 1) >= 16 ? { start: name + 1, end, next: end } : none(end);
515
+ },
516
+ };
517
+ const isUpper = (code) => code >= 65 && code <= 90;
518
+ /** An API key made in this server's console (api-keys.ts): `ar_key_` and its 32 random bytes in base64url, 43
519
+ * characters or more to the end of that run, so a key glued to more of its characters is cut whole. The server keeps
520
+ * no copy of such a key (only a keyed hash), so its shape is the one way it is found in a text, and it is found
521
+ * whatever stands before it: after a word's character too (the `n` of a line break as JSON text writes it, a name
522
+ * glued to it). What tells a key from a long name that only holds the prefix's letters (`similar_key_for_the_...`) is
523
+ * in the run itself: a capital or a digit, which 32 random bytes all but always hold and a snake_case name does not.
524
+ * A start inside a run already read ends where that run ends and holds no more of it, so it is not read again. */
525
+ const AGENTRUN_API_KEY = {
526
+ kind: "AgentRun API key",
527
+ prefixes: ["ar_key_"],
528
+ scan(text, at, prefix) {
529
+ const from = at + prefix.length;
530
+ let end = from;
531
+ let mixed = false;
532
+ for (; end < text.length; end++) {
533
+ const code = text.charCodeAt(end);
534
+ if (!PART(code))
535
+ break;
536
+ mixed ||= isDigit(code) || isUpper(code);
537
+ }
538
+ scanned.chars += end - from + 1;
539
+ const next = end - (prefix.length - 1);
540
+ return end - from >= 43 && mixed ? { start: at, end, next } : none(next);
541
+ },
542
+ };
543
+ /** Text shaped like a secret, by kind. The same shapes the Pi learning loop's guard refuses. */
544
+ export const SECRET_SHAPES = [
545
+ prefixFixed("AWS access key id", ["AKIA", "ASIA"], only(UPPER + DIGIT), 16),
546
+ prefixFixed("Google API key", ["AIza"], only(`${ALNUM}_-`), 35),
547
+ PRIVATE_KEY,
548
+ prefixRun("GitHub token", ["ghp_", "gho_", "ghu_", "ghs_", "ghr_"], ALNUM_CLASS, 30),
549
+ prefixRun("GitHub token", ["github_pat_"], WORD, 20),
550
+ prefixRun("sk- key", ["sk-"], PART, 20, (text, at) => at === 0 || !ALNUM_CLASS(text.charCodeAt(at - 1))),
551
+ AGENTRUN_API_KEY,
552
+ prefixRun("Slack token", [..."abposre"].map((kind) => `xox${kind}-`).concat("xapp-"), only(`${ALNUM}-`), 10),
553
+ JWT,
554
+ WEBHOOK_SECRET,
555
+ URL_PASSWORD,
556
+ BEARER_TOKEN,
557
+ URL_CREDENTIAL,
558
+ ];
559
+ /** A bank's number beside its word, tried as `pattern` at each of its words only. Each try reads its word's bounded
560
+ * head (`head` characters), and ACCOUNT_NUMBER's digits, single dashes or spaces between them, to their end: what the
561
+ * regex can read from that start. */
562
+ const besideWord = (kind, words, pattern, head, digits = false) => {
563
+ const sticky = new RegExp(pattern.source, "iy");
564
+ return {
565
+ kind,
566
+ prefixes: words,
567
+ ci: true,
568
+ scan(text, at) {
569
+ let reach = Math.min(text.length, at + head);
570
+ if (digits)
571
+ while (reach < text.length && /[\d -]/.test(text[reach]))
572
+ reach++;
573
+ scanned.chars += reach - at + 1;
574
+ sticky.lastIndex = at;
575
+ const match = sticky.exec(text);
576
+ return match ? { start: at, end: at + match[0].length, next: at + 1 } : none(at + 1);
577
+ },
578
+ };
579
+ };
580
+ /** A bank account number beside its word: "account", "acct", "a/c" or "bank account", maybe "number", "no.", "#", ":"
581
+ * or "is" after it, then six digits or more, single dashes or spaces between them. A count before the word ("4
582
+ * accounts"), a date (YYYY-MM-DD), a year or a card's last four is none: the word must come first, the digits right
583
+ * after it, and there must be six. Every gap is at most three whitespace characters. */
584
+ const ACCOUNT_NUMBER = /\b(?:bank\s{1,3})?(?:account|acct|a\/c)(?:\s{1,3}(?:number|no\.?|num))?\s{0,3}(?:#|:|\bis\b)?\s{0,3}(?!\d{4}-\d{2}-\d{2}\b)\d(?:[ -]?\d){5,}/;
585
+ /** An IBAN beside its word: two letters, two check digits, then ten to thirty letters or digits, spaces between. */
586
+ const IBAN = /\bIBAN\s{0,3}(?:#|:|\bis\b)?\s{0,3}[A-Z]{2}\d{2}(?:\s?[A-Z0-9]){10,30}/;
587
+ /** A US routing (ABA) number beside its word: nine digits. The word ends at a word end, so an id or hash whose hex
588
+ * holds "aba" glued to nine digits (a UUID's last group, a sha cut to twelve) is none. The other words hold a letter
589
+ * no hex does, so no id spells them. */
590
+ const ROUTING_NUMBER = /\b(?:routing|ABA)\b(?:\s{1,3}(?:number|no\.?|num))?\s{0,3}(?:#|:|\bis\b)?\s{0,3}\d{9}\b/;
591
+ /** A UK sort code beside its word: three pairs of digits. */
592
+ const SORT_CODE = /\bsort\s{1,3}code\s{0,3}(?:#|:|\bis\b)?\s{0,3}\d{2}[- ]?\d{2}[- ]?\d{2}\b/;
593
+ /** A bank's numbers beside their words, which learning never keeps: an account, IBAN, routing or sort-code number. Not
594
+ * one of SECRET_SHAPES: a run may show its user an account number (a finance job's answer), and those shapes cut every
595
+ * run's view; only what learning keeps refuses them. */
596
+ export const MONEY_SHAPES = [
597
+ besideWord("bank account number", ["bank", "account", "acct", "a/c"], ACCOUNT_NUMBER, 40, true),
598
+ besideWord("IBAN", ["iban"], IBAN, 80),
599
+ besideWord("routing number", ["routing", "aba"], ROUTING_NUMBER, 40),
600
+ besideWord("sort code", ["sort"], SORT_CODE, 40),
601
+ ];
602
+ /** Every span `shape` matches in `text` (only the first with `first`). `lower`: the text lowered (asciiLower), for a
603
+ * shape found in any case. */
604
+ function spansOf(text, lower, shape, first = false) {
605
+ const hay = shape.ci ? lower() : text;
606
+ const { prefixes } = shape;
607
+ const next = prefixes.map(() => -1);
608
+ const out = [];
609
+ for (let from = 0;;) {
610
+ let at = Number.POSITIVE_INFINITY;
611
+ let prefix = "";
612
+ for (let i = 0; i < prefixes.length; i++) {
613
+ if (next[i] < from)
614
+ next[i] = seek(hay, prefixes[i], from);
615
+ if (next[i] < at) {
616
+ at = next[i];
617
+ prefix = prefixes[i];
618
+ }
619
+ }
620
+ if (at === Number.POSITIVE_INFINITY)
621
+ return out;
622
+ const found = shape.scan(text, at, prefix);
623
+ if (found.start >= 0) {
624
+ out.push([found.start, found.end]);
625
+ if (first)
626
+ return out;
627
+ }
628
+ from = Math.max(at + 1, found.next);
629
+ }
630
+ }
631
+ /** A text lowered once, on first use, counted as a read of the text. */
632
+ function lowered(text) {
633
+ let low;
634
+ return () => {
635
+ if (low === undefined) {
636
+ scanned.chars += text.length;
637
+ low = asciiLower(text);
638
+ }
639
+ return low;
640
+ };
641
+ }
642
+ /** Every span `shape` matches in `text`, each on its own (not merged), in order: the scrubber's known-format rules
643
+ * (secret-rules.ts) read each match, a URL's password inside its `://user:password@`, a PEM header stretched to its
644
+ * block's end. */
645
+ export function shapeSpans(text, shape) {
646
+ return spansOf(text, lowered(text), shape);
647
+ }
648
+ /** The kinds of `shapes` in `text`, each once, in their order. */
649
+ export function shapeKinds(text, shapes) {
650
+ const lower = lowered(text);
651
+ const kinds = [];
652
+ for (const shape of shapes)
653
+ if (!kinds.includes(shape.kind) && spansOf(text, lower, shape, true).length > 0)
654
+ kinds.push(shape.kind);
655
+ return kinds;
656
+ }
657
+ /** Adds each place `needle` stands in `hay` to `out`, overlapping places too. */
658
+ function places(hay, needle, out) {
659
+ if (!needle)
660
+ return;
661
+ for (let at = find(hay, needle, 0); at >= 0; at = find(hay, needle, at + 1))
662
+ out.push([at, at + needle.length]);
663
+ }
664
+ const isSeparator = (code) => code === 45 || code === 95 || code === 58 || code === 46;
665
+ /** Each place a folded needle stands in `text`: its digits in order, in any case, at most one separator between any
666
+ * two. Found in the text lowered with its separators gone, each character's offset in the text kept, and a place kept
667
+ * only where no two of its digits are more than one separator apart. */
668
+ function foldSpans(text, folds, out) {
669
+ // The text lowered, then read once for its separators.
670
+ scanned.chars += 2 * text.length;
671
+ const lower = asciiLower(text);
672
+ const at = new Int32Array(text.length);
673
+ const parts = [];
674
+ let count = 0;
675
+ let from = 0;
676
+ for (let i = 0; i <= text.length; i++) {
677
+ if (i < text.length && !isSeparator(text.charCodeAt(i))) {
678
+ at[count++] = i;
679
+ continue;
680
+ }
681
+ if (i > from)
682
+ parts.push(lower.slice(from, i));
683
+ from = i + 1;
684
+ }
685
+ const flat = parts.join("");
686
+ // The start of the stretch each character is in: a stretch ends where two kept characters are more than one apart.
687
+ const stretch = new Int32Array(count);
688
+ for (let k = 1; k < count; k++)
689
+ stretch[k] = at[k] - at[k - 1] > 2 ? k : stretch[k - 1];
690
+ for (const needle of folds) {
691
+ if (!needle)
692
+ continue;
693
+ for (let i = find(flat, needle, 0); i >= 0; i = find(flat, needle, i + 1)) {
694
+ const last = i + needle.length - 1;
695
+ if (stretch[last] <= i)
696
+ out.push([at[i], at[last] + 1]);
697
+ }
698
+ }
699
+ }
700
+ /** `found` in order, each run of overlapping or touching spans as one. */
701
+ export function merged(found) {
702
+ // Each find read once: they come as one sorted run per form, hex, fold and shape, which the sort merges.
703
+ scanned.chars += found.length;
704
+ const out = [];
705
+ for (const [start, end] of [...found].sort((a, b) => a[0] - b[0])) {
706
+ const last = out.at(-1);
707
+ if (last && start <= last[1])
708
+ last[1] = Math.max(last[1], end);
709
+ else
710
+ out.push([start, end]);
711
+ }
712
+ return out;
713
+ }
714
+ /** `text` with each of `spans` (merged, in order) replaced by "[redacted]". */
715
+ export function cutAt(text, spans) {
716
+ scanned.chars += text.length;
717
+ let out = "";
718
+ let from = 0;
719
+ for (const [start, end] of spans) {
720
+ out += `${text.slice(from, start)}[redacted]`;
721
+ from = end;
722
+ }
723
+ return out + text.slice(from);
724
+ }
725
+ const HEX = only("0123456789abcdefABCDEF");
726
+ const BLANKS = /[\t-\r ]+/y;
727
+ /** A character that renders as nothing (a zero-width space, a soft hyphen, a byte order mark, a variation selector). */
728
+ const IGNORABLE = /\p{Default_Ignorable_Code_Point}+/gu;
729
+ const GONE = /[\s\p{Default_Ignorable_Code_Point}]+/gu;
730
+ /** `text` as a view reads it, and as a held value's needles are read: NFKC, with its whitespace and its characters that
731
+ * render as nothing gone, before NFKC (so one between a letter and its accent hides neither) and after. A held value
732
+ * with a zero-width space or a soft hyphen between its characters reads as itself. */
733
+ export const squeeze = (text) => text.replace(IGNORABLE, "").normalize("NFKC").replace(GONE, "");
734
+ /** A run of percent-encoded bytes, decoded as UTF-8 (decoded). */
735
+ const PERCENT = {
736
+ trigger: "%",
737
+ decode(text, at, unit) {
738
+ let end = at;
739
+ while (text[end] === "%" && HEX(text.charCodeAt(end + 1)) && HEX(text.charCodeAt(end + 2)))
740
+ end += 3;
741
+ // Each byte read, and the three characters past the run that end it.
742
+ scanned.chars += end - at + 3;
743
+ if (end === at)
744
+ return -1;
745
+ decoded(text, at, end, unit);
746
+ return end;
747
+ },
748
+ };
749
+ /** "+" as a space, as a form's encoding writes one. */
750
+ const PLUS = { trigger: "+", decode: (_text, at, unit) => (scanned.chars++, unit(" ", at, at + 1), at + 1) };
751
+ /** What JSON's one-character escapes stand for. */
752
+ const ESCAPED = {
753
+ n: "\n", r: "\r", t: "\t", '"': '"', "\\": "\\", "/": "/", b: "\b", f: "\f",
754
+ };
755
+ function unescaped(text, at) {
756
+ // Counted as the most it reads, six characters ("\u" and four hex digits), whatever it reads.
757
+ if (at >= text.length)
758
+ return undefined;
759
+ scanned.chars += Math.min(6, text.length - at);
760
+ if (text[at] !== "\\")
761
+ return { char: text[at], end: at + 1 };
762
+ const next = text[at + 1];
763
+ if (next !== undefined && ESCAPED[next] !== undefined)
764
+ return { char: ESCAPED[next], end: at + 2 };
765
+ if (next !== "u")
766
+ return undefined;
767
+ for (let i = at + 2; i < at + 6; i++)
768
+ if (!HEX(text.charCodeAt(i)))
769
+ return undefined;
770
+ return { char: String.fromCharCode(Number.parseInt(text.slice(at + 2, at + 6), 16)), end: at + 6 };
771
+ }
772
+ /** JSON's escapes, decoded twice: a held value a JSON writer wrote, every character or some ("\n", "\"", a "\u" and
773
+ * four hex digits), and one written again as a JSON string's text (JSON in JSON: "\\n", "\\\""). Where one level's "\"
774
+ * starts an escape of the next, each character that escape decodes to comes from all of the raw text the two levels
775
+ * read; a "\" that starts none is itself. A surrogate pair is two escapes, two units, NFKC'd together as any non-ASCII
776
+ * stretch is. Line breaks written "\r\n" decode to whitespace, gone from the view. */
777
+ const JSON_ESCAPE = {
778
+ trigger: "\\",
779
+ decode(text, at, unit) {
780
+ const first = unescaped(text, at);
781
+ if (!first)
782
+ return -1;
783
+ if (first.char !== "\\") {
784
+ unit(first.char, at, first.end);
785
+ return first.end;
786
+ }
787
+ // The first level decoded a "\": what follows it, itself read through the first level, may be a second escape.
788
+ const second = unescaped(text, first.end);
789
+ if (second && ESCAPED[second.char] !== undefined) {
790
+ unit(ESCAPED[second.char], at, second.end);
791
+ return second.end;
792
+ }
793
+ if (second?.char === "u") {
794
+ let end = second.end;
795
+ let digits = "";
796
+ for (let i = 0; i < 4; i++) {
797
+ const digit = unescaped(text, end);
798
+ if (!digit || !HEX(digit.char.charCodeAt(0)))
799
+ break;
800
+ digits += digit.char;
801
+ end = digit.end;
802
+ }
803
+ if (digits.length === 4) {
804
+ unit(String.fromCharCode(Number.parseInt(digits, 16)), at, end);
805
+ return end;
806
+ }
807
+ }
808
+ unit("\\", at, first.end);
809
+ return first.end;
810
+ },
811
+ };
812
+ /** JSON's escapes, decoded once: a "\" that starts an escape and what follows it, as one character. A held value that
813
+ * holds a backslash before a character an escape starts with ("\n", "A" as written), written by a JSON writer
814
+ * ("\\n", "\u0041"), reads as itself here, where the two levels JSON_ESCAPE reads make the escaped backslash and
815
+ * what follows it one escape. */
816
+ const JSON_ESCAPE_ONCE = {
817
+ trigger: "\\",
818
+ decode(text, at, unit) {
819
+ const char = unescaped(text, at);
820
+ if (!char)
821
+ return -1;
822
+ unit(char.char, at, char.end);
823
+ return char.end;
824
+ },
825
+ };
826
+ /** What JSON_ESCAPE reads at `at`: the character the escape there decodes to, through both levels, and where it ends;
827
+ * undefined where no escape starts (the "\" is then itself). key-refusal.ts's peek counts an escape by it, so the
828
+ * read past a call's stop and the JSON view see the same characters. */
829
+ export function jsonEscapeAt(text, at) {
830
+ let char;
831
+ const end = JSON_ESCAPE.decode(text, at, (decoded) => {
832
+ char = decoded;
833
+ });
834
+ return end < 0 || char === undefined ? undefined : { char, end };
835
+ }
836
+ const viewSpec = (when, decoders) => ({
837
+ when,
838
+ decoders,
839
+ special: new RegExp(`[\\s${decoders.map((decoder) => `\\${decoder.trigger}`).join("")}\\u0080-\\uffff]`, "g"),
840
+ });
841
+ /** The views of a text read for each held value, in order: squeezed; percent-decoded; percent-decoded with "+" as a
842
+ * space; JSON's escapes decoded twice; and decoded once, where the text holds an escape that decodes to a backslash
843
+ * (elsewhere the two levels read as one does). Each is lowered for hexes and flattened for folded identifiers in
844
+ * holds. */
845
+ const VIEWS = [
846
+ viewSpec(() => true, []),
847
+ viewSpec((text) => /%[0-9a-fA-F]{2}/.test(text), [PERCENT]),
848
+ viewSpec((text) => text.includes("+"), [PERCENT, PLUS]),
849
+ viewSpec((text) => /\\(?:u[0-9a-fA-F]{4}|["\\/bfnrt])/.test(text), [JSON_ESCAPE]),
850
+ viewSpec((text) => /\\(?:\\|u005[cC])/.test(text), [JSON_ESCAPE_ONCE]),
851
+ ];
852
+ /** `text` as the whole-text check reads it: decoded by `spec`'s decoders, then squeezed (squeeze: NFKC, its whitespace
853
+ * and its characters that render as nothing gone), as a held value's needles are. The squeeze is applied to each
854
+ * stretch of non-ASCII characters with the ASCII character before it, which gives what it gives over the whole text (an
855
+ * ASCII character is a starter nothing composes onto), and each character it makes comes from that whole stretch. With `cuts` (merged spans of `text`), the view's
856
+ * covered stretches: where every character comes from inside one cut. */
857
+ function viewOf(text, spec, cuts) {
858
+ const out = [];
859
+ const covered = [];
860
+ let length = 0;
861
+ let cut = 0;
862
+ const cover = (from, to) => {
863
+ const last = covered.at(-1);
864
+ if (last && last[1] === from)
865
+ last[1] = to;
866
+ else
867
+ covered.push([from, to]);
868
+ };
869
+ /** Text characters [from, to) as they are, all ASCII and none whitespace. */
870
+ const emitSlice = (from, to) => {
871
+ if (to <= from)
872
+ return;
873
+ out.push(text.slice(from, to));
874
+ if (cuts) {
875
+ // The cover's cursor only goes forward: each cut is passed once in the whole view.
876
+ while (cut < cuts.length && cuts[cut][1] <= from) {
877
+ cut++;
878
+ scanned.chars++;
879
+ }
880
+ for (let k = cut; k < cuts.length && cuts[k][0] < to; k++) {
881
+ scanned.chars++;
882
+ const start = Math.max(from, cuts[k][0]);
883
+ const end = Math.min(to, cuts[k][1]);
884
+ if (start < end)
885
+ cover(length + start - from, length + end - from);
886
+ }
887
+ }
888
+ length += to - from;
889
+ };
890
+ /** View characters `chars`, each made of text [from, to). */
891
+ const emit = (chars, from, to) => {
892
+ if (!chars)
893
+ return;
894
+ out.push(chars);
895
+ if (cuts) {
896
+ while (cut < cuts.length && cuts[cut][1] <= from) {
897
+ cut++;
898
+ scanned.chars++;
899
+ }
900
+ if (cut < cuts.length && cuts[cut][0] <= from && to <= cuts[cut][1])
901
+ cover(length, length + chars.length);
902
+ }
903
+ length += chars.length;
904
+ };
905
+ let held;
906
+ let group;
907
+ const flushHeld = () => {
908
+ if (held && !isSpace(held.char.charCodeAt(0)))
909
+ emit(held.char, held.from, held.to);
910
+ held = undefined;
911
+ };
912
+ const flushGroup = () => {
913
+ if (!group)
914
+ return;
915
+ // The stretch squeezed twice: whole, and without its lead.
916
+ scanned.chars += 2 * group.chars.length;
917
+ const made = squeeze(group.chars);
918
+ const { lead } = group;
919
+ const rest = lead ? squeeze(group.chars.slice(lead.char.length)) : "";
920
+ // Where nothing composed onto the ASCII character, it comes from itself alone: a value cut in place right before
921
+ // a non-ASCII character is still covered to its last character. A stretch that squeezes to nothing (characters that
922
+ // render as nothing) adds nothing to the view, as whitespace adds nothing.
923
+ if (lead && made === squeeze(lead.char) + rest) {
924
+ held = lead;
925
+ flushHeld();
926
+ emit(rest, lead.to, group.to);
927
+ }
928
+ else
929
+ emit(made, group.from, group.to);
930
+ group = undefined;
931
+ };
932
+ const unit = (char, from, to) => {
933
+ if (char.charCodeAt(0) >= 128) {
934
+ if (group) {
935
+ group.chars += char;
936
+ group.to = to;
937
+ }
938
+ else {
939
+ group = held ? { chars: held.char + char, from: held.from, to, lead: held } : { chars: char, from, to };
940
+ held = undefined;
941
+ }
942
+ return;
943
+ }
944
+ flushGroup();
945
+ flushHeld();
946
+ held = { char, from, to };
947
+ };
948
+ const special = new RegExp(spec.special.source, "g");
949
+ let at = 0;
950
+ while (at < text.length) {
951
+ special.lastIndex = at;
952
+ const hit = special.exec(text);
953
+ const stop = hit ? hit.index : text.length;
954
+ // The characters copied as they are, and the special one that stopped the search.
955
+ scanned.chars += (hit ? stop + 1 : stop) - at;
956
+ if (stop > at) {
957
+ flushGroup();
958
+ flushHeld();
959
+ emitSlice(at, stop - 1);
960
+ held = { char: text[stop - 1], from: stop - 1, to: stop };
961
+ }
962
+ if (!hit)
963
+ break;
964
+ const char = text[stop];
965
+ let end = -1;
966
+ for (const decoder of spec.decoders)
967
+ if (decoder.trigger === char)
968
+ end = decoder.decode(text, stop, unit);
969
+ if (end >= 0)
970
+ at = end;
971
+ else if (char.charCodeAt(0) < 128 && isSpace(char.charCodeAt(0))) {
972
+ // A run of ASCII whitespace is gone from the view: only its last character is held, as the one a non-ASCII
973
+ // character after it could compose onto.
974
+ BLANKS.lastIndex = stop;
975
+ BLANKS.test(text);
976
+ scanned.chars += BLANKS.lastIndex - stop;
977
+ flushGroup();
978
+ flushHeld();
979
+ held = { char: text[BLANKS.lastIndex - 1], from: BLANKS.lastIndex - 1, to: BLANKS.lastIndex };
980
+ at = BLANKS.lastIndex;
981
+ }
982
+ else {
983
+ unit(char, stop, stop + 1);
984
+ at = stop + 1;
985
+ }
986
+ }
987
+ flushGroup();
988
+ flushHeld();
989
+ return { text: out.join(""), covered };
990
+ }
991
+ /** The characters a run of percent-encoded bytes text[from, to) decodes to (as UTF-8, invalid bytes as U+FFFD, as
992
+ * Buffer decodes the run whole), each with the bytes it came from; a run whose bytes decode otherwise one sequence at
993
+ * a time has each character come from the whole run. */
994
+ function decoded(text, from, to, unit) {
995
+ // An ASCII byte is its own character: a run of them (the common "%20", "%2F%3D") is read without a buffer.
996
+ let ascii = true;
997
+ for (let at = from + 1; at < to && ascii; at += 3)
998
+ ascii = text.charCodeAt(at) < 56;
999
+ if (ascii) {
1000
+ for (let at = from; at < to; at += 3)
1001
+ unit(String.fromCharCode(Number.parseInt(text.slice(at + 1, at + 3), 16)), at, at + 3);
1002
+ return;
1003
+ }
1004
+ // The run read three times: its hex parsed, decoded whole, and decoded one sequence at a time.
1005
+ scanned.chars += 3 * (to - from);
1006
+ const bytes = Buffer.from(text.slice(from, to).replaceAll("%", ""), "hex");
1007
+ const whole = bytes.toString("utf8");
1008
+ const pieces = [];
1009
+ for (let k = 0; k < bytes.length;) {
1010
+ const lead = bytes[k];
1011
+ const size = Math.min(bytes.length - k, lead < 0x80 ? 1 : lead >> 5 === 6 ? 2 : lead >> 4 === 14 ? 3 : lead >> 3 === 30 ? 4 : 1);
1012
+ pieces.push([bytes.subarray(k, k + size).toString("utf8"), from + 3 * k, from + 3 * (k + size)]);
1013
+ k += size;
1014
+ }
1015
+ if (pieces.map(([chars]) => chars).join("") === whole) {
1016
+ for (const [chars, start, end] of pieces)
1017
+ for (const char of chars)
1018
+ for (let i = 0; i < char.length; i++)
1019
+ unit(char[i], start, end);
1020
+ }
1021
+ else
1022
+ for (let i = 0; i < whole.length; i++)
1023
+ unit(whole[i], from, to);
1024
+ }
1025
+ /** A view with its separators ("-", "_", ":", ".") gone, its covered stretches moved to match. */
1026
+ function flatOf(view) {
1027
+ scanned.chars += view.text.length + view.covered.length;
1028
+ const parts = [];
1029
+ const kept = new Int32Array(view.text.length + 1);
1030
+ let from = 0;
1031
+ let count = 0;
1032
+ for (let i = 0; i < view.text.length; i++) {
1033
+ kept[i] = count;
1034
+ if (isSeparator(view.text.charCodeAt(i))) {
1035
+ if (i > from)
1036
+ parts.push(view.text.slice(from, i));
1037
+ from = i + 1;
1038
+ }
1039
+ else
1040
+ count++;
1041
+ }
1042
+ kept[view.text.length] = count;
1043
+ if (view.text.length > from)
1044
+ parts.push(view.text.slice(from));
1045
+ const covered = [];
1046
+ for (const [start, end] of view.covered) {
1047
+ const [a, b] = [kept[start], kept[end]];
1048
+ if (a >= b)
1049
+ continue;
1050
+ const last = covered.at(-1);
1051
+ if (last && last[1] === a)
1052
+ last[1] = b;
1053
+ else
1054
+ covered.push([a, b]);
1055
+ }
1056
+ return { text: parts.join(""), covered };
1057
+ }
1058
+ /** Whether [start, end) of a view lies in one of its covered stretches: a binary search, each stretch it visits
1059
+ * counted. */
1060
+ function inside(covered, start, end) {
1061
+ let lo = 0;
1062
+ let hi = covered.length - 1;
1063
+ while (lo <= hi) {
1064
+ scanned.chars++;
1065
+ const mid = (lo + hi) >> 1;
1066
+ if (covered[mid][0] <= start)
1067
+ lo = mid + 1;
1068
+ else
1069
+ hi = mid - 1;
1070
+ }
1071
+ return hi >= 0 && covered[hi][1] >= end;
1072
+ }
1073
+ /** Whether `view` holds one of `needles` outside its covered stretches (with no `covered`, anywhere). */
1074
+ function holdsIn(view, covered, needles) {
1075
+ for (const needle of needles) {
1076
+ if (!needle)
1077
+ continue;
1078
+ if (!covered) {
1079
+ if (find(view, needle, 0) >= 0)
1080
+ return true;
1081
+ continue;
1082
+ }
1083
+ for (let at = find(view, needle, 0); at >= 0; at = find(view, needle, at + 1))
1084
+ if (!inside(covered, at, at + needle.length))
1085
+ return true;
1086
+ }
1087
+ return false;
1088
+ }
1089
+ /** Whether `text` holds a held value in a form the cut does not find as it stands: split by whitespace, percent or
1090
+ * form encoded, an NFKC variant, its hex in any case, a hex identifier folded (`fold`). With `cuts`, a value whose
1091
+ * every character the view read comes from inside the cuts is not held: it is cut in place. */
1092
+ export function holds(text, needles, { fold = true, cuts } = {}) {
1093
+ const folds = fold ? needles.folds : [];
1094
+ if (!needles.plain.length && !needles.hexes.length && !folds.length)
1095
+ return false;
1096
+ for (const spec of VIEWS) {
1097
+ // Whether a decoding view is read: its test reads the text to its first trigger at most.
1098
+ if (spec.decoders.length)
1099
+ scanned.chars += text.length;
1100
+ if (!spec.when(text))
1101
+ continue;
1102
+ const view = viewOf(text, spec, cuts);
1103
+ const covered = cuts ? view.covered : undefined;
1104
+ if (holdsIn(view.text, covered, needles.plain))
1105
+ return true;
1106
+ if (!needles.hexes.length && !folds.length)
1107
+ continue;
1108
+ scanned.chars += view.text.length;
1109
+ const lower = { text: asciiLower(view.text), covered: view.covered };
1110
+ if (holdsIn(lower.text, covered, needles.hexes))
1111
+ return true;
1112
+ if (!folds.length)
1113
+ continue;
1114
+ const flat = flatOf(lower);
1115
+ if (holdsIn(flat.text, cuts ? flat.covered : undefined, folds))
1116
+ return true;
1117
+ }
1118
+ return false;
1119
+ }
1120
+ /** planCut's first step: every form, hex, folded identifier and shape of `text` as it came, and `held`, merged. */
1121
+ export function cutSpans(text, needles, shapes, held = []) {
1122
+ const lower = lowered(text);
1123
+ const found = held.map(([start, end]) => [start, end]);
1124
+ for (const form of needles.forms)
1125
+ places(text, form, found);
1126
+ for (const hex of needles.hexes)
1127
+ places(lower(), hex, found);
1128
+ // One by one: a text of very many finds would overflow the stack as one call's arguments.
1129
+ for (const shape of shapes)
1130
+ for (const span of spansOf(text, lower, shape))
1131
+ found.push(span);
1132
+ if (needles.folds.length)
1133
+ foldSpans(text, needles.folds, found);
1134
+ return merged(found);
1135
+ }
1136
+ /** Where `text` is cut of `needles` and of each of `shapes`, and the text so cut; or "whole" when it must be withheld
1137
+ * whole. `held`: spans cut in place beside the finds. The order is fixed:
1138
+ * 1. every form, hex, folded identifier and shape is found in the text as it came, and the spans merged;
1139
+ * 2. the views of the text as it came are read for each held value: one any of whose characters comes from outside
1140
+ * the spans withholds the text (a cut can hide part of a value, so the check never reads the cut text for it);
1141
+ * 3. the spans are cut;
1142
+ * 4. what is left is read again, for a value or a shape the cut made (a value whose rest the cut joined, a shape whose
1143
+ * guard the cut removed), and withholds the text if it holds one. */
1144
+ export function planCut(text, needles, shapes, held = []) {
1145
+ const spans = cutSpans(text, needles, shapes, held);
1146
+ if (holds(text, needles, { cuts: spans }))
1147
+ return "whole";
1148
+ const out = spans.length ? cutAt(text, spans) : text;
1149
+ if (spans.length && (holds(out, needles) || shapeKinds(out, shapes).length > 0))
1150
+ return "whole";
1151
+ return { spans, out };
1152
+ }