@criogaid/pi-hashline-edit 0.6.0 → 0.7.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.
- package/README.md +161 -304
- package/THIRD_PARTY_NOTICES.md +80 -0
- package/package.json +10 -6
- package/src/core/AGENTS.md +20 -0
- package/src/core/apply.test.ts +189 -60
- package/src/core/apply.ts +110 -74
- package/src/core/case-fold.test.ts +40 -0
- package/src/core/case-fold.ts +81 -0
- package/src/core/character-set.test.ts +103 -0
- package/src/core/character-set.ts +170 -0
- package/src/core/errors.test.ts +23 -0
- package/src/core/errors.ts +70 -4
- package/src/core/lines.ts +7 -0
- package/src/core/regex.ts +21 -0
- package/src/core/replace-schema.ts +34 -0
- package/src/core/replace.ts +37 -54
- package/src/core/search-analysis.test.ts +199 -0
- package/src/core/search-analysis.ts +375 -0
- package/src/core/search-matrix.test.ts +64 -0
- package/src/core/search-matrix.testing.ts +183 -0
- package/src/core/search-schema.ts +18 -0
- package/src/core/search.test.ts +145 -0
- package/src/core/search.ts +119 -0
- package/src/core/text.test.ts +16 -8
- package/src/core/text.ts +26 -6
- package/src/core/types.ts +16 -11
- package/src/index.ts +25 -15
- package/src/integration/config-registration.test.ts +30 -24
- package/src/integration/forget-grep.test.ts +52 -2
- package/src/integration/fusion-dispatch.test.ts +21 -105
- package/src/integration/grep-errors.test.ts +50 -0
- package/src/integration/grep-flags.test.ts +280 -0
- package/src/integration/grep-js-completeness.test.ts +208 -0
- package/src/integration/grep-line-candidates.test.ts +233 -0
- package/src/integration/grep-matrix.test.ts +121 -0
- package/src/integration/grep-path-matrix.test.ts +132 -0
- package/src/integration/grep-prefilter-coverage.test.ts +189 -0
- package/src/integration/grep-regex.test.ts +410 -0
- package/src/integration/grep-rg.test.ts +220 -402
- package/src/integration/grep-scan-budget.test.ts +89 -0
- package/src/integration/grep-translation.test.ts +206 -0
- package/src/integration/large-text.test.ts +57 -1
- package/src/integration/model-budget-lifecycle.test.ts +128 -0
- package/src/integration/mutation-file-types.test.ts +12 -25
- package/src/integration/mutation-file-types.testing.ts +33 -0
- package/src/integration/npm-package.test.ts +17 -0
- package/src/integration/npm-package.testing.ts +123 -0
- package/src/integration/publication-read-changes.test.ts +344 -0
- package/src/integration/read-changes.test.ts +98 -0
- package/src/integration/replace-package.test.ts +17 -36
- package/src/integration/replace-package.testing.ts +33 -0
- package/src/integration/replace-worker-boundary.test.ts +107 -0
- package/src/integration/report-replay.test.ts +90 -0
- package/src/integration/utf8-errors.test.ts +46 -0
- package/src/pi/AGENTS.md +55 -0
- package/src/pi/action-fusion.test.ts +253 -103
- package/src/pi/action-fusion.ts +116 -290
- package/src/pi/anchor-format.ts +9 -0
- package/src/pi/argument-diagnostics.ts +478 -0
- package/src/pi/argument-error.testing.ts +43 -0
- package/src/pi/argument-error.ts +78 -0
- package/src/pi/argument-format.test.ts +208 -0
- package/src/pi/argument-validation.test.ts +742 -45
- package/src/pi/argument-validation.ts +56 -59
- package/src/pi/budgets.ts +45 -16
- package/src/pi/codemode.test.ts +96 -0
- package/src/pi/config.test.ts +14 -10
- package/src/pi/config.ts +21 -7
- package/src/pi/diagnostic-buffer.test.ts +52 -16
- package/src/pi/diagnostic-buffer.ts +11 -14
- package/src/pi/directory-sync.test.ts +4 -1
- package/src/pi/edit-tool.ts +100 -93
- package/src/pi/error-text.ts +39 -16
- package/src/pi/execute.test.ts +362 -315
- package/src/pi/extension-loading.test.ts +14 -0
- package/src/pi/extension-loading.testing.ts +3 -0
- package/src/pi/failure-context.test.ts +220 -88
- package/src/pi/failure-context.ts +161 -180
- package/src/pi/failure-path.test.ts +85 -88
- package/src/pi/file-commit.test.ts +78 -45
- package/src/pi/file-commit.ts +218 -151
- package/src/pi/file-read.test.ts +29 -0
- package/src/pi/file-read.ts +60 -0
- package/src/pi/file-snapshot.test.ts +1 -1
- package/src/pi/forget-tool.ts +189 -90
- package/src/pi/forget.test.ts +309 -22
- package/src/pi/forget.testing.ts +41 -113
- package/src/pi/fusion-card.test.ts +40 -14
- package/src/pi/fusion-card.ts +84 -50
- package/src/pi/grep-candidates.test.ts +127 -0
- package/src/pi/grep-candidates.ts +193 -0
- package/src/pi/grep-matrix.test.ts +83 -0
- package/src/pi/grep-output.ts +181 -138
- package/src/pi/grep-render.ts +28 -25
- package/src/pi/grep-scope.ts +61 -53
- package/src/pi/grep-search.ts +299 -242
- package/src/pi/grep-tool.ts +150 -140
- package/src/pi/grep-worker.mjs +4 -0
- package/src/pi/grep-worker.ts +14 -0
- package/src/pi/grep.test.ts +631 -632
- package/src/pi/model-budgets.test.ts +43 -0
- package/src/pi/model-budgets.ts +44 -0
- package/src/pi/mutation-outcome.testing.ts +5 -5
- package/src/pi/mutation-result.test.ts +21 -74
- package/src/pi/mutation-result.ts +74 -87
- package/src/pi/mutation-runner.ts +83 -75
- package/src/pi/output-budgets.test.ts +166 -0
- package/src/pi/path.ts +7 -0
- package/src/pi/read-tool.ts +151 -137
- package/src/pi/read.test.ts +39 -33
- package/src/pi/regex-worker-contract.ts +73 -0
- package/src/pi/regex-worker.ts +101 -0
- package/src/pi/registration.test.ts +111 -92
- package/src/pi/render.test.ts +193 -19
- package/src/pi/render.ts +137 -29
- package/src/pi/replace-regex.ts +11 -44
- package/src/pi/replace-tool.ts +38 -145
- package/src/pi/replace-worker-contract.ts +19 -0
- package/src/pi/replace-worker.ts +12 -8
- package/src/pi/replace.test.ts +93 -160
- package/src/pi/report-cause.ts +99 -0
- package/src/pi/report-failure.testing.ts +20 -0
- package/src/pi/report-schema.ts +512 -0
- package/src/pi/report.test.ts +276 -0
- package/src/pi/report.ts +288 -0
- package/src/pi/result-safety.test.ts +122 -427
- package/src/pi/rg-process.test.ts +78 -79
- package/src/pi/rg-process.ts +124 -177
- package/src/pi/rg-regex.test.ts +50 -0
- package/src/pi/rg-regex.ts +709 -0
- package/src/pi/text-stream.test.ts +67 -38
- package/src/pi/text-stream.ts +96 -75
- package/src/pi/tool-call.testing.ts +3 -39
- package/src/pi/write-tool.ts +45 -34
- package/src/pi/write.test.ts +45 -37
- package/src/testing/extension-loader.testing.ts +24 -0
- package/src/testing/installation.testing.ts +77 -0
- package/src/testing/process.testing.ts +33 -0
- package/src/testing/regex-host.testing.ts +20 -0
- package/src/testing/regex-translation-corpus.ts +308 -0
- package/src/testing/rg-line-listing.fixture.mjs +7 -0
- package/src/testing/run-tests.ts +47 -0
- package/src/testing/session.testing.ts +127 -0
- package/src/pi/rg-line-ranges.test.ts +0 -66
- package/src/pi/rg-line-ranges.ts +0 -75
- package/src/pi/rg-match-bytes.ts +0 -95
- package/src/pi/rg-text-view.ts +0 -192
- package/src/pi/tool-prompts.ts +0 -15
package/src/pi/read.test.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { rejectsArgument, rejectsArguments } from "./argument-error.testing.ts";
|
|
1
2
|
import { test } from "node:test";
|
|
2
3
|
import assert from "node:assert/strict";
|
|
3
4
|
import { mkdtemp, rm, readFile, writeFile } from "node:fs/promises";
|
|
@@ -10,10 +11,11 @@ import { makeReadOverride } from "./read-tool.ts";
|
|
|
10
11
|
import { computeLineHash } from "../core/hash.ts";
|
|
11
12
|
import { callTool } from "./tool-call.testing.ts";
|
|
12
13
|
import { DEFAULT_CONFIG } from "./config.ts";
|
|
13
|
-
import { FORGET_MIN_BYTES, formatKiB } from "./budgets.ts";
|
|
14
|
+
import { DEFAULT_OUTPUT_BUDGETS, FORGET_MIN_BYTES, formatKiB } from "./budgets.ts";
|
|
14
15
|
import { taggedResultId } from "./forget.testing.ts";
|
|
16
|
+
import { reportOf } from "./report.ts";
|
|
15
17
|
|
|
16
|
-
const DEFAULT_READ_MAX_BYTES =
|
|
18
|
+
const DEFAULT_READ_MAX_BYTES = DEFAULT_OUTPUT_BUDGETS.readBytes;
|
|
17
19
|
|
|
18
20
|
async function withDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
|
|
19
21
|
const dir = await mkdtemp(join(tmpdir(), "hl-"));
|
|
@@ -92,10 +94,8 @@ test("read byte truncation counts UTF-8 and separators without cutting anchors",
|
|
|
92
94
|
assert.equal(result.details.truncation.outputLines, 1);
|
|
93
95
|
assert.equal(result.details.truncation.truncatedBy, "bytes");
|
|
94
96
|
assert.equal(result.details.truncation.maxBytes, maxBytes);
|
|
95
|
-
assert.
|
|
96
|
-
assert.ok(
|
|
97
|
-
result.content[0].text.includes(`1#${computeLineHash(1, first, hashLen)}│${first}\n`),
|
|
98
|
-
);
|
|
97
|
+
assert.equal(reportOf(result)?.truncatedAt, formatKiB(maxBytes));
|
|
98
|
+
assert.ok(result.content[0].text.includes(`1#${computeLineHash(1, first, hashLen)}│${first}`));
|
|
99
99
|
assert.doesNotMatch(result.content[0].text, /\n2#/);
|
|
100
100
|
const next = await call(makeReadOverride(dir, DEFAULT_CONFIG), {
|
|
101
101
|
path: "large.txt",
|
|
@@ -113,8 +113,8 @@ test("read reports an oversized first row without suggesting an ineffective retr
|
|
|
113
113
|
assert.equal(result.details.truncation.outputLines, 0);
|
|
114
114
|
assert.doesNotMatch(result.content[0].text, /^\d+#/m);
|
|
115
115
|
assert.doesNotMatch(result.content[0].text, /use offset\/limit/);
|
|
116
|
-
assert.
|
|
117
|
-
assert.match(result
|
|
116
|
+
assert.equal(reportOf(result)?.lineTooLong?.line, 1);
|
|
117
|
+
assert.match(reportOf(result)?.next ?? "", /chunks.*bash.*replace/);
|
|
118
118
|
}));
|
|
119
119
|
|
|
120
120
|
test("read preserves empty files and explicit limits above the native default", async () =>
|
|
@@ -122,14 +122,14 @@ test("read preserves empty files and explicit limits above the native default",
|
|
|
122
122
|
await writeFile(join(dir, "empty.txt"), "");
|
|
123
123
|
const empty = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "empty.txt" });
|
|
124
124
|
assert.match(empty.content[0].text, /0 lines/);
|
|
125
|
-
assert.equal(empty
|
|
125
|
+
assert.equal(reportOf(empty)?.pagination, undefined);
|
|
126
126
|
await writeFile(join(dir, "many.txt"), "x\n".repeat(2001));
|
|
127
127
|
const many = await call(makeReadOverride(dir, DEFAULT_CONFIG), {
|
|
128
128
|
path: "many.txt",
|
|
129
129
|
limit: 2001,
|
|
130
130
|
});
|
|
131
131
|
assert.match(many.content[0].text, /\n2001#[0-9A-Z]+│x/);
|
|
132
|
-
assert.equal(many
|
|
132
|
+
assert.equal(reportOf(many)?.pagination, undefined);
|
|
133
133
|
}));
|
|
134
134
|
|
|
135
135
|
test("read uses the configured default limit and respects explicit limits", async () =>
|
|
@@ -149,10 +149,13 @@ test("read uses the configured default limit and respects explicit limits", asyn
|
|
|
149
149
|
assert.match(result.content[0].text, new RegExp(`large\\.txt · ${totalLines} lines`));
|
|
150
150
|
assert.match(result.content[0].text, new RegExp(`\\n${end}#[0-9A-Z]+│line${end}`));
|
|
151
151
|
assert.doesNotMatch(result.content[0].text, new RegExp(`\\n${end + 1}#[0-9A-Z]+│`));
|
|
152
|
-
assert.deepEqual(result
|
|
153
|
-
|
|
152
|
+
assert.deepEqual(reportOf(result)?.pagination, {
|
|
153
|
+
start: 1,
|
|
154
|
+
end,
|
|
155
|
+
totalLines,
|
|
156
|
+
nextOffset: end + 1,
|
|
154
157
|
});
|
|
155
|
-
assert.match(result
|
|
158
|
+
assert.match(reportOf(result)?.next ?? "", /offset.*pagination\.nextOffset/);
|
|
156
159
|
}
|
|
157
160
|
}));
|
|
158
161
|
|
|
@@ -167,22 +170,20 @@ test("read pagination supports offset windows and stops suggesting continuation
|
|
|
167
170
|
);
|
|
168
171
|
const read = makeReadOverride(dir, DEFAULT_CONFIG);
|
|
169
172
|
const page = await call(read, { path: "pages.txt", offset: start });
|
|
170
|
-
assert.match(page
|
|
171
|
-
assert.deepEqual(page
|
|
172
|
-
pagination: { start, end, totalLines, nextOffset: end + 1 },
|
|
173
|
-
});
|
|
173
|
+
assert.match(reportOf(page)?.next ?? "", /offset.*pagination\.nextOffset/);
|
|
174
|
+
assert.deepEqual(reportOf(page)?.pagination, { start, end, totalLines, nextOffset: end + 1 });
|
|
174
175
|
const next = await call(read, {
|
|
175
176
|
path: "pages.txt",
|
|
176
177
|
offset: page.details.pagination.nextOffset,
|
|
177
178
|
});
|
|
178
179
|
assert.match(next.content[0].text, new RegExp(`\\n${end + 1}#[0-9A-Z]+│line${end + 1}`));
|
|
179
180
|
assert.match(next.content[0].text, new RegExp(`\\n${totalLines}#[0-9A-Z]+│line${totalLines}`));
|
|
180
|
-
assert.equal(next
|
|
181
|
-
assert.
|
|
181
|
+
assert.equal(reportOf(next)?.pagination, undefined);
|
|
182
|
+
assert.equal(reportOf(next)?.next, undefined);
|
|
182
183
|
for (const offset of [totalLines - DEFAULT_CONFIG.read.defaultLimit + 1, totalLines + 1]) {
|
|
183
184
|
const result = await call(read, { path: "pages.txt", offset });
|
|
184
|
-
assert.equal(result
|
|
185
|
-
assert.
|
|
185
|
+
assert.equal(reportOf(result)?.pagination, undefined);
|
|
186
|
+
assert.equal(reportOf(result)?.next, undefined);
|
|
186
187
|
}
|
|
187
188
|
}));
|
|
188
189
|
|
|
@@ -207,10 +208,7 @@ test("read rejects noninteger and nonpositive offsets and limits before reading"
|
|
|
207
208
|
Number.MAX_SAFE_INTEGER + 1,
|
|
208
209
|
]) {
|
|
209
210
|
const params = { path: "pages.txt", [key]: invalid };
|
|
210
|
-
await assert.rejects(
|
|
211
|
-
call(read, params),
|
|
212
|
-
new RegExp(`Validation failed for tool "read":\\n {2}- ${key}: `),
|
|
213
|
-
);
|
|
211
|
+
await assert.rejects(call(read, params), rejectsArgument(key));
|
|
214
212
|
}
|
|
215
213
|
}
|
|
216
214
|
assert.deepEqual(
|
|
@@ -224,13 +222,16 @@ test("read rejects noninteger and nonpositive offsets and limits before reading"
|
|
|
224
222
|
);
|
|
225
223
|
await assert.rejects(
|
|
226
224
|
call(read, { path: "missing.txt", offset: 1.5 }),
|
|
227
|
-
|
|
225
|
+
rejectsArguments("read"),
|
|
228
226
|
);
|
|
229
227
|
const page = await call(read, { path: "pages.txt", offset: 2, limit: 1 });
|
|
230
228
|
assert.match(page.content[0].text, /\n2#[0-9A-Z]+│second/);
|
|
231
|
-
assert.match(page
|
|
232
|
-
assert.deepEqual(page
|
|
233
|
-
|
|
229
|
+
assert.match(reportOf(page)?.next ?? "", /offset.*pagination\.nextOffset/);
|
|
230
|
+
assert.deepEqual(reportOf(page)?.pagination, {
|
|
231
|
+
start: 2,
|
|
232
|
+
end: 2,
|
|
233
|
+
totalLines: 3,
|
|
234
|
+
nextOffset: 3,
|
|
234
235
|
});
|
|
235
236
|
await writeFile(join(dir, "long.txt"), "x".repeat(DEFAULT_READ_MAX_BYTES + 1));
|
|
236
237
|
const long = await call(read, { path: "long.txt", offset: 1, limit: 1 });
|
|
@@ -247,11 +248,11 @@ test("read schema rejects empty paths and unknown fields before file access", as
|
|
|
247
248
|
{ path: "missing.txt", offest: 3 },
|
|
248
249
|
];
|
|
249
250
|
for (const args of invalidArgs) {
|
|
250
|
-
await assert.rejects(call(read, args),
|
|
251
|
+
await assert.rejects(call(read, args), rejectsArguments("read"));
|
|
251
252
|
}
|
|
252
253
|
}));
|
|
253
254
|
|
|
254
|
-
test("read byte truncation
|
|
255
|
+
test("read byte truncation retains its budget and a continuation after complete returned rows", async () =>
|
|
255
256
|
withDir(async (dir) => {
|
|
256
257
|
await writeFile(join(dir, "large.txt"), `first\n${"x".repeat(DEFAULT_READ_MAX_BYTES)}\ntail\n`);
|
|
257
258
|
const result = await call(makeReadOverride(dir, DEFAULT_CONFIG), {
|
|
@@ -259,7 +260,12 @@ test("read byte truncation takes precedence over line pagination", async () =>
|
|
|
259
260
|
limit: 2,
|
|
260
261
|
});
|
|
261
262
|
assert.equal(result.details.truncation.truncatedBy, "bytes");
|
|
262
|
-
assert.
|
|
263
|
+
assert.deepEqual(reportOf(result)?.pagination, {
|
|
264
|
+
start: 1,
|
|
265
|
+
end: 1,
|
|
266
|
+
totalLines: 3,
|
|
267
|
+
nextOffset: 2,
|
|
268
|
+
});
|
|
263
269
|
assert.equal(result.details.truncation.maxBytes, DEFAULT_READ_MAX_BYTES);
|
|
264
270
|
assert.doesNotMatch(result.content[0].text, /showing lines|to continue/);
|
|
265
271
|
}));
|
|
@@ -330,7 +336,7 @@ test("read accepts safe offsets and limits whose sum exceeds the safe integer ra
|
|
|
330
336
|
offset,
|
|
331
337
|
limit: Number.MAX_SAFE_INTEGER,
|
|
332
338
|
});
|
|
333
|
-
assert.equal(result
|
|
339
|
+
assert.equal(reportOf(result)?.pagination, undefined);
|
|
334
340
|
assert.doesNotMatch(result.content[0].text, /to continue|│first/);
|
|
335
341
|
if (offset <= 3) assert.match(result.content[0].text, /│third/);
|
|
336
342
|
else assert.doesNotMatch(result.content[0].text, /│/);
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/** Closed reply envelopes shared by isolated regex evaluators; decoded in the host. */
|
|
2
|
+
import { Type, type Static, type TSchema } from "typebox";
|
|
3
|
+
import { Value } from "typebox/value";
|
|
4
|
+
import {
|
|
5
|
+
HashlineError,
|
|
6
|
+
type HashlineErrorArguments,
|
|
7
|
+
type HashlineErrorOptions,
|
|
8
|
+
} from "../core/errors.ts";
|
|
9
|
+
import {
|
|
10
|
+
ERROR_CODES,
|
|
11
|
+
ERROR_DEFINITIONS,
|
|
12
|
+
CAUSE_SCHEMA,
|
|
13
|
+
type ErrorCode,
|
|
14
|
+
type Cause,
|
|
15
|
+
} from "./report-schema.ts";
|
|
16
|
+
import { restoreCause } from "./report-cause.ts";
|
|
17
|
+
|
|
18
|
+
const ERROR_SCHEMAS = ERROR_CODES.map((code) => {
|
|
19
|
+
const facts = ERROR_DEFINITIONS[code].facts;
|
|
20
|
+
return Type.Object(
|
|
21
|
+
{
|
|
22
|
+
code: Type.Literal(code),
|
|
23
|
+
message: Type.String(),
|
|
24
|
+
facts: (facts.required?.length ?? 0) > 0 ? facts : Type.Optional(facts),
|
|
25
|
+
cause: Type.Optional(CAUSE_SCHEMA),
|
|
26
|
+
},
|
|
27
|
+
{ additionalProperties: false },
|
|
28
|
+
);
|
|
29
|
+
});
|
|
30
|
+
/** A worker error that passed its code's schema: the facts are those that code requires. */
|
|
31
|
+
export type CheckedWorkerError = {
|
|
32
|
+
[C in ErrorCode]: {
|
|
33
|
+
readonly code: C;
|
|
34
|
+
readonly message: string;
|
|
35
|
+
readonly cause?: Cause;
|
|
36
|
+
} & Pick<HashlineErrorOptions<C>, "facts">;
|
|
37
|
+
}[ErrorCode];
|
|
38
|
+
export type RegexWorkerReply<Result> =
|
|
39
|
+
| { readonly result: Result }
|
|
40
|
+
| { readonly error: CheckedWorkerError };
|
|
41
|
+
|
|
42
|
+
export function invalidWorkerResult(): HashlineError<"REGEX_WORKER_FAILED"> {
|
|
43
|
+
return new HashlineError("REGEX_WORKER_FAILED", "Regex worker returned an invalid result.");
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function workerReplyDecoder<T extends TSchema>(result: T) {
|
|
47
|
+
const schema = Type.Union([
|
|
48
|
+
Type.Object({ result }, { additionalProperties: false }),
|
|
49
|
+
Type.Object({ error: Type.Union(ERROR_SCHEMAS) }, { additionalProperties: false }),
|
|
50
|
+
]);
|
|
51
|
+
return (value: unknown): RegexWorkerReply<Static<T>> | undefined => {
|
|
52
|
+
if (typeof value !== "object" || value === null) return undefined;
|
|
53
|
+
try {
|
|
54
|
+
const error: unknown = Reflect.get(value, "error");
|
|
55
|
+
// Structured cloning permits cycles and BigInt; reports must remain JSON-serializable.
|
|
56
|
+
if (typeof error === "object" && error !== null) JSON.stringify(error);
|
|
57
|
+
// The dynamic error union is validated against the same code-specific schemas.
|
|
58
|
+
return Value.Check(schema, value) ? (value as RegexWorkerReply<Static<T>>) : undefined;
|
|
59
|
+
} catch (error) {
|
|
60
|
+
if (error instanceof TypeError || error instanceof RangeError) return undefined;
|
|
61
|
+
throw error;
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Restore an error workerReplyDecoder checked as the same HashlineError the worker threw. */
|
|
67
|
+
export function restoreWorkerError(error: CheckedWorkerError): HashlineError {
|
|
68
|
+
// The parameter ties facts to code; TypeScript cannot carry that link into the generic constructor.
|
|
69
|
+
const options = [
|
|
70
|
+
{ facts: error.facts, cause: restoreCause(error.cause) },
|
|
71
|
+
] as HashlineErrorArguments<ErrorCode>;
|
|
72
|
+
return new HashlineError(error.code, error.message, ...options);
|
|
73
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/** Serialize regex requests in one worker; timeout, cancellation, and cleanup have one owner. */
|
|
2
|
+
import { Worker, type ResourceLimits } from "node:worker_threads";
|
|
3
|
+
import { HashlineError } from "../core/errors.ts";
|
|
4
|
+
import { cancellationError, throwIfCancelled } from "./error-text.ts";
|
|
5
|
+
import {
|
|
6
|
+
restoreWorkerError,
|
|
7
|
+
invalidWorkerResult,
|
|
8
|
+
type RegexWorkerReply,
|
|
9
|
+
} from "./regex-worker-contract.ts";
|
|
10
|
+
|
|
11
|
+
export async function withRegexWorker<Input, Result, Output>(
|
|
12
|
+
entry: URL,
|
|
13
|
+
decode: (value: unknown) => RegexWorkerReply<Result> | undefined,
|
|
14
|
+
timeoutMs: number,
|
|
15
|
+
signal: AbortSignal | undefined,
|
|
16
|
+
execute: (run: (input: Input) => Promise<Result>) => Promise<Output>,
|
|
17
|
+
resourceLimits?: ResourceLimits,
|
|
18
|
+
): Promise<Output> {
|
|
19
|
+
throwIfCancelled(signal);
|
|
20
|
+
const worker = new Worker(entry, { resourceLimits });
|
|
21
|
+
let failure: Error | undefined;
|
|
22
|
+
let pending: { resolve: (result: Result) => void; reject: (error: Error) => void } | undefined;
|
|
23
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
24
|
+
const clear = () => {
|
|
25
|
+
clearTimeout(timer);
|
|
26
|
+
const previous = pending;
|
|
27
|
+
pending = undefined;
|
|
28
|
+
return previous;
|
|
29
|
+
};
|
|
30
|
+
const fail = (error: Error) => {
|
|
31
|
+
failure ??= error;
|
|
32
|
+
clear()?.reject(error);
|
|
33
|
+
};
|
|
34
|
+
const abort = () => fail(cancellationError());
|
|
35
|
+
worker.on("message", (value: unknown) => {
|
|
36
|
+
try {
|
|
37
|
+
const reply = decode(value);
|
|
38
|
+
if (!reply) fail(invalidWorkerResult());
|
|
39
|
+
else if ("error" in reply) fail(restoreWorkerError(reply.error));
|
|
40
|
+
else clear()?.resolve(reply.result);
|
|
41
|
+
} catch (error) {
|
|
42
|
+
fail(
|
|
43
|
+
new HashlineError("REGEX_WORKER_FAILED", "Could not decode the regex worker result.", {
|
|
44
|
+
cause: error,
|
|
45
|
+
}),
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
worker.on("error", (error) =>
|
|
50
|
+
fail(new HashlineError("REGEX_WORKER_FAILED", "Regex worker failed.", { cause: error })),
|
|
51
|
+
);
|
|
52
|
+
worker.on("exit", (exitCode) =>
|
|
53
|
+
fail(
|
|
54
|
+
new HashlineError("REGEX_WORKER_FAILED", "Regex worker exited before replying.", {
|
|
55
|
+
facts: { exitCode },
|
|
56
|
+
}),
|
|
57
|
+
),
|
|
58
|
+
);
|
|
59
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
60
|
+
let queue = Promise.resolve();
|
|
61
|
+
const run = (input: Input): Promise<Result> => {
|
|
62
|
+
const result = queue.then(() => {
|
|
63
|
+
throwIfCancelled(signal);
|
|
64
|
+
if (failure) throw failure;
|
|
65
|
+
return new Promise<Result>((resolve, reject) => {
|
|
66
|
+
pending = { resolve, reject };
|
|
67
|
+
timer = setTimeout(
|
|
68
|
+
() =>
|
|
69
|
+
fail(
|
|
70
|
+
new HashlineError("REGEX_TIMEOUT", "Regex evaluation timed out.", {
|
|
71
|
+
facts: { timeoutMs },
|
|
72
|
+
}),
|
|
73
|
+
),
|
|
74
|
+
timeoutMs,
|
|
75
|
+
);
|
|
76
|
+
try {
|
|
77
|
+
worker.postMessage(input);
|
|
78
|
+
} catch (error) {
|
|
79
|
+
fail(
|
|
80
|
+
new HashlineError("REGEX_WORKER_FAILED", "Could not send the regex request.", {
|
|
81
|
+
cause: error,
|
|
82
|
+
}),
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
});
|
|
87
|
+
queue = result.then(
|
|
88
|
+
() => undefined,
|
|
89
|
+
() => undefined,
|
|
90
|
+
);
|
|
91
|
+
return result;
|
|
92
|
+
};
|
|
93
|
+
try {
|
|
94
|
+
if (signal?.aborted) abort();
|
|
95
|
+
return await execute(run);
|
|
96
|
+
} finally {
|
|
97
|
+
clear();
|
|
98
|
+
signal?.removeEventListener("abort", abort);
|
|
99
|
+
await worker.terminate();
|
|
100
|
+
}
|
|
101
|
+
}
|