@dsh-ray/assistant-association 0.0.0-stage → 0.2.0

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 (120) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +133 -2
  3. package/cordis.patch.yml +26 -0
  4. package/lib/aho-corasick.d.ts +41 -0
  5. package/lib/aho-corasick.d.ts.map +1 -0
  6. package/lib/aho-corasick.js +352 -0
  7. package/lib/aho-corasick.js.map +1 -0
  8. package/lib/bm25.d.ts +17 -0
  9. package/lib/bm25.d.ts.map +1 -0
  10. package/lib/bm25.js +73 -0
  11. package/lib/bm25.js.map +1 -0
  12. package/lib/clustering.d.ts +161 -0
  13. package/lib/clustering.d.ts.map +1 -0
  14. package/lib/clustering.js +1043 -0
  15. package/lib/clustering.js.map +1 -0
  16. package/lib/config.d.ts +67 -0
  17. package/lib/config.d.ts.map +1 -0
  18. package/lib/config.js +834 -0
  19. package/lib/config.js.map +1 -0
  20. package/lib/cues.d.ts +134 -0
  21. package/lib/cues.d.ts.map +1 -0
  22. package/lib/cues.js +793 -0
  23. package/lib/cues.js.map +1 -0
  24. package/lib/dreaming.d.ts +211 -0
  25. package/lib/dreaming.d.ts.map +1 -0
  26. package/lib/dreaming.js +1418 -0
  27. package/lib/dreaming.js.map +1 -0
  28. package/lib/entities.d.ts +18 -0
  29. package/lib/entities.d.ts.map +1 -0
  30. package/lib/entities.js +111 -0
  31. package/lib/entities.js.map +1 -0
  32. package/lib/eval-pool.d.ts +111 -0
  33. package/lib/eval-pool.d.ts.map +1 -0
  34. package/lib/eval-pool.js +392 -0
  35. package/lib/eval-pool.js.map +1 -0
  36. package/lib/hebbian.d.ts +54 -0
  37. package/lib/hebbian.d.ts.map +1 -0
  38. package/lib/hebbian.js +226 -0
  39. package/lib/hebbian.js.map +1 -0
  40. package/lib/holdout.d.ts +18 -0
  41. package/lib/holdout.d.ts.map +1 -0
  42. package/lib/holdout.js +97 -0
  43. package/lib/holdout.js.map +1 -0
  44. package/lib/hot-path.d.ts +8 -0
  45. package/lib/hot-path.d.ts.map +1 -0
  46. package/lib/hot-path.js +503 -0
  47. package/lib/hot-path.js.map +1 -0
  48. package/lib/hysteresis.d.ts +39 -0
  49. package/lib/hysteresis.d.ts.map +1 -0
  50. package/lib/hysteresis.js +297 -0
  51. package/lib/hysteresis.js.map +1 -0
  52. package/lib/index-memory.d.ts +112 -0
  53. package/lib/index-memory.d.ts.map +1 -0
  54. package/lib/index-memory.js +391 -0
  55. package/lib/index-memory.js.map +1 -0
  56. package/lib/index.d.ts +37 -0
  57. package/lib/index.d.ts.map +1 -0
  58. package/lib/index.js +37 -0
  59. package/lib/index.js.map +1 -0
  60. package/lib/intake-signal.d.ts +158 -0
  61. package/lib/intake-signal.d.ts.map +1 -0
  62. package/lib/intake-signal.js +366 -0
  63. package/lib/intake-signal.js.map +1 -0
  64. package/lib/param-tuning.d.ts +302 -0
  65. package/lib/param-tuning.d.ts.map +1 -0
  66. package/lib/param-tuning.js +1743 -0
  67. package/lib/param-tuning.js.map +1 -0
  68. package/lib/service.d.ts +164 -0
  69. package/lib/service.d.ts.map +1 -0
  70. package/lib/service.js +2071 -0
  71. package/lib/service.js.map +1 -0
  72. package/lib/sources.d.ts +42 -0
  73. package/lib/sources.d.ts.map +1 -0
  74. package/lib/sources.js +2024 -0
  75. package/lib/sources.js.map +1 -0
  76. package/lib/sqlite.d.ts +88 -0
  77. package/lib/sqlite.d.ts.map +1 -0
  78. package/lib/sqlite.js +1815 -0
  79. package/lib/sqlite.js.map +1 -0
  80. package/lib/tokenize.d.ts +4 -0
  81. package/lib/tokenize.d.ts.map +1 -0
  82. package/lib/tokenize.js +35 -0
  83. package/lib/tokenize.js.map +1 -0
  84. package/lib/tools.d.ts +27 -0
  85. package/lib/tools.d.ts.map +1 -0
  86. package/lib/tools.js +126 -0
  87. package/lib/tools.js.map +1 -0
  88. package/lib/types.d.ts +551 -0
  89. package/lib/types.d.ts.map +1 -0
  90. package/lib/types.js +163 -0
  91. package/lib/types.js.map +1 -0
  92. package/lib/version.d.ts +2 -0
  93. package/lib/version.d.ts.map +1 -0
  94. package/lib/version.js +2 -0
  95. package/lib/version.js.map +1 -0
  96. package/lib/web-fetch.d.ts +95 -0
  97. package/lib/web-fetch.d.ts.map +1 -0
  98. package/lib/web-fetch.js +833 -0
  99. package/lib/web-fetch.js.map +1 -0
  100. package/lib/web-learning-interests.d.ts +42 -0
  101. package/lib/web-learning-interests.d.ts.map +1 -0
  102. package/lib/web-learning-interests.js +4344 -0
  103. package/lib/web-learning-interests.js.map +1 -0
  104. package/lib/web-learning-runner.d.ts +43 -0
  105. package/lib/web-learning-runner.d.ts.map +1 -0
  106. package/lib/web-learning-runner.js +322 -0
  107. package/lib/web-learning-runner.js.map +1 -0
  108. package/lib/web-learning-worker.d.ts +75 -0
  109. package/lib/web-learning-worker.d.ts.map +1 -0
  110. package/lib/web-learning-worker.js +367 -0
  111. package/lib/web-learning-worker.js.map +1 -0
  112. package/lib/web-learning.d.ts +161 -0
  113. package/lib/web-learning.d.ts.map +1 -0
  114. package/lib/web-learning.js +912 -0
  115. package/lib/web-learning.js.map +1 -0
  116. package/lib/write-queue.d.ts +42 -0
  117. package/lib/write-queue.d.ts.map +1 -0
  118. package/lib/write-queue.js +439 -0
  119. package/lib/write-queue.js.map +1 -0
  120. package/package.json +156 -3
@@ -0,0 +1,4344 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { isIP } from 'node:net';
3
+ import { DEFAULT_ASSOCIATION_WEB_LEARNING_CONFIG } from './config.js';
4
+ import { extractEntities } from './entities.js';
5
+ import { tokenizeAssociationText } from './tokenize.js';
6
+ import { validateWhitelistedWebUrl } from './web-fetch.js';
7
+ export const INTEREST_SOURCE_PRIORITIES = Object.freeze({
8
+ goal: 1.2,
9
+ 'implicit-signal': 1.1,
10
+ 'work-item': 1.0,
11
+ 'low-coverage': 0.9,
12
+ dream: 0.85,
13
+ abstraction: 0.85,
14
+ });
15
+ const MAX_TOKENS_PER_QUERY = 3;
16
+ const MAX_QUERY_CHARS = 64;
17
+ const MAX_TOKEN_CHARS = 48;
18
+ const MAX_CJK_TOKEN_CHARS = 16;
19
+ const STOPWORDS = new Set([
20
+ 'the', 'and', 'for', 'with', 'that', 'this', 'from', 'into', 'your', 'have',
21
+ 'will', 'are', 'was', 'were', 'not', 'but', 'can', 'use', 'used', 'using',
22
+ 'when', 'what', 'which', 'where', 'how', 'all', 'any', 'has', 'had', 'been',
23
+ 'true', 'false', 'null', 'undefined', 'about', 'also', 'than', 'then', 'them',
24
+ 'they', 'their', 'there', 'here', 'more', 'some', 'only', 'other', 'such',
25
+ 'each', 'over', 'unknown', 'none', 'error', 'failed', 'success', 'completed',
26
+ 'active', 'private', 'sensitive', 'http', 'https', 'www', 'localhost',
27
+ 'execution', 'objective', 'status', 'task', 'item', 'work', 'goal', 'dream',
28
+ ]);
29
+ const SECRET_EXACT_TOKENS = new Set([
30
+ 'bearer',
31
+ 'token',
32
+ 'tokens',
33
+ 'secret',
34
+ 'secrets',
35
+ 'password',
36
+ 'passwords',
37
+ 'passphrase',
38
+ 'passphrases',
39
+ 'passwd',
40
+ 'pwd',
41
+ 'apikey',
42
+ 'apikeys',
43
+ 'api_key',
44
+ 'api-key',
45
+ 'access_token',
46
+ 'access-token',
47
+ 'refresh_token',
48
+ 'refresh-token',
49
+ 'private_key',
50
+ 'private-key',
51
+ 'secret_key',
52
+ 'secret-key',
53
+ 'secretkey',
54
+ 'auth_key',
55
+ 'auth-key',
56
+ 'authkey',
57
+ 'access_key',
58
+ 'access-key',
59
+ 'accesskey',
60
+ 'client_secret',
61
+ 'client-secret',
62
+ 'client_key',
63
+ 'client-key',
64
+ 'clientkey',
65
+ 'auth_token',
66
+ 'auth-token',
67
+ 'authorization',
68
+ 'credential',
69
+ 'credentials',
70
+ 'creds',
71
+ 'cookie',
72
+ 'cookies',
73
+ 'session_id',
74
+ 'session-id',
75
+ 'sessionid',
76
+ 'ssh_key',
77
+ 'ssh-key',
78
+ 'sshkey',
79
+ 'ssh_keys',
80
+ 'ssh-keys',
81
+ 'sshkeys',
82
+ 'signing_key',
83
+ 'signing-key',
84
+ 'master_key',
85
+ 'master-key',
86
+ 'encryption_key',
87
+ 'encryption-key',
88
+ 'deploy_key',
89
+ 'deploy-key',
90
+ 'deploykey',
91
+ 'jwt_key',
92
+ 'jwt-key',
93
+ 'jwtkey',
94
+ 'jwt_secret',
95
+ 'jwt-secret',
96
+ 'app_key',
97
+ 'app-key',
98
+ 'appkey',
99
+ 'hmac_key',
100
+ 'hmac-key',
101
+ 'hmackey',
102
+ 'tls_key',
103
+ 'tls-key',
104
+ 'tlskey',
105
+ 'ssl_key',
106
+ 'ssl-key',
107
+ 'sslkey',
108
+ 'aes_key',
109
+ 'aes-key',
110
+ 'aeskey',
111
+ 'kms_key',
112
+ 'kms-key',
113
+ 'kmskey',
114
+ 'fernet_key',
115
+ 'fernet-key',
116
+ 'fernetkey',
117
+ 'cipher_key',
118
+ 'cipher-key',
119
+ 'cipherkey',
120
+ 'pk_key',
121
+ 'pk-key',
122
+ 'pkkey',
123
+ 'pk_keys',
124
+ 'pk-keys',
125
+ 'pkkeys',
126
+ 'sk_key',
127
+ 'sk-key',
128
+ 'skkey',
129
+ 'sk_keys',
130
+ 'sk-keys',
131
+ 'skkeys',
132
+ 'rk_key',
133
+ 'rk-key',
134
+ 'rkkey',
135
+ 'rk_keys',
136
+ 'rk-keys',
137
+ 'rkkeys',
138
+ 'whsec_key',
139
+ 'whsec-key',
140
+ 'whseckey',
141
+ 'whsec_keys',
142
+ 'whsec-keys',
143
+ 'whseckeys',
144
+ 'ghp_key',
145
+ 'ghp-key',
146
+ 'ghpkey',
147
+ 'ghp_keys',
148
+ 'ghp-keys',
149
+ 'ghpkeys',
150
+ 'gho_key',
151
+ 'gho-key',
152
+ 'ghokey',
153
+ 'gho_keys',
154
+ 'gho-keys',
155
+ 'ghokeys',
156
+ 'ghu_key',
157
+ 'ghu-key',
158
+ 'ghukey',
159
+ 'ghu_keys',
160
+ 'ghu-keys',
161
+ 'ghukeys',
162
+ 'ghs_key',
163
+ 'ghs-key',
164
+ 'ghskey',
165
+ 'ghs_keys',
166
+ 'ghs-keys',
167
+ 'ghskeys',
168
+ 'ghr_key',
169
+ 'ghr-key',
170
+ 'ghrkey',
171
+ 'ghr_keys',
172
+ 'ghr-keys',
173
+ 'ghrkeys',
174
+ 'glpat_key',
175
+ 'glpat-key',
176
+ 'glpatkey',
177
+ 'glpat_keys',
178
+ 'glpat-keys',
179
+ 'glpatkeys',
180
+ 'npm_key',
181
+ 'npm-key',
182
+ 'npmkey',
183
+ 'npm_keys',
184
+ 'npm-keys',
185
+ 'npmkeys',
186
+ 'xoxb_key',
187
+ 'xoxb-key',
188
+ 'xoxbkey',
189
+ 'xoxb_keys',
190
+ 'xoxb-keys',
191
+ 'xoxbkeys',
192
+ 'xoxp_key',
193
+ 'xoxp-key',
194
+ 'xoxpkey',
195
+ 'xoxp_keys',
196
+ 'xoxp-keys',
197
+ 'xoxpkeys',
198
+ 'xoxa_key',
199
+ 'xoxa-key',
200
+ 'xoxakey',
201
+ 'xoxa_keys',
202
+ 'xoxa-keys',
203
+ 'xoxakeys',
204
+ 'xoxr_key',
205
+ 'xoxr-key',
206
+ 'xoxrkey',
207
+ 'xoxr_keys',
208
+ 'xoxr-keys',
209
+ 'xoxrkeys',
210
+ 'github_pat_key',
211
+ 'github-pat-key',
212
+ 'github_pat-key',
213
+ 'githubpatkey',
214
+ 'github_pat_keys',
215
+ 'github-pat-keys',
216
+ 'github_pat-keys',
217
+ 'githubpatkeys',
218
+ ]);
219
+ const SECRET_PREFIX_RE = /^(?:sk|pk|rk|ghp|gho|ghu|ghs|ghr|xox[bpar]|glpat)[_-]|^(?:npm|whsec)_|^github_pat_|^akia[0-9a-z]{8,}|^asia[0-9a-z]{8,}|^aiza[0-9a-z_-]{8,}|^ya29\.|^eyj[a-z0-9_-]{8,}/iu;
220
+ const SECRET_KEY_PART_RE = /(?:bearer|token|secret|passphrases?|password|passwd|pwd|api[_-]?key|apikeys|apikey|access[_-]?token|refresh[_-]?token|private[_-]?key|secret[_-]?key|auth[_-]?key|access[_-]?key|client[_-]?(?:secret|key)|auth[_-]?token|authorization|credential|credentials|creds|cookie|cookies|session[_-]?id|(?:^|[_.-])ssh[_-]?keys?(?:[_.-]|$)|signing[_-]?key|master[_-]?key|encryption[_-]?key|deploy[_-]?key|jwt[_-]?key|jwt[_-]?secret|(?:app|hmac|tls|ssl|aes|kms|fernet|cipher)[_-]?key|(?:^|[_.-])(?:pk|sk|rk|whsec|ghp|gho|ghu|ghs|ghr|glpat|npm|xox[bpar]|github[_-]?pat)[_-]?keys?(?:[_.-]|$)|(?:^|[_.-])github[_-]?pat$|(?:^|[_.-])jwt(?:$|[_.-])|[A-Za-z0-9][_.-]+pass(?:[_.-]|$))/iu;
221
+ const CAMEL_PASS_OR_JWT_KEY_RE = /[a-z0-9](?:Pass|Jwt)(?:[^a-z]|$)/u;
222
+ const AUTH_KEY_PART_RE = /authorization/iu;
223
+ const BEARER_KEY_PART_RE = /bearer/iu;
224
+ const SECRET_VALUE_CHAR_RE = /[0-9!@#$%^&*_+/=\\~-]/u;
225
+ const SCHEME_PREFIX_STICKY_RE = /(bearer|basic|token|apikey|api[_-]?key|digest|oauth|signature|mac|negotiate|hoba|mutual|scram-sha-1|scram-sha-256|scram-sha-512|aws4-hmac-sha256|vapid|dpop)[ \t:]+/iyu;
226
+ const KNOWN_AUTH_SCHEMES = new Set([
227
+ 'bearer',
228
+ 'basic',
229
+ 'token',
230
+ 'apikey',
231
+ 'api_key',
232
+ 'api-key',
233
+ 'digest',
234
+ 'oauth',
235
+ 'signature',
236
+ 'mac',
237
+ 'negotiate',
238
+ 'hoba',
239
+ 'mutual',
240
+ 'scram-sha-1',
241
+ 'scram-sha-256',
242
+ 'scram-sha-512',
243
+ 'aws4-hmac-sha256',
244
+ 'vapid',
245
+ 'dpop',
246
+ ]);
247
+ const QUOTED_AUTH_SCHEME_STICKY_RE = /(?:"([^\s"\r\n]+)"|'([^\s'\r\n]+)'|`([^\s`\r\n]+)`)(?:[ \t]*(?:\r?\n[ \t]+)?[,;][ \t]*(?:\r?\n[ \t]+)?|[ \t]+|\r?\n[ \t]+)/yu;
248
+ const CAMEL_OR_NUMBERED_SECRET_SUFFIX_RE = /(?:ApiKey|Token|Secret|Passphrases?|Password|Passwd|Pass|Key|Cred|Auth|Cookie|Session|Jwt|Bearer|Oauth)\d*$/u;
249
+ const UNSEPARATED_SECRET_SUFFIX_RE = /(?:api[_-]?key|apikeys|apikey|token|tokens|secret[_-]?key|auth[_-]?key|access[_-]?key|client[_-]?key|secret|passphrases?|password|passwd|pwd|bearer|credential|credentials|creds|cookie|cookies|session[_-]?id|ssh[_-]?key|signing[_-]?key|master[_-]?key|encryption[_-]?key|(?:app|hmac|tls|ssl|aes|kms|fernet|cipher|pk|sk|rk|whsec|ghp|gho|ghu|ghs|ghr|glpat|npm|xox[bpar]|github[_-]?pat)[_-]?keys?)$/iu;
250
+ const PARAMETERIZED_AUTH_SCHEMES = new Set([
251
+ 'aws4-hmac-sha256',
252
+ 'digest',
253
+ 'oauth',
254
+ 'signature',
255
+ 'mac',
256
+ 'scram-sha-1',
257
+ 'scram-sha-256',
258
+ 'scram-sha-512',
259
+ 'vapid',
260
+ 'hoba',
261
+ 'mutual',
262
+ ]);
263
+ const PEM_OPEN_OPT_NL_STICKY_RE = /[ \t]*(?:\r?\n[ \t]*)?-----BEGIN [A-Z0-9 _-]+-----/yu;
264
+ const PEM_END_STICKY_RE = /[ \t]*-----END [A-Z0-9 _-]+-----/yu;
265
+ const LINE_ASSIGNMENT_PREFIX = '(?:-[ \\t]+|\\*[ \\t]+|,[ \\t]*)?(?:(?:export|local|readonly|declare|const|let|var|set|env)[ \\t]+)*';
266
+ const SUBSCRIPT_SEGMENT_SRC = '(?:[ \\t]*\\[[ \\t]*(?:"[^"\\r\\n]+"|\'[^\'\\r\\n]+\'|`[^`\\r\\n]+`|\\$?[A-Za-z0-9_.-]*)[ \\t]*\\])';
267
+ const SUBSCRIPT_CHAIN_CAPTURE_SRC = `((?:${SUBSCRIPT_SEGMENT_SRC}(?:\\.[A-Za-z0-9_.-]+)?)+)`;
268
+ const LINE_START_ASSIGNMENT_RE = new RegExp(`[ \\t]*${LINE_ASSIGNMENT_PREFIX}(?:(["'\`])([A-Za-z0-9_.-]+)\\1|([A-Za-z0-9_.-]+))${SUBSCRIPT_CHAIN_CAPTURE_SRC}?[ \\t]*(?::=|==|:|=)(?![ \\t]*(?:$|[\\r\\n]|["'\`][ \\t]*(?:[,;][ \\t]*)?(?:$|[\\r\\n])))`, 'yu');
269
+ const LINE_START_SECRET_SPACE_QUOTE_RE = new RegExp(`[ \\t]*${LINE_ASSIGNMENT_PREFIX}(?:(["'\`])([A-Za-z0-9_.-]+)\\1|([A-Za-z0-9_.-]+))[ \\t]+["'\`]`, 'yu');
270
+ const INLINE_ASSIGNMENT_RE = new RegExp(`(?<![A-Za-z0-9_.-])(?:(["'\`])([A-Za-z0-9_.-]+)\\1|([A-Za-z0-9_.-]+))${SUBSCRIPT_CHAIN_CAPTURE_SRC}?[ \\t]*(?::=|==|:|=)(?![ \\t]*(?:$|["'\`][ \\t]*(?:[,;][ \\t]*)?$))`, 'gu');
271
+ const INLINE_SECRET_SPACE_QUOTE_RE = /(?<![A-Za-z0-9_.-])(?:(["'`])([A-Za-z0-9_.-]+)\1|([A-Za-z0-9_.-]+))[ \t]+["'`]/gu;
272
+ const NEXT_KEY_ASSIGNMENT_STICKY_RE = new RegExp(`(?:(["'\`])([A-Za-z0-9_.-]+)\\1|([A-Za-z0-9_.-]+))${SUBSCRIPT_CHAIN_CAPTURE_SRC}?([ \\t]*)(:=|==|:|=)([ \\t]*)(\\S)`, 'yu');
273
+ const NEXT_SECRET_SPACE_QUOTE_STICKY_RE = /(?:(["'`])([A-Za-z0-9_.-]+)\1|([A-Za-z0-9_.-]+))[ \t]+["'`]/yu;
274
+ const COOKIE_KEY_PART_RE = /(?:^|[_.-])(?:set)?cookies?2?(?:[_.-]|$)/iu;
275
+ const COOKIE_PAIR_START_STICKY_RE = /(?:(?:"[^"\r\n]+"|'[^'\r\n]+'|`[^`\r\n]+`)|[A-Za-z0-9_.!$%&'*+^`|~-]+)[ \t]*=[ \t]*/yu;
276
+ const COOKIE_ATTR_FLAG_STICKY_RE = /(?:httponly|secure|partitioned|discard|hostonly|samesite)(?=[ \t]*(?:[;,]|$|\r|\n))/iyu;
277
+ const COOKIE_BARE_FLAG_PREFIX_STICKY_RE = /\$?[A-Za-z][A-Za-z0-9_-]*(?=[ \t]*(?:\r?\n[ \t]+)?[;,])/yu;
278
+ const COOKIE_BARE_FLAG_FOLDED_STICKY_RE = /\$?[A-Za-z][A-Za-z0-9_-]*(?=[ \t]*\r?\n[ \t]+)/yu;
279
+ const COOKIE_COLON_SECRET_STICKY_RE = /(?:(["'`])([A-Za-z0-9_.-]+)\1|([A-Za-z0-9_.-]+))[ \t]*:[ \t]*/yu;
280
+ const COOKIE_EXPIRES_DATE_STICKY_RE = /expires[ \t]*=[ \t]*(?:[A-Za-z]{3,9},[ \t]+)?\d{1,2}[ \t-]+[A-Za-z]{3,9}[ \t-]+\d{2,4}[ \t]+(?:\d{2}:\d{2}:\d{2}[ \t]+)?[A-Za-z0-9+-]+/iyu;
281
+ const ARRAY_ELEMENT_OR_CLOSE_STICKY_RE = /[ \t]*(?:[,;][ \t]*)?(?:[\]}]|(["'`])[ \t]*(?![ \t]*(?:[,;\r\n\]}]|$)))/yu;
282
+ const YAML_BLOCK_SCALAR_HEADER_STICKY_RE = /[|>](?:[+-]?\d*|\d*[+-]?)(?:[ \t]+#[^\r\n]*)?[ \t]*(?=\r?\n|$)/yu;
283
+ const AUTH_PARAM_NAME_EQ_STICKY_RE = /(?:(["'`])[A-Za-z0-9_.-]+\1|[A-Za-z0-9_.-]+)[ \t]*(?::=|==|=(?!=))/yu;
284
+ const AUTH_PARAM_NAME_COLON_STICKY_RE = /(?:(["'`])[A-Za-z0-9_.-]+\1|[A-Za-z0-9_.-]+)[ \t]*:(?!=)/yu;
285
+ const AUTH_PARAM_NAME_COLON_OR_EQ_STICKY_RE = /(?:(["'`])[A-Za-z0-9_.-]+\1|[A-Za-z0-9_.-]+)[ \t]*(?::=|==|:(?!=)|=(?!=))/yu;
286
+ const TITLECASE_SECRET_PREFIX_RE = /^(?:ApiKey|Bearer|Token|Secret|Passphrases?|Password|Passwd|Pwd|Credential|Cookie|Session)[a-z0-9]*$/u;
287
+ const KNOWN_NUM_SECRET_PREFIX_RE = /^(?:api[_-]?key|apikey|api|ssh[_-]?key|sshkey|ssh|auth|authorization|token|tokens|secret|secrets|key|keys|pass|passwd|passphrases?|password|passwords|pwd|cred|credential|credentials|cookie|cookies|session|sessions|jwt|jwts|oauth|oauths|bearer|access|refresh|private|client|signing|master|encryption)\d+[A-Za-z0-9]*$/iu;
288
+ const DIGIT_SEP_SECRET_STEM_RE = /^(?:api[_-]?key|apikeys|apikey|signing|master|encryption|access[_-]?key|access|refresh|private|client|jwt|jwts|oauth|oauths|ssh|sshkey|token|tokens|secret[_-]?key|secret|secrets|key|keys|pass|passwd|passphrases?|password|passwords|pwd|creds|cred|credential|credentials|cookie|cookies|session[_-]?id|session|sessions|auth[_-]?key|auth|authorization|bearer)(?:\d*(?:val|value|str|data|item|field)(?:v?\d+)?|v?\d+)?$/iu;
289
+ const DIGIT_SEP_UNSEPARATED_STEM_RE = /(?:api[_-]?key|apikeys|apikey|token|tokens|secret[_-]?key|secret|secrets|passphrases?|password|passwords|passwd|pwd|bearer|credential|credentials|creds|cookie|cookies|session[_-]?id|session|sessions|ssh[_-]?key|sshkey|signing[_-]?key|master[_-]?key|encryption[_-]?key|access[_-]?token|access[_-]?key|refresh[_-]?token|private[_-]?key|client[_-]?(?:secret|key)|auth[_-]?token|auth[_-]?key|authorization|jwt|jwts|oauth|oauths|(?:app|hmac|tls|ssl|aes|kms|fernet|cipher|pk|sk|rk|whsec|ghp|gho|ghu|ghs|ghr|glpat|npm|xox[bpar]|github[_-]?pat)[_-]?keys?)(?:\d*(?:val|value|str|data|item|field)(?:v?\d+)?|v?\d+)?$/iu;
290
+ const SUBSCRIPT_EXTRACT_RE = /\[[ \t]*(?:"([^"\r\n]+)"|'([^'\r\n]+)'|`([^`\r\n]+)`|(\$?[A-Za-z0-9_.-]*))[ \t]*\]|\.([A-Za-z0-9_-]+)/gu;
291
+ const OBJECT_PROPERTY_ASSIGN_STICKY_RE = /(?:(["'`])[A-Za-z0-9_.-]+\1|[A-Za-z0-9_.-]+)[ \t]*(?::(?!=)|=(?!=))/yu;
292
+ const YAML_MAPPING_KEY_STICKY_RE = /(?:(["'`])[A-Za-z0-9_.-]+\1|[A-Za-z0-9_.-]+)[ \t]*:(?![:=])/yu;
293
+ const DANGEROUS_EXT_RE = /\.(?:sqlite|sqlite3|db|env|pem|key|p12|pfx|crt|cer|pub|der|jks|keystore|kdbx|log|bak|secret|passwd|htpasswd|netrc|npmrc|pypirc|dockercfg)$/iu;
294
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu;
295
+ const IPV4_RE = /^\d{1,3}(?:\.\d{1,3}){3}$/u;
296
+ const HEX_LONG_RE = /^[0-9a-f]{20,}$/iu;
297
+ const NON_HYPHEN_LONG_RE = /^[a-z0-9_]{20,}$/iu;
298
+ const SAFE_ASCII_TOKEN_RE = /^[a-z0-9][a-z0-9._-]{1,47}$/u;
299
+ const CJK_CHAR_RE = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;
300
+ const SAFE_CJK_TOKEN_RE = /^[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}a-z0-9_-]{2,16}$/u;
301
+ function sha256Hex(value) {
302
+ return createHash('sha256').update(value, 'utf8').digest('hex');
303
+ }
304
+ function asDatabase(storeOrDb) {
305
+ return 'database' in storeOrDb ? storeOrDb.database : storeOrDb;
306
+ }
307
+ function hasTable(db, tableName) {
308
+ const row = db
309
+ .prepare("SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = ?")
310
+ .get(tableName);
311
+ return row !== undefined;
312
+ }
313
+ function escapeRegExp(value) {
314
+ return value.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
315
+ }
316
+ function collectScopeSensitiveTerms(scope) {
317
+ const exactTerms = new Set();
318
+ const substringTerms = new Set();
319
+ const rawLiterals = new Set();
320
+ if (typeof scope?.workspace === 'string' && scope.workspace.trim().length > 0) {
321
+ const ws = scope.workspace.trim();
322
+ rawLiterals.add(ws);
323
+ const lowerWs = ws.normalize('NFKC').toLocaleLowerCase('en-US');
324
+ exactTerms.add(lowerWs);
325
+ for (const seg of lowerWs.split(/[/\\]+/u)) {
326
+ const cleaned = seg.trim();
327
+ if (cleaned.length >= 2) {
328
+ exactTerms.add(cleaned);
329
+ }
330
+ if (cleaned.length >= 5) {
331
+ substringTerms.add(cleaned);
332
+ }
333
+ }
334
+ }
335
+ if (typeof scope?.principalId === 'string' && scope.principalId.trim().length > 0) {
336
+ const principal = scope.principalId.trim();
337
+ rawLiterals.add(principal);
338
+ const lowerPrincipal = principal.normalize('NFKC').toLocaleLowerCase('en-US');
339
+ exactTerms.add(lowerPrincipal);
340
+ if (lowerPrincipal.length >= 4) {
341
+ substringTerms.add(lowerPrincipal);
342
+ }
343
+ for (const seg of lowerPrincipal.split(/[:/\\@\s]+/u)) {
344
+ const cleaned = seg.trim();
345
+ if (cleaned.length >= 2) {
346
+ exactTerms.add(cleaned);
347
+ }
348
+ if (cleaned.length >= 5) {
349
+ substringTerms.add(cleaned);
350
+ }
351
+ }
352
+ for (const subSeg of lowerPrincipal.split(/[:/\\@\s_-]+/u)) {
353
+ const cleaned = subSeg.trim();
354
+ if (cleaned.length >= 4) {
355
+ exactTerms.add(cleaned);
356
+ }
357
+ }
358
+ }
359
+ return {
360
+ exactTerms,
361
+ substringTerms: [...substringTerms],
362
+ rawLiterals: [...rawLiterals].sort((a, b) => b.length - a.length),
363
+ };
364
+ }
365
+ function matchStickyAt(re, text, startIdx) {
366
+ re.lastIndex = startIdx;
367
+ return re.exec(text);
368
+ }
369
+ function findLineEnd(text, startIdx) {
370
+ let lineEnd = startIdx;
371
+ while (lineEnd < text.length && text[lineEnd] !== '\r' && text[lineEnd] !== '\n') {
372
+ lineEnd += 1;
373
+ }
374
+ return lineEnd;
375
+ }
376
+ function inspectLineStartAndMeta(text, lineStart) {
377
+ let i = lineStart;
378
+ let hasColonOrEq = false;
379
+ let hasQuote = false;
380
+ while (i < text.length) {
381
+ const code = text.charCodeAt(i);
382
+ if (code === 10 /* '\n' */ || code === 13 /* '\r' */)
383
+ break;
384
+ if (code === 58 /* ':' */ || code === 61 /* '=' */) {
385
+ hasColonOrEq = true;
386
+ }
387
+ else if (code === 34 /* '"' */ || code === 39 /* "'" */ || code === 96 /* '`' */) {
388
+ hasQuote = true;
389
+ }
390
+ i += 1;
391
+ }
392
+ return { lineEnd: i, hasColonOrEq, hasQuote };
393
+ }
394
+ function extractSubscriptSegments(subscriptChain) {
395
+ if (subscriptChain === undefined || subscriptChain.length === 0)
396
+ return [];
397
+ const segments = [];
398
+ SUBSCRIPT_EXTRACT_RE.lastIndex = 0;
399
+ let m;
400
+ while ((m = SUBSCRIPT_EXTRACT_RE.exec(subscriptChain)) !== null) {
401
+ const seg = m[1] ?? m[2] ?? m[3] ?? m[4] ?? m[5] ?? '';
402
+ if (seg.length > 0) {
403
+ segments.push(seg);
404
+ }
405
+ }
406
+ return segments;
407
+ }
408
+ function createBlockCommentCloseFinder(text) {
409
+ let starSlashPositions = null;
410
+ let lastHintIdx = 0;
411
+ return (openPos) => {
412
+ if (starSlashPositions === null) {
413
+ starSlashPositions = [];
414
+ let searchFrom = 0;
415
+ while (searchFrom < text.length) {
416
+ const found = text.indexOf('*/', searchFrom);
417
+ if (found === -1)
418
+ break;
419
+ starSlashPositions.push(found);
420
+ searchFrom = found + 2;
421
+ }
422
+ }
423
+ const target = openPos + 2;
424
+ const n = starSlashPositions.length;
425
+ if (n === 0 || starSlashPositions[n - 1] < target) {
426
+ return -1;
427
+ }
428
+ if (lastHintIdx < n &&
429
+ starSlashPositions[lastHintIdx] >= target &&
430
+ (lastHintIdx === 0 || starSlashPositions[lastHintIdx - 1] < target)) {
431
+ return starSlashPositions[lastHintIdx] + 2;
432
+ }
433
+ let lo = 0;
434
+ let hi = n - 1;
435
+ while (lo < hi) {
436
+ const mid = (lo + hi) >>> 1;
437
+ if (starSlashPositions[mid] < target) {
438
+ lo = mid + 1;
439
+ }
440
+ else {
441
+ hi = mid;
442
+ }
443
+ }
444
+ lastHintIdx = lo;
445
+ return starSlashPositions[lo] + 2;
446
+ };
447
+ }
448
+ function isLineStartKeyAssignment(text, lineStart, inPemBlock, hasColonOrEq = true, hasQuote = true) {
449
+ if (lineStart >= text.length)
450
+ return false;
451
+ if (hasColonOrEq) {
452
+ const assignMatch = matchStickyAt(LINE_START_ASSIGNMENT_RE, text, lineStart);
453
+ if (assignMatch !== null) {
454
+ if (!inPemBlock)
455
+ return true;
456
+ const baseIdent = assignMatch[3] ?? assignMatch[2] ?? '';
457
+ if (baseIdent.toLowerCase() === 'pass' || SECRET_KEY_PART_RE.test(baseIdent)) {
458
+ return true;
459
+ }
460
+ for (const seg of extractSubscriptSegments(assignMatch[4])) {
461
+ if (seg.toLowerCase() === 'pass' || SECRET_KEY_PART_RE.test(seg)) {
462
+ return true;
463
+ }
464
+ }
465
+ }
466
+ }
467
+ if (hasQuote) {
468
+ const spaceQuoteMatch = matchStickyAt(LINE_START_SECRET_SPACE_QUOTE_RE, text, lineStart);
469
+ if (spaceQuoteMatch !== null) {
470
+ const key = spaceQuoteMatch[3] ?? spaceQuoteMatch[2] ?? '';
471
+ if (SECRET_KEY_PART_RE.test(key)) {
472
+ return true;
473
+ }
474
+ }
475
+ }
476
+ return false;
477
+ }
478
+ function findFirstUnescapedCharOffset(line, targetChar) {
479
+ let i = 0;
480
+ while (i < line.length) {
481
+ const code = line.charCodeAt(i);
482
+ if (code === 92 /* '\\' */) {
483
+ i += 2;
484
+ continue;
485
+ }
486
+ if (line[i] === targetChar) {
487
+ return i;
488
+ }
489
+ i += 1;
490
+ }
491
+ return line.length;
492
+ }
493
+ function stripLineCommentsForAssignmentScan(line) {
494
+ if (!line.includes('/') && !line.includes('#')) {
495
+ return line;
496
+ }
497
+ let out = '';
498
+ let lastCopied = 0;
499
+ let quote = null;
500
+ let k = 0;
501
+ while (k < line.length) {
502
+ const ch = line[k];
503
+ if (quote !== null) {
504
+ if (line.charCodeAt(k) === 92 /* '\\' */) {
505
+ k += 2;
506
+ continue;
507
+ }
508
+ if (ch === quote) {
509
+ quote = null;
510
+ }
511
+ k += 1;
512
+ continue;
513
+ }
514
+ if (ch === '"' || ch === "'" || ch === '`') {
515
+ quote = ch;
516
+ k += 1;
517
+ continue;
518
+ }
519
+ if ((ch === '#' && (k === 0 || /[\s,;[{]/u.test(line[k - 1] ?? ''))) ||
520
+ (ch === '/' &&
521
+ k + 1 < line.length &&
522
+ line[k + 1] === '/' &&
523
+ (k === 0 || line[k - 1] !== ':'))) {
524
+ out += line.slice(lastCopied, k);
525
+ return out;
526
+ }
527
+ if (ch === '/' && k + 1 < line.length && line[k + 1] === '*') {
528
+ out += line.slice(lastCopied, k) + ' ';
529
+ let closeIdx = -1;
530
+ for (let m = k + 2; m + 1 < line.length; m += 1) {
531
+ if (line[m] === '*' && line[m + 1] === '/') {
532
+ closeIdx = m + 2;
533
+ break;
534
+ }
535
+ }
536
+ if (closeIdx === -1) {
537
+ return out;
538
+ }
539
+ lastCopied = closeIdx;
540
+ k = closeIdx;
541
+ continue;
542
+ }
543
+ k += 1;
544
+ }
545
+ return lastCopied === 0 ? line : out + line.slice(lastCopied);
546
+ }
547
+ function crossedLineHasKeyAssignment(text, lineStart, inPemBlock, closingQuoteChar = null, requireSecretKey = false) {
548
+ if (lineStart >= text.length)
549
+ return false;
550
+ const { lineEnd, hasColonOrEq, hasQuote } = inspectLineStartAndMeta(text, lineStart);
551
+ if (!hasColonOrEq && !hasQuote)
552
+ return false;
553
+ if (isLineStartKeyAssignment(text, lineStart, inPemBlock || requireSecretKey, hasColonOrEq, hasQuote)) {
554
+ return true;
555
+ }
556
+ if (inPemBlock || lineEnd <= lineStart)
557
+ return false;
558
+ const rawLine = text.slice(lineStart, lineEnd);
559
+ const rawLimitOffset = closingQuoteChar !== null ? findFirstUnescapedCharOffset(rawLine, closingQuoteChar) : rawLine.length;
560
+ if (rawLimitOffset === 0)
561
+ return false;
562
+ const line = !inPemBlock && closingQuoteChar === null
563
+ ? stripLineCommentsForAssignmentScan(rawLine)
564
+ : rawLine;
565
+ const limitOffset = closingQuoteChar !== null ? rawLimitOffset : line.length;
566
+ if (limitOffset === 0)
567
+ return false;
568
+ if (hasColonOrEq) {
569
+ INLINE_ASSIGNMENT_RE.lastIndex = 0;
570
+ let inlineAssign;
571
+ while ((inlineAssign = INLINE_ASSIGNMENT_RE.exec(line)) !== null) {
572
+ if (inlineAssign.index > limitOffset ||
573
+ (inlineAssign.index === limitOffset && inlineAssign[2] === undefined)) {
574
+ break;
575
+ }
576
+ const baseIdent = inlineAssign[3] ?? inlineAssign[2] ?? '';
577
+ if (baseIdent.toLowerCase() === 'pass' || SECRET_KEY_PART_RE.test(baseIdent)) {
578
+ return true;
579
+ }
580
+ for (const seg of extractSubscriptSegments(inlineAssign[4])) {
581
+ if (seg.toLowerCase() === 'pass' || SECRET_KEY_PART_RE.test(seg)) {
582
+ return true;
583
+ }
584
+ }
585
+ }
586
+ }
587
+ if (hasQuote) {
588
+ INLINE_SECRET_SPACE_QUOTE_RE.lastIndex = 0;
589
+ let inlineSpaceQuote;
590
+ while ((inlineSpaceQuote = INLINE_SECRET_SPACE_QUOTE_RE.exec(line)) !== null) {
591
+ if (inlineSpaceQuote.index > limitOffset ||
592
+ (inlineSpaceQuote.index === limitOffset && inlineSpaceQuote[2] === undefined)) {
593
+ break;
594
+ }
595
+ const key = inlineSpaceQuote[3] ?? inlineSpaceQuote[2] ?? '';
596
+ if (SECRET_KEY_PART_RE.test(key)) {
597
+ return true;
598
+ }
599
+ }
600
+ }
601
+ return false;
602
+ }
603
+ function matchEscapedQuotedValueEnd(text, pos) {
604
+ if (pos + 1 >= text.length || text[pos] !== '\\')
605
+ return -1;
606
+ const quote = text[pos + 1];
607
+ if (quote !== '"' && quote !== "'" && quote !== '`')
608
+ return -1;
609
+ let i = pos + 2;
610
+ while (i < text.length) {
611
+ const ch = text[i];
612
+ if (ch === '\r' || ch === '\n')
613
+ return -1;
614
+ if (ch === '\\') {
615
+ let j = i;
616
+ while (j < text.length && text[j] === '\\') {
617
+ j += 1;
618
+ }
619
+ const bsCount = j - i;
620
+ if (j < text.length && text[j] === quote) {
621
+ if (bsCount % 2 === 0) {
622
+ return -1;
623
+ }
624
+ if (bsCount >= 3 &&
625
+ j + 1 < text.length &&
626
+ !/[\s,;\r\n"'`)\]}]/u.test(text[j + 1])) {
627
+ i = j + 1;
628
+ continue;
629
+ }
630
+ return j + 1;
631
+ }
632
+ i = j < text.length && text[j] !== '\r' && text[j] !== '\n' ? j + 1 : j;
633
+ continue;
634
+ }
635
+ i += 1;
636
+ }
637
+ return -1;
638
+ }
639
+ function isAuthPrefixBeforeQuote(afterOp) {
640
+ const schemePrefixRe = /^[ \t]*(?:(?:["'`][A-Za-z0-9_-]+["'`]|[A-Za-z0-9_-]+)(?:[ \t:]+|[ \t]*[,;][ \t]*))?/yu;
641
+ const schemeMatch = matchStickyAt(schemePrefixRe, afterOp, 0);
642
+ let pos = schemeMatch !== null ? schemeMatch[0].length : 0;
643
+ if (pos === afterOp.length)
644
+ return true;
645
+ const paramNameEqRe = /(?:(["'`])[A-Za-z0-9_.-]+\1|[A-Za-z0-9_.-]+)[ \t]*(?::=|==|:(?!=)|=(?!=))[ \t]*/yu;
646
+ const paramValRe = /(?:"(?:[^"\\\r\n]|\\.)*"|'(?:[^'\\\r\n]|\\.)*'|`(?:[^`\\\r\n]|\\.)*`|(?:[^\s"'`<>|,;\\]|\\[^\r\n])+)/yu;
647
+ const paramSepRe = /(?:[ \t]*[,;][ \t]*|[ \t]+)/yu;
648
+ if (schemeMatch !== null &&
649
+ schemeMatch[0].length > 0 &&
650
+ afterOp[pos] === '\\' &&
651
+ matchStickyAt(paramNameEqRe, afterOp, pos) === null) {
652
+ const escCredEnd = matchEscapedQuotedValueEnd(afterOp, pos);
653
+ if (escCredEnd !== -1) {
654
+ const sepAfterCred = matchStickyAt(paramSepRe, afterOp, escCredEnd);
655
+ if (sepAfterCred !== null) {
656
+ pos = paramSepRe.lastIndex;
657
+ if (pos === afterOp.length)
658
+ return true;
659
+ }
660
+ }
661
+ }
662
+ while (pos < afterOp.length) {
663
+ const nameEq = matchStickyAt(paramNameEqRe, afterOp, pos);
664
+ if (nameEq === null)
665
+ return false;
666
+ pos = paramNameEqRe.lastIndex;
667
+ if (pos === afterOp.length)
668
+ return true;
669
+ if (afterOp[pos] === '\\') {
670
+ const escValEnd = matchEscapedQuotedValueEnd(afterOp, pos);
671
+ if (escValEnd !== -1) {
672
+ pos = escValEnd;
673
+ }
674
+ else {
675
+ const valMatch = matchStickyAt(paramValRe, afterOp, pos);
676
+ if (valMatch === null)
677
+ return false;
678
+ pos = paramValRe.lastIndex;
679
+ }
680
+ }
681
+ else {
682
+ const valMatch = matchStickyAt(paramValRe, afterOp, pos);
683
+ if (valMatch === null)
684
+ return false;
685
+ pos = paramValRe.lastIndex;
686
+ }
687
+ const sepMatch = matchStickyAt(paramSepRe, afterOp, pos);
688
+ if (sepMatch === null)
689
+ return false;
690
+ pos = paramSepRe.lastIndex;
691
+ }
692
+ return false;
693
+ }
694
+ function isCookiePrefixBeforeQuote(afterOp) {
695
+ let pos = 0;
696
+ while (pos < afterOp.length && (afterOp[pos] === ' ' || afterOp[pos] === '\t')) {
697
+ pos += 1;
698
+ }
699
+ const unquotedValRe = /[^\s"'`<>|;,{}[\]]+/yu;
700
+ const sepRe = /(?:[ \t]*[;,][ \t]*)+/yu;
701
+ while (pos < afterOp.length) {
702
+ if (matchStickyAt(COOKIE_EXPIRES_DATE_STICKY_RE, afterOp, pos) !== null) {
703
+ pos = COOKIE_EXPIRES_DATE_STICKY_RE.lastIndex;
704
+ }
705
+ else if (matchStickyAt(COOKIE_PAIR_START_STICKY_RE, afterOp, pos) !== null) {
706
+ pos = COOKIE_PAIR_START_STICKY_RE.lastIndex;
707
+ if (pos === afterOp.length)
708
+ return true;
709
+ const valMatch = matchStickyAt(unquotedValRe, afterOp, pos);
710
+ if (valMatch !== null) {
711
+ pos = unquotedValRe.lastIndex;
712
+ }
713
+ }
714
+ else if (matchStickyAt(COOKIE_ATTR_FLAG_STICKY_RE, afterOp, pos) !== null) {
715
+ pos = COOKIE_ATTR_FLAG_STICKY_RE.lastIndex;
716
+ }
717
+ else if (matchStickyAt(COOKIE_BARE_FLAG_PREFIX_STICKY_RE, afterOp, pos) !== null) {
718
+ pos = COOKIE_BARE_FLAG_PREFIX_STICKY_RE.lastIndex;
719
+ }
720
+ else {
721
+ const colonMatch = matchStickyAt(COOKIE_COLON_SECRET_STICKY_RE, afterOp, pos);
722
+ const colonKey = colonMatch !== null ? (colonMatch[3] ?? colonMatch[2] ?? '') : '';
723
+ if (colonMatch === null || !SECRET_KEY_PART_RE.test(colonKey)) {
724
+ return false;
725
+ }
726
+ pos = COOKIE_COLON_SECRET_STICKY_RE.lastIndex;
727
+ if (pos === afterOp.length)
728
+ return true;
729
+ const valMatch = matchStickyAt(unquotedValRe, afterOp, pos);
730
+ if (valMatch !== null) {
731
+ pos = unquotedValRe.lastIndex;
732
+ }
733
+ }
734
+ const sepMatch = matchStickyAt(sepRe, afterOp, pos);
735
+ if (sepMatch === null)
736
+ return false;
737
+ pos = sepRe.lastIndex;
738
+ }
739
+ return false;
740
+ }
741
+ function findInlineSecretAssignmentBefore(slice, maxOffset, requireAdjacentToMaxOffset) {
742
+ let bestIndex = -1;
743
+ INLINE_ASSIGNMENT_RE.lastIndex = 0;
744
+ let inlineAssign;
745
+ while ((inlineAssign = INLINE_ASSIGNMENT_RE.exec(slice)) !== null) {
746
+ if (inlineAssign.index >= maxOffset)
747
+ break;
748
+ const baseIdent = inlineAssign[3] ?? inlineAssign[2] ?? '';
749
+ const segments = extractSubscriptSegments(inlineAssign[4]);
750
+ const matchesAny = (re) => re.test(baseIdent) || segments.some((seg) => re.test(seg));
751
+ const isAuthKey = matchesAny(AUTH_KEY_PART_RE);
752
+ const isCookieKey = matchesAny(COOKIE_KEY_PART_RE);
753
+ if (matchesAny(SECRET_KEY_PART_RE)) {
754
+ if (requireAdjacentToMaxOffset) {
755
+ const afterOp = slice.slice(inlineAssign.index + inlineAssign[0].length, maxOffset);
756
+ const matchesAfterOp = isAuthKey
757
+ ? isAuthPrefixBeforeQuote(afterOp)
758
+ : isCookieKey
759
+ ? isCookiePrefixBeforeQuote(afterOp) || /^[ \t]*$/u.test(afterOp)
760
+ : /^[ \t]*$/u.test(afterOp);
761
+ if (matchesAfterOp) {
762
+ bestIndex = inlineAssign.index;
763
+ break;
764
+ }
765
+ continue;
766
+ }
767
+ bestIndex = inlineAssign.index;
768
+ break;
769
+ }
770
+ }
771
+ INLINE_SECRET_SPACE_QUOTE_RE.lastIndex = 0;
772
+ let spaceQuote;
773
+ while ((spaceQuote = INLINE_SECRET_SPACE_QUOTE_RE.exec(slice)) !== null) {
774
+ if (spaceQuote.index >= maxOffset)
775
+ break;
776
+ if (bestIndex !== -1 && spaceQuote.index >= bestIndex)
777
+ break;
778
+ const key = spaceQuote[3] ?? spaceQuote[2] ?? '';
779
+ if (SECRET_KEY_PART_RE.test(key)) {
780
+ if (requireAdjacentToMaxOffset) {
781
+ if (spaceQuote.index + spaceQuote[0].length - 1 === maxOffset) {
782
+ return spaceQuote.index;
783
+ }
784
+ continue;
785
+ }
786
+ return spaceQuote.index;
787
+ }
788
+ }
789
+ return bestIndex;
790
+ }
791
+ function findQuotedValueEnd(text, openIdx, noClosingQuote, isAuthContext = false, onAuthParamBoundary) {
792
+ const quote = text[openIdx];
793
+ if (quote !== '"' && quote !== "'" && quote !== '`')
794
+ return -1;
795
+ if (!noClosingQuote[quote]) {
796
+ const inPemBlock = matchStickyAt(PEM_OPEN_OPT_NL_STICKY_RE, text, openIdx + 1) !== null;
797
+ let i = openIdx + 1;
798
+ let onStartLine = true;
799
+ let sawEscapedQuoteOnStartLine = false;
800
+ while (i < text.length) {
801
+ if (text.charCodeAt(i) === 92 /* '\\' */) {
802
+ if (i + 1 < text.length && (text[i + 1] === '\r' || text[i + 1] === '\n')) {
803
+ i += 1;
804
+ continue;
805
+ }
806
+ if (onStartLine && i + 1 < text.length && text[i + 1] === quote) {
807
+ sawEscapedQuoteOnStartLine = true;
808
+ }
809
+ i += 2;
810
+ continue;
811
+ }
812
+ const ch = text[i];
813
+ if (ch === quote) {
814
+ if (onStartLine && sawEscapedQuoteOnStartLine) {
815
+ const startLineEnd = findLineEnd(text, openIdx + 1);
816
+ const startLineSlice = text.slice(openIdx + 1, startLineEnd);
817
+ const assignOffset = findInlineSecretAssignmentBefore(startLineSlice, i - (openIdx + 1), true);
818
+ if (assignOffset !== -1) {
819
+ return openIdx + 1 + assignOffset;
820
+ }
821
+ }
822
+ if (isAuthContext &&
823
+ onAuthParamBoundary !== undefined &&
824
+ isAuthPrefixBeforeQuote(onStartLine
825
+ ? text.slice(openIdx + 1, i)
826
+ : text.slice(openIdx + 1, i).replace(/\r?\n[ \t]+/gu, ' '))) {
827
+ const authBoundaryEnd = onAuthParamBoundary();
828
+ if (authBoundaryEnd > openIdx) {
829
+ return authBoundaryEnd;
830
+ }
831
+ }
832
+ return i + 1;
833
+ }
834
+ if (ch === '\r' || ch === '\n') {
835
+ if (onStartLine && sawEscapedQuoteOnStartLine) {
836
+ const startLineSlice = text.slice(openIdx + 1, i);
837
+ const assignOffset = findInlineSecretAssignmentBefore(startLineSlice, startLineSlice.length, false);
838
+ if (assignOffset !== -1) {
839
+ return openIdx + 1 + assignOffset;
840
+ }
841
+ }
842
+ onStartLine = false;
843
+ const nextLineStart = ch === '\r' && text[i + 1] === '\n' ? i + 2 : i + 1;
844
+ if (inPemBlock) {
845
+ if (matchStickyAt(PEM_END_STICKY_RE, text, nextLineStart) !== null) {
846
+ const pemEndPos = PEM_END_STICKY_RE.lastIndex;
847
+ return text[pemEndPos] === quote ? pemEndPos + 1 : pemEndPos;
848
+ }
849
+ if (isLineStartKeyAssignment(text, nextLineStart, true)) {
850
+ return i;
851
+ }
852
+ }
853
+ else if (crossedLineHasKeyAssignment(text, nextLineStart, false, quote)) {
854
+ if (isAuthContext && onAuthParamBoundary !== undefined) {
855
+ let np = nextLineStart;
856
+ while (np < text.length && (text[np] === ' ' || text[np] === '\t'))
857
+ np += 1;
858
+ if (text[np] === ',' || text[np] === ';') {
859
+ np += 1;
860
+ while (np < text.length && (text[np] === ' ' || text[np] === '\t'))
861
+ np += 1;
862
+ }
863
+ if (matchStickyAt(AUTH_PARAM_NAME_EQ_STICKY_RE, text, np) !== null) {
864
+ const nextParamHead = text.slice(np, AUTH_PARAM_NAME_EQ_STICKY_RE.lastIndex);
865
+ const foldedPrefix = text.slice(openIdx + 1, i).replace(/\r?\n[ \t]+/gu, ' ');
866
+ const sep = foldedPrefix.length === 0 || /\s$/u.test(foldedPrefix) ? '' : ' ';
867
+ if (isAuthPrefixBeforeQuote(`${foldedPrefix}${sep}${nextParamHead}`)) {
868
+ const authBoundaryEnd = onAuthParamBoundary();
869
+ if (authBoundaryEnd > openIdx) {
870
+ return authBoundaryEnd;
871
+ }
872
+ }
873
+ }
874
+ }
875
+ return findLineEnd(text, openIdx + 1);
876
+ }
877
+ i = nextLineStart;
878
+ continue;
879
+ }
880
+ i += 1;
881
+ }
882
+ if (onStartLine && sawEscapedQuoteOnStartLine) {
883
+ const startLineSlice = text.slice(openIdx + 1, text.length);
884
+ const assignOffset = findInlineSecretAssignmentBefore(startLineSlice, startLineSlice.length, false);
885
+ if (assignOffset !== -1) {
886
+ return openIdx + 1 + assignOffset;
887
+ }
888
+ }
889
+ if (inPemBlock) {
890
+ return text.length;
891
+ }
892
+ noClosingQuote[quote] = true;
893
+ }
894
+ // Unclosed quote fallback: scrub to the end of the current line only
895
+ return findLineEnd(text, openIdx + 1);
896
+ }
897
+ function findEffectiveLineEndBeforeComment(text, lineStart, lineEnd) {
898
+ let quote = null;
899
+ let k = lineStart;
900
+ let trailingCommentStart = -1;
901
+ while (k < lineEnd) {
902
+ const ch = text[k];
903
+ if (quote !== null) {
904
+ if (text.charCodeAt(k) === 92 /* '\\' */) {
905
+ k += 2;
906
+ continue;
907
+ }
908
+ if (ch === quote) {
909
+ quote = null;
910
+ }
911
+ trailingCommentStart = -1;
912
+ k += 1;
913
+ continue;
914
+ }
915
+ if (ch === '"' || ch === "'" || ch === '`') {
916
+ quote = ch;
917
+ trailingCommentStart = -1;
918
+ k += 1;
919
+ continue;
920
+ }
921
+ if ((ch === '#' && (k === lineStart || /[\s,;[{]/u.test(text[k - 1] ?? ''))) ||
922
+ (ch === '/' &&
923
+ k + 1 < lineEnd &&
924
+ text[k + 1] === '/' &&
925
+ (k === lineStart || text[k - 1] !== ':'))) {
926
+ return trailingCommentStart !== -1 ? trailingCommentStart : k;
927
+ }
928
+ if (ch === '/' && k + 1 < lineEnd && text[k + 1] === '*') {
929
+ let closeIdx = -1;
930
+ for (let m = k + 2; m + 1 < lineEnd; m += 1) {
931
+ if (text[m] === '*' && text[m + 1] === '/') {
932
+ closeIdx = m;
933
+ break;
934
+ }
935
+ }
936
+ if (closeIdx === -1) {
937
+ return trailingCommentStart !== -1 ? trailingCommentStart : k;
938
+ }
939
+ if (trailingCommentStart === -1) {
940
+ trailingCommentStart = k;
941
+ }
942
+ k = closeIdx + 2;
943
+ continue;
944
+ }
945
+ if (ch !== ' ' && ch !== '\t') {
946
+ trailingCommentStart = -1;
947
+ }
948
+ k += 1;
949
+ }
950
+ return trailingCommentStart !== -1 ? trailingCommentStart : lineEnd;
951
+ }
952
+ function lineEndsWithContainerToken(text, lineStart, lineEnd) {
953
+ const effectiveEnd = findEffectiveLineEndBeforeComment(text, lineStart, lineEnd);
954
+ let p = effectiveEnd - 1;
955
+ while (p >= lineStart && (text[p] === ' ' || text[p] === '\t')) {
956
+ p -= 1;
957
+ }
958
+ if (p < lineStart)
959
+ return false;
960
+ const ch = text[p];
961
+ return ch === ',' || ch === '[' || ch === '{';
962
+ }
963
+ function updatePrevLineEndedWithDelim(text, lineStart, lineEnd, prevFlag) {
964
+ const effectiveEnd = findEffectiveLineEndBeforeComment(text, lineStart, lineEnd);
965
+ let p = effectiveEnd - 1;
966
+ while (p >= lineStart && (text[p] === ' ' || text[p] === '\t')) {
967
+ p -= 1;
968
+ }
969
+ if (p < lineStart)
970
+ return prevFlag;
971
+ const ch = text[p];
972
+ return ch === ',' || ch === '[' || ch === '{';
973
+ }
974
+ function isContainerContinuationLine(text, lineStart, lineEnd, prevLineEndedWithDelimOrComma, braceDepth = 0, otherDepth = 0) {
975
+ let p = lineStart;
976
+ while (p < lineEnd && (text[p] === ' ' || text[p] === '\t')) {
977
+ p += 1;
978
+ }
979
+ if (p >= lineEnd)
980
+ return false;
981
+ const firstNonWs = text[p];
982
+ if (firstNonWs === '"' ||
983
+ firstNonWs === "'" ||
984
+ firstNonWs === '`' ||
985
+ firstNonWs === '[' ||
986
+ firstNonWs === '{' ||
987
+ firstNonWs === ']' ||
988
+ firstNonWs === '}' ||
989
+ firstNonWs === ',' ||
990
+ firstNonWs === ';') {
991
+ return true;
992
+ }
993
+ if (firstNonWs === '/' && p + 1 < lineEnd && (text[p + 1] === '/' || text[p + 1] === '*')) {
994
+ return true;
995
+ }
996
+ if (firstNonWs === '#' && (prevLineEndedWithDelimOrComma || braceDepth > 0 || otherDepth > 0)) {
997
+ return true;
998
+ }
999
+ if ((firstNonWs === '-' || firstNonWs === '*') &&
1000
+ (text[p + 1] === ' ' || text[p + 1] === '\t')) {
1001
+ return true;
1002
+ }
1003
+ if (braceDepth > 0 && isObjectPropertyLine(text, lineStart, lineEnd, true)) {
1004
+ return true;
1005
+ }
1006
+ if (!prevLineEndedWithDelimOrComma)
1007
+ return false;
1008
+ return p > lineStart || lineEndsWithContainerToken(text, lineStart, lineEnd);
1009
+ }
1010
+ function hasEvenUnescapedQuotes(text, lineStart, lineEnd, quoteChar) {
1011
+ let count = 0;
1012
+ let idx = lineStart;
1013
+ while (idx < lineEnd) {
1014
+ if (text.charCodeAt(idx) === 92 /* '\\' */) {
1015
+ idx += 2;
1016
+ continue;
1017
+ }
1018
+ if (text[idx] === quoteChar) {
1019
+ count += 1;
1020
+ }
1021
+ idx += 1;
1022
+ }
1023
+ return count >= 2 && count % 2 === 0;
1024
+ }
1025
+ function nextNonEmptyLineStartsWithCloser(text, afterLineEnd, allowBracketClose, allowBraceClose) {
1026
+ let pos = afterLineEnd;
1027
+ while (pos < text.length) {
1028
+ if (text[pos] === '\r' && text[pos + 1] === '\n')
1029
+ pos += 2;
1030
+ else if (text[pos] === '\r' || text[pos] === '\n')
1031
+ pos += 1;
1032
+ else
1033
+ break;
1034
+ const lineEnd = findLineEnd(text, pos);
1035
+ let p = pos;
1036
+ while (p < lineEnd && (text[p] === ' ' || text[p] === '\t'))
1037
+ p += 1;
1038
+ if (p < lineEnd) {
1039
+ return (allowBracketClose && text[p] === ']') || (allowBraceClose && text[p] === '}');
1040
+ }
1041
+ pos = lineEnd;
1042
+ }
1043
+ return false;
1044
+ }
1045
+ function skipLeadingHorizontalAndBlockComments(text, start, limit) {
1046
+ let p = start;
1047
+ while (p < limit) {
1048
+ if (text[p] === ' ' || text[p] === '\t') {
1049
+ p += 1;
1050
+ continue;
1051
+ }
1052
+ if (text[p] === '/' && p + 1 < limit && text[p + 1] === '*') {
1053
+ let closeIdx = -1;
1054
+ for (let k = p + 2; k + 1 < limit; k += 1) {
1055
+ if (text[k] === '*' && text[k + 1] === '/') {
1056
+ closeIdx = k + 2;
1057
+ break;
1058
+ }
1059
+ }
1060
+ if (closeIdx === -1)
1061
+ return limit;
1062
+ p = closeIdx;
1063
+ continue;
1064
+ }
1065
+ break;
1066
+ }
1067
+ return p;
1068
+ }
1069
+ function isObjectPropertyLine(text, lineStart, lineEnd, allowUnquotedCol0 = false) {
1070
+ let p = lineStart;
1071
+ while (p < lineEnd && (text[p] === ' ' || text[p] === '\t')) {
1072
+ p += 1;
1073
+ }
1074
+ const isCol0 = p === lineStart;
1075
+ p = skipLeadingHorizontalAndBlockComments(text, p, lineEnd);
1076
+ if (p >= lineEnd)
1077
+ return false;
1078
+ const ch = text[p];
1079
+ if (isCol0) {
1080
+ if (ch === '"' || ch === "'" || ch === '`') {
1081
+ return matchStickyAt(OBJECT_PROPERTY_ASSIGN_STICKY_RE, text, p) !== null;
1082
+ }
1083
+ if (!allowUnquotedCol0)
1084
+ return false;
1085
+ const propMatch = matchStickyAt(OBJECT_PROPERTY_ASSIGN_STICKY_RE, text, p);
1086
+ if (propMatch === null)
1087
+ return false;
1088
+ let valStart = propMatch.index + propMatch[0].length;
1089
+ while (valStart < lineEnd && (text[valStart] === ' ' || text[valStart] === '\t')) {
1090
+ valStart += 1;
1091
+ }
1092
+ if (valStart >= lineEnd)
1093
+ return false;
1094
+ const valChar = text[valStart];
1095
+ if (valChar === '"' ||
1096
+ valChar === "'" ||
1097
+ valChar === '`' ||
1098
+ valChar === '[' ||
1099
+ valChar === '{') {
1100
+ return true;
1101
+ }
1102
+ const effectiveEnd = findEffectiveLineEndBeforeComment(text, valStart, lineEnd);
1103
+ let tailIdx = effectiveEnd - 1;
1104
+ while (tailIdx >= valStart && (text[tailIdx] === ' ' || text[tailIdx] === '\t')) {
1105
+ tailIdx -= 1;
1106
+ }
1107
+ return tailIdx >= valStart && text[tailIdx] === ',';
1108
+ }
1109
+ return matchStickyAt(OBJECT_PROPERTY_ASSIGN_STICKY_RE, text, p) !== null;
1110
+ }
1111
+ function isUnquotedCol0NoCommaPropertyLine(text, lineStart, lineEnd) {
1112
+ if (lineStart >= lineEnd)
1113
+ return false;
1114
+ const firstCh = text[lineStart];
1115
+ if (firstCh === ' ' || firstCh === '\t' || firstCh === '"' || firstCh === "'" || firstCh === '`') {
1116
+ return false;
1117
+ }
1118
+ const p = skipLeadingHorizontalAndBlockComments(text, lineStart, lineEnd);
1119
+ if (p >= lineEnd)
1120
+ return false;
1121
+ const ch = text[p];
1122
+ if (ch === '"' || ch === "'" || ch === '`')
1123
+ return false;
1124
+ return matchStickyAt(OBJECT_PROPERTY_ASSIGN_STICKY_RE, text, p) !== null;
1125
+ }
1126
+ function propertyLineHasTrailingProse(text, lineStart, lineEnd) {
1127
+ const p = skipLeadingHorizontalAndBlockComments(text, lineStart, lineEnd);
1128
+ if (p >= lineEnd)
1129
+ return false;
1130
+ const propMatch = matchStickyAt(OBJECT_PROPERTY_ASSIGN_STICKY_RE, text, p);
1131
+ if (propMatch === null)
1132
+ return false;
1133
+ let valStart = propMatch.index + propMatch[0].length;
1134
+ while (valStart < lineEnd && (text[valStart] === ' ' || text[valStart] === '\t')) {
1135
+ valStart += 1;
1136
+ }
1137
+ if (valStart >= lineEnd)
1138
+ return false;
1139
+ const valChar = text[valStart];
1140
+ if (valChar === '[' || valChar === '{')
1141
+ return false;
1142
+ let afterVal = valStart;
1143
+ if (valChar === '"' || valChar === "'" || valChar === '`') {
1144
+ let j = valStart + 1;
1145
+ while (j < lineEnd) {
1146
+ if (text.charCodeAt(j) === 92 /* '\\' */) {
1147
+ j += 2;
1148
+ continue;
1149
+ }
1150
+ if (text[j] === valChar) {
1151
+ afterVal = j + 1;
1152
+ break;
1153
+ }
1154
+ j += 1;
1155
+ }
1156
+ if (afterVal === valStart)
1157
+ return false;
1158
+ }
1159
+ else {
1160
+ while (afterVal < lineEnd &&
1161
+ text[afterVal] !== ' ' &&
1162
+ text[afterVal] !== '\t' &&
1163
+ text[afterVal] !== ',' &&
1164
+ text[afterVal] !== ';' &&
1165
+ text[afterVal] !== '}' &&
1166
+ text[afterVal] !== ']') {
1167
+ afterVal += 1;
1168
+ }
1169
+ }
1170
+ while (afterVal < lineEnd && (text[afterVal] === ' ' || text[afterVal] === '\t')) {
1171
+ afterVal += 1;
1172
+ }
1173
+ if (afterVal >= lineEnd)
1174
+ return false;
1175
+ const tail = text[afterVal];
1176
+ if (tail === ',' ||
1177
+ tail === ';' ||
1178
+ tail === '}' ||
1179
+ tail === ']' ||
1180
+ tail === '#' ||
1181
+ (tail === '/' && (text[afterVal + 1] === '/' || text[afterVal + 1] === '*'))) {
1182
+ return false;
1183
+ }
1184
+ return true;
1185
+ }
1186
+ function findDelimitedValueEnd(text, openIdx, unclosedDelimiterPositions, findBlockCommentClose) {
1187
+ const openChar = text[openIdx];
1188
+ if (openChar !== '[' && openChar !== '{')
1189
+ return -1;
1190
+ if (unclosedDelimiterPositions.has(openIdx)) {
1191
+ return findLineEnd(text, openIdx + 1);
1192
+ }
1193
+ const resolveBlockClose = findBlockCommentClose ?? createBlockCommentCloseFinder(text);
1194
+ const primaryOpen = openChar;
1195
+ const primaryClose = openChar === '[' ? ']' : '}';
1196
+ const otherOpen = openChar === '[' ? '{' : '[';
1197
+ const unmatchedPrimaryStack = [
1198
+ { pos: openIdx, otherDepth: 0 },
1199
+ ];
1200
+ const unmatchedOtherStack = [];
1201
+ const recordUnclosedAtBreak = (requireZeroOtherDepth) => {
1202
+ for (const entry of unmatchedPrimaryStack) {
1203
+ if (!requireZeroOtherDepth || entry.otherDepth === 0) {
1204
+ unclosedDelimiterPositions.add(entry.pos);
1205
+ }
1206
+ }
1207
+ for (const entry of unmatchedOtherStack) {
1208
+ unclosedDelimiterPositions.add(entry.pos);
1209
+ }
1210
+ };
1211
+ const firstLineEnd = findLineEnd(text, openIdx + 1);
1212
+ let containerEndPos = firstLineEnd;
1213
+ let unclosedAssignBreakPos = -1;
1214
+ let tentativeCol0BreakPos = -1;
1215
+ let sawNonContainerLine = false;
1216
+ let prevLineEndedWithDelimOrComma = lineEndsWithContainerToken(text, openIdx, firstLineEnd);
1217
+ const pickBreakPos = (fallbackPos) => {
1218
+ if (unclosedAssignBreakPos !== -1 && tentativeCol0BreakPos !== -1) {
1219
+ return Math.min(unclosedAssignBreakPos, tentativeCol0BreakPos);
1220
+ }
1221
+ if (unclosedAssignBreakPos !== -1)
1222
+ return unclosedAssignBreakPos;
1223
+ if (tentativeCol0BreakPos !== -1)
1224
+ return tentativeCol0BreakPos;
1225
+ return fallbackPos;
1226
+ };
1227
+ let i = openIdx + 1;
1228
+ let primaryDepth = 1;
1229
+ let otherDepth = 0;
1230
+ let braceDepth = openChar === '{' ? 1 : 0;
1231
+ let activeQuote = null;
1232
+ let inActiveQuotePem = false;
1233
+ let inBlockComment = false;
1234
+ let lineStartedInBlockComment = false;
1235
+ while (i < text.length) {
1236
+ const ch = text[i];
1237
+ if (inBlockComment) {
1238
+ if (ch === '*' && text[i + 1] === '/') {
1239
+ inBlockComment = false;
1240
+ if (lineStartedInBlockComment) {
1241
+ lineStartedInBlockComment = false;
1242
+ const codeStart = i + 2;
1243
+ const curLineEnd = findLineEnd(text, codeStart);
1244
+ prevLineEndedWithDelimOrComma = updatePrevLineEndedWithDelim(text, codeStart, curLineEnd, prevLineEndedWithDelimOrComma);
1245
+ }
1246
+ i += 2;
1247
+ continue;
1248
+ }
1249
+ if (ch === '\r' || ch === '\n') {
1250
+ const nextLineStart = ch === '\r' && text[i + 1] === '\n' ? i + 2 : i + 1;
1251
+ const nextLineEnd = findLineEnd(text, nextLineStart);
1252
+ const requireSecretKey = braceDepth > 0 || otherDepth > 0;
1253
+ if (crossedLineHasKeyAssignment(text, nextLineStart, false, null, requireSecretKey)) {
1254
+ recordUnclosedAtBreak(false);
1255
+ return pickBreakPos(sawNonContainerLine ? containerEndPos : i);
1256
+ }
1257
+ if (!sawNonContainerLine) {
1258
+ containerEndPos = nextLineEnd;
1259
+ }
1260
+ lineStartedInBlockComment = true;
1261
+ i = nextLineStart;
1262
+ continue;
1263
+ }
1264
+ i += 1;
1265
+ continue;
1266
+ }
1267
+ if (activeQuote !== null) {
1268
+ if (text.charCodeAt(i) === 92 /* '\\' */) {
1269
+ if (i + 1 < text.length && (text[i + 1] === '\r' || text[i + 1] === '\n')) {
1270
+ i += 1;
1271
+ continue;
1272
+ }
1273
+ i += 2;
1274
+ continue;
1275
+ }
1276
+ if (ch === activeQuote) {
1277
+ activeQuote = null;
1278
+ inActiveQuotePem = false;
1279
+ i += 1;
1280
+ continue;
1281
+ }
1282
+ if (ch === '\r' || ch === '\n') {
1283
+ const nextLineStart = ch === '\r' && text[i + 1] === '\n' ? i + 2 : i + 1;
1284
+ const nextLineEnd = findLineEnd(text, nextLineStart);
1285
+ const requireSecretKey = braceDepth > 0 || otherDepth > 0;
1286
+ if (crossedLineHasKeyAssignment(text, nextLineStart, inActiveQuotePem, activeQuote, requireSecretKey)) {
1287
+ if (braceDepth > 0 && isObjectPropertyLine(text, nextLineStart, nextLineEnd, true)) {
1288
+ if (unclosedAssignBreakPos === -1) {
1289
+ unclosedAssignBreakPos = sawNonContainerLine ? containerEndPos : i;
1290
+ }
1291
+ }
1292
+ else if (braceDepth > 0 &&
1293
+ isUnquotedCol0NoCommaPropertyLine(text, nextLineStart, nextLineEnd)) {
1294
+ if (tentativeCol0BreakPos === -1) {
1295
+ tentativeCol0BreakPos = sawNonContainerLine ? containerEndPos : i;
1296
+ }
1297
+ }
1298
+ else {
1299
+ recordUnclosedAtBreak(false);
1300
+ return pickBreakPos(sawNonContainerLine ? containerEndPos : i);
1301
+ }
1302
+ }
1303
+ if (!inActiveQuotePem) {
1304
+ const elemMatch = matchStickyAt(ARRAY_ELEMENT_OR_CLOSE_STICKY_RE, text, nextLineStart);
1305
+ if ((elemMatch !== null && (elemMatch[1] === undefined || elemMatch[1] === activeQuote)) ||
1306
+ hasEvenUnescapedQuotes(text, nextLineStart, nextLineEnd, activeQuote)) {
1307
+ activeQuote = null;
1308
+ inActiveQuotePem = false;
1309
+ }
1310
+ }
1311
+ let p = nextLineStart;
1312
+ while (p < nextLineEnd && (text[p] === ' ' || text[p] === '\t'))
1313
+ p += 1;
1314
+ if (p < nextLineEnd && !sawNonContainerLine) {
1315
+ if (isContainerContinuationLine(text, nextLineStart, nextLineEnd, prevLineEndedWithDelimOrComma, braceDepth, otherDepth)) {
1316
+ containerEndPos = nextLineEnd;
1317
+ prevLineEndedWithDelimOrComma = updatePrevLineEndedWithDelim(text, nextLineStart, nextLineEnd, prevLineEndedWithDelimOrComma);
1318
+ }
1319
+ else if (braceDepth > 0 &&
1320
+ isUnquotedCol0NoCommaPropertyLine(text, nextLineStart, nextLineEnd)) {
1321
+ if (tentativeCol0BreakPos === -1) {
1322
+ tentativeCol0BreakPos = containerEndPos;
1323
+ }
1324
+ containerEndPos = nextLineEnd;
1325
+ prevLineEndedWithDelimOrComma = false;
1326
+ }
1327
+ else {
1328
+ sawNonContainerLine = true;
1329
+ }
1330
+ }
1331
+ lineStartedInBlockComment = false;
1332
+ i = nextLineStart;
1333
+ continue;
1334
+ }
1335
+ i += 1;
1336
+ continue;
1337
+ }
1338
+ if (ch === '#' && (i === openIdx + 1 || /[\s,;[{]/u.test(text[i - 1] ?? ''))) {
1339
+ i = findLineEnd(text, i);
1340
+ continue;
1341
+ }
1342
+ if (ch === '/' &&
1343
+ i + 1 < text.length &&
1344
+ text[i + 1] === '/' &&
1345
+ (i === openIdx + 1 || text[i - 1] !== ':')) {
1346
+ i = findLineEnd(text, i);
1347
+ continue;
1348
+ }
1349
+ if (ch === '/' && i + 1 < text.length && text[i + 1] === '*') {
1350
+ const closeEnd = resolveBlockClose(i);
1351
+ if (closeEnd !== -1) {
1352
+ const curLineEnd = findLineEnd(text, i);
1353
+ const closeLineEnd = findLineEnd(text, closeEnd);
1354
+ if (closeLineEnd !== curLineEnd) {
1355
+ prevLineEndedWithDelimOrComma = updatePrevLineEndedWithDelim(text, closeEnd, closeLineEnd, prevLineEndedWithDelimOrComma);
1356
+ if (!sawNonContainerLine && closeLineEnd > containerEndPos) {
1357
+ containerEndPos = closeLineEnd;
1358
+ }
1359
+ }
1360
+ i = closeEnd;
1361
+ continue;
1362
+ }
1363
+ inBlockComment = true;
1364
+ i += 2;
1365
+ continue;
1366
+ }
1367
+ if (ch === '"' || ch === "'" || ch === '`') {
1368
+ activeQuote = ch;
1369
+ inActiveQuotePem = matchStickyAt(PEM_OPEN_OPT_NL_STICKY_RE, text, i + 1) !== null;
1370
+ }
1371
+ else if (ch === primaryOpen) {
1372
+ primaryDepth += 1;
1373
+ if (primaryOpen === '{')
1374
+ braceDepth += 1;
1375
+ unmatchedPrimaryStack.push({ pos: i, otherDepth });
1376
+ }
1377
+ else if (ch === primaryClose) {
1378
+ primaryDepth -= 1;
1379
+ if (primaryClose === '}' && braceDepth > 0)
1380
+ braceDepth -= 1;
1381
+ if (unmatchedPrimaryStack.length > 0) {
1382
+ unmatchedPrimaryStack.pop();
1383
+ }
1384
+ if (primaryDepth === 0) {
1385
+ return i + 1;
1386
+ }
1387
+ }
1388
+ else if (ch === otherOpen) {
1389
+ otherDepth += 1;
1390
+ if (otherOpen === '{')
1391
+ braceDepth += 1;
1392
+ unmatchedOtherStack.push({ pos: i });
1393
+ }
1394
+ else if (ch === (openChar === '[' ? '}' : ']')) {
1395
+ if (otherDepth > 0) {
1396
+ otherDepth -= 1;
1397
+ }
1398
+ if (unmatchedOtherStack.length > 0) {
1399
+ unmatchedOtherStack.pop();
1400
+ }
1401
+ if (openChar === '[' && braceDepth > 0) {
1402
+ braceDepth -= 1;
1403
+ }
1404
+ }
1405
+ else if (ch === '\r' || ch === '\n') {
1406
+ const nextLineStart = ch === '\r' && text[i + 1] === '\n' ? i + 2 : i + 1;
1407
+ const nextLineEnd = findLineEnd(text, nextLineStart);
1408
+ const requireSecretKey = braceDepth > 0 || otherDepth > 0;
1409
+ let matchedNoCommaCol0Secret = false;
1410
+ if (crossedLineHasKeyAssignment(text, nextLineStart, false, null, requireSecretKey)) {
1411
+ if (braceDepth > 0 && isObjectPropertyLine(text, nextLineStart, nextLineEnd, true)) {
1412
+ if (unclosedAssignBreakPos === -1 &&
1413
+ propertyLineHasTrailingProse(text, nextLineStart, nextLineEnd)) {
1414
+ unclosedAssignBreakPos = sawNonContainerLine ? containerEndPos : i;
1415
+ }
1416
+ }
1417
+ else if (braceDepth > 0 &&
1418
+ isUnquotedCol0NoCommaPropertyLine(text, nextLineStart, nextLineEnd)) {
1419
+ matchedNoCommaCol0Secret = true;
1420
+ if (tentativeCol0BreakPos === -1) {
1421
+ tentativeCol0BreakPos = sawNonContainerLine ? containerEndPos : i;
1422
+ }
1423
+ }
1424
+ else {
1425
+ recordUnclosedAtBreak(false);
1426
+ return pickBreakPos(sawNonContainerLine ? containerEndPos : i);
1427
+ }
1428
+ }
1429
+ let p = nextLineStart;
1430
+ while (p < nextLineEnd && (text[p] === ' ' || text[p] === '\t'))
1431
+ p += 1;
1432
+ if (p < nextLineEnd && !sawNonContainerLine) {
1433
+ if (!matchedNoCommaCol0Secret &&
1434
+ isContainerContinuationLine(text, nextLineStart, nextLineEnd, prevLineEndedWithDelimOrComma, braceDepth, otherDepth)) {
1435
+ containerEndPos = nextLineEnd;
1436
+ prevLineEndedWithDelimOrComma = updatePrevLineEndedWithDelim(text, nextLineStart, nextLineEnd, prevLineEndedWithDelimOrComma);
1437
+ }
1438
+ else if (braceDepth > 0 &&
1439
+ isUnquotedCol0NoCommaPropertyLine(text, nextLineStart, nextLineEnd)) {
1440
+ if (tentativeCol0BreakPos === -1) {
1441
+ tentativeCol0BreakPos = containerEndPos;
1442
+ }
1443
+ containerEndPos = nextLineEnd;
1444
+ prevLineEndedWithDelimOrComma = false;
1445
+ }
1446
+ else if (prevLineEndedWithDelimOrComma &&
1447
+ nextNonEmptyLineStartsWithCloser(text, nextLineEnd, (primaryClose === ']' && primaryDepth > 0) || (primaryClose === '}' && otherDepth > 0), (primaryClose === '}' && primaryDepth > 0) || (primaryClose === ']' && otherDepth > 0))) {
1448
+ containerEndPos = nextLineEnd;
1449
+ prevLineEndedWithDelimOrComma = false;
1450
+ }
1451
+ else {
1452
+ sawNonContainerLine = true;
1453
+ recordUnclosedAtBreak(false);
1454
+ return pickBreakPos(containerEndPos);
1455
+ }
1456
+ }
1457
+ lineStartedInBlockComment = false;
1458
+ i = nextLineStart;
1459
+ continue;
1460
+ }
1461
+ i += 1;
1462
+ }
1463
+ recordUnclosedAtBreak(false);
1464
+ return pickBreakPos(containerEndPos);
1465
+ }
1466
+ function findUnquotedPemValueEnd(text, valueStart, pemBodyStart) {
1467
+ let i = pemBodyStart;
1468
+ while (i < text.length) {
1469
+ const ch = text[i];
1470
+ if (ch === '-' && matchStickyAt(PEM_END_STICKY_RE, text, i) !== null) {
1471
+ return PEM_END_STICKY_RE.lastIndex;
1472
+ }
1473
+ if (ch === '\r' || ch === '\n') {
1474
+ const nextLineStart = ch === '\r' && text[i + 1] === '\n' ? i + 2 : i + 1;
1475
+ if (isLineStartKeyAssignment(text, nextLineStart, true)) {
1476
+ return i >= valueStart ? i : findLineEnd(text, valueStart);
1477
+ }
1478
+ i = nextLineStart;
1479
+ continue;
1480
+ }
1481
+ i += 1;
1482
+ }
1483
+ return text.length;
1484
+ }
1485
+ function findYamlBlockScalarEnd(text, matchIndex, blockHeaderEnd) {
1486
+ let keyLineStart = matchIndex;
1487
+ while (keyLineStart > 0 && text[keyLineStart - 1] !== '\n' && text[keyLineStart - 1] !== '\r') {
1488
+ keyLineStart -= 1;
1489
+ }
1490
+ let listMarkerIndent = 0;
1491
+ while (keyLineStart + listMarkerIndent < matchIndex &&
1492
+ (text[keyLineStart + listMarkerIndent] === ' ' || text[keyLineStart + listMarkerIndent] === '\t')) {
1493
+ listMarkerIndent += 1;
1494
+ }
1495
+ let keyIndent = listMarkerIndent;
1496
+ let hasListMarker = false;
1497
+ if (keyLineStart + keyIndent + 1 < matchIndex &&
1498
+ (text[keyLineStart + keyIndent] === '-' || text[keyLineStart + keyIndent] === '*') &&
1499
+ (text[keyLineStart + keyIndent + 1] === ' ' || text[keyLineStart + keyIndent + 1] === '\t')) {
1500
+ hasListMarker = true;
1501
+ keyIndent += 2;
1502
+ while (keyLineStart + keyIndent < matchIndex &&
1503
+ (text[keyLineStart + keyIndent] === ' ' || text[keyLineStart + keyIndent] === '\t')) {
1504
+ keyIndent += 1;
1505
+ }
1506
+ }
1507
+ let lastContentEnd = blockHeaderEnd;
1508
+ let pos = blockHeaderEnd;
1509
+ while (pos < text.length) {
1510
+ if (text[pos] === '\r' && text[pos + 1] === '\n') {
1511
+ pos += 2;
1512
+ }
1513
+ else if (text[pos] === '\r' || text[pos] === '\n') {
1514
+ pos += 1;
1515
+ }
1516
+ else {
1517
+ break;
1518
+ }
1519
+ const lineStart = pos;
1520
+ const lineEnd = findLineEnd(text, lineStart);
1521
+ let p = lineStart;
1522
+ while (p < lineEnd && (text[p] === ' ' || text[p] === '\t')) {
1523
+ p += 1;
1524
+ }
1525
+ if (p < lineEnd) {
1526
+ const indent = p - lineStart;
1527
+ const isValidIndent = hasListMarker
1528
+ ? indent > keyIndent ||
1529
+ (indent > listMarkerIndent &&
1530
+ !(indent === keyIndent && isLineStartKeyAssignment(text, lineStart, false)))
1531
+ : indent > keyIndent;
1532
+ if (isValidIndent) {
1533
+ lastContentEnd = lineEnd;
1534
+ pos = lineEnd;
1535
+ continue;
1536
+ }
1537
+ break;
1538
+ }
1539
+ pos = lineEnd;
1540
+ }
1541
+ return lastContentEnd;
1542
+ }
1543
+ function matchesSecretParts(rawParts, hasDigit = false) {
1544
+ const lowerParts = rawParts.map((part) => part.toLowerCase());
1545
+ for (let idx = 0; idx < rawParts.length; idx += 1) {
1546
+ const rawPart = rawParts[idx];
1547
+ const part = lowerParts[idx];
1548
+ if (SECRET_EXACT_TOKENS.has(part) ||
1549
+ UNSEPARATED_SECRET_SUFFIX_RE.test(part) ||
1550
+ TITLECASE_SECRET_PREFIX_RE.test(rawPart)) {
1551
+ return true;
1552
+ }
1553
+ if (rawParts.length >= 2 &&
1554
+ (hasDigit
1555
+ ? DIGIT_SEP_SECRET_STEM_RE.test(part) || DIGIT_SEP_UNSEPARATED_STEM_RE.test(part)
1556
+ : /^(?:AUTH|SESSION|CRED|APIKEY|BEARER|TOKEN|SECRET|PASSPHRASES?|PASSWORD|PASSWD|PWD|COOKIE|PASS|JWT|Passphrases?|Pass|Jwt)$/u.test(rawPart))) {
1557
+ return true;
1558
+ }
1559
+ if (idx + 1 < lowerParts.length) {
1560
+ const nextPart = lowerParts[idx + 1];
1561
+ if (SECRET_EXACT_TOKENS.has(`${part}_${nextPart}`)) {
1562
+ return true;
1563
+ }
1564
+ if ((part === 'api' ||
1565
+ part === 'client' ||
1566
+ part === 'jwt' ||
1567
+ part === 'deploy' ||
1568
+ part === 'app' ||
1569
+ part === 'hmac' ||
1570
+ part === 'tls' ||
1571
+ part === 'ssl' ||
1572
+ part === 'aes' ||
1573
+ part === 'kms' ||
1574
+ part === 'fernet' ||
1575
+ part === 'cipher' ||
1576
+ part === 'pk' ||
1577
+ part === 'sk' ||
1578
+ part === 'rk' ||
1579
+ part === 'whsec' ||
1580
+ part === 'ghp' ||
1581
+ part === 'gho' ||
1582
+ part === 'ghu' ||
1583
+ part === 'ghs' ||
1584
+ part === 'ghr' ||
1585
+ part === 'glpat' ||
1586
+ part === 'npm' ||
1587
+ part === 'xoxb' ||
1588
+ part === 'xoxp' ||
1589
+ part === 'xoxa' ||
1590
+ part === 'xoxr' ||
1591
+ part === 'githubpat') &&
1592
+ nextPart.startsWith('key')) {
1593
+ return true;
1594
+ }
1595
+ if (idx + 2 < lowerParts.length &&
1596
+ part === 'github' &&
1597
+ nextPart === 'pat' &&
1598
+ lowerParts[idx + 2].startsWith('key')) {
1599
+ return true;
1600
+ }
1601
+ if (idx === lowerParts.length - 2 && part === 'github' && nextPart === 'pat') {
1602
+ return true;
1603
+ }
1604
+ }
1605
+ }
1606
+ return false;
1607
+ }
1608
+ function hasSecretStem(ident) {
1609
+ const hasDigit = /\d/u.test(ident);
1610
+ const prep = ident.replace(/([A-Za-z])([vV]\d+)$/u, '$1_$2');
1611
+ const camelSplit = prep
1612
+ .replace(/([A-Z]+)([A-Z][a-z])/gu, '$1_$2')
1613
+ .replace(/([a-z0-9])([A-Z])/gu, '$1_$2')
1614
+ .replace(/\d+/gu, '_');
1615
+ const camelParts = camelSplit.split(/[._-]+/u).filter((part) => part.length > 0);
1616
+ if (matchesSecretParts(camelParts, hasDigit))
1617
+ return true;
1618
+ const acronymLowerSplit = prep
1619
+ .replace(/([A-Z]{2,})([a-z]+)/gu, '$1_$2')
1620
+ .replace(/([a-z0-9])([A-Z])/gu, '$1_$2')
1621
+ .replace(/\d+/gu, '_');
1622
+ const acronymParts = acronymLowerSplit.split(/[._-]+/u).filter((part) => part.length > 0);
1623
+ return matchesSecretParts(acronymParts, hasDigit);
1624
+ }
1625
+ function isIdentifierLikeSecretKey(ident) {
1626
+ const lower = ident.toLowerCase();
1627
+ if (SECRET_EXACT_TOKENS.has(lower) ||
1628
+ CAMEL_OR_NUMBERED_SECRET_SUFFIX_RE.test(ident) ||
1629
+ /[._-]/u.test(lower) ||
1630
+ !/[A-Z]/u.test(ident) ||
1631
+ /^[A-Z][a-z0-9]*$/u.test(ident) ||
1632
+ /^[A-Z]+\d*$/u.test(ident)) {
1633
+ return true;
1634
+ }
1635
+ const prep = ident.replace(/([A-Za-z])([vV]\d+)$/u, '$1_$2');
1636
+ const splitParts = (raw) => raw.split(/[._-]+/u).filter((part) => part.length > 0);
1637
+ const noMidBase64DigitSplit = (raw) => splitParts(raw
1638
+ .replace(/([A-Z]+)([A-Z][a-z])/gu, '$1_$2')
1639
+ .replace(/([a-z0-9])([A-Z])/gu, '$1_$2'));
1640
+ const acronymNoMidDigitSplit = (raw) => splitParts(raw
1641
+ .replace(/([A-Z]{2,})([a-z]+)/gu, '$1_$2')
1642
+ .replace(/([a-z0-9])([A-Z])/gu, '$1_$2'));
1643
+ const checkPartsNoMidDigit = (parts) => {
1644
+ const lowerParts = parts.map((p) => p.toLowerCase());
1645
+ const strippedLowerParts = parts.map((p) => p.replace(/\d+$/u, '').toLowerCase());
1646
+ const isValidAcronymPos = (atIdx) => atIdx === 0 ||
1647
+ parts
1648
+ .slice(0, atIdx)
1649
+ .every((prev) => /^(?:[A-Z][a-z]+|[a-z]{2,}|[A-Z]{2,}|[a-z](?=\d))(?:\d+[a-z]*)?$/u.test(prev));
1650
+ for (let idx = 0; idx < parts.length; idx += 1) {
1651
+ const rawPart = parts[idx];
1652
+ const part = lowerParts[idx];
1653
+ const strippedRaw = rawPart.replace(/\d+$/u, '');
1654
+ const strippedPart = strippedLowerParts[idx];
1655
+ if (SECRET_EXACT_TOKENS.has(part) ||
1656
+ SECRET_EXACT_TOKENS.has(strippedPart) ||
1657
+ TITLECASE_SECRET_PREFIX_RE.test(rawPart)) {
1658
+ return true;
1659
+ }
1660
+ if (/^[A-Z]?[a-z]+$/u.test(strippedRaw) && UNSEPARATED_SECRET_SUFFIX_RE.test(strippedPart)) {
1661
+ return true;
1662
+ }
1663
+ if (KNOWN_NUM_SECRET_PREFIX_RE.test(rawPart) &&
1664
+ (!/^[A-Z]{2,}\d+/u.test(rawPart) || isValidAcronymPos(idx))) {
1665
+ return true;
1666
+ }
1667
+ const digitSepMatch = /^([A-Z][a-z]+|[A-Z]{2,}|[A-Z]|[a-z]+)\d+([A-Za-z0-9]+)$/u.exec(rawPart);
1668
+ if (digitSepMatch !== null) {
1669
+ const prefix = digitSepMatch[1];
1670
+ const tail = digitSepMatch[2];
1671
+ const prefixValid = /^[A-Z]$/u.test(prefix)
1672
+ ? idx > 0 && isValidAcronymPos(idx)
1673
+ : !/^[A-Z]{2,}$/u.test(prefix) || isValidAcronymPos(idx);
1674
+ if (prefixValid &&
1675
+ (DIGIT_SEP_SECRET_STEM_RE.test(tail) || DIGIT_SEP_UNSEPARATED_STEM_RE.test(tail))) {
1676
+ return true;
1677
+ }
1678
+ }
1679
+ if (idx > 0) {
1680
+ const prevPart = parts[idx - 1];
1681
+ const prevValid = /^(?:[A-Z][a-z]+|[A-Z]{2,}|[a-z]+)\d+[a-z]*$/u.test(prevPart) &&
1682
+ (!/^[A-Z]{2,}\d+/u.test(prevPart) || isValidAcronymPos(idx - 1)) &&
1683
+ (!/^[a-z]\d+[a-z]+$/u.test(prevPart) || isValidAcronymPos(idx - 1));
1684
+ if (prevValid &&
1685
+ (DIGIT_SEP_SECRET_STEM_RE.test(part) || DIGIT_SEP_UNSEPARATED_STEM_RE.test(part))) {
1686
+ return true;
1687
+ }
1688
+ }
1689
+ if (idx + 1 < lowerParts.length &&
1690
+ (SECRET_EXACT_TOKENS.has(`${part}_${lowerParts[idx + 1]}`) ||
1691
+ SECRET_EXACT_TOKENS.has(`${strippedPart}_${strippedLowerParts[idx + 1]}`))) {
1692
+ return true;
1693
+ }
1694
+ }
1695
+ return false;
1696
+ };
1697
+ if (checkPartsNoMidDigit(noMidBase64DigitSplit(prep)) ||
1698
+ checkPartsNoMidDigit(acronymNoMidDigitSplit(prep))) {
1699
+ return true;
1700
+ }
1701
+ if ((/[A-Z][a-z]+$/u.test(ident) ||
1702
+ (/[A-Za-z][vV]\d+$/u.test(ident) && !/^[a-z][A-Z]\d+[a-z]/u.test(ident))) &&
1703
+ hasSecretStem(ident)) {
1704
+ return true;
1705
+ }
1706
+ return false;
1707
+ }
1708
+ function isNextKeyAssignmentAt(text, valueStart, allowNonSecretNext) {
1709
+ const hadSpaceBeforeValue = valueStart > 0 && (text[valueStart - 1] === ' ' || text[valueStart - 1] === '\t');
1710
+ const assignMatch = matchStickyAt(NEXT_KEY_ASSIGNMENT_STICKY_RE, text, valueStart);
1711
+ if (assignMatch !== null) {
1712
+ const baseIdent = assignMatch[3] ?? assignMatch[2] ?? '';
1713
+ const segments = extractSubscriptSegments(assignMatch[4]);
1714
+ const preOpSpace = assignMatch[5] ?? '';
1715
+ const op = assignMatch[6] ?? '';
1716
+ const opSpace = assignMatch[7] ?? '';
1717
+ const rhsChar = assignMatch[8] ?? '';
1718
+ const isSecretIdent = (s) => s.toLowerCase() === 'pass' || SECRET_KEY_PART_RE.test(s) || hasSecretStem(s);
1719
+ const isSecretNext = isSecretIdent(baseIdent) || segments.some((seg) => isSecretIdent(seg));
1720
+ if (isSecretNext) {
1721
+ const prevChar = valueStart > 0 ? text[valueStart - 1] : undefined;
1722
+ const hasBase64Shape = segments.length === 0 &&
1723
+ ((/[A-Z]/u.test(baseIdent) && /[a-z]/u.test(baseIdent)) || /\d/u.test(baseIdent));
1724
+ if (!hadSpaceBeforeValue &&
1725
+ prevChar !== undefined &&
1726
+ !/\s/u.test(prevChar) &&
1727
+ preOpSpace.length === 0 &&
1728
+ op === '==' &&
1729
+ opSpace.length > 0 &&
1730
+ hasBase64Shape &&
1731
+ !isIdentifierLikeSecretKey(baseIdent) &&
1732
+ rhsChar !== '"' &&
1733
+ rhsChar !== "'" &&
1734
+ rhsChar !== '`' &&
1735
+ rhsChar !== '[' &&
1736
+ rhsChar !== '{') {
1737
+ return false;
1738
+ }
1739
+ return true;
1740
+ }
1741
+ if (allowNonSecretNext &&
1742
+ hadSpaceBeforeValue &&
1743
+ op !== '==' &&
1744
+ (rhsChar === '"' || rhsChar === "'" || rhsChar === '`' || rhsChar === '[' || rhsChar === '{')) {
1745
+ return true;
1746
+ }
1747
+ return false;
1748
+ }
1749
+ if (hadSpaceBeforeValue) {
1750
+ const spaceQuoteMatch = matchStickyAt(NEXT_SECRET_SPACE_QUOTE_STICKY_RE, text, valueStart);
1751
+ if (spaceQuoteMatch !== null) {
1752
+ const nextKey = spaceQuoteMatch[3] ?? spaceQuoteMatch[2] ?? '';
1753
+ if (SECRET_KEY_PART_RE.test(nextKey)) {
1754
+ return true;
1755
+ }
1756
+ }
1757
+ }
1758
+ return false;
1759
+ }
1760
+ function matchAuthParamSepEnd(text, pos, allowSpaceSep, minFoldedIndent, allowSemi = allowSpaceSep) {
1761
+ let p = pos;
1762
+ while (p < text.length && (text[p] === ' ' || text[p] === '\t')) {
1763
+ p += 1;
1764
+ }
1765
+ if (p < text.length && (text[p] === '\r' || text[p] === '\n')) {
1766
+ const folded = matchStickyAt(/\r?\n([ \t]+)/yu, text, p);
1767
+ if (folded !== null) {
1768
+ const afterFold = folded.index + folded[0].length;
1769
+ const foldIndent = (folded[1] ?? '').length;
1770
+ if (afterFold < text.length &&
1771
+ (text[afterFold] === ',' || (allowSemi && text[afterFold] === ';'))) {
1772
+ p = afterFold;
1773
+ }
1774
+ else if (allowSpaceSep &&
1775
+ minFoldedIndent !== undefined &&
1776
+ foldIndent >= minFoldedIndent &&
1777
+ afterFold < text.length) {
1778
+ return afterFold;
1779
+ }
1780
+ }
1781
+ }
1782
+ if (p < text.length && (text[p] === ',' || (allowSemi && text[p] === ';'))) {
1783
+ p += 1;
1784
+ while (p < text.length && (text[p] === ' ' || text[p] === '\t')) {
1785
+ p += 1;
1786
+ }
1787
+ if (p < text.length && (text[p] === '\r' || text[p] === '\n')) {
1788
+ const folded = matchStickyAt(/\r?\n[ \t]+/yu, text, p);
1789
+ if (folded !== null) {
1790
+ p = folded.index + folded[0].length;
1791
+ }
1792
+ }
1793
+ return p;
1794
+ }
1795
+ if (allowSpaceSep && p > pos) {
1796
+ return p;
1797
+ }
1798
+ return -1;
1799
+ }
1800
+ function consumeSingleAuthParamEnd(text, segStart, noClosingQuote, allowColonOp = false) {
1801
+ const nameOpRe = allowColonOp
1802
+ ? AUTH_PARAM_NAME_COLON_OR_EQ_STICKY_RE
1803
+ : AUTH_PARAM_NAME_EQ_STICKY_RE;
1804
+ const nameEqMatch = matchStickyAt(nameOpRe, text, segStart);
1805
+ if (nameEqMatch === null)
1806
+ return null;
1807
+ const opEnd = nameOpRe.lastIndex;
1808
+ const paramKey = text.slice(segStart, opEnd).replace(/[ \t]*(?::=|==|:|=)$/u, '').replace(/^["'`]|["'`]$/gu, '');
1809
+ let valStart = opEnd;
1810
+ while (valStart < text.length && (text[valStart] === ' ' || text[valStart] === '\t')) {
1811
+ valStart += 1;
1812
+ }
1813
+ const hadSpaceAfterOp = valStart > opEnd;
1814
+ if (valStart >= text.length)
1815
+ return { endPos: opEnd, isSecretOrQuoted: SECRET_KEY_PART_RE.test(paramKey) };
1816
+ const valChar = text[valStart];
1817
+ if (valChar === '[' || valChar === '{') {
1818
+ return null;
1819
+ }
1820
+ if (valChar === '"' || valChar === "'" || valChar === '`') {
1821
+ return {
1822
+ endPos: findQuotedValueEnd(text, valStart, noClosingQuote),
1823
+ isSecretOrQuoted: true,
1824
+ };
1825
+ }
1826
+ if (valChar === '\\') {
1827
+ const escEnd = matchEscapedQuotedValueEnd(text, valStart);
1828
+ if (escEnd !== -1) {
1829
+ return {
1830
+ endPos: escEnd,
1831
+ isSecretOrQuoted: true,
1832
+ };
1833
+ }
1834
+ }
1835
+ if (hadSpaceAfterOp &&
1836
+ (matchStickyAt(AUTH_PARAM_NAME_EQ_STICKY_RE, text, valStart) !== null ||
1837
+ (allowColonOp && matchStickyAt(AUTH_PARAM_NAME_COLON_STICKY_RE, text, valStart) !== null) ||
1838
+ isNextKeyAssignmentAt(text, valStart, true))) {
1839
+ return { endPos: opEnd, isSecretOrQuoted: SECRET_KEY_PART_RE.test(paramKey) };
1840
+ }
1841
+ const unquotedRe = /[^\s"'`<>|,{}[\]]+/yu;
1842
+ if (matchStickyAt(unquotedRe, text, valStart) !== null) {
1843
+ return {
1844
+ endPos: unquotedRe.lastIndex,
1845
+ isSecretOrQuoted: SECRET_KEY_PART_RE.test(paramKey),
1846
+ };
1847
+ }
1848
+ return { endPos: opEnd, isSecretOrQuoted: SECRET_KEY_PART_RE.test(paramKey) };
1849
+ }
1850
+ function resolveCommaAuthParamsEnd(text, credStart, noClosingQuote, allowSpaceOrSemiSep = false, allowColonOp = false, foldedOriginPos, requireMultiOrSecretOnColonOp = false) {
1851
+ const firstParam = consumeSingleAuthParamEnd(text, credStart, noClosingQuote, allowColonOp);
1852
+ if (firstParam === null)
1853
+ return -1;
1854
+ let endPos = firstParam.endPos;
1855
+ let paramCount = 1;
1856
+ let cachedMinFoldedIndent;
1857
+ while (endPos < text.length) {
1858
+ let minFoldedIndent;
1859
+ if (foldedOriginPos !== undefined && allowSpaceOrSemiSep) {
1860
+ let p = endPos;
1861
+ while (p < text.length && (text[p] === ' ' || text[p] === '\t'))
1862
+ p += 1;
1863
+ if (p < text.length && (text[p] === '\r' || text[p] === '\n')) {
1864
+ if (cachedMinFoldedIndent === undefined) {
1865
+ cachedMinFoldedIndent = Math.max(1, getLineIndentAt(text, foldedOriginPos));
1866
+ }
1867
+ minFoldedIndent = cachedMinFoldedIndent;
1868
+ }
1869
+ }
1870
+ const nextSegStart = matchAuthParamSepEnd(text, endPos, allowSpaceOrSemiSep, minFoldedIndent, allowSpaceOrSemiSep);
1871
+ if (nextSegStart === -1)
1872
+ break;
1873
+ const nextParam = consumeSingleAuthParamEnd(text, nextSegStart, noClosingQuote, allowColonOp);
1874
+ if (nextParam === null)
1875
+ break;
1876
+ endPos = nextParam.endPos;
1877
+ paramCount += 1;
1878
+ }
1879
+ if (requireMultiOrSecretOnColonOp && paramCount < 2 && !firstParam.isSecretOrQuoted) {
1880
+ return -1;
1881
+ }
1882
+ return endPos;
1883
+ }
1884
+ function getLineIndentAt(text, pos) {
1885
+ let lineStart = pos;
1886
+ while (lineStart > 0 && text[lineStart - 1] !== '\n' && text[lineStart - 1] !== '\r') {
1887
+ lineStart -= 1;
1888
+ }
1889
+ let p = lineStart;
1890
+ while (p < text.length && (text[p] === ' ' || text[p] === '\t')) {
1891
+ p += 1;
1892
+ }
1893
+ return p - lineStart;
1894
+ }
1895
+ function consumePostSchemeCredentialEnd(text, schemeEnd, afterWsPos, isKnownScheme, allowSpaceOrSemiAuthParams, isCookie, noClosingQuote, unclosedDelimiterPositions, findBlockCommentClose) {
1896
+ let credPos = afterWsPos;
1897
+ let wasFolded = false;
1898
+ let foldedIndent = 0;
1899
+ if (credPos < text.length && (text[credPos] === '\r' || text[credPos] === '\n')) {
1900
+ const foldedMatch = matchStickyAt(/\r?\n([ \t]+)/yu, text, credPos);
1901
+ if (foldedMatch !== null) {
1902
+ credPos = foldedMatch.index + foldedMatch[0].length;
1903
+ wasFolded = true;
1904
+ foldedIndent = (foldedMatch[1] ?? '').length;
1905
+ }
1906
+ }
1907
+ if (!isCookie) {
1908
+ const schemeLineIndent = getLineIndentAt(text, schemeEnd);
1909
+ const allowColonOp = !wasFolded || foldedIndent >= Math.max(1, schemeLineIndent);
1910
+ const multiParamEnd = resolveCommaAuthParamsEnd(text, credPos, noClosingQuote, allowSpaceOrSemiAuthParams, allowColonOp, schemeEnd);
1911
+ if (multiParamEnd !== -1) {
1912
+ return multiParamEnd;
1913
+ }
1914
+ }
1915
+ if (isNextKeyAssignmentAt(text, credPos, !isCookie) ||
1916
+ (wasFolded && matchStickyAt(OBJECT_PROPERTY_ASSIGN_STICKY_RE, text, credPos) !== null)) {
1917
+ return schemeEnd;
1918
+ }
1919
+ if (credPos >= text.length) {
1920
+ return schemeEnd;
1921
+ }
1922
+ const credFirstChar = text[credPos];
1923
+ if (credFirstChar === '"' || credFirstChar === "'" || credFirstChar === '`') {
1924
+ return findQuotedValueEnd(text, credPos, noClosingQuote);
1925
+ }
1926
+ if (credFirstChar === '\\') {
1927
+ const escEnd = matchEscapedQuotedValueEnd(text, credPos);
1928
+ if (escEnd !== -1) {
1929
+ if (!isCookie) {
1930
+ const nextSep = matchAuthParamSepEnd(text, escEnd, allowSpaceOrSemiAuthParams, undefined, allowSpaceOrSemiAuthParams);
1931
+ if (nextSep !== -1) {
1932
+ const trailingParamsEnd = resolveCommaAuthParamsEnd(text, nextSep, noClosingQuote, allowSpaceOrSemiAuthParams, !wasFolded || foldedIndent >= Math.max(1, getLineIndentAt(text, schemeEnd)), schemeEnd);
1933
+ if (trailingParamsEnd !== -1) {
1934
+ return trailingParamsEnd;
1935
+ }
1936
+ }
1937
+ }
1938
+ return escEnd;
1939
+ }
1940
+ }
1941
+ if (credFirstChar === '[' || credFirstChar === '{') {
1942
+ return findDelimitedValueEnd(text, credPos, unclosedDelimiterPositions, findBlockCommentClose);
1943
+ }
1944
+ const tokenRe = /[^\s"'`<>|;,{}[\]]{2,}/yu;
1945
+ const tokenMatch = matchStickyAt(tokenRe, text, credPos);
1946
+ if (tokenMatch !== null) {
1947
+ const cred = tokenMatch[0];
1948
+ if (isKnownScheme) {
1949
+ return tokenRe.lastIndex;
1950
+ }
1951
+ if (SECRET_VALUE_CHAR_RE.test(cred) ||
1952
+ (/[A-Z]/u.test(cred) && /[a-z]/u.test(cred)) ||
1953
+ (cred.length >= 8 && !STOPWORDS.has(cred.toLowerCase()))) {
1954
+ return tokenRe.lastIndex;
1955
+ }
1956
+ }
1957
+ return schemeEnd;
1958
+ }
1959
+ function resolveAuthValueEnd(text, authStart, allowScalarOnlyFallback, noClosingQuote, unclosedDelimiterPositions, headerLineOriginPos = authStart, findBlockCommentClose) {
1960
+ if (authStart >= text.length)
1961
+ return -1;
1962
+ const firstChar = text[authStart];
1963
+ if (firstChar === '"' || firstChar === "'" || firstChar === '`') {
1964
+ const quotedSchemeMatch = matchStickyAt(QUOTED_AUTH_SCHEME_STICKY_RE, text, authStart);
1965
+ if (quotedSchemeMatch !== null) {
1966
+ const rawScheme = quotedSchemeMatch[1] ?? quotedSchemeMatch[2] ?? quotedSchemeMatch[3] ?? '';
1967
+ const schemeEnd = authStart + rawScheme.length + 2;
1968
+ const afterSchemeSep = quotedSchemeMatch[0].slice(rawScheme.length + 2);
1969
+ if (afterSchemeSep.includes(',') || afterSchemeSep.includes(';')) {
1970
+ const multiParamEnd = resolveCommaAuthParamsEnd(text, QUOTED_AUTH_SCHEME_STICKY_RE.lastIndex, noClosingQuote, true, true, schemeEnd);
1971
+ return multiParamEnd !== -1 ? multiParamEnd : schemeEnd;
1972
+ }
1973
+ const isKnown = KNOWN_AUTH_SCHEMES.has(rawScheme.toLowerCase());
1974
+ return consumePostSchemeCredentialEnd(text, schemeEnd, QUOTED_AUTH_SCHEME_STICKY_RE.lastIndex, isKnown, true, false, noClosingQuote, unclosedDelimiterPositions, findBlockCommentClose);
1975
+ }
1976
+ return findQuotedValueEnd(text, authStart, noClosingQuote, true, () => resolveAuthValueEnd(text, authStart + 1, false, noClosingQuote, unclosedDelimiterPositions, headerLineOriginPos, findBlockCommentClose));
1977
+ }
1978
+ if (firstChar === '[' || firstChar === '{') {
1979
+ return findDelimitedValueEnd(text, authStart, unclosedDelimiterPositions, findBlockCommentClose);
1980
+ }
1981
+ const schemeMatch = matchStickyAt(SCHEME_PREFIX_STICKY_RE, text, authStart);
1982
+ if (schemeMatch !== null) {
1983
+ const afterWsPos = SCHEME_PREFIX_STICKY_RE.lastIndex;
1984
+ const delimSepEnd = matchAuthParamSepEnd(text, afterWsPos, false, undefined, true);
1985
+ if (delimSepEnd !== -1) {
1986
+ const multiParamEnd = resolveCommaAuthParamsEnd(text, delimSepEnd, noClosingQuote, true, true, authStart);
1987
+ if (multiParamEnd !== -1) {
1988
+ return multiParamEnd;
1989
+ }
1990
+ return afterWsPos;
1991
+ }
1992
+ return consumePostSchemeCredentialEnd(text, afterWsPos, afterWsPos, true, true, false, noClosingQuote, unclosedDelimiterPositions, findBlockCommentClose);
1993
+ }
1994
+ if (allowScalarOnlyFallback) {
1995
+ if (firstChar === ',' || firstChar === ';') {
1996
+ const sepEnd = matchAuthParamSepEnd(text, authStart, false, undefined, true);
1997
+ if (sepEnd !== -1) {
1998
+ const multiParamEnd = resolveCommaAuthParamsEnd(text, sepEnd, noClosingQuote, true, true, headerLineOriginPos);
1999
+ if (multiParamEnd !== -1) {
2000
+ return multiParamEnd;
2001
+ }
2002
+ }
2003
+ }
2004
+ const foldedEqParamEnd = resolveCommaAuthParamsEnd(text, authStart, noClosingQuote, true, false, headerLineOriginPos);
2005
+ if (foldedEqParamEnd !== -1) {
2006
+ return foldedEqParamEnd;
2007
+ }
2008
+ const foldedColonParamEnd = resolveCommaAuthParamsEnd(text, authStart, noClosingQuote, true, true, headerLineOriginPos, true);
2009
+ if (foldedColonParamEnd !== -1) {
2010
+ return foldedColonParamEnd;
2011
+ }
2012
+ }
2013
+ else {
2014
+ const directEqParamEnd = resolveCommaAuthParamsEnd(text, authStart, noClosingQuote, true, false, headerLineOriginPos);
2015
+ if (directEqParamEnd !== -1) {
2016
+ return directEqParamEnd;
2017
+ }
2018
+ const directColonParamEnd = resolveCommaAuthParamsEnd(text, authStart, noClosingQuote, true, true, headerLineOriginPos, true);
2019
+ if (directColonParamEnd !== -1) {
2020
+ return directColonParamEnd;
2021
+ }
2022
+ }
2023
+ if (isNextKeyAssignmentAt(text, authStart, true)) {
2024
+ return allowScalarOnlyFallback ? -1 : authStart;
2025
+ }
2026
+ if (allowScalarOnlyFallback && matchStickyAt(OBJECT_PROPERTY_ASSIGN_STICKY_RE, text, authStart) !== null) {
2027
+ return -1;
2028
+ }
2029
+ const tokenRe = /[^\s"'`<>|;,{}[\]]{2,}/yu;
2030
+ const tokenMatch = matchStickyAt(tokenRe, text, authStart);
2031
+ if (tokenMatch === null)
2032
+ return -1;
2033
+ const schemeTok = tokenMatch[0];
2034
+ const isKnown = KNOWN_AUTH_SCHEMES.has(schemeTok.toLowerCase());
2035
+ const commaSepEnd = matchAuthParamSepEnd(text, tokenRe.lastIndex, false, undefined, true);
2036
+ if (commaSepEnd !== -1) {
2037
+ const multiParamEnd = resolveCommaAuthParamsEnd(text, commaSepEnd, noClosingQuote, true, true, authStart);
2038
+ if (multiParamEnd !== -1) {
2039
+ return multiParamEnd;
2040
+ }
2041
+ }
2042
+ else {
2043
+ const wsAfterScheme = matchStickyAt(/[ \t:]+/yu, text, tokenRe.lastIndex);
2044
+ if (wsAfterScheme !== null) {
2045
+ const wsEnd = wsAfterScheme.index + wsAfterScheme[0].length;
2046
+ const credEnd = consumePostSchemeCredentialEnd(text, tokenRe.lastIndex, wsEnd, isKnown, true, false, noClosingQuote, unclosedDelimiterPositions, findBlockCommentClose);
2047
+ if (credEnd > tokenRe.lastIndex) {
2048
+ return credEnd;
2049
+ }
2050
+ }
2051
+ else {
2052
+ const credEnd = consumePostSchemeCredentialEnd(text, tokenRe.lastIndex, tokenRe.lastIndex, isKnown, true, false, noClosingQuote, unclosedDelimiterPositions, findBlockCommentClose);
2053
+ if (credEnd > tokenRe.lastIndex) {
2054
+ return credEnd;
2055
+ }
2056
+ }
2057
+ }
2058
+ if (allowScalarOnlyFallback) {
2059
+ if (isKnown ||
2060
+ SECRET_VALUE_CHAR_RE.test(schemeTok) ||
2061
+ (/[A-Z]/u.test(schemeTok) && /[a-z]/u.test(schemeTok)) ||
2062
+ (schemeTok.length >= 8 && !STOPWORDS.has(schemeTok.toLowerCase())) ||
2063
+ (/^[A-Z]{4,}$/u.test(schemeTok) &&
2064
+ countTrailingWordsOnLine(text, tokenRe.lastIndex) <= 1)) {
2065
+ return tokenRe.lastIndex;
2066
+ }
2067
+ return -1;
2068
+ }
2069
+ return tokenRe.lastIndex;
2070
+ }
2071
+ function countTrailingWordsOnLine(text, pos) {
2072
+ const lineEnd = findLineEnd(text, pos);
2073
+ let count = 0;
2074
+ let p = pos;
2075
+ while (p < lineEnd) {
2076
+ while (p < lineEnd && (text[p] === ' ' || text[p] === '\t'))
2077
+ p += 1;
2078
+ if (p >= lineEnd)
2079
+ break;
2080
+ const start = p;
2081
+ while (p < lineEnd && text[p] !== ' ' && text[p] !== '\t')
2082
+ p += 1;
2083
+ if (p > start)
2084
+ count += 1;
2085
+ if (count > 2)
2086
+ break;
2087
+ }
2088
+ return count;
2089
+ }
2090
+ function isCrossLineSecretScalar(tok, key, text, afterTokIdx) {
2091
+ if (SECRET_VALUE_CHAR_RE.test(tok))
2092
+ return true;
2093
+ if (/[A-Z]/u.test(tok) && /[a-z]/u.test(tok))
2094
+ return true;
2095
+ if (/^[A-Z]{4,}$/u.test(tok)) {
2096
+ return countTrailingWordsOnLine(text, afterTokIdx) <= 1 || /[_-]/u.test(key);
2097
+ }
2098
+ const lower = tok.toLowerCase();
2099
+ if (STOPWORDS.has(lower))
2100
+ return false;
2101
+ if (tok.length >= 8)
2102
+ return true;
2103
+ if (tok.length >= 4) {
2104
+ return countTrailingWordsOnLine(text, afterTokIdx) <= 1;
2105
+ }
2106
+ return false;
2107
+ }
2108
+ function getYamlKeyIndentInfo(text, matchIndex) {
2109
+ let keyLineStart = matchIndex;
2110
+ while (keyLineStart > 0 && text[keyLineStart - 1] !== '\n' && text[keyLineStart - 1] !== '\r') {
2111
+ keyLineStart -= 1;
2112
+ }
2113
+ let listMarkerIndent = 0;
2114
+ while (keyLineStart + listMarkerIndent < matchIndex &&
2115
+ (text[keyLineStart + listMarkerIndent] === ' ' || text[keyLineStart + listMarkerIndent] === '\t')) {
2116
+ listMarkerIndent += 1;
2117
+ }
2118
+ let keyIndent = listMarkerIndent;
2119
+ let hasListMarker = false;
2120
+ if (keyLineStart + keyIndent + 1 < matchIndex &&
2121
+ (text[keyLineStart + keyIndent] === '-' || text[keyLineStart + keyIndent] === '*') &&
2122
+ (text[keyLineStart + keyIndent + 1] === ' ' || text[keyLineStart + keyIndent + 1] === '\t')) {
2123
+ hasListMarker = true;
2124
+ keyIndent += 2;
2125
+ while (keyLineStart + keyIndent < matchIndex &&
2126
+ (text[keyLineStart + keyIndent] === ' ' || text[keyLineStart + keyIndent] === '\t')) {
2127
+ keyIndent += 1;
2128
+ }
2129
+ }
2130
+ return { listMarkerIndent, keyIndent, hasListMarker };
2131
+ }
2132
+ function consumeYamlPureCommentEnd(text, startPos, findBlockCommentClose) {
2133
+ let p = startPos;
2134
+ while (p < text.length) {
2135
+ while (p < text.length && (text[p] === ' ' || text[p] === '\t')) {
2136
+ p += 1;
2137
+ }
2138
+ if (p >= text.length || text[p] === '\r' || text[p] === '\n') {
2139
+ return p;
2140
+ }
2141
+ if (text[p] === '#' || (text[p] === '/' && text[p + 1] === '/')) {
2142
+ return findLineEnd(text, p);
2143
+ }
2144
+ if (text[p] === '/' && text[p + 1] === '*') {
2145
+ const closeEnd = findBlockCommentClose(p);
2146
+ if (closeEnd === -1)
2147
+ return -1;
2148
+ p = closeEnd;
2149
+ continue;
2150
+ }
2151
+ return -1;
2152
+ }
2153
+ return p;
2154
+ }
2155
+ function skipLeadingClosedBlockComments(text, startPos, resolveBlockClose) {
2156
+ let p = startPos;
2157
+ while (p < text.length && text[p] === '/' && text[p + 1] === '*') {
2158
+ const closeEnd = resolveBlockClose(p);
2159
+ if (closeEnd === -1) {
2160
+ return { codeStart: p, unclosed: true };
2161
+ }
2162
+ p = closeEnd;
2163
+ while (p < text.length && (text[p] === ' ' || text[p] === '\t')) {
2164
+ p += 1;
2165
+ }
2166
+ }
2167
+ return { codeStart: p, unclosed: false };
2168
+ }
2169
+ function findYamlEntryLineExtent(text, entryStart, entryLineEnd, resolveBlockClose) {
2170
+ let curEnd = entryLineEnd;
2171
+ let quote = null;
2172
+ let k = entryStart;
2173
+ while (k < curEnd) {
2174
+ const ch = text[k];
2175
+ if (quote !== null) {
2176
+ if (text.charCodeAt(k) === 92 /* '\\' */) {
2177
+ k += 2;
2178
+ continue;
2179
+ }
2180
+ if (ch === quote) {
2181
+ quote = null;
2182
+ }
2183
+ k += 1;
2184
+ continue;
2185
+ }
2186
+ if (ch === '"' || ch === "'" || ch === '`') {
2187
+ quote = ch;
2188
+ k += 1;
2189
+ continue;
2190
+ }
2191
+ if ((ch === '#' && (k === entryStart || /[\s,;[{]/u.test(text[k - 1] ?? ''))) ||
2192
+ (ch === '/' &&
2193
+ k + 1 < curEnd &&
2194
+ text[k + 1] === '/' &&
2195
+ (k === entryStart || text[k - 1] !== ':'))) {
2196
+ break;
2197
+ }
2198
+ if (ch === '/' && k + 1 < curEnd && text[k + 1] === '*') {
2199
+ const closeEnd = resolveBlockClose(k);
2200
+ if (closeEnd === -1) {
2201
+ break;
2202
+ }
2203
+ if (closeEnd > curEnd) {
2204
+ curEnd = findLineEnd(text, closeEnd);
2205
+ }
2206
+ k = closeEnd;
2207
+ continue;
2208
+ }
2209
+ k += 1;
2210
+ }
2211
+ return curEnd;
2212
+ }
2213
+ function isYamlListItemMarkerAt(text, pos) {
2214
+ return (pos < text.length &&
2215
+ (text[pos] === '-' || text[pos] === '*') &&
2216
+ (text[pos + 1] === ' ' ||
2217
+ text[pos + 1] === '\t' ||
2218
+ text[pos + 1] === '\r' ||
2219
+ text[pos + 1] === '\n'));
2220
+ }
2221
+ function findYamlIndentedListEnd(text, matchIndex, indentedStart, nlIndentLen, failedYamlCommentLineStarts, findBlockCommentClose) {
2222
+ const { keyIndent } = getYamlKeyIndentInfo(text, matchIndex);
2223
+ if (nlIndentLen < keyIndent) {
2224
+ return -1;
2225
+ }
2226
+ const resolveBlockClose = findBlockCommentClose ?? createBlockCommentCloseFinder(text);
2227
+ let lastContentEnd = findYamlEntryLineExtent(text, indentedStart, findLineEnd(text, indentedStart), resolveBlockClose);
2228
+ let pos = lastContentEnd;
2229
+ const trailingCommentStarts = [];
2230
+ let abortedOnHigherIndent = false;
2231
+ while (pos < text.length) {
2232
+ if (text[pos] === '\r' && text[pos + 1] === '\n')
2233
+ pos += 2;
2234
+ else if (text[pos] === '\r' || text[pos] === '\n')
2235
+ pos += 1;
2236
+ else
2237
+ break;
2238
+ const lineStart = pos;
2239
+ const lineEnd = findLineEnd(text, lineStart);
2240
+ let p = lineStart;
2241
+ while (p < lineEnd && (text[p] === ' ' || text[p] === '\t'))
2242
+ p += 1;
2243
+ if (p === lineEnd) {
2244
+ trailingCommentStarts.push(p);
2245
+ pos = lineEnd;
2246
+ continue;
2247
+ }
2248
+ if (text[p] === '#' ||
2249
+ (text[p] === '/' && (text[p + 1] === '/' || text[p + 1] === '*'))) {
2250
+ const pureEnd = consumeYamlPureCommentEnd(text, p, resolveBlockClose);
2251
+ if (pureEnd !== -1) {
2252
+ if (failedYamlCommentLineStarts?.has(p)) {
2253
+ break;
2254
+ }
2255
+ trailingCommentStarts.push(p);
2256
+ pos = pureEnd;
2257
+ continue;
2258
+ }
2259
+ if (text[p] === '/' && text[p + 1] === '*') {
2260
+ const { codeStart, unclosed } = skipLeadingClosedBlockComments(text, p, resolveBlockClose);
2261
+ if (unclosed || codeStart >= text.length)
2262
+ break;
2263
+ const effectiveIndent = Math.max(p - lineStart, getLineIndentAt(text, codeStart));
2264
+ if (effectiveIndent < nlIndentLen) {
2265
+ if (effectiveIndent > keyIndent) {
2266
+ abortedOnHigherIndent = true;
2267
+ }
2268
+ break;
2269
+ }
2270
+ if (effectiveIndent > nlIndentLen || isYamlListItemMarkerAt(text, codeStart)) {
2271
+ trailingCommentStarts.length = 0;
2272
+ const extEnd = findYamlEntryLineExtent(text, codeStart, findLineEnd(text, codeStart), resolveBlockClose);
2273
+ lastContentEnd = extEnd;
2274
+ pos = extEnd;
2275
+ continue;
2276
+ }
2277
+ }
2278
+ break;
2279
+ }
2280
+ const indent = p - lineStart;
2281
+ if (indent < nlIndentLen) {
2282
+ if (indent > keyIndent) {
2283
+ abortedOnHigherIndent = true;
2284
+ }
2285
+ break;
2286
+ }
2287
+ if (indent > nlIndentLen || isYamlListItemMarkerAt(text, p)) {
2288
+ trailingCommentStarts.length = 0;
2289
+ const extEnd = findYamlEntryLineExtent(text, p, lineEnd, resolveBlockClose);
2290
+ lastContentEnd = extEnd;
2291
+ pos = extEnd;
2292
+ continue;
2293
+ }
2294
+ break;
2295
+ }
2296
+ if (!abortedOnHigherIndent && failedYamlCommentLineStarts !== undefined) {
2297
+ for (const cStart of trailingCommentStarts) {
2298
+ failedYamlCommentLineStarts.add(cStart);
2299
+ }
2300
+ }
2301
+ return lastContentEnd;
2302
+ }
2303
+ function findYamlIndentedMappingEnd(text, matchIndex, indentedStart, nlIndentLen, failedYamlCommentLineStarts, findBlockCommentClose) {
2304
+ const { keyIndent } = getYamlKeyIndentInfo(text, matchIndex);
2305
+ if (nlIndentLen <= keyIndent) {
2306
+ return -1;
2307
+ }
2308
+ if (matchStickyAt(YAML_MAPPING_KEY_STICKY_RE, text, indentedStart) === null) {
2309
+ return -1;
2310
+ }
2311
+ const resolveBlockClose = findBlockCommentClose ?? createBlockCommentCloseFinder(text);
2312
+ let lastContentEnd = findYamlEntryLineExtent(text, indentedStart, findLineEnd(text, indentedStart), resolveBlockClose);
2313
+ let pos = lastContentEnd;
2314
+ const trailingCommentStarts = [];
2315
+ let abortedOnHigherIndent = false;
2316
+ while (pos < text.length) {
2317
+ if (text[pos] === '\r' && text[pos + 1] === '\n')
2318
+ pos += 2;
2319
+ else if (text[pos] === '\r' || text[pos] === '\n')
2320
+ pos += 1;
2321
+ else
2322
+ break;
2323
+ const lineStart = pos;
2324
+ const lineEnd = findLineEnd(text, lineStart);
2325
+ let p = lineStart;
2326
+ while (p < lineEnd && (text[p] === ' ' || text[p] === '\t'))
2327
+ p += 1;
2328
+ if (p === lineEnd) {
2329
+ trailingCommentStarts.push(p);
2330
+ pos = lineEnd;
2331
+ continue;
2332
+ }
2333
+ if (text[p] === '#' ||
2334
+ (text[p] === '/' && (text[p + 1] === '/' || text[p + 1] === '*'))) {
2335
+ const pureEnd = consumeYamlPureCommentEnd(text, p, resolveBlockClose);
2336
+ if (pureEnd !== -1) {
2337
+ if (failedYamlCommentLineStarts?.has(p)) {
2338
+ break;
2339
+ }
2340
+ trailingCommentStarts.push(p);
2341
+ pos = pureEnd;
2342
+ continue;
2343
+ }
2344
+ if (text[p] === '/' && text[p + 1] === '*') {
2345
+ const { codeStart, unclosed } = skipLeadingClosedBlockComments(text, p, resolveBlockClose);
2346
+ if (unclosed || codeStart >= text.length)
2347
+ break;
2348
+ const effectiveIndent = Math.max(p - lineStart, getLineIndentAt(text, codeStart));
2349
+ if (effectiveIndent < nlIndentLen || effectiveIndent <= keyIndent) {
2350
+ if (effectiveIndent > keyIndent) {
2351
+ abortedOnHigherIndent = true;
2352
+ }
2353
+ break;
2354
+ }
2355
+ if (effectiveIndent > nlIndentLen ||
2356
+ matchStickyAt(YAML_MAPPING_KEY_STICKY_RE, text, codeStart) !== null ||
2357
+ isYamlListItemMarkerAt(text, codeStart)) {
2358
+ trailingCommentStarts.length = 0;
2359
+ const extEnd = findYamlEntryLineExtent(text, codeStart, findLineEnd(text, codeStart), resolveBlockClose);
2360
+ lastContentEnd = extEnd;
2361
+ pos = extEnd;
2362
+ continue;
2363
+ }
2364
+ }
2365
+ break;
2366
+ }
2367
+ const indent = p - lineStart;
2368
+ if (indent < nlIndentLen || indent <= keyIndent) {
2369
+ if (indent > keyIndent) {
2370
+ abortedOnHigherIndent = true;
2371
+ }
2372
+ break;
2373
+ }
2374
+ if (indent > nlIndentLen ||
2375
+ matchStickyAt(YAML_MAPPING_KEY_STICKY_RE, text, p) !== null ||
2376
+ isYamlListItemMarkerAt(text, p)) {
2377
+ trailingCommentStarts.length = 0;
2378
+ const extEnd = findYamlEntryLineExtent(text, p, lineEnd, resolveBlockClose);
2379
+ lastContentEnd = extEnd;
2380
+ pos = extEnd;
2381
+ continue;
2382
+ }
2383
+ break;
2384
+ }
2385
+ if (!abortedOnHigherIndent && failedYamlCommentLineStarts !== undefined) {
2386
+ for (const cStart of trailingCommentStarts) {
2387
+ failedYamlCommentLineStarts.add(cStart);
2388
+ }
2389
+ }
2390
+ return lastContentEnd;
2391
+ }
2392
+ function matchCookieListSepEnd(text, pos) {
2393
+ const skipHoriz = (idx) => {
2394
+ let p = idx;
2395
+ while (p < text.length && (text[p] === ' ' || text[p] === '\t')) {
2396
+ p += 1;
2397
+ }
2398
+ return p;
2399
+ };
2400
+ const skipObsFold = (idx) => {
2401
+ if (idx >= text.length || (text[idx] !== '\r' && text[idx] !== '\n'))
2402
+ return -1;
2403
+ const folded = matchStickyAt(/\r?\n[ \t]+/yu, text, idx);
2404
+ return folded !== null ? folded.index + folded[0].length : -1;
2405
+ };
2406
+ let p = skipHoriz(pos);
2407
+ const preFold = skipObsFold(p);
2408
+ if (preFold !== -1 && (text[preFold] === ';' || text[preFold] === ',')) {
2409
+ p = preFold;
2410
+ }
2411
+ if (text[p] === ';') {
2412
+ while (p < text.length && text[p] === ';') {
2413
+ p += 1;
2414
+ p = skipHoriz(p);
2415
+ const folded = skipObsFold(p);
2416
+ if (folded !== -1) {
2417
+ p = folded;
2418
+ }
2419
+ }
2420
+ return { segStart: p, viaComma: false };
2421
+ }
2422
+ if (text[p] === ',') {
2423
+ p += 1;
2424
+ p = skipHoriz(p);
2425
+ const folded = skipObsFold(p);
2426
+ if (folded !== -1) {
2427
+ p = folded;
2428
+ }
2429
+ return { segStart: p, viaComma: true };
2430
+ }
2431
+ return null;
2432
+ }
2433
+ function isCookieContinuationStart(text, pos) {
2434
+ if (pos >= text.length)
2435
+ return false;
2436
+ const nextColonMatch = matchStickyAt(COOKIE_COLON_SECRET_STICKY_RE, text, pos);
2437
+ const nextColonKey = nextColonMatch !== null ? (nextColonMatch[3] ?? nextColonMatch[2] ?? '') : '';
2438
+ return (matchStickyAt(COOKIE_PAIR_START_STICKY_RE, text, pos) !== null ||
2439
+ matchStickyAt(/(?:"[^"\r\n=]+=[^"\r\n]+"|'[^'\r\n=]+=[^'\r\n]+'|`[^`\r\n=]+=[^`\r\n]+`)/yu, text, pos) !== null ||
2440
+ matchStickyAt(COOKIE_ATTR_FLAG_STICKY_RE, text, pos) !== null ||
2441
+ matchStickyAt(COOKIE_EXPIRES_DATE_STICKY_RE, text, pos) !== null ||
2442
+ (nextColonMatch !== null && SECRET_KEY_PART_RE.test(nextColonKey)));
2443
+ }
2444
+ function consumeCookieSegmentEnd(text, segStart, allowBareToken, noClosingQuote, unclosedDelimiterPositions, findBlockCommentClose) {
2445
+ const plain = (endPos) => ({
2446
+ endPos,
2447
+ endedPreStripped: false,
2448
+ endedBareFlag: false,
2449
+ });
2450
+ if (matchStickyAt(COOKIE_EXPIRES_DATE_STICKY_RE, text, segStart) !== null) {
2451
+ return plain(COOKIE_EXPIRES_DATE_STICKY_RE.lastIndex);
2452
+ }
2453
+ const segFirstChar = text[segStart];
2454
+ if (segFirstChar === '"' || segFirstChar === "'" || segFirstChar === '`') {
2455
+ const quotedEnd = findQuotedValueEnd(text, segStart, noClosingQuote);
2456
+ if (quotedEnd > segStart + 1 &&
2457
+ text.slice(segStart + 1, quotedEnd).includes('=') &&
2458
+ matchStickyAt(/[ \t]*=/yu, text, quotedEnd) === null) {
2459
+ return plain(quotedEnd);
2460
+ }
2461
+ }
2462
+ const pairMatch = matchStickyAt(COOKIE_PAIR_START_STICKY_RE, text, segStart);
2463
+ if (pairMatch !== null) {
2464
+ const valStart = COOKIE_PAIR_START_STICKY_RE.lastIndex;
2465
+ let opEnd = valStart;
2466
+ while (opEnd > pairMatch.index && (text[opEnd - 1] === ' ' || text[opEnd - 1] === '\t')) {
2467
+ opEnd -= 1;
2468
+ }
2469
+ const hadSpaceAfterOp = valStart > opEnd;
2470
+ if (valStart >= text.length ||
2471
+ text[valStart] === '\r' ||
2472
+ text[valStart] === '\n' ||
2473
+ (hadSpaceAfterOp &&
2474
+ (text[valStart] === '#' ||
2475
+ (text[valStart] === '/' &&
2476
+ (text[valStart + 1] === '/' || text[valStart + 1] === '*'))))) {
2477
+ return { endPos: opEnd, endedPreStripped: true, endedBareFlag: false };
2478
+ }
2479
+ const valChar = text[valStart];
2480
+ if (valChar === '[' || valChar === '{') {
2481
+ return plain(findDelimitedValueEnd(text, valStart, unclosedDelimiterPositions, findBlockCommentClose));
2482
+ }
2483
+ if (valChar === '"' || valChar === "'" || valChar === '`') {
2484
+ return plain(findQuotedValueEnd(text, valStart, noClosingQuote));
2485
+ }
2486
+ if (hadSpaceAfterOp) {
2487
+ const nextColonMatch = matchStickyAt(COOKIE_COLON_SECRET_STICKY_RE, text, valStart);
2488
+ const nextColonKey = nextColonMatch !== null ? (nextColonMatch[3] ?? nextColonMatch[2] ?? '') : '';
2489
+ if (matchStickyAt(COOKIE_PAIR_START_STICKY_RE, text, valStart) !== null ||
2490
+ (nextColonMatch !== null && SECRET_KEY_PART_RE.test(nextColonKey)) ||
2491
+ isNextKeyAssignmentAt(text, valStart, true)) {
2492
+ return { endPos: opEnd, endedPreStripped: true, endedBareFlag: false };
2493
+ }
2494
+ }
2495
+ const unquotedValRe = /[^\s"'`<>|;,{}[\]]*/yu;
2496
+ matchStickyAt(unquotedValRe, text, valStart);
2497
+ return plain(unquotedValRe.lastIndex);
2498
+ }
2499
+ if (matchStickyAt(COOKIE_ATTR_FLAG_STICKY_RE, text, segStart) !== null) {
2500
+ return {
2501
+ endPos: COOKIE_ATTR_FLAG_STICKY_RE.lastIndex,
2502
+ endedPreStripped: false,
2503
+ endedBareFlag: true,
2504
+ };
2505
+ }
2506
+ const firstBareFlag = matchStickyAt(COOKIE_BARE_FLAG_PREFIX_STICKY_RE, text, segStart) ??
2507
+ matchStickyAt(COOKIE_BARE_FLAG_FOLDED_STICKY_RE, text, segStart);
2508
+ if (firstBareFlag !== null) {
2509
+ let scanPos = firstBareFlag.index + firstBareFlag[0].length;
2510
+ let lastFlagEnd = scanPos;
2511
+ while (scanPos < text.length) {
2512
+ const sep = matchCookieListSepEnd(text, scanPos);
2513
+ let nextSeg = -1;
2514
+ if (sep !== null) {
2515
+ nextSeg = sep.segStart;
2516
+ }
2517
+ else {
2518
+ const wsFold = matchStickyAt(/[ \t]*\r?\n[ \t]+/yu, text, scanPos);
2519
+ if (wsFold !== null) {
2520
+ nextSeg = wsFold.index + wsFold[0].length;
2521
+ }
2522
+ }
2523
+ if (nextSeg === -1 || nextSeg >= text.length)
2524
+ break;
2525
+ if (isCookieContinuationStart(text, nextSeg)) {
2526
+ return { endPos: lastFlagEnd, endedPreStripped: false, endedBareFlag: true };
2527
+ }
2528
+ const nextBare = matchStickyAt(COOKIE_BARE_FLAG_PREFIX_STICKY_RE, text, nextSeg) ??
2529
+ matchStickyAt(COOKIE_BARE_FLAG_FOLDED_STICKY_RE, text, nextSeg);
2530
+ if (nextBare !== null) {
2531
+ lastFlagEnd = nextBare.index + nextBare[0].length;
2532
+ scanPos = lastFlagEnd;
2533
+ continue;
2534
+ }
2535
+ break;
2536
+ }
2537
+ }
2538
+ const colonSecretMatch = matchStickyAt(COOKIE_COLON_SECRET_STICKY_RE, text, segStart);
2539
+ const colonKey = colonSecretMatch !== null ? (colonSecretMatch[3] ?? colonSecretMatch[2] ?? '') : '';
2540
+ if (colonSecretMatch !== null && SECRET_KEY_PART_RE.test(colonKey)) {
2541
+ const valStart = COOKIE_COLON_SECRET_STICKY_RE.lastIndex;
2542
+ let opEnd = valStart;
2543
+ while (opEnd > colonSecretMatch.index &&
2544
+ (text[opEnd - 1] === ' ' || text[opEnd - 1] === '\t')) {
2545
+ opEnd -= 1;
2546
+ }
2547
+ const hadSpaceAfterOp = valStart > opEnd;
2548
+ if (valStart >= text.length ||
2549
+ text[valStart] === '\r' ||
2550
+ text[valStart] === '\n' ||
2551
+ (hadSpaceAfterOp &&
2552
+ (text[valStart] === '#' ||
2553
+ (text[valStart] === '/' &&
2554
+ (text[valStart + 1] === '/' || text[valStart + 1] === '*'))))) {
2555
+ return { endPos: opEnd, endedPreStripped: true, endedBareFlag: false };
2556
+ }
2557
+ const valChar = text[valStart];
2558
+ if (AUTH_KEY_PART_RE.test(colonKey)) {
2559
+ const authEnd = resolveAuthValueEnd(text, valStart, false, noClosingQuote, unclosedDelimiterPositions, segStart, findBlockCommentClose);
2560
+ if (authEnd !== -1) {
2561
+ return plain(authEnd);
2562
+ }
2563
+ }
2564
+ if (valChar === '"' || valChar === "'" || valChar === '`') {
2565
+ return plain(findQuotedValueEnd(text, valStart, noClosingQuote));
2566
+ }
2567
+ if (valChar === '[' || valChar === '{') {
2568
+ return plain(findDelimitedValueEnd(text, valStart, unclosedDelimiterPositions, findBlockCommentClose));
2569
+ }
2570
+ if (hadSpaceAfterOp) {
2571
+ const nextColonMatch = matchStickyAt(COOKIE_COLON_SECRET_STICKY_RE, text, valStart);
2572
+ const nextColonKey = nextColonMatch !== null ? (nextColonMatch[3] ?? nextColonMatch[2] ?? '') : '';
2573
+ if (matchStickyAt(COOKIE_PAIR_START_STICKY_RE, text, valStart) !== null ||
2574
+ (nextColonMatch !== null && SECRET_KEY_PART_RE.test(nextColonKey)) ||
2575
+ isNextKeyAssignmentAt(text, valStart, true)) {
2576
+ return { endPos: opEnd, endedPreStripped: true, endedBareFlag: false };
2577
+ }
2578
+ }
2579
+ const unquotedValRe = /[^\s"'`<>|;,{}[\]]*/yu;
2580
+ matchStickyAt(unquotedValRe, text, valStart);
2581
+ return plain(unquotedValRe.lastIndex);
2582
+ }
2583
+ if (allowBareToken && !isNextKeyAssignmentAt(text, segStart, true)) {
2584
+ const tokRe = /[^\s"'`<>|;,{}[\]]+/yu;
2585
+ if (matchStickyAt(tokRe, text, segStart) !== null) {
2586
+ return plain(tokRe.lastIndex);
2587
+ }
2588
+ }
2589
+ return null;
2590
+ }
2591
+ function skipFoldedCookiePureComments(text, segStart, resolveBlockClose, failedCommentLineStarts) {
2592
+ let cur = segStart;
2593
+ if (cur >= text.length ||
2594
+ (text[cur] !== '#' && !(text[cur] === '/' && (text[cur + 1] === '/' || text[cur + 1] === '*')))) {
2595
+ return segStart;
2596
+ }
2597
+ const visited = [];
2598
+ while (cur < text.length) {
2599
+ if (text[cur] === '#' ||
2600
+ (text[cur] === '/' && (text[cur + 1] === '/' || text[cur + 1] === '*'))) {
2601
+ if (failedCommentLineStarts?.has(cur)) {
2602
+ return -1;
2603
+ }
2604
+ const pureEnd = consumeYamlPureCommentEnd(text, cur, resolveBlockClose);
2605
+ if (pureEnd === -1) {
2606
+ for (const v of visited)
2607
+ failedCommentLineStarts?.add(v);
2608
+ return -1;
2609
+ }
2610
+ visited.push(cur);
2611
+ const folded = matchStickyAt(/\r?\n[ \t]+/yu, text, pureEnd);
2612
+ if (folded === null) {
2613
+ for (const v of visited)
2614
+ failedCommentLineStarts?.add(v);
2615
+ return -1;
2616
+ }
2617
+ cur = folded.index + folded[0].length;
2618
+ continue;
2619
+ }
2620
+ if (isCookieContinuationStart(text, cur)) {
2621
+ return cur;
2622
+ }
2623
+ for (const v of visited)
2624
+ failedCommentLineStarts?.add(v);
2625
+ return -1;
2626
+ }
2627
+ for (const v of visited)
2628
+ failedCommentLineStarts?.add(v);
2629
+ return -1;
2630
+ }
2631
+ function resolveCookieListEnd(text, valueStart, spaceSeparated, noClosingQuote, unclosedDelimiterPositions, findBlockCommentClose, failedCommentLineStarts) {
2632
+ const resolveBlockClose = findBlockCommentClose ?? createBlockCommentCloseFinder(text);
2633
+ let segInfo = consumeCookieSegmentEnd(text, valueStart, !spaceSeparated, noClosingQuote, unclosedDelimiterPositions, resolveBlockClose);
2634
+ if (segInfo === null)
2635
+ return -1;
2636
+ let endPos = segInfo.endPos;
2637
+ while (endPos < text.length) {
2638
+ let segStart;
2639
+ let viaComma = false;
2640
+ const sep = matchCookieListSepEnd(text, endPos);
2641
+ if (sep !== null) {
2642
+ segStart = sep.segStart;
2643
+ viaComma = sep.viaComma;
2644
+ if (segStart < text.length && endPos < segStart && text.slice(endPos, segStart).includes('\n')) {
2645
+ const afterComments = skipFoldedCookiePureComments(text, segStart, resolveBlockClose, failedCommentLineStarts);
2646
+ if (afterComments === -1)
2647
+ break;
2648
+ segStart = afterComments;
2649
+ }
2650
+ }
2651
+ else {
2652
+ let wsEnd = endPos;
2653
+ while (wsEnd < text.length && (text[wsEnd] === ' ' || text[wsEnd] === '\t')) {
2654
+ wsEnd += 1;
2655
+ }
2656
+ if (wsEnd < text.length && (text[wsEnd] === '\r' || text[wsEnd] === '\n')) {
2657
+ const folded = matchStickyAt(/\r?\n[ \t]+/yu, text, wsEnd);
2658
+ if (folded === null)
2659
+ break;
2660
+ wsEnd = folded.index + folded[0].length;
2661
+ const afterComments = skipFoldedCookiePureComments(text, wsEnd, resolveBlockClose, failedCommentLineStarts);
2662
+ if (afterComments === -1)
2663
+ break;
2664
+ wsEnd = afterComments;
2665
+ }
2666
+ else if (!segInfo.endedPreStripped || wsEnd <= endPos) {
2667
+ break;
2668
+ }
2669
+ if (wsEnd >= text.length)
2670
+ break;
2671
+ const isBareFlagCandidate = matchStickyAt(COOKIE_BARE_FLAG_PREFIX_STICKY_RE, text, wsEnd) !== null ||
2672
+ matchStickyAt(COOKIE_BARE_FLAG_FOLDED_STICKY_RE, text, wsEnd) !== null;
2673
+ if (!isCookieContinuationStart(text, wsEnd) && !isBareFlagCandidate) {
2674
+ break;
2675
+ }
2676
+ segStart = wsEnd;
2677
+ }
2678
+ if (segStart >= text.length)
2679
+ break;
2680
+ if (viaComma && !isCookieContinuationStart(text, segStart)) {
2681
+ break;
2682
+ }
2683
+ const nextInfo = consumeCookieSegmentEnd(text, segStart, false, noClosingQuote, unclosedDelimiterPositions, resolveBlockClose);
2684
+ if (nextInfo === null) {
2685
+ break;
2686
+ }
2687
+ segInfo = nextInfo;
2688
+ endPos = nextInfo.endPos;
2689
+ }
2690
+ return endPos;
2691
+ }
2692
+ function resolveSecretValueEnd(text, valueStart, key, container, matchIndex, spaceSeparated, noClosingQuote, unclosedDelimiterPositions, failedYamlCommentLineStarts, findBlockCommentClose, keyParts) {
2693
+ if (valueStart >= text.length)
2694
+ return -1;
2695
+ const resolveBlockClose = findBlockCommentClose ?? createBlockCommentCloseFinder(text);
2696
+ const partsToCheck = keyParts ?? (container.length > 0 ? [key, container] : [key]);
2697
+ const isAuth = partsToCheck.some((part) => AUTH_KEY_PART_RE.test(part));
2698
+ const isBearer = partsToCheck.some((part) => BEARER_KEY_PART_RE.test(part));
2699
+ const isCookie = partsToCheck.some((part) => COOKIE_KEY_PART_RE.test(part));
2700
+ const yamlHeaderNlPos = (() => {
2701
+ if (spaceSeparated)
2702
+ return -1;
2703
+ const pureEnd = consumeYamlPureCommentEnd(text, valueStart, resolveBlockClose);
2704
+ return pureEnd !== -1 &&
2705
+ pureEnd < text.length &&
2706
+ (text[pureEnd] === '\r' || text[pureEnd] === '\n')
2707
+ ? pureEnd
2708
+ : -1;
2709
+ })();
2710
+ let effectiveStart = valueStart;
2711
+ if (!spaceSeparated &&
2712
+ yamlHeaderNlPos === -1 &&
2713
+ text[effectiveStart] === '/' &&
2714
+ text[effectiveStart + 1] === '*') {
2715
+ const { codeStart } = skipLeadingClosedBlockComments(text, effectiveStart, resolveBlockClose);
2716
+ if (codeStart > effectiveStart) {
2717
+ if (codeStart >= text.length)
2718
+ return -1;
2719
+ effectiveStart = codeStart;
2720
+ }
2721
+ }
2722
+ const firstChar = text[effectiveStart];
2723
+ if (firstChar === '"' || firstChar === "'" || firstChar === '`') {
2724
+ if (isCookie && !spaceSeparated) {
2725
+ const cookieEnd = resolveCookieListEnd(text, effectiveStart, spaceSeparated, noClosingQuote, unclosedDelimiterPositions, resolveBlockClose, failedYamlCommentLineStarts);
2726
+ if (cookieEnd !== -1) {
2727
+ return cookieEnd;
2728
+ }
2729
+ }
2730
+ if (!spaceSeparated && isAuth) {
2731
+ return resolveAuthValueEnd(text, effectiveStart, false, noClosingQuote, unclosedDelimiterPositions, matchIndex, resolveBlockClose);
2732
+ }
2733
+ if (spaceSeparated && isAuth && !isBearer) {
2734
+ if (matchStickyAt(SCHEME_PREFIX_STICKY_RE, text, effectiveStart + 1) === null) {
2735
+ return -1;
2736
+ }
2737
+ }
2738
+ return findQuotedValueEnd(text, effectiveStart, noClosingQuote);
2739
+ }
2740
+ if (!spaceSeparated && (firstChar === '[' || firstChar === '{')) {
2741
+ return findDelimitedValueEnd(text, effectiveStart, unclosedDelimiterPositions, resolveBlockClose);
2742
+ }
2743
+ if (!spaceSeparated && matchStickyAt(PEM_OPEN_OPT_NL_STICKY_RE, text, effectiveStart) !== null) {
2744
+ return findUnquotedPemValueEnd(text, effectiveStart, PEM_OPEN_OPT_NL_STICKY_RE.lastIndex);
2745
+ }
2746
+ if (!spaceSeparated) {
2747
+ const yamlBlockMatch = matchStickyAt(YAML_BLOCK_SCALAR_HEADER_STICKY_RE, text, effectiveStart);
2748
+ if (yamlBlockMatch !== null) {
2749
+ return findYamlBlockScalarEnd(text, matchIndex, YAML_BLOCK_SCALAR_HEADER_STICKY_RE.lastIndex);
2750
+ }
2751
+ }
2752
+ if (!spaceSeparated && yamlHeaderNlPos !== -1) {
2753
+ const nlIndentMatch = matchStickyAt(/\r?\n([ \t]*)/yu, text, yamlHeaderNlPos);
2754
+ if (nlIndentMatch !== null) {
2755
+ const indentedStart = nlIndentMatch.index + nlIndentMatch[0].length;
2756
+ const nlIndentLen = (nlIndentMatch[1] ?? '').length;
2757
+ if (indentedStart < text.length) {
2758
+ const { keyIndent } = getYamlKeyIndentInfo(text, matchIndex);
2759
+ let yamlContentStart = indentedStart;
2760
+ let yamlContentIndent = nlIndentLen;
2761
+ const visitedYamlCommentStarts = [];
2762
+ let abortedYamlScan = false;
2763
+ {
2764
+ let scanLineStart = indentedStart;
2765
+ let scanIndent = nlIndentLen;
2766
+ while (scanLineStart < text.length) {
2767
+ let scanLineEnd = findLineEnd(text, scanLineStart);
2768
+ if (scanLineStart === scanLineEnd) {
2769
+ if (failedYamlCommentLineStarts?.has(scanLineStart)) {
2770
+ abortedYamlScan = true;
2771
+ break;
2772
+ }
2773
+ visitedYamlCommentStarts.push(scanLineStart);
2774
+ }
2775
+ else if (text[scanLineStart] === '#' ||
2776
+ (text[scanLineStart] === '/' &&
2777
+ (text[scanLineStart + 1] === '/' || text[scanLineStart + 1] === '*'))) {
2778
+ const pureEnd = consumeYamlPureCommentEnd(text, scanLineStart, resolveBlockClose);
2779
+ if (pureEnd !== -1) {
2780
+ if (failedYamlCommentLineStarts?.has(scanLineStart)) {
2781
+ abortedYamlScan = true;
2782
+ break;
2783
+ }
2784
+ visitedYamlCommentStarts.push(scanLineStart);
2785
+ scanLineEnd = pureEnd;
2786
+ }
2787
+ else if (text[scanLineStart] === '/' && text[scanLineStart + 1] === '*') {
2788
+ const { codeStart, unclosed } = skipLeadingClosedBlockComments(text, scanLineStart, resolveBlockClose);
2789
+ if (unclosed) {
2790
+ abortedYamlScan = true;
2791
+ break;
2792
+ }
2793
+ yamlContentStart = codeStart;
2794
+ yamlContentIndent = Math.max(scanIndent, getLineIndentAt(text, codeStart));
2795
+ break;
2796
+ }
2797
+ else {
2798
+ yamlContentStart = scanLineStart;
2799
+ yamlContentIndent = scanIndent;
2800
+ break;
2801
+ }
2802
+ }
2803
+ else {
2804
+ yamlContentStart = scanLineStart;
2805
+ yamlContentIndent = scanIndent;
2806
+ break;
2807
+ }
2808
+ if (scanLineEnd >= text.length) {
2809
+ yamlContentStart = text.length;
2810
+ break;
2811
+ }
2812
+ const nextStart = text[scanLineEnd] === '\r' && text[scanLineEnd + 1] === '\n'
2813
+ ? scanLineEnd + 2
2814
+ : scanLineEnd + 1;
2815
+ let np = nextStart;
2816
+ while (np < text.length && (text[np] === ' ' || text[np] === '\t'))
2817
+ np += 1;
2818
+ scanLineStart = np;
2819
+ scanIndent = np - nextStart;
2820
+ }
2821
+ }
2822
+ const recordFailedYamlScan = () => {
2823
+ if (failedYamlCommentLineStarts !== undefined && visitedYamlCommentStarts.length > 0) {
2824
+ for (const cStart of visitedYamlCommentStarts) {
2825
+ failedYamlCommentLineStarts.add(cStart);
2826
+ }
2827
+ }
2828
+ };
2829
+ const yamlChar = yamlContentStart < text.length ? text[yamlContentStart] : '';
2830
+ const isYamlListItem = !abortedYamlScan &&
2831
+ yamlContentStart < text.length &&
2832
+ (yamlChar === '-' || yamlChar === '*') &&
2833
+ (text[yamlContentStart + 1] === ' ' ||
2834
+ text[yamlContentStart + 1] === '\t' ||
2835
+ text[yamlContentStart + 1] === '\r' ||
2836
+ text[yamlContentStart + 1] === '\n');
2837
+ if (isYamlListItem && yamlContentIndent >= keyIndent) {
2838
+ const listEnd = findYamlIndentedListEnd(text, matchIndex, yamlContentStart, yamlContentIndent, failedYamlCommentLineStarts, resolveBlockClose);
2839
+ if (listEnd !== -1) {
2840
+ return listEnd;
2841
+ }
2842
+ }
2843
+ if (!abortedYamlScan && yamlContentStart < text.length && yamlContentIndent > keyIndent) {
2844
+ if (matchStickyAt(YAML_BLOCK_SCALAR_HEADER_STICKY_RE, text, yamlContentStart) !== null) {
2845
+ return findYamlBlockScalarEnd(text, matchIndex, YAML_BLOCK_SCALAR_HEADER_STICKY_RE.lastIndex);
2846
+ }
2847
+ if (isCookie) {
2848
+ if (yamlChar === '[' || yamlChar === '{') {
2849
+ return findDelimitedValueEnd(text, yamlContentStart, unclosedDelimiterPositions, resolveBlockClose);
2850
+ }
2851
+ const startsWithPair = matchStickyAt(COOKIE_PAIR_START_STICKY_RE, text, yamlContentStart) !== null;
2852
+ const colonMatch = matchStickyAt(COOKIE_COLON_SECRET_STICKY_RE, text, yamlContentStart);
2853
+ const colonKey = colonMatch !== null ? (colonMatch[3] ?? colonMatch[2] ?? '') : '';
2854
+ const startsWithSecretColon = colonMatch !== null && SECRET_KEY_PART_RE.test(colonKey);
2855
+ const startsWithYamlMapKey = matchStickyAt(YAML_MAPPING_KEY_STICKY_RE, text, yamlContentStart) !== null;
2856
+ if (!startsWithPair && !startsWithSecretColon && startsWithYamlMapKey) {
2857
+ const yamlMapEnd = findYamlIndentedMappingEnd(text, matchIndex, yamlContentStart, yamlContentIndent, failedYamlCommentLineStarts, resolveBlockClose);
2858
+ if (yamlMapEnd !== -1) {
2859
+ return yamlMapEnd;
2860
+ }
2861
+ }
2862
+ const cookieEnd = resolveCookieListEnd(text, yamlContentStart, false, noClosingQuote, unclosedDelimiterPositions, resolveBlockClose, failedYamlCommentLineStarts);
2863
+ if (startsWithSecretColon && startsWithYamlMapKey) {
2864
+ const firstLineEnd = findLineEnd(text, yamlContentStart);
2865
+ let onlyWsOrCommentTail = false;
2866
+ if (cookieEnd !== -1 && cookieEnd <= firstLineEnd) {
2867
+ let tp = cookieEnd;
2868
+ while (tp < firstLineEnd && (text[tp] === ' ' || text[tp] === '\t')) {
2869
+ tp += 1;
2870
+ }
2871
+ if (tp === firstLineEnd ||
2872
+ text[tp] === '#' ||
2873
+ (text[tp] === '/' && (text[tp + 1] === '/' || text[tp + 1] === '*'))) {
2874
+ onlyWsOrCommentTail = true;
2875
+ }
2876
+ }
2877
+ const yamlMapEnd = findYamlIndentedMappingEnd(text, matchIndex, yamlContentStart, yamlContentIndent, failedYamlCommentLineStarts, resolveBlockClose);
2878
+ if (yamlMapEnd !== -1 &&
2879
+ (yamlMapEnd > firstLineEnd || cookieEnd === -1 || onlyWsOrCommentTail)) {
2880
+ return cookieEnd === -1 ? yamlMapEnd : Math.max(cookieEnd, yamlMapEnd);
2881
+ }
2882
+ }
2883
+ if (cookieEnd !== -1) {
2884
+ return cookieEnd;
2885
+ }
2886
+ recordFailedYamlScan();
2887
+ return -1;
2888
+ }
2889
+ if (isAuth) {
2890
+ const authEnd = resolveAuthValueEnd(text, yamlContentStart, true, noClosingQuote, unclosedDelimiterPositions, matchIndex, resolveBlockClose);
2891
+ if (authEnd !== -1) {
2892
+ return authEnd;
2893
+ }
2894
+ recordFailedYamlScan();
2895
+ return -1;
2896
+ }
2897
+ if (!isAuth && !isCookie) {
2898
+ const yamlMapEnd = findYamlIndentedMappingEnd(text, matchIndex, yamlContentStart, yamlContentIndent, failedYamlCommentLineStarts, resolveBlockClose);
2899
+ if (yamlMapEnd !== -1) {
2900
+ return yamlMapEnd;
2901
+ }
2902
+ const schemeMatch = matchStickyAt(SCHEME_PREFIX_STICKY_RE, text, yamlContentStart);
2903
+ if (schemeMatch !== null) {
2904
+ const schemeName = (schemeMatch[1] ?? '').toLowerCase();
2905
+ const credStart = SCHEME_PREFIX_STICKY_RE.lastIndex;
2906
+ if (PARAMETERIZED_AUTH_SCHEMES.has(schemeName)) {
2907
+ const multiParamEnd = resolveCommaAuthParamsEnd(text, credStart, noClosingQuote, false);
2908
+ if (multiParamEnd !== -1) {
2909
+ return multiParamEnd;
2910
+ }
2911
+ }
2912
+ if (isNextKeyAssignmentAt(text, credStart, true)) {
2913
+ return credStart;
2914
+ }
2915
+ const credFirstChar = text[credStart];
2916
+ if (credFirstChar === '"' || credFirstChar === "'" || credFirstChar === '`') {
2917
+ return findQuotedValueEnd(text, credStart, noClosingQuote);
2918
+ }
2919
+ if (credFirstChar === '[' || credFirstChar === '{') {
2920
+ return findDelimitedValueEnd(text, credStart, unclosedDelimiterPositions, resolveBlockClose);
2921
+ }
2922
+ const tokenRe = /[^\s"'`<>|;,{}[\]]{2,}/yu;
2923
+ if (matchStickyAt(tokenRe, text, credStart) !== null) {
2924
+ return tokenRe.lastIndex;
2925
+ }
2926
+ }
2927
+ if (matchStickyAt(OBJECT_PROPERTY_ASSIGN_STICKY_RE, text, yamlContentStart) === null &&
2928
+ !isNextKeyAssignmentAt(text, yamlContentStart, true)) {
2929
+ if (yamlChar === '"' || yamlChar === "'" || yamlChar === '`') {
2930
+ return findQuotedValueEnd(text, yamlContentStart, noClosingQuote);
2931
+ }
2932
+ if (yamlChar === '[' || yamlChar === '{') {
2933
+ return findDelimitedValueEnd(text, yamlContentStart, unclosedDelimiterPositions, resolveBlockClose);
2934
+ }
2935
+ const indTokenRe = /[^\s"'`<>|;,{}[\]]{2,}/yu;
2936
+ const indTokenMatch = matchStickyAt(indTokenRe, text, yamlContentStart);
2937
+ if (indTokenMatch !== null) {
2938
+ const tok = indTokenMatch[0];
2939
+ if (isCrossLineSecretScalar(tok, partsToCheck.join('_'), text, indTokenRe.lastIndex)) {
2940
+ return indTokenRe.lastIndex;
2941
+ }
2942
+ }
2943
+ }
2944
+ }
2945
+ }
2946
+ recordFailedYamlScan();
2947
+ }
2948
+ }
2949
+ return -1;
2950
+ }
2951
+ if (!spaceSeparated && !isCookie && !isAuth && isNextKeyAssignmentAt(text, effectiveStart, true)) {
2952
+ return effectiveStart;
2953
+ }
2954
+ if (isCookie &&
2955
+ (!spaceSeparated || matchStickyAt(COOKIE_PAIR_START_STICKY_RE, text, effectiveStart) !== null)) {
2956
+ const cookieEnd = resolveCookieListEnd(text, effectiveStart, spaceSeparated, noClosingQuote, unclosedDelimiterPositions, resolveBlockClose, failedYamlCommentLineStarts);
2957
+ if (cookieEnd !== -1) {
2958
+ return cookieEnd;
2959
+ }
2960
+ return -1;
2961
+ }
2962
+ if (!spaceSeparated && isAuth) {
2963
+ return resolveAuthValueEnd(text, effectiveStart, false, noClosingQuote, unclosedDelimiterPositions, matchIndex, resolveBlockClose);
2964
+ }
2965
+ const schemeMatch = !isCookie ? matchStickyAt(SCHEME_PREFIX_STICKY_RE, text, effectiveStart) : null;
2966
+ if (schemeMatch !== null) {
2967
+ const schemeName = (schemeMatch[1] ?? '').toLowerCase();
2968
+ const credStart = SCHEME_PREFIX_STICKY_RE.lastIndex;
2969
+ if (!spaceSeparated && PARAMETERIZED_AUTH_SCHEMES.has(schemeName)) {
2970
+ const multiParamEnd = resolveCommaAuthParamsEnd(text, credStart, noClosingQuote, false);
2971
+ if (multiParamEnd !== -1) {
2972
+ return multiParamEnd;
2973
+ }
2974
+ }
2975
+ if (!spaceSeparated && isNextKeyAssignmentAt(text, credStart, !isCookie)) {
2976
+ return credStart;
2977
+ }
2978
+ const credFirstChar = text[credStart];
2979
+ if (credFirstChar === '"' || credFirstChar === "'" || credFirstChar === '`') {
2980
+ return findQuotedValueEnd(text, credStart, noClosingQuote);
2981
+ }
2982
+ if (!spaceSeparated && (credFirstChar === '[' || credFirstChar === '{')) {
2983
+ return findDelimitedValueEnd(text, credStart, unclosedDelimiterPositions, resolveBlockClose);
2984
+ }
2985
+ const tokenRe = /[^\s"'`<>|;,{}[\]]{2,}/yu;
2986
+ const tokenMatch = matchStickyAt(tokenRe, text, credStart);
2987
+ if (tokenMatch !== null) {
2988
+ if (spaceSeparated && !isBearer && !SECRET_VALUE_CHAR_RE.test(tokenMatch[0])) {
2989
+ return -1;
2990
+ }
2991
+ return tokenRe.lastIndex;
2992
+ }
2993
+ return spaceSeparated ? -1 : credStart;
2994
+ }
2995
+ if (spaceSeparated && isAuth && !isBearer) {
2996
+ return -1;
2997
+ }
2998
+ const tokenRe = /[^\s"'`<>|;,{}[\]]{2,}/yu;
2999
+ const tokenMatch = matchStickyAt(tokenRe, text, effectiveStart);
3000
+ if (tokenMatch === null)
3001
+ return -1;
3002
+ if (spaceSeparated && !isBearer && !SECRET_VALUE_CHAR_RE.test(tokenMatch[0])) {
3003
+ return -1;
3004
+ }
3005
+ return tokenRe.lastIndex;
3006
+ }
3007
+ function isSecretAssignmentKey(ident) {
3008
+ if (ident.toLowerCase() === 'pass')
3009
+ return true;
3010
+ if (SECRET_KEY_PART_RE.test(ident))
3011
+ return true;
3012
+ if (!/[A-Z0-9]/u.test(ident))
3013
+ return false;
3014
+ return hasSecretStem(ident);
3015
+ }
3016
+ function scrubByKeyPattern(text, headRe, spaceSeparated) {
3017
+ headRe.lastIndex = 0;
3018
+ const noClosingQuote = {};
3019
+ const unclosedDelimiterPositions = new Set();
3020
+ const failedYamlCommentLineStarts = new Set();
3021
+ const findBlockCommentClose = createBlockCommentCloseFinder(text);
3022
+ let out = '';
3023
+ let cursor = 0;
3024
+ let match;
3025
+ const isSecretIdent = (ident) => spaceSeparated
3026
+ ? SECRET_KEY_PART_RE.test(ident) || CAMEL_PASS_OR_JWT_KEY_RE.test(ident)
3027
+ : isSecretAssignmentKey(ident);
3028
+ while ((match = headRe.exec(text)) !== null) {
3029
+ const baseIdent = match[3] ?? match[2] ?? '';
3030
+ const subscriptChain = match[4];
3031
+ const segments = extractSubscriptSegments(subscriptChain);
3032
+ const baseIsSecret = isSecretIdent(baseIdent);
3033
+ const secretSegment = segments.find((seg) => isSecretIdent(seg));
3034
+ if (!baseIsSecret && secretSegment === undefined) {
3035
+ continue;
3036
+ }
3037
+ const key = secretSegment ?? (segments.length > 0 ? segments[segments.length - 1] : baseIdent);
3038
+ const container = segments.length > 0 ? baseIdent : '';
3039
+ const keyParts = segments.length > 0 ? [baseIdent, ...segments] : [baseIdent];
3040
+ const valueEnd = resolveSecretValueEnd(text, headRe.lastIndex, key, container, match.index, spaceSeparated, noClosingQuote, unclosedDelimiterPositions, failedYamlCommentLineStarts, findBlockCommentClose, keyParts);
3041
+ if (valueEnd === -1) {
3042
+ continue;
3043
+ }
3044
+ out += text.slice(cursor, match.index) + ' ';
3045
+ cursor = valueEnd;
3046
+ headRe.lastIndex = valueEnd;
3047
+ }
3048
+ if (cursor === 0)
3049
+ return text;
3050
+ return out + text.slice(cursor);
3051
+ }
3052
+ const URL_BASE_RE = /(?<![a-z0-9+.-])[a-z][a-z0-9+.-]*:\/\/[^\s"'`<>|;,)]+/giu;
3053
+ const URL_SEMI_ASSIGN_STICKY_RE = new RegExp(`(?:(?:"[^"\\r\\n]+"|'[^'\\r\\n]+'|` +
3054
+ '`[^`\\r\\n]+`' +
3055
+ `)(?:\\.[A-Za-z0-9_.-]+)?|[A-Za-z0-9_.-]+)(?:${SUBSCRIPT_SEGMENT_SRC}(?:\\.[A-Za-z0-9_.-]+)?)*[ \\t]*[:=]`, 'yu');
3056
+ const URL_SEMI_SPACE_KEY_STICKY_RE = /["'`]?([A-Za-z0-9_.-]+)["'`]?[ \t]+/yu;
3057
+ const URL_CONT_SEG_STICKY_RE = /[^\s"'`<>|;,)]+/yu;
3058
+ const SCRUB_ASSIGN_HEAD_RE = new RegExp(`(?<![A-Za-z0-9_.-])(?:(["'\`])([A-Za-z0-9_.-]+)\\1|([A-Za-z0-9_.-]+))${SUBSCRIPT_CHAIN_CAPTURE_SRC}?[ \\t]*(?::=|==|:|=)[ \\t]*`, 'giu');
3059
+ const SCRUB_SPACE_HEAD_RE = /(?<![A-Za-z0-9_.-])(?:(["'`])([A-Za-z0-9_.-]+)\1|([A-Za-z0-9_.-]+))[ \t]+/giu;
3060
+ function stripUrlsFromInterestText(text) {
3061
+ URL_BASE_RE.lastIndex = 0;
3062
+ let out = '';
3063
+ let cursor = 0;
3064
+ let match;
3065
+ while ((match = URL_BASE_RE.exec(text)) !== null) {
3066
+ let end = URL_BASE_RE.lastIndex;
3067
+ while (end < text.length && (text[end] === ';' || text[end] === ',')) {
3068
+ let sepEnd = end + 1;
3069
+ while (sepEnd < text.length && (text[sepEnd] === ';' || text[sepEnd] === ',')) {
3070
+ sepEnd += 1;
3071
+ }
3072
+ if (matchStickyAt(URL_SEMI_ASSIGN_STICKY_RE, text, sepEnd) !== null) {
3073
+ break;
3074
+ }
3075
+ const spaceKeyMatch = matchStickyAt(URL_SEMI_SPACE_KEY_STICKY_RE, text, sepEnd);
3076
+ if (spaceKeyMatch !== null && SECRET_KEY_PART_RE.test(spaceKeyMatch[1] ?? '')) {
3077
+ break;
3078
+ }
3079
+ const segMatch = matchStickyAt(URL_CONT_SEG_STICKY_RE, text, sepEnd);
3080
+ if (segMatch === null) {
3081
+ break;
3082
+ }
3083
+ end = URL_CONT_SEG_STICKY_RE.lastIndex;
3084
+ }
3085
+ out += text.slice(cursor, match.index) + ' ';
3086
+ cursor = end;
3087
+ URL_BASE_RE.lastIndex = end;
3088
+ }
3089
+ return cursor === 0 ? text : out + text.slice(cursor);
3090
+ }
3091
+ const CLI_BASIC_AUTH_RE = /(?:^|(?<=[\s;|&(]))(?:-u|--user|--proxy-user)(?:=|[ \t]+)(?:"(?:[^"\r\n:]+:[^"\r\n]*|:[^"\r\n]+)"|'(?:[^'\r\n:]+:[^'\r\n]*|:[^'\r\n]+)'|`(?:[^`\r\n:]+:[^`\r\n]*|:[^`\r\n]+)`|(?:[^\s"'`:<>|;,()]+:[^\s"'`<>|;,()]*|:[^\s"'`<>|;,()]+))/gu;
3092
+ const NAMED_SECRET_KEY_PROP_RE = /(?:^|(?<=[\s,{[\-*]))(?:(["'`])(?:name|key)\1|(?:name|key))[ \t]*:[ \t]*(?!=)(?:(["'`])([A-Za-z0-9_.-]+)\2|([A-Za-z0-9_.-]+))/giu;
3093
+ const VALUE_PROP_STICKY_RE = /(?:(["'`])value\1|value)[ \t]*:[ \t]*/iyu;
3094
+ const ANY_PROP_HEAD_STICKY_RE = /(?:(["'`])([A-Za-z0-9_.-]+)\1|([A-Za-z0-9_.-]+))[ \t]*:[ \t]*/yu;
3095
+ function skipSiblingPropValueEnd(text, valStart, noClosingQuote, unclosedDelimiterPositions, findBlockCommentClose) {
3096
+ let p = valStart;
3097
+ if (p >= text.length)
3098
+ return -1;
3099
+ if (text[p] === '/' && text[p + 1] === '*') {
3100
+ const { codeStart, unclosed } = skipLeadingClosedBlockComments(text, p, findBlockCommentClose);
3101
+ if (unclosed || codeStart >= text.length)
3102
+ return -1;
3103
+ p = codeStart;
3104
+ }
3105
+ const ch = text[p];
3106
+ if (ch === '"' || ch === "'" || ch === '`') {
3107
+ return findQuotedValueEnd(text, p, noClosingQuote);
3108
+ }
3109
+ if (ch === '{' || ch === '[') {
3110
+ return findDelimitedValueEnd(text, p, unclosedDelimiterPositions, findBlockCommentClose);
3111
+ }
3112
+ const scalarRe = /[^\s"'`<>|,;{}[\]]+/yu;
3113
+ if (matchStickyAt(scalarRe, text, p) !== null) {
3114
+ return scalarRe.lastIndex;
3115
+ }
3116
+ return -1;
3117
+ }
3118
+ function scrubNamedSecretValuePairs(text) {
3119
+ if (!/\b(?:name|key)\b/iu.test(text) || !/\bvalue\b/iu.test(text)) {
3120
+ return text;
3121
+ }
3122
+ NAMED_SECRET_KEY_PROP_RE.lastIndex = 0;
3123
+ const noClosingQuote = {};
3124
+ const unclosedDelimiterPositions = new Set();
3125
+ const failedYamlCommentLineStarts = new Set();
3126
+ const findBlockCommentClose = createBlockCommentCloseFinder(text);
3127
+ let out = '';
3128
+ let cursor = 0;
3129
+ let match;
3130
+ while ((match = NAMED_SECRET_KEY_PROP_RE.exec(text)) !== null) {
3131
+ const nameVal = match[3] ?? match[4] ?? '';
3132
+ if (!isSecretAssignmentKey(nameVal)) {
3133
+ continue;
3134
+ }
3135
+ const pos = NAMED_SECRET_KEY_PROP_RE.lastIndex;
3136
+ if (pos < text.length && !/[\s,;}\]/#]/u.test(text[pos])) {
3137
+ continue;
3138
+ }
3139
+ let p = pos;
3140
+ while (p < text.length && (text[p] === ' ' || text[p] === '\t')) {
3141
+ p += 1;
3142
+ }
3143
+ let foundValueKeyStart = -1;
3144
+ let foundValueEnd = -1;
3145
+ if (p < text.length && (text[p] === ',' || text[p] === ';')) {
3146
+ let cur = p;
3147
+ for (let propIdx = 0; propIdx < 6 && cur < text.length; propIdx += 1) {
3148
+ if (text[cur] !== ',' && text[cur] !== ';')
3149
+ break;
3150
+ cur += 1;
3151
+ while (cur < text.length) {
3152
+ const ch = text[cur];
3153
+ if (ch === ' ' || ch === '\t' || ch === '\r' || ch === '\n') {
3154
+ cur += 1;
3155
+ continue;
3156
+ }
3157
+ if (ch === '#' || (ch === '/' && text[cur + 1] === '/')) {
3158
+ cur = findLineEnd(text, cur);
3159
+ continue;
3160
+ }
3161
+ if (ch === '/' && text[cur + 1] === '*') {
3162
+ const closeEnd = findBlockCommentClose(cur);
3163
+ if (closeEnd === -1) {
3164
+ cur = text.length;
3165
+ break;
3166
+ }
3167
+ cur = closeEnd;
3168
+ continue;
3169
+ }
3170
+ break;
3171
+ }
3172
+ if (cur >= text.length || text[cur] === '}' || text[cur] === ']')
3173
+ break;
3174
+ if (matchStickyAt(VALUE_PROP_STICKY_RE, text, cur) !== null) {
3175
+ const valueKeyStart = cur;
3176
+ const valueStart = VALUE_PROP_STICKY_RE.lastIndex;
3177
+ const valueEnd = resolveSecretValueEnd(text, valueStart, nameVal, '', valueKeyStart, false, noClosingQuote, unclosedDelimiterPositions, failedYamlCommentLineStarts, findBlockCommentClose, [nameVal]);
3178
+ if (valueEnd !== -1) {
3179
+ foundValueKeyStart = valueKeyStart;
3180
+ foundValueEnd = valueEnd;
3181
+ }
3182
+ break;
3183
+ }
3184
+ const otherProp = matchStickyAt(ANY_PROP_HEAD_STICKY_RE, text, cur);
3185
+ if (otherProp === null)
3186
+ break;
3187
+ const otherKey = (otherProp[3] ?? otherProp[2] ?? '').toLowerCase();
3188
+ if (otherKey === 'name' || otherKey === 'key')
3189
+ break;
3190
+ const skippedEnd = skipSiblingPropValueEnd(text, ANY_PROP_HEAD_STICKY_RE.lastIndex, noClosingQuote, unclosedDelimiterPositions, findBlockCommentClose);
3191
+ if (skippedEnd === -1)
3192
+ break;
3193
+ cur = skippedEnd;
3194
+ while (cur < text.length &&
3195
+ (text[cur] === ' ' || text[cur] === '\t' || text[cur] === '\r' || text[cur] === '\n')) {
3196
+ cur += 1;
3197
+ }
3198
+ }
3199
+ }
3200
+ else {
3201
+ const lineTailEnd = consumeYamlPureCommentEnd(text, pos, findBlockCommentClose);
3202
+ if (lineTailEnd !== -1 &&
3203
+ lineTailEnd < text.length &&
3204
+ (text[lineTailEnd] === '\r' || text[lineTailEnd] === '\n')) {
3205
+ const { listMarkerIndent, keyIndent, hasListMarker } = getYamlKeyIndentInfo(text, match.index);
3206
+ let linePos = lineTailEnd;
3207
+ for (let lineCount = 0; lineCount < 8 && linePos < text.length; lineCount += 1) {
3208
+ if (text[linePos] === '\r' && text[linePos + 1] === '\n') {
3209
+ linePos += 2;
3210
+ }
3211
+ else if (text[linePos] === '\r' || text[linePos] === '\n') {
3212
+ linePos += 1;
3213
+ }
3214
+ else {
3215
+ break;
3216
+ }
3217
+ const lineStart = linePos;
3218
+ const lineEnd = findLineEnd(text, lineStart);
3219
+ let contentStart = lineStart;
3220
+ while (contentStart < lineEnd &&
3221
+ (text[contentStart] === ' ' || text[contentStart] === '\t')) {
3222
+ contentStart += 1;
3223
+ }
3224
+ if (contentStart === lineEnd) {
3225
+ linePos = lineEnd;
3226
+ continue;
3227
+ }
3228
+ const pureCommentEnd = consumeYamlPureCommentEnd(text, contentStart, findBlockCommentClose);
3229
+ if (pureCommentEnd === lineEnd) {
3230
+ linePos = lineEnd;
3231
+ continue;
3232
+ }
3233
+ const indent = contentStart - lineStart;
3234
+ const isListItemStart = (text[contentStart] === '-' || text[contentStart] === '*') &&
3235
+ (contentStart + 1 === lineEnd ||
3236
+ text[contentStart + 1] === ' ' ||
3237
+ text[contentStart + 1] === '\t');
3238
+ if (indent < keyIndent || (hasListMarker && indent === listMarkerIndent) || isListItemStart) {
3239
+ break;
3240
+ }
3241
+ if (indent > keyIndent) {
3242
+ linePos = lineEnd;
3243
+ continue;
3244
+ }
3245
+ if (matchStickyAt(VALUE_PROP_STICKY_RE, text, contentStart) !== null) {
3246
+ const valueKeyStart = contentStart;
3247
+ const valueStart = VALUE_PROP_STICKY_RE.lastIndex;
3248
+ const valueEnd = resolveSecretValueEnd(text, valueStart, nameVal, '', valueKeyStart, false, noClosingQuote, unclosedDelimiterPositions, failedYamlCommentLineStarts, findBlockCommentClose, [nameVal]);
3249
+ if (valueEnd !== -1) {
3250
+ foundValueKeyStart = valueKeyStart;
3251
+ foundValueEnd = valueEnd;
3252
+ }
3253
+ break;
3254
+ }
3255
+ const siblingProp = matchStickyAt(ANY_PROP_HEAD_STICKY_RE, text, contentStart);
3256
+ if (siblingProp !== null) {
3257
+ const siblingKey = (siblingProp[3] ?? siblingProp[2] ?? '').toLowerCase();
3258
+ if (siblingKey === 'name' || siblingKey === 'key') {
3259
+ break;
3260
+ }
3261
+ }
3262
+ linePos = lineEnd;
3263
+ }
3264
+ }
3265
+ }
3266
+ if (foundValueEnd !== -1 && foundValueKeyStart >= cursor) {
3267
+ out += text.slice(cursor, foundValueKeyStart) + ' ';
3268
+ cursor = foundValueEnd;
3269
+ NAMED_SECRET_KEY_PROP_RE.lastIndex = foundValueEnd;
3270
+ }
3271
+ }
3272
+ return cursor === 0 ? text : out + text.slice(cursor);
3273
+ }
3274
+ function stripStandalonePrivateKeyPemBlocks(text) {
3275
+ let pos = text.indexOf('-----BEGIN ');
3276
+ if (pos === -1)
3277
+ return text;
3278
+ let out = '';
3279
+ let cursor = 0;
3280
+ while (pos !== -1) {
3281
+ const headerClose = text.indexOf('-----', pos + 11);
3282
+ if (headerClose === -1)
3283
+ break;
3284
+ const label = text.slice(pos + 11, headerClose);
3285
+ if (/^[A-Z0-9 _-]*PRIVATE KEY[A-Z0-9 _-]*$/u.test(label)) {
3286
+ const searchFrom = headerClose + 5;
3287
+ let endIdx = text.indexOf('-----END ', searchFrom);
3288
+ let blockEnd = text.length;
3289
+ while (endIdx !== -1) {
3290
+ const endClose = text.indexOf('-----', endIdx + 9);
3291
+ if (endClose === -1)
3292
+ break;
3293
+ const endLabel = text.slice(endIdx + 9, endClose);
3294
+ if (/^[A-Z0-9 _-]*PRIVATE KEY[A-Z0-9 _-]*$/u.test(endLabel)) {
3295
+ blockEnd = endClose + 5;
3296
+ break;
3297
+ }
3298
+ endIdx = text.indexOf('-----END ', endClose);
3299
+ }
3300
+ out += text.slice(cursor, pos) + ' ';
3301
+ cursor = blockEnd;
3302
+ pos = text.indexOf('-----BEGIN ', blockEnd);
3303
+ continue;
3304
+ }
3305
+ pos = text.indexOf('-----BEGIN ', headerClose);
3306
+ }
3307
+ return cursor === 0 ? text : out + text.slice(cursor);
3308
+ }
3309
+ function isFollowedByAssignmentOperator(text, pos) {
3310
+ let i = pos;
3311
+ while (i < text.length && (text[i] === ' ' || text[i] === '\t')) {
3312
+ i += 1;
3313
+ }
3314
+ const ch = text[i];
3315
+ return ch === ':' || ch === '=';
3316
+ }
3317
+ const CLI_SECRET_FAST_GUARD_RE = /(?:curl|ssh-keygen|docker|-u[:'"`])/iu;
3318
+ const DOCKER_GLOBAL_VALUE_FLAGS = new Set([
3319
+ '-h',
3320
+ '--host',
3321
+ '-c',
3322
+ '--context',
3323
+ '-l',
3324
+ '--log-level',
3325
+ '--config',
3326
+ '--tlscacert',
3327
+ '--tlscert',
3328
+ '--tlskey',
3329
+ ]);
3330
+ const CLI_TOKEN_BREAKER_ASCII = (() => {
3331
+ const table = new Uint8Array(128);
3332
+ for (const ch of ' \t\r\n;|&()<>,{}[]"\'`') {
3333
+ table[ch.charCodeAt(0)] = 1;
3334
+ }
3335
+ return table;
3336
+ })();
3337
+ function isCliTokenBreakerCode(code) {
3338
+ return code < 128 && CLI_TOKEN_BREAKER_ASCII[code] === 1;
3339
+ }
3340
+ function findClosingQuoteSameLine(text, openIdx, failedQuoteLine, lineId) {
3341
+ const quote = text[openIdx];
3342
+ if (quote !== '"' && quote !== "'" && quote !== '`')
3343
+ return -1;
3344
+ if (failedQuoteLine[quote] === lineId)
3345
+ return -1;
3346
+ let j = openIdx + 1;
3347
+ while (j < text.length) {
3348
+ const ch = text[j];
3349
+ if (ch === '\r' || ch === '\n') {
3350
+ failedQuoteLine[quote] = lineId;
3351
+ return -1;
3352
+ }
3353
+ if (text.charCodeAt(j) === 92 /* '\\' */) {
3354
+ if (j + 1 < text.length && text[j + 1] !== '\r' && text[j + 1] !== '\n') {
3355
+ j += 2;
3356
+ continue;
3357
+ }
3358
+ }
3359
+ if (ch === quote) {
3360
+ return j + 1;
3361
+ }
3362
+ j += 1;
3363
+ }
3364
+ failedQuoteLine[quote] = lineId;
3365
+ return -1;
3366
+ }
3367
+ function consumeCliArgEnd(text, startIdx, failedQuoteLine, lineId) {
3368
+ if (startIdx >= text.length)
3369
+ return -1;
3370
+ const first = text[startIdx];
3371
+ if (first === ' ' ||
3372
+ first === '\t' ||
3373
+ first === '\r' ||
3374
+ first === '\n' ||
3375
+ first === ';' ||
3376
+ first === '|' ||
3377
+ first === '&' ||
3378
+ first === '(' ||
3379
+ first === ')' ||
3380
+ first === '<' ||
3381
+ first === '>' ||
3382
+ first === ',' ||
3383
+ first === '}' ||
3384
+ first === ']') {
3385
+ return -1;
3386
+ }
3387
+ let p = startIdx;
3388
+ while (p < text.length) {
3389
+ const ch = text[p];
3390
+ if (ch === '"' || ch === "'" || ch === '`') {
3391
+ const qEnd = findClosingQuoteSameLine(text, p, failedQuoteLine, lineId);
3392
+ if (qEnd !== -1) {
3393
+ p = qEnd;
3394
+ continue;
3395
+ }
3396
+ if (p === startIdx) {
3397
+ p += 1;
3398
+ continue;
3399
+ }
3400
+ break;
3401
+ }
3402
+ if (ch === '\\' && p + 1 < text.length && text[p + 1] !== '\r' && text[p + 1] !== '\n') {
3403
+ p += 2;
3404
+ continue;
3405
+ }
3406
+ if (ch === ' ' ||
3407
+ ch === '\t' ||
3408
+ ch === '\r' ||
3409
+ ch === '\n' ||
3410
+ ch === ';' ||
3411
+ ch === '|' ||
3412
+ ch === '&' ||
3413
+ ch === '(' ||
3414
+ ch === ')' ||
3415
+ ch === '<' ||
3416
+ ch === '>' ||
3417
+ ch === ',' ||
3418
+ ch === '}' ||
3419
+ ch === ']') {
3420
+ break;
3421
+ }
3422
+ p += 1;
3423
+ }
3424
+ return p > startIdx ? p : -1;
3425
+ }
3426
+ function hasColonInRange(text, start, end) {
3427
+ for (let k = start; k < end; k += 1) {
3428
+ if (text.charCodeAt(k) === 58 /* ':' */)
3429
+ return true;
3430
+ }
3431
+ return false;
3432
+ }
3433
+ function scrubCommandScopedCliSecrets(text) {
3434
+ if (!CLI_SECRET_FAST_GUARD_RE.test(text)) {
3435
+ return text;
3436
+ }
3437
+ const hasColon = text.includes(':');
3438
+ const failedQuoteLine = {};
3439
+ let activeCmd = 'none';
3440
+ let expectDockerGlobalArg = false;
3441
+ let lineId = 0;
3442
+ let out = '';
3443
+ let cursor = 0;
3444
+ let i = 0;
3445
+ while (i < text.length) {
3446
+ const ch = text[i];
3447
+ if (ch === ' ' || ch === '\t') {
3448
+ i += 1;
3449
+ continue;
3450
+ }
3451
+ if (ch === '\r' || ch === '\n') {
3452
+ i += ch === '\r' && text[i + 1] === '\n' ? 2 : 1;
3453
+ lineId = i;
3454
+ activeCmd = 'none';
3455
+ expectDockerGlobalArg = false;
3456
+ continue;
3457
+ }
3458
+ if (ch === '\\' && i + 1 < text.length && (text[i + 1] === '\r' || text[i + 1] === '\n')) {
3459
+ i += text[i + 1] === '\r' && text[i + 2] === '\n' ? 3 : 2;
3460
+ lineId = i;
3461
+ continue;
3462
+ }
3463
+ if (ch === ';' || ch === '|' || ch === '&' || ch === '(' || ch === ')') {
3464
+ activeCmd = 'none';
3465
+ expectDockerGlobalArg = false;
3466
+ i += 1;
3467
+ continue;
3468
+ }
3469
+ if (ch === '<' || ch === '>' || ch === ',' || ch === '{' || ch === '}' || ch === '[' || ch === ']') {
3470
+ i += 1;
3471
+ continue;
3472
+ }
3473
+ if (ch === '"' || ch === "'" || ch === '`') {
3474
+ if (activeCmd !== 'none') {
3475
+ const qEnd = findClosingQuoteSameLine(text, i, failedQuoteLine, lineId);
3476
+ if (qEnd !== -1) {
3477
+ if (activeCmd === 'docker' && expectDockerGlobalArg) {
3478
+ expectDockerGlobalArg = false;
3479
+ }
3480
+ i = qEnd;
3481
+ continue;
3482
+ }
3483
+ }
3484
+ i += 1;
3485
+ continue;
3486
+ }
3487
+ // Check attached `-u:` (anywhere) or `-u":..."` (outside `curl`, where `curl` uses `consumeCliArgEnd` below).
3488
+ if (hasColon && ch === '-' && text[i + 1] === 'u' && i + 2 < text.length) {
3489
+ const nextCh = text[i + 2];
3490
+ if (nextCh === ':') {
3491
+ const argEnd = consumeCliArgEnd(text, i + 3, failedQuoteLine, lineId);
3492
+ if (argEnd !== -1) {
3493
+ out += text.slice(cursor, i) + ' ';
3494
+ cursor = argEnd;
3495
+ i = argEnd;
3496
+ continue;
3497
+ }
3498
+ }
3499
+ else if (activeCmd !== 'curl' &&
3500
+ (nextCh === '"' || nextCh === "'" || nextCh === '`')) {
3501
+ const qEnd = findClosingQuoteSameLine(text, i + 2, failedQuoteLine, lineId);
3502
+ if (qEnd !== -1 && hasColonInRange(text, i + 3, qEnd - 1)) {
3503
+ out += text.slice(cursor, i) + ' ';
3504
+ cursor = qEnd;
3505
+ i = qEnd;
3506
+ continue;
3507
+ }
3508
+ }
3509
+ }
3510
+ // Check `curl`-command-scoped `-u` / `--user` / `-U` / `--proxy-user` (spaced, `=`, attached, or mixed-quoted).
3511
+ if (hasColon && activeCmd === 'curl' && ch === '-' && i + 2 < text.length) {
3512
+ let valStart = -1;
3513
+ let isSpaced = false;
3514
+ const c1 = text[i + 1];
3515
+ if (c1 === 'u' || c1 === 'U') {
3516
+ if (text[i + 2] === ' ' || text[i + 2] === '\t') {
3517
+ let p = i + 2;
3518
+ while (p < text.length && (text[p] === ' ' || text[p] === '\t')) {
3519
+ p += 1;
3520
+ }
3521
+ valStart = p;
3522
+ isSpaced = true;
3523
+ }
3524
+ else if (text[i + 2] === '=') {
3525
+ valStart = i + 3;
3526
+ }
3527
+ else {
3528
+ valStart = i + 2;
3529
+ }
3530
+ }
3531
+ else if (c1 === '-') {
3532
+ const c2 = text[i + 2];
3533
+ if ((c2 === 'u' || c2 === 'U') &&
3534
+ i + 6 < text.length &&
3535
+ text.slice(i, i + 6).toLowerCase() === '--user') {
3536
+ if (text[i + 6] === ' ' || text[i + 6] === '\t') {
3537
+ let p = i + 6;
3538
+ while (p < text.length && (text[p] === ' ' || text[p] === '\t')) {
3539
+ p += 1;
3540
+ }
3541
+ valStart = p;
3542
+ isSpaced = true;
3543
+ }
3544
+ else if (text[i + 6] === '=') {
3545
+ valStart = i + 7;
3546
+ }
3547
+ else if (text[i + 6] === ':') {
3548
+ valStart = i + 6;
3549
+ }
3550
+ }
3551
+ else if ((c2 === 'p' || c2 === 'P') &&
3552
+ i + 12 < text.length &&
3553
+ text.slice(i, i + 12).toLowerCase() === '--proxy-user') {
3554
+ if (text[i + 12] === ' ' || text[i + 12] === '\t') {
3555
+ let p = i + 12;
3556
+ while (p < text.length && (text[p] === ' ' || text[p] === '\t')) {
3557
+ p += 1;
3558
+ }
3559
+ valStart = p;
3560
+ isSpaced = true;
3561
+ }
3562
+ else if (text[i + 12] === '=') {
3563
+ valStart = i + 13;
3564
+ }
3565
+ }
3566
+ }
3567
+ if (valStart !== -1) {
3568
+ const valEnd = consumeCliArgEnd(text, valStart, failedQuoteLine, lineId);
3569
+ if (valEnd !== -1) {
3570
+ if (hasColonInRange(text, valStart, valEnd)) {
3571
+ out += text.slice(cursor, i) + ' ';
3572
+ cursor = valEnd;
3573
+ i = valEnd;
3574
+ }
3575
+ else {
3576
+ i = isSpaced ? valStart : valEnd;
3577
+ }
3578
+ continue;
3579
+ }
3580
+ }
3581
+ }
3582
+ // Check `ssh-keygen` `-N` / `-P` passphrase flags.
3583
+ if (activeCmd === 'ssh-keygen' && ch === '-' && (text[i + 1] === 'N' || text[i + 1] === 'P')) {
3584
+ let valStart = -1;
3585
+ if (i + 2 < text.length && (text[i + 2] === ' ' || text[i + 2] === '\t')) {
3586
+ let p = i + 2;
3587
+ while (p < text.length && (text[p] === ' ' || text[p] === '\t')) {
3588
+ p += 1;
3589
+ }
3590
+ valStart = p;
3591
+ }
3592
+ else if (text[i + 2] === '=') {
3593
+ valStart = i + 3;
3594
+ }
3595
+ else if (i + 2 < text.length && !isCliTokenBreakerCode(text.charCodeAt(i + 2))) {
3596
+ valStart = i + 2;
3597
+ }
3598
+ if (valStart !== -1) {
3599
+ const valEnd = consumeCliArgEnd(text, valStart, failedQuoteLine, lineId);
3600
+ if (valEnd !== -1) {
3601
+ out += text.slice(cursor, i) + ' ';
3602
+ cursor = valEnd;
3603
+ i = valEnd;
3604
+ continue;
3605
+ }
3606
+ }
3607
+ }
3608
+ // Check `docker login` `-p` / `--password` flags (excluding `--password-stdin`).
3609
+ if (activeCmd === 'docker-login' && ch === '-') {
3610
+ let valStart = -1;
3611
+ if (text[i + 1] === 'p') {
3612
+ if (i + 2 < text.length && (text[i + 2] === ' ' || text[i + 2] === '\t')) {
3613
+ let p = i + 2;
3614
+ while (p < text.length && (text[p] === ' ' || text[p] === '\t')) {
3615
+ p += 1;
3616
+ }
3617
+ valStart = p;
3618
+ }
3619
+ else if (text[i + 2] === '=') {
3620
+ valStart = i + 3;
3621
+ }
3622
+ else if (i + 2 < text.length && !isCliTokenBreakerCode(text.charCodeAt(i + 2))) {
3623
+ valStart = i + 2;
3624
+ }
3625
+ }
3626
+ else if (i + 10 <= text.length && text.slice(i, i + 10).toLowerCase() === '--password') {
3627
+ if (i + 10 < text.length && (text[i + 10] === ' ' || text[i + 10] === '\t')) {
3628
+ let p = i + 10;
3629
+ while (p < text.length && (text[p] === ' ' || text[p] === '\t')) {
3630
+ p += 1;
3631
+ }
3632
+ valStart = p;
3633
+ }
3634
+ else if (text[i + 10] === '=') {
3635
+ valStart = i + 11;
3636
+ }
3637
+ }
3638
+ if (valStart !== -1) {
3639
+ const valEnd = consumeCliArgEnd(text, valStart, failedQuoteLine, lineId);
3640
+ if (valEnd !== -1) {
3641
+ out += text.slice(cursor, i) + ' ';
3642
+ cursor = valEnd;
3643
+ i = valEnd;
3644
+ continue;
3645
+ }
3646
+ }
3647
+ }
3648
+ // Consume ordinary command/argument token and update `activeCmd`.
3649
+ let tokEnd = i;
3650
+ while (tokEnd < text.length) {
3651
+ const tCode = text.charCodeAt(tokEnd);
3652
+ if (tCode === 92 /* '\\' */ &&
3653
+ tokEnd + 1 < text.length &&
3654
+ text[tokEnd + 1] !== '\r' &&
3655
+ text[tokEnd + 1] !== '\n') {
3656
+ tokEnd += 2;
3657
+ continue;
3658
+ }
3659
+ if (tCode < 128 && CLI_TOKEN_BREAKER_ASCII[tCode] === 1) {
3660
+ break;
3661
+ }
3662
+ tokEnd += 1;
3663
+ }
3664
+ if (tokEnd === i) {
3665
+ i += 1;
3666
+ continue;
3667
+ }
3668
+ if (ch === '-' && activeCmd !== 'docker') {
3669
+ i = tokEnd;
3670
+ continue;
3671
+ }
3672
+ const tokLower = text.slice(i, tokEnd).toLowerCase();
3673
+ const lastSlash = Math.max(tokLower.lastIndexOf('/'), tokLower.lastIndexOf('\\'));
3674
+ const baseName = lastSlash >= 0 ? tokLower.slice(lastSlash + 1) : tokLower;
3675
+ if (baseName === 'curl' || baseName === 'curl.exe') {
3676
+ activeCmd = 'curl';
3677
+ expectDockerGlobalArg = false;
3678
+ }
3679
+ else if (baseName === 'ssh-keygen' || baseName === 'ssh-keygen.exe') {
3680
+ activeCmd = 'ssh-keygen';
3681
+ expectDockerGlobalArg = false;
3682
+ }
3683
+ else if (baseName === 'docker' || baseName === 'docker.exe') {
3684
+ activeCmd = 'docker';
3685
+ expectDockerGlobalArg = false;
3686
+ }
3687
+ else if (activeCmd === 'docker') {
3688
+ if (expectDockerGlobalArg) {
3689
+ expectDockerGlobalArg = false;
3690
+ }
3691
+ else if (tokLower.startsWith('-')) {
3692
+ if (DOCKER_GLOBAL_VALUE_FLAGS.has(tokLower)) {
3693
+ expectDockerGlobalArg = true;
3694
+ }
3695
+ }
3696
+ else if (tokLower === 'login') {
3697
+ activeCmd = 'docker-login';
3698
+ }
3699
+ else {
3700
+ activeCmd = 'none';
3701
+ }
3702
+ }
3703
+ i = tokEnd;
3704
+ }
3705
+ return cursor === 0 ? text : out + text.slice(cursor);
3706
+ }
3707
+ export function scrubInterestText(raw, scope) {
3708
+ let scrubbed = raw.normalize('NFKC');
3709
+ const scopeTerms = collectScopeSensitiveTerms(scope);
3710
+ for (const literal of scopeTerms.rawLiterals) {
3711
+ scrubbed = scrubbed.replace(new RegExp(escapeRegExp(literal), 'giu'), ' ');
3712
+ }
3713
+ // Strip CLI basic-auth flags, command-scoped CLI secrets, URLs, emails, paths, IP literals, UUIDs, secrets,
3714
+ // and sensitive dotfiles/extensions BEFORE tokenization so path/secret subwords never enter entity extraction.
3715
+ // Run `scrubCommandScopedCliSecrets` before URL/path stripping so `docker -H tcp://... login -p ...` keeps
3716
+ // its global flag argument intact while parsing.
3717
+ scrubbed = scrubCommandScopedCliSecrets(scrubbed);
3718
+ if (scrubbed.includes(':') &&
3719
+ (scrubbed.includes('-u') || scrubbed.includes('--user') || scrubbed.includes('--proxy-user'))) {
3720
+ scrubbed = scrubbed.replace(CLI_BASIC_AUTH_RE, ' ');
3721
+ }
3722
+ if (scrubbed.includes('://')) {
3723
+ scrubbed = stripUrlsFromInterestText(scrubbed);
3724
+ }
3725
+ if (scrubbed.includes('@')) {
3726
+ scrubbed = scrubbed.replace(/(?<![A-Za-z0-9._%+-])[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/gu, ' ');
3727
+ }
3728
+ if (scrubbed.includes('\\')) {
3729
+ scrubbed = scrubbed
3730
+ .replace(/[A-Za-z]:\\[^\s"'`<>|;,()]+/gu, ' ')
3731
+ .replace(/(?<=^|[\s<>|;,()]|(?<!\\)["'`])[^\s"'`<>|;,()\\]*(?:\\+[^\s"'`<>|;,()\\]+)+/gu, ' ');
3732
+ }
3733
+ if (scrubbed.includes('/')) {
3734
+ scrubbed = scrubbed.replace(/(?<=^|[\s"'`(,=])(?:~|\.{1,2})?(?!\/\/[^/\s"'`<>|;,()]*(?:$|[\s])|\/\*)(?:\/[^\s"'`<>|;,()]+)+/gu, ' ');
3735
+ }
3736
+ if (scrubbed.includes('-')) {
3737
+ scrubbed = scrubbed.replace(/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/giu, ' ');
3738
+ }
3739
+ if (scrubbed.includes('.')) {
3740
+ scrubbed = scrubbed.replace(/\b\d{1,3}(?:\.\d{1,3}){3}\b/gu, ' ');
3741
+ }
3742
+ if (scrubbed.includes(':')) {
3743
+ scrubbed = scrubbed.replace(/(?:\[[0-9a-f:]+\]|(?:[0-9a-f]{0,4}:){2,7}[0-9a-f]{0,4})/giu, ' ');
3744
+ }
3745
+ if (scrubbed.includes(':') || scrubbed.includes('=')) {
3746
+ scrubbed = scrubByKeyPattern(scrubbed, SCRUB_ASSIGN_HEAD_RE, false);
3747
+ }
3748
+ if (scrubbed.includes(':')) {
3749
+ scrubbed = scrubNamedSecretValuePairs(scrubbed);
3750
+ }
3751
+ if (scrubbed.includes('-----BEGIN ')) {
3752
+ scrubbed = stripStandalonePrivateKeyPemBlocks(scrubbed);
3753
+ }
3754
+ scrubbed = scrubByKeyPattern(scrubbed, SCRUB_SPACE_HEAD_RE, true);
3755
+ if (scrubbed.includes('_') || scrubbed.includes('-')) {
3756
+ scrubbed = scrubbed.replace(/\b(?:(?:sk|pk|rk|ghp|gho|ghu|ghs|ghr|xox[bpar]|glpat)[_-]|(?:npm|whsec)_)[A-Za-z0-9._-]+\b/giu, (match, offset, full) => isFollowedByAssignmentOperator(full, offset + match.length) && isSecretAssignmentKey(match)
3757
+ ? match
3758
+ : ' ');
3759
+ }
3760
+ if (scrubbed.includes('_')) {
3761
+ scrubbed = scrubbed.replace(/\bgithub_pat_[A-Za-z0-9_]+\b/giu, (match, offset, full) => isFollowedByAssignmentOperator(full, offset + match.length) && isSecretAssignmentKey(match)
3762
+ ? match
3763
+ : ' ');
3764
+ }
3765
+ if (scrubbed.includes('AKIA') || scrubbed.includes('ASIA') || scrubbed.includes('AIza')) {
3766
+ scrubbed = scrubbed.replace(/\b(?:AKIA|ASIA|AIza)[0-9A-Za-z_-]{8,}\b/gu, ' ');
3767
+ }
3768
+ if (scrubbed.includes('ya29.') || scrubbed.includes('YA29.')) {
3769
+ scrubbed = scrubbed.replace(/\bya29\.[A-Za-z0-9._-]+\b/giu, ' ');
3770
+ }
3771
+ if (scrubbed.includes('eyJ')) {
3772
+ scrubbed = scrubbed.replace(/\beyJ[A-Za-z0-9_-]{8,}(?:\.[A-Za-z0-9_-]+)*\b/gu, ' ');
3773
+ }
3774
+ if (scrubbed.includes('.')) {
3775
+ scrubbed = scrubbed
3776
+ .replace(/(?<![A-Za-z0-9._-])[A-Za-z0-9._-]+\.(?:sqlite|sqlite3|db|env|pem|key|p12|pfx|crt|cer|pub|der|jks|keystore|kdbx|log|bak|secret|passwd|htpasswd|netrc|npmrc|pypirc|dockercfg)\b/giu, ' ')
3777
+ .replace(/(?:^|[\s(,=])\.[A-Za-z0-9._-]+(?=$|[\s),])/gu, ' ');
3778
+ }
3779
+ return scrubbed;
3780
+ }
3781
+ export function sanitizeInterestToken(token, scope) {
3782
+ if (typeof token !== 'string')
3783
+ return null;
3784
+ const rawTrimmed = token.normalize('NFKC').trim();
3785
+ if (rawTrimmed.length < 2 || rawTrimmed.length > 128)
3786
+ return null;
3787
+ if (/\s|\p{Cc}/u.test(rawTrimmed))
3788
+ return null;
3789
+ if (rawTrimmed.includes('/') ||
3790
+ rawTrimmed.includes('\\') ||
3791
+ rawTrimmed.includes('~') ||
3792
+ rawTrimmed.includes('@') ||
3793
+ rawTrimmed.includes(':') ||
3794
+ rawTrimmed.includes('..') ||
3795
+ rawTrimmed.includes('+') ||
3796
+ rawTrimmed.includes('=') ||
3797
+ rawTrimmed.startsWith('.') ||
3798
+ rawTrimmed.endsWith('.')) {
3799
+ return null;
3800
+ }
3801
+ if (isIP(rawTrimmed) !== 0)
3802
+ return null;
3803
+ const lower = rawTrimmed.toLocaleLowerCase('en-US');
3804
+ if (STOPWORDS.has(lower))
3805
+ return null;
3806
+ if (/^\d+$/u.test(lower))
3807
+ return null;
3808
+ if (IPV4_RE.test(lower))
3809
+ return null;
3810
+ if (UUID_RE.test(lower))
3811
+ return null;
3812
+ if (DANGEROUS_EXT_RE.test(lower))
3813
+ return null;
3814
+ if (SECRET_PREFIX_RE.test(rawTrimmed))
3815
+ return null;
3816
+ if (HEX_LONG_RE.test(lower))
3817
+ return null;
3818
+ if (SECRET_EXACT_TOKENS.has(lower))
3819
+ return null;
3820
+ if (hasSecretStem(rawTrimmed))
3821
+ return null;
3822
+ const subParts = lower.split(/[._-]+/u).filter((part) => part.length > 0);
3823
+ for (const part of subParts) {
3824
+ if (SECRET_EXACT_TOKENS.has(part))
3825
+ return null;
3826
+ }
3827
+ if (rawTrimmed.includes('_') && subParts.includes('pass')) {
3828
+ return null;
3829
+ }
3830
+ if (lower === 'github_pat' || lower === 'github-pat' || lower === 'githubpat') {
3831
+ return null;
3832
+ }
3833
+ if ((subParts.includes('api') ||
3834
+ subParts.includes('private') ||
3835
+ subParts.includes('secret') ||
3836
+ subParts.includes('access') ||
3837
+ subParts.includes('auth') ||
3838
+ subParts.includes('client') ||
3839
+ subParts.includes('ssh') ||
3840
+ subParts.includes('signing') ||
3841
+ subParts.includes('master') ||
3842
+ subParts.includes('encryption') ||
3843
+ subParts.includes('deploy') ||
3844
+ subParts.includes('jwt') ||
3845
+ subParts.includes('app') ||
3846
+ subParts.includes('hmac') ||
3847
+ subParts.includes('tls') ||
3848
+ subParts.includes('ssl') ||
3849
+ subParts.includes('aes') ||
3850
+ subParts.includes('kms') ||
3851
+ subParts.includes('fernet') ||
3852
+ subParts.includes('cipher') ||
3853
+ subParts.includes('pk') ||
3854
+ subParts.includes('sk') ||
3855
+ subParts.includes('rk') ||
3856
+ subParts.includes('whsec') ||
3857
+ subParts.includes('ghp') ||
3858
+ subParts.includes('gho') ||
3859
+ subParts.includes('ghu') ||
3860
+ subParts.includes('ghs') ||
3861
+ subParts.includes('ghr') ||
3862
+ subParts.includes('glpat') ||
3863
+ subParts.includes('npm') ||
3864
+ subParts.includes('xoxb') ||
3865
+ subParts.includes('xoxp') ||
3866
+ subParts.includes('xoxa') ||
3867
+ subParts.includes('xoxr') ||
3868
+ (subParts.includes('github') && subParts.includes('pat'))) &&
3869
+ (subParts.includes('key') || subParts.includes('keys'))) {
3870
+ return null;
3871
+ }
3872
+ // Reject base64/high-entropy strings >= 20 chars:
3873
+ // - any >= 20 char non-hyphenated alphanumeric/underscore token
3874
+ // - any >= 20 char token containing underscores or >= 2 digits
3875
+ if (lower.length >= 20) {
3876
+ if (NON_HYPHEN_LONG_RE.test(lower))
3877
+ return null;
3878
+ const digitCount = lower.replace(/[^0-9]/gu, '').length;
3879
+ if (lower.includes('_') || digitCount >= 2)
3880
+ return null;
3881
+ if (/[A-Z]/u.test(rawTrimmed) && /[a-z]/u.test(rawTrimmed) && digitCount >= 1)
3882
+ return null;
3883
+ }
3884
+ const scopeTerms = collectScopeSensitiveTerms(scope);
3885
+ if (scopeTerms.exactTerms.has(lower))
3886
+ return null;
3887
+ for (const term of scopeTerms.substringTerms) {
3888
+ if (lower.includes(term))
3889
+ return null;
3890
+ }
3891
+ if (CJK_CHAR_RE.test(lower)) {
3892
+ if (lower.length > MAX_CJK_TOKEN_CHARS || !SAFE_CJK_TOKEN_RE.test(lower))
3893
+ return null;
3894
+ return lower;
3895
+ }
3896
+ if (lower.length > MAX_TOKEN_CHARS || !SAFE_ASCII_TOKEN_RE.test(lower)) {
3897
+ return null;
3898
+ }
3899
+ return lower;
3900
+ }
3901
+ function extractCleanTokensFromTextAndEntities(rawTextOrParts, storedEntities, scope) {
3902
+ const result = [];
3903
+ const seen = new Set();
3904
+ const push = (candidate) => {
3905
+ const clean = sanitizeInterestToken(candidate, scope);
3906
+ if (clean === null || seen.has(clean))
3907
+ return;
3908
+ seen.add(clean);
3909
+ result.push(clean);
3910
+ };
3911
+ const parts = typeof rawTextOrParts === 'string' ? [rawTextOrParts] : rawTextOrParts;
3912
+ const hasNonEmptyRaw = parts.some((part) => part.trim().length > 0);
3913
+ const scrubbed = parts
3914
+ .filter((part) => part.length > 0)
3915
+ .map((part) => scrubInterestText(part, scope))
3916
+ .join('\n');
3917
+ const scrubbedEntitySet = new Set(extractEntities(scrubbed, 48));
3918
+ const scrubbedTokenSet = new Set(tokenizeAssociationText(scrubbed));
3919
+ if (!hasNonEmptyRaw) {
3920
+ for (const ent of storedEntities) {
3921
+ push(ent);
3922
+ }
3923
+ }
3924
+ else {
3925
+ // Only admit stored entities that remain present after sensitive-text scrubbing.
3926
+ for (const ent of storedEntities) {
3927
+ const normalized = ent.normalize('NFKC').toLocaleLowerCase('en-US').trim();
3928
+ if (scrubbedEntitySet.has(normalized) || scrubbedTokenSet.has(normalized)) {
3929
+ push(normalized);
3930
+ }
3931
+ }
3932
+ for (const ent of scrubbedEntitySet) {
3933
+ push(ent);
3934
+ }
3935
+ for (const tok of scrubbedTokenSet) {
3936
+ push(tok);
3937
+ }
3938
+ }
3939
+ return result;
3940
+ }
3941
+ function buildBoundedQueryTokens(tokens) {
3942
+ const selected = [];
3943
+ let totalChars = 0;
3944
+ for (const tok of tokens) {
3945
+ if (selected.length >= MAX_TOKENS_PER_QUERY)
3946
+ break;
3947
+ const extraChars = selected.length === 0 ? tok.length : 1 + tok.length;
3948
+ if (totalChars + extraChars > MAX_QUERY_CHARS)
3949
+ continue;
3950
+ selected.push(tok);
3951
+ totalChars += extraChars;
3952
+ }
3953
+ return selected;
3954
+ }
3955
+ function parseJsonStringArray(raw) {
3956
+ try {
3957
+ const parsed = JSON.parse(raw);
3958
+ if (!Array.isArray(parsed))
3959
+ return [];
3960
+ return parsed.filter((item) => typeof item === 'string');
3961
+ }
3962
+ catch {
3963
+ return [];
3964
+ }
3965
+ }
3966
+ function parseCueTextsAndEntities(raw) {
3967
+ try {
3968
+ const parsed = JSON.parse(raw);
3969
+ if (!Array.isArray(parsed))
3970
+ return [];
3971
+ const out = [];
3972
+ for (const item of parsed) {
3973
+ if (typeof item === 'string') {
3974
+ out.push({ text: item, entities: [] });
3975
+ }
3976
+ else if (item !== null && typeof item === 'object' && !Array.isArray(item)) {
3977
+ const obj = item;
3978
+ const text = typeof obj.text === 'string' ? obj.text : '';
3979
+ const entities = Array.isArray(obj.entities)
3980
+ ? obj.entities.filter((v) => typeof v === 'string')
3981
+ : [];
3982
+ if (text.length > 0 || entities.length > 0) {
3983
+ out.push({ text, entities });
3984
+ }
3985
+ }
3986
+ }
3987
+ return out;
3988
+ }
3989
+ catch {
3990
+ return [];
3991
+ }
3992
+ }
3993
+ function loadHoldoutTaskIds(db, ownerScopeKey) {
3994
+ const holdouts = new Set();
3995
+ if (!hasTable(db, 'assoc_holdout_assignments'))
3996
+ return holdouts;
3997
+ const rows = db
3998
+ .prepare('SELECT task_id FROM assoc_holdout_assignments WHERE owner_scope_key = ? AND in_holdout = 1')
3999
+ .all(ownerScopeKey);
4000
+ for (const row of rows) {
4001
+ holdouts.add(row.task_id);
4002
+ }
4003
+ return holdouts;
4004
+ }
4005
+ export function extractWebLearningInterests(storeOrDb, scope, options) {
4006
+ const db = asDatabase(storeOrDb);
4007
+ const cfg = options?.config ?? DEFAULT_ASSOCIATION_WEB_LEARNING_CONFIG;
4008
+ const allowedDomains = options?.allowedDomains ?? cfg.allowedDomains;
4009
+ const seedUrls = options?.seedUrls ?? cfg.seedUrls;
4010
+ const allowSubdomains = options?.allowSubdomains ?? cfg.allowSubdomains;
4011
+ const cooldownMs = options?.cooldownMs ?? cfg.cooldownMs;
4012
+ const maxInterests = Math.max(0, Math.floor(options?.maxInterestsPerRun ?? cfg.maxInterestsPerRun));
4013
+ const discoverLinks = options?.discoverLinks ?? cfg.discoverLinks;
4014
+ const nowMs = options?.nowMs ?? Date.now();
4015
+ if (maxInterests === 0 || allowedDomains.length === 0) {
4016
+ return {
4017
+ interests: [],
4018
+ targets: [],
4019
+ skippedCooldownCount: 0,
4020
+ rejectedSeedUrls: [],
4021
+ };
4022
+ }
4023
+ const holdoutTaskIds = loadHoldoutTaskIds(db, scope.ownerScopeKey);
4024
+ const rawCandidates = [];
4025
+ const addCandidate = (tokens, priority, sourceKind, originNodeIds, updatedAt) => {
4026
+ const bounded = buildBoundedQueryTokens(tokens);
4027
+ if (bounded.length === 0)
4028
+ return;
4029
+ const query = bounded.join(' ');
4030
+ const interestKey = `int-${sha256Hex(query).slice(0, 16)}`;
4031
+ rawCandidates.push({
4032
+ tokens: bounded,
4033
+ query,
4034
+ interestKey,
4035
+ priority,
4036
+ sourceKind,
4037
+ originNodeIds,
4038
+ updatedAt,
4039
+ });
4040
+ };
4041
+ // 1. Active private goal, work-item, dream, abstraction nodes
4042
+ if (hasTable(db, 'assoc_nodes')) {
4043
+ const nodeRows = db
4044
+ .prepare(`
4045
+ SELECT id, kind, title, body, entities_json, updated_at
4046
+ FROM assoc_nodes
4047
+ WHERE owner_scope_key = ?
4048
+ AND status = 'active'
4049
+ AND sensitivity = 'private'
4050
+ AND kind IN ('goal', 'work-item', 'dream', 'abstraction')
4051
+ AND (expires_at IS NULL OR expires_at > ?)
4052
+ ORDER BY updated_at DESC, id ASC
4053
+ LIMIT 200
4054
+ `)
4055
+ .all(scope.ownerScopeKey, nowMs);
4056
+ for (const row of nodeRows) {
4057
+ const cleanTokens = extractCleanTokensFromTextAndEntities([row.title, row.body], parseJsonStringArray(row.entities_json), scope);
4058
+ if (cleanTokens.length === 0)
4059
+ continue;
4060
+ const priority = INTEREST_SOURCE_PRIORITIES[row.kind];
4061
+ addCandidate(cleanTokens, priority, row.kind, [row.id], row.updated_at);
4062
+ }
4063
+ }
4064
+ // Helper: inspect private active episode nodes for a taskId (never sensitive, never holdout)
4065
+ const lookupPrivateEpisodeByTaskId = (taskId) => {
4066
+ if (!hasTable(db, 'assoc_nodes'))
4067
+ return null;
4068
+ const row = db
4069
+ .prepare(`
4070
+ SELECT id, sensitivity, title, body, entities_json
4071
+ FROM assoc_nodes
4072
+ WHERE owner_scope_key = ?
4073
+ AND kind = 'episode'
4074
+ AND status = 'active'
4075
+ AND (source_ref = ? OR id = ?)
4076
+ LIMIT 1
4077
+ `)
4078
+ .get(scope.ownerScopeKey, taskId, taskId);
4079
+ if (row === undefined)
4080
+ return null;
4081
+ return {
4082
+ id: row.id,
4083
+ sensitivity: row.sensitivity,
4084
+ title: row.title,
4085
+ body: row.body,
4086
+ entities: parseJsonStringArray(row.entities_json),
4087
+ };
4088
+ };
4089
+ // 2. Recent non-holdout assoc_implicit_signals ('re-ask' / 'redo', priority 1.1)
4090
+ if (hasTable(db, 'assoc_implicit_signals')) {
4091
+ const signalRows = db
4092
+ .prepare(`
4093
+ SELECT signal_id, kind, evidence_json, created_at
4094
+ FROM assoc_implicit_signals
4095
+ WHERE owner_scope_key = ?
4096
+ AND kind IN ('re-ask', 'redo')
4097
+ ORDER BY created_at DESC, signal_id ASC
4098
+ LIMIT 100
4099
+ `)
4100
+ .all(scope.ownerScopeKey);
4101
+ for (const sig of signalRows) {
4102
+ let evidence = {};
4103
+ try {
4104
+ const parsed = JSON.parse(sig.evidence_json);
4105
+ if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {
4106
+ evidence = parsed;
4107
+ }
4108
+ }
4109
+ catch {
4110
+ evidence = {};
4111
+ }
4112
+ const rawTaskIds = [
4113
+ ...(Array.isArray(evidence.taskIds) ? evidence.taskIds : []),
4114
+ ...(Array.isArray(evidence.failedTaskIds) ? evidence.failedTaskIds : []),
4115
+ ...(Array.isArray(evidence.followUpTaskIds) ? evidence.followUpTaskIds : []),
4116
+ ].filter((id) => typeof id === 'string' && id.length > 0);
4117
+ if (rawTaskIds.some((taskId) => holdoutTaskIds.has(taskId))) {
4118
+ continue;
4119
+ }
4120
+ const originIds = [];
4121
+ const collectedTokens = [];
4122
+ let sawSensitiveEpisode = false;
4123
+ for (const taskId of rawTaskIds) {
4124
+ const ep = lookupPrivateEpisodeByTaskId(taskId);
4125
+ if (ep === null)
4126
+ continue;
4127
+ if (ep.sensitivity !== 'private') {
4128
+ sawSensitiveEpisode = true;
4129
+ break;
4130
+ }
4131
+ originIds.push(ep.id);
4132
+ for (const tok of extractCleanTokensFromTextAndEntities([ep.title, ep.body], ep.entities, scope)) {
4133
+ if (!collectedTokens.includes(tok)) {
4134
+ collectedTokens.push(tok);
4135
+ }
4136
+ }
4137
+ }
4138
+ if (sawSensitiveEpisode)
4139
+ continue;
4140
+ for (const field of ['entities', 'topics', 'sharedEntities']) {
4141
+ const value = evidence[field];
4142
+ if (!Array.isArray(value))
4143
+ continue;
4144
+ for (const entry of value) {
4145
+ if (typeof entry !== 'string')
4146
+ continue;
4147
+ const clean = sanitizeInterestToken(entry, scope);
4148
+ if (clean !== null && !collectedTokens.includes(clean)) {
4149
+ collectedTokens.push(clean);
4150
+ }
4151
+ }
4152
+ }
4153
+ if (collectedTokens.length > 0) {
4154
+ addCandidate(collectedTokens, INTEREST_SOURCE_PRIORITIES['implicit-signal'], 'implicit-signal', originIds, sig.created_at);
4155
+ }
4156
+ }
4157
+ }
4158
+ // 3. Recent non-holdout low-coverage step metrics / replay episodes (candidate_count <= 1, priority 0.9)
4159
+ if (hasTable(db, 'assoc_step_metrics')) {
4160
+ const metricRows = db
4161
+ .prepare(`
4162
+ SELECT task_id, candidate_count, occurred_at
4163
+ FROM assoc_step_metrics
4164
+ WHERE owner_scope_key = ?
4165
+ AND in_holdout = 0
4166
+ AND candidate_count <= 1
4167
+ AND task_id IS NOT NULL
4168
+ ORDER BY occurred_at DESC, seq DESC
4169
+ LIMIT 100
4170
+ `)
4171
+ .all(scope.ownerScopeKey);
4172
+ const seenLowCovTasks = new Set();
4173
+ for (const metric of metricRows) {
4174
+ if (seenLowCovTasks.has(metric.task_id) || holdoutTaskIds.has(metric.task_id))
4175
+ continue;
4176
+ seenLowCovTasks.add(metric.task_id);
4177
+ const ep = lookupPrivateEpisodeByTaskId(metric.task_id);
4178
+ if (ep !== null && ep.sensitivity !== 'private') {
4179
+ continue;
4180
+ }
4181
+ const collectedTokens = [];
4182
+ const originIds = [];
4183
+ if (ep !== null) {
4184
+ originIds.push(ep.id);
4185
+ for (const tok of extractCleanTokensFromTextAndEntities([ep.title, ep.body], ep.entities, scope)) {
4186
+ if (!collectedTokens.includes(tok)) {
4187
+ collectedTokens.push(tok);
4188
+ }
4189
+ }
4190
+ }
4191
+ if (hasTable(db, 'assoc_replay_episodes')) {
4192
+ const replayRow = db
4193
+ .prepare(`
4194
+ SELECT in_holdout, cues_json
4195
+ FROM assoc_replay_episodes
4196
+ WHERE owner_scope_key = ? AND task_id = ?
4197
+ LIMIT 1
4198
+ `)
4199
+ .get(scope.ownerScopeKey, metric.task_id);
4200
+ if (replayRow !== undefined) {
4201
+ if (replayRow.in_holdout === 1)
4202
+ continue;
4203
+ const cues = parseCueTextsAndEntities(replayRow.cues_json);
4204
+ for (const cue of cues) {
4205
+ for (const tok of extractCleanTokensFromTextAndEntities(cue.text, cue.entities, scope)) {
4206
+ if (!collectedTokens.includes(tok)) {
4207
+ collectedTokens.push(tok);
4208
+ }
4209
+ }
4210
+ }
4211
+ }
4212
+ }
4213
+ if (collectedTokens.length > 0) {
4214
+ addCandidate(collectedTokens, INTEREST_SOURCE_PRIORITIES['low-coverage'], 'low-coverage', originIds, metric.occurred_at);
4215
+ }
4216
+ }
4217
+ }
4218
+ // Merge duplicate queries, keeping highest priority, newest timestamp, and union of originNodeIds
4219
+ const mergedByKey = new Map();
4220
+ for (const cand of rawCandidates) {
4221
+ const existing = mergedByKey.get(cand.interestKey);
4222
+ if (existing === undefined) {
4223
+ mergedByKey.set(cand.interestKey, {
4224
+ interestKey: cand.interestKey,
4225
+ query: cand.query,
4226
+ tokens: cand.tokens,
4227
+ priority: cand.priority,
4228
+ sourceKind: cand.sourceKind,
4229
+ originNodeIds: new Set(cand.originNodeIds),
4230
+ updatedAt: cand.updatedAt,
4231
+ });
4232
+ }
4233
+ else {
4234
+ if (cand.priority > existing.priority) {
4235
+ existing.priority = cand.priority;
4236
+ existing.sourceKind = cand.sourceKind;
4237
+ }
4238
+ if (cand.updatedAt > existing.updatedAt) {
4239
+ existing.updatedAt = cand.updatedAt;
4240
+ }
4241
+ for (const id of cand.originNodeIds) {
4242
+ existing.originNodeIds.add(id);
4243
+ }
4244
+ }
4245
+ }
4246
+ const sortedInterests = [...mergedByKey.values()]
4247
+ .map((entry) => ({
4248
+ interestKey: entry.interestKey,
4249
+ query: entry.query,
4250
+ tokens: entry.tokens,
4251
+ priority: entry.priority,
4252
+ sourceKind: entry.sourceKind,
4253
+ originNodeIds: [...entry.originNodeIds].sort(),
4254
+ updatedAt: entry.updatedAt,
4255
+ }))
4256
+ .sort((a, b) => {
4257
+ if (b.priority !== a.priority)
4258
+ return b.priority - a.priority;
4259
+ if (b.updatedAt !== a.updatedAt)
4260
+ return b.updatedAt - a.updatedAt;
4261
+ return a.interestKey.localeCompare(b.interestKey);
4262
+ });
4263
+ // Load recent fetches for cooldown deduplication
4264
+ const cooledInterestKeys = new Set();
4265
+ const cooledUrls = new Set();
4266
+ if (cooldownMs > 0 && hasTable(db, 'assoc_web_learning_fetches')) {
4267
+ const cutoff = nowMs - cooldownMs;
4268
+ const recentRows = db
4269
+ .prepare(`
4270
+ SELECT canonical_url, interest_key, status
4271
+ FROM assoc_web_learning_fetches
4272
+ WHERE owner_scope_key = ? AND fetched_at >= ?
4273
+ `)
4274
+ .all(scope.ownerScopeKey, cutoff);
4275
+ for (const row of recentRows) {
4276
+ if (row.status === 'ok') {
4277
+ cooledUrls.add(row.canonical_url);
4278
+ cooledInterestKeys.add(row.interest_key);
4279
+ }
4280
+ }
4281
+ }
4282
+ const selectedInterests = [];
4283
+ const targets = [];
4284
+ const seenTargetUrls = new Set();
4285
+ const rejectedSeedUrlSet = new Set();
4286
+ let skippedCooldownCount = 0;
4287
+ for (const interest of sortedInterests) {
4288
+ if (selectedInterests.length >= maxInterests)
4289
+ break;
4290
+ if (cooledInterestKeys.has(interest.interestKey)) {
4291
+ skippedCooldownCount += 1;
4292
+ continue;
4293
+ }
4294
+ const interestTargets = [];
4295
+ let blockedAllByCooldown = seedUrls.length > 0;
4296
+ for (const seed of seedUrls) {
4297
+ const candidateRaw = seed.includes('{query}')
4298
+ ? seed.replaceAll('{query}', encodeURIComponent(interest.query))
4299
+ : seed;
4300
+ try {
4301
+ const validated = validateWhitelistedWebUrl(candidateRaw, {
4302
+ allowedDomains,
4303
+ allowSubdomains,
4304
+ });
4305
+ if (cooledUrls.has(validated.canonicalUrl)) {
4306
+ continue;
4307
+ }
4308
+ blockedAllByCooldown = false;
4309
+ if (seenTargetUrls.has(validated.canonicalUrl)) {
4310
+ continue;
4311
+ }
4312
+ seenTargetUrls.add(validated.canonicalUrl);
4313
+ interestTargets.push({
4314
+ url: validated.canonicalUrl,
4315
+ interestKey: interest.interestKey,
4316
+ originNodeIds: interest.originNodeIds,
4317
+ discoverLinks,
4318
+ });
4319
+ }
4320
+ catch {
4321
+ rejectedSeedUrlSet.add(candidateRaw);
4322
+ }
4323
+ }
4324
+ if (seedUrls.length === 0) {
4325
+ selectedInterests.push(interest);
4326
+ continue;
4327
+ }
4328
+ if (interestTargets.length === 0) {
4329
+ if (blockedAllByCooldown) {
4330
+ skippedCooldownCount += 1;
4331
+ }
4332
+ continue;
4333
+ }
4334
+ selectedInterests.push(interest);
4335
+ targets.push(...interestTargets);
4336
+ }
4337
+ return {
4338
+ interests: selectedInterests,
4339
+ targets,
4340
+ skippedCooldownCount,
4341
+ rejectedSeedUrls: [...rejectedSeedUrlSet],
4342
+ };
4343
+ }
4344
+ //# sourceMappingURL=web-learning-interests.js.map