agent-rag-mcp 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.
@@ -0,0 +1,81 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ class NamespaceRequiredError extends Error {
4
+ code = "namespace_required";
5
+ constructor() {
6
+ super("namespace_required: write commands require a namespace; set --client and --project, RAG_CLIENT/RAG_PROJECT, or configure rag.config.json.");
7
+ this.name = "NamespaceRequiredError";
8
+ }
9
+ }
10
+ class ConfigDiscoveryError extends Error {
11
+ code;
12
+ path;
13
+ constructor(configPath, code, cause) {
14
+ const detail = cause instanceof Error ? cause.message : String(cause);
15
+ super(code === "config_invalid" ? `Invalid JSON in config file ${configPath}: ${detail}` : `Unable to read config file ${configPath}: ${detail}`, { cause });
16
+ this.name = "ConfigDiscoveryError";
17
+ this.code = code;
18
+ this.path = configPath;
19
+ }
20
+ }
21
+ function readConfigFile(configPath) {
22
+ let contents;
23
+ try {
24
+ contents = fs.readFileSync(configPath, "utf8");
25
+ } catch (error) {
26
+ throw new ConfigDiscoveryError(configPath, "config_unreadable", error);
27
+ }
28
+ try {
29
+ return JSON.parse(contents);
30
+ } catch (error) {
31
+ throw new ConfigDiscoveryError(configPath, "config_invalid", error);
32
+ }
33
+ }
34
+ function resolveCommandNamespace(config, command) {
35
+ if (command === "write" && config.namespace === null) {
36
+ if (config.failClosed) throw new NamespaceRequiredError();
37
+ return { namespace: { client: "default", project: "default" } };
38
+ }
39
+ return { namespace: config.namespace };
40
+ }
41
+ function discoverConfig({ cwd, homeDir, argv, env }) {
42
+ const args = {};
43
+ for (let index = 0; index < argv.length; index += 1) {
44
+ const match = /^--(client|project|root)=(.*)$/.exec(argv[index]);
45
+ if (match) {
46
+ args[match[1]] = match[2];
47
+ } else if (/^--(client|project|root)$/.test(argv[index]) && argv[index + 1] !== void 0) {
48
+ args[argv[index].slice(2)] = argv[index + 1];
49
+ index += 1;
50
+ }
51
+ }
52
+ const envValues = {
53
+ client: env.RAG_CLIENT,
54
+ project: env.RAG_PROJECT,
55
+ root: env.RAG_ROOT
56
+ };
57
+ const cwdConfigPath = path.join(cwd, "rag.config.json");
58
+ const parentConfigPath = path.join(path.dirname(cwd), "rag.config.json");
59
+ const homeConfigPath = path.join(homeDir, ".rag", "config.json");
60
+ const configPath = fs.existsSync(cwdConfigPath) ? cwdConfigPath : fs.existsSync(parentConfigPath) ? parentConfigPath : fs.existsSync(homeConfigPath) ? homeConfigPath : null;
61
+ const fileConfig = configPath === null ? {} : readConfigFile(configPath);
62
+ const configClient = typeof fileConfig.client === "string" ? fileConfig.client : void 0;
63
+ const configProject = typeof fileConfig.project === "string" ? fileConfig.project : void 0;
64
+ const client = args.client ?? envValues.client ?? configClient ?? null;
65
+ const project = args.project ?? envValues.project ?? configProject ?? null;
66
+ const namespace = client === null && project === null ? null : { client, project };
67
+ const source = args.client !== void 0 || args.project !== void 0 ? "args" : envValues.client !== void 0 || envValues.project !== void 0 ? "env" : configClient !== void 0 || configProject !== void 0 ? configPath === cwdConfigPath ? "cwd" : configPath === parentConfigPath ? "parent" : "home" : "unscoped";
68
+ return {
69
+ namespace,
70
+ source,
71
+ configPath: source === "cwd" || source === "parent" || source === "home" ? configPath : null,
72
+ failClosed: typeof fileConfig.failClosed === "boolean" ? fileConfig.failClosed : true,
73
+ root: args.root ?? envValues.root ?? (typeof fileConfig.root === "string" ? fileConfig.root : path.join(homeDir, ".rag"))
74
+ };
75
+ }
76
+ export {
77
+ ConfigDiscoveryError,
78
+ NamespaceRequiredError,
79
+ discoverConfig,
80
+ resolveCommandNamespace
81
+ };
@@ -0,0 +1,71 @@
1
+ import * as fs from "node:fs/promises";
2
+ import * as path from "node:path";
3
+ import { getExtractorForPath, UnsupportedMediaTypeError } from "../adapters/registry.mjs";
4
+ import { ingestFile } from "./pipeline.mjs";
5
+ async function collectFiles(rootDirectory, currentDirectory, files) {
6
+ const entries = await fs.readdir(currentDirectory, { withFileTypes: true });
7
+ for (const entry of entries) {
8
+ const absolutePath = path.join(currentDirectory, entry.name);
9
+ if (entry.isDirectory()) await collectFiles(rootDirectory, absolutePath, files);
10
+ else if (entry.isFile()) {
11
+ const relativePath = path.relative(rootDirectory, absolutePath).split(path.sep).join("/");
12
+ files.push({ absolutePath, relativePath });
13
+ }
14
+ }
15
+ }
16
+ function failureResult(relativePath, error) {
17
+ const errorCode = error !== null && typeof error === "object" && "code" in error ? error.code : void 0;
18
+ const isIoError = typeof errorCode === "string" && /^E[A-Z0-9]+$/.test(errorCode);
19
+ const message = error instanceof Error ? error.message : "Unknown ingestion failure";
20
+ return {
21
+ relativePath,
22
+ status: "failed",
23
+ code: isIoError ? "io_error" : "ingest_failed",
24
+ message: isIoError && typeof errorCode === "string" ? message.replace(new RegExp(`^${errorCode}:\\s*`), "") : message
25
+ };
26
+ }
27
+ async function importDirectory(input) {
28
+ const directoryPath = path.resolve(input.directoryPath);
29
+ const sourceFiles = [];
30
+ await collectFiles(directoryPath, directoryPath, sourceFiles);
31
+ sourceFiles.sort((left, right) => left.relativePath < right.relativePath ? -1 : left.relativePath > right.relativePath ? 1 : 0);
32
+ const ingest = input.ingestFile ?? ingestFile;
33
+ const files = [];
34
+ for (const source of sourceFiles) {
35
+ let extractor;
36
+ try {
37
+ extractor = getExtractorForPath(source.absolutePath);
38
+ } catch (error) {
39
+ if (error instanceof UnsupportedMediaTypeError) {
40
+ files.push({ relativePath: source.relativePath, status: "skipped" });
41
+ continue;
42
+ }
43
+ files.push(failureResult(source.relativePath, error));
44
+ continue;
45
+ }
46
+ const ingestInput = {
47
+ root: input.root,
48
+ client: input.client,
49
+ project: input.project,
50
+ sourcePath: source.absolutePath,
51
+ extractor
52
+ };
53
+ try {
54
+ const result = await ingest(ingestInput);
55
+ files.push({ relativePath: source.relativePath, status: result.status });
56
+ } catch (error) {
57
+ files.push(failureResult(source.relativePath, error));
58
+ }
59
+ }
60
+ const summary = {
61
+ inserted: files.filter((file) => file.status === "inserted").length,
62
+ unchanged: files.filter((file) => file.status === "unchanged").length,
63
+ skipped: files.filter((file) => file.status === "skipped").length,
64
+ failed: files.filter((file) => file.status === "failed").length,
65
+ total: files.length
66
+ };
67
+ return { files, summary };
68
+ }
69
+ export {
70
+ importDirectory
71
+ };
@@ -0,0 +1,112 @@
1
+ import * as fs from "node:fs/promises";
2
+ import { performance } from "node:perf_hooks";
3
+ import { getExtractorForPath, UnsupportedMediaTypeError } from "../adapters/registry.mjs";
4
+ import { StructuredTextExtractionError } from "../adapters/structured-text.mjs";
5
+ import { MAX_SOURCE_FILE_BYTES } from "../limits.mjs";
6
+ import { ResourceLimitError } from "../ports/extractor.mjs";
7
+ const V8_ALLOCATION_CODES = /* @__PURE__ */ new Set([
8
+ "ERR_BUFFER_TOO_LARGE",
9
+ "ERR_MEMORY_ALLOCATION_FAILED",
10
+ "ERR_OUT_OF_MEMORY",
11
+ "ERR_STRING_TOO_LONG"
12
+ ]);
13
+ const V8_ALLOCATION_MESSAGES = /invalid string length|array buffer allocation failed|invalid array buffer length|invalid typed array length|invalid array length|allocation failed|out of memory|cannot create a string longer than/i;
14
+ function classifyParseError(error) {
15
+ if (!(error instanceof Error)) return "parse_failed";
16
+ if ("code" in error && typeof error.code === "string" && V8_ALLOCATION_CODES.has(error.code)) {
17
+ return "parse_resource_exhausted";
18
+ }
19
+ return error instanceof RangeError && V8_ALLOCATION_MESSAGES.test(error.message) ? "parse_resource_exhausted" : "parse_failed";
20
+ }
21
+ function send(message, disconnect = false) {
22
+ const sendMessage = process.send;
23
+ if (!sendMessage) {
24
+ process.exitCode = 1;
25
+ return;
26
+ }
27
+ try {
28
+ sendMessage.call(process, message, (error) => {
29
+ if (error) process.exitCode = 1;
30
+ if (disconnect && process.connected) process.disconnect?.();
31
+ });
32
+ } catch {
33
+ process.exitCode = 1;
34
+ if (process.connected) process.disconnect?.();
35
+ }
36
+ }
37
+ async function parse(request) {
38
+ const startedAt = performance.now();
39
+ try {
40
+ const extractorPath = request.mediaHint === void 0 ? request.filePath : `${request.filePath}${request.mediaHint.toLowerCase()}`;
41
+ const extractor = getExtractorForPath(extractorPath);
42
+ const bytes = await fs.readFile(request.filePath);
43
+ if (bytes.byteLength > MAX_SOURCE_FILE_BYTES) {
44
+ throw new ResourceLimitError("source_too_large", "Source document exceeds the maximum supported size.");
45
+ }
46
+ const document = await extractor.extract(bytes);
47
+ send({
48
+ type: "result",
49
+ requestId: request.requestId,
50
+ result: {
51
+ ...document,
52
+ extractorName: extractor.name,
53
+ extractorVersion: extractor.version,
54
+ childParseMs: performance.now() - startedAt
55
+ }
56
+ });
57
+ } catch (error) {
58
+ if (error instanceof UnsupportedMediaTypeError) {
59
+ send({ type: "failure", requestId: request.requestId, code: "unsupported_media_type" }, true);
60
+ return;
61
+ }
62
+ if (error instanceof ResourceLimitError) {
63
+ send({ type: "failure", requestId: request.requestId, code: error.code }, true);
64
+ return;
65
+ }
66
+ if (error instanceof StructuredTextExtractionError) {
67
+ send({ type: "failure", requestId: request.requestId, code: error.code }, true);
68
+ return;
69
+ }
70
+ send({ type: "failure", requestId: request.requestId, code: classifyParseError(error) }, true);
71
+ }
72
+ }
73
+ function isRecord(value) {
74
+ return typeof value === "object" && value !== null;
75
+ }
76
+ function isParseRequest(value) {
77
+ if (!isRecord(value) || value.type !== "parse" || typeof value.requestId !== "string" || typeof value.filePath !== "string") return false;
78
+ if (!isRecord(value.namespace) || typeof value.namespace.client !== "string" || typeof value.namespace.project !== "string") return false;
79
+ return value.mediaHint === void 0 || typeof value.mediaHint === "string";
80
+ }
81
+ function validMediaHint(value) {
82
+ return /^\.[a-z0-9]+$/i.test(value);
83
+ }
84
+ let activeRequest = false;
85
+ process.on("message", (message) => {
86
+ if (isRecord(message) && message.type === "terminate") {
87
+ send({ type: "terminated" }, true);
88
+ return;
89
+ }
90
+ if (isRecord(message) && message.type === "parse" && typeof message.requestId === "string" && "mediaHint" in message && (typeof message.mediaHint !== "string" || !validMediaHint(message.mediaHint))) {
91
+ send({ type: "failure", requestId: message.requestId, code: "invalid_media_hint" }, true);
92
+ return;
93
+ }
94
+ if (!isParseRequest(message)) {
95
+ process.exitCode = 1;
96
+ if (process.connected) process.disconnect?.();
97
+ return;
98
+ }
99
+ if (activeRequest) {
100
+ process.exitCode = 1;
101
+ if (process.connected) process.disconnect?.();
102
+ return;
103
+ }
104
+ activeRequest = true;
105
+ void parse(message).catch((error) => {
106
+ send({ type: "failure", requestId: message.requestId, code: classifyParseError(error) }, true);
107
+ });
108
+ });
109
+ process.send?.({ type: "ready", requestId: "" });
110
+ export {
111
+ classifyParseError
112
+ };
@@ -0,0 +1,270 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { fork } from "node:child_process";
3
+ import * as fs from "node:fs/promises";
4
+ import * as path from "node:path";
5
+ import { performance } from "node:perf_hooks";
6
+ import { fileURLToPath } from "node:url";
7
+ import { UnsupportedMediaTypeError } from "../adapters/registry.mjs";
8
+ import { DEFAULT_PARSE_MAX_OLD_SPACE_SIZE_MB, DEFAULT_PARSE_TIMEOUT_MS, MAX_SOURCE_FILE_BYTES } from "../limits.mjs";
9
+ const PARSE_ERROR_MESSAGES = {
10
+ parse_resource_exhausted: "Document parsing exceeded its memory limit.",
11
+ parse_timeout: "Document parsing exceeded its time limit.",
12
+ parse_failed: "Document parsing failed.",
13
+ parse_aborted: "Document parsing was aborted.",
14
+ parse_crashed: "Document parsing worker exited abnormally.",
15
+ parse_terminated: "Document parsing worker was terminated.",
16
+ parse_invalid_result: "Document parsing returned an invalid result.",
17
+ unsupported_media_type: "Document media type is not supported.",
18
+ invalid_media_hint: "Document media hint is invalid.",
19
+ extraction_invalid_json: "Structured JSON is invalid.",
20
+ extraction_invalid_yaml: "Structured YAML is invalid.",
21
+ source_too_large: "Source document exceeds the maximum supported size.",
22
+ too_many_pages: "Document contains more pages than allowed.",
23
+ archive_too_large: "Document archive exceeds the maximum supported size.",
24
+ image_too_large: "Document image exceeds the maximum supported size.",
25
+ sheet_too_large: "Document sheet exceeds a configured limit (16777216-byte XML scan cap)."
26
+ };
27
+ class ParseHostError extends Error {
28
+ code;
29
+ constructor(code, diagnostic) {
30
+ const message = code === "parse_crashed" && diagnostic ? `Document parsing worker exited abnormally (exit code: ${diagnostic.exitCode ?? "none"}, signal: ${diagnostic.signal ?? "none"}).` : PARSE_ERROR_MESSAGES[code];
31
+ super(message);
32
+ this.name = "ParseHostError";
33
+ this.code = code;
34
+ }
35
+ }
36
+ const RESOURCE_LIMIT_CODES = /* @__PURE__ */ new Set([
37
+ "source_too_large",
38
+ "too_many_pages",
39
+ "archive_too_large",
40
+ "image_too_large",
41
+ "sheet_too_large"
42
+ ]);
43
+ const CHILD_FAILURE_CODES = /* @__PURE__ */ new Set([
44
+ "parse_failed",
45
+ "parse_resource_exhausted",
46
+ "unsupported_media_type",
47
+ "invalid_media_hint",
48
+ "extraction_invalid_json",
49
+ "extraction_invalid_yaml",
50
+ ...RESOURCE_LIMIT_CODES
51
+ ]);
52
+ const CHILD_DRAIN_GRACE_MS = 100;
53
+ const CHILD_FORCE_KILL_MS = 1e3;
54
+ const liveChildren = /* @__PURE__ */ new Set();
55
+ function killLiveChildren() {
56
+ for (const child of liveChildren) {
57
+ if (child.exitCode !== null || child.signalCode !== null) continue;
58
+ try {
59
+ child.kill("SIGKILL");
60
+ } catch {
61
+ }
62
+ }
63
+ }
64
+ process.on("exit", killLiveChildren);
65
+ process.on("SIGINT", () => {
66
+ killLiveChildren();
67
+ process.exit(130);
68
+ });
69
+ function childModulePath() {
70
+ const hostPath = fileURLToPath(import.meta.url);
71
+ return path.join(path.dirname(hostPath), `parse-child${path.extname(hostPath)}`);
72
+ }
73
+ function isObject(value) {
74
+ return typeof value === "object" && value !== null;
75
+ }
76
+ function isSection(value) {
77
+ if (!isObject(value)) return false;
78
+ return Number.isSafeInteger(value.ordinal) && value.ordinal >= 0 && (value.heading === null || typeof value.heading === "string") && (value.level === null || Number.isSafeInteger(value.level)) && typeof value.text === "string";
79
+ }
80
+ function isChildMessage(value) {
81
+ if (!isObject(value) || typeof value.type !== "string") return false;
82
+ if (value.type === "terminated") return true;
83
+ if (typeof value.requestId !== "string") return false;
84
+ if (value.type === "ready") return true;
85
+ if (value.type === "failure") {
86
+ return typeof value.code === "string" && CHILD_FAILURE_CODES.has(value.code);
87
+ }
88
+ if (value.type !== "result" || !isObject(value.result)) return false;
89
+ return Array.isArray(value.result.sections) && value.result.sections.every(isSection) && (value.result.versionLabel === null || typeof value.result.versionLabel === "string") && (value.result.mediaType === null || typeof value.result.mediaType === "string") && typeof value.result.extractorName === "string" && typeof value.result.extractorVersion === "string" && typeof value.result.childParseMs === "number" && Number.isFinite(value.result.childParseMs) && value.result.childParseMs >= 0;
90
+ }
91
+ function childFailure(filePath, mediaHint, message) {
92
+ if (message.code === "unsupported_media_type") return new UnsupportedMediaTypeError(mediaHint ? `${filePath}${mediaHint}` : filePath);
93
+ return new ParseHostError(message.code);
94
+ }
95
+ function isRunning(child) {
96
+ return child.exitCode === null && child.signalCode === null;
97
+ }
98
+ function forceKill(child) {
99
+ if (!isRunning(child)) return;
100
+ try {
101
+ child.kill("SIGKILL");
102
+ } catch {
103
+ }
104
+ }
105
+ function terminate(child) {
106
+ if (!isRunning(child)) return void 0;
107
+ try {
108
+ if (child.connected) {
109
+ child.send({ type: "terminate" }, (error) => {
110
+ if (error) forceKill(child);
111
+ });
112
+ } else {
113
+ forceKill(child);
114
+ }
115
+ } catch {
116
+ forceKill(child);
117
+ }
118
+ const timer = setTimeout(() => forceKill(child), CHILD_FORCE_KILL_MS);
119
+ timer.unref();
120
+ return timer;
121
+ }
122
+ async function parseDocument(filePath, namespace, signal, options = {}) {
123
+ if (signal?.aborted) throw new ParseHostError("parse_aborted");
124
+ const mediaHint = options.mediaHint?.toLowerCase();
125
+ if (mediaHint !== void 0 && !/^\.[a-z0-9]+$/.test(mediaHint)) throw new ParseHostError("invalid_media_hint");
126
+ let sourceSize;
127
+ try {
128
+ sourceSize = (await fs.stat(filePath)).size;
129
+ } catch {
130
+ throw new ParseHostError("parse_failed");
131
+ }
132
+ if (sourceSize > MAX_SOURCE_FILE_BYTES) throw new ParseHostError("source_too_large");
133
+ if (signal?.aborted) throw new ParseHostError("parse_aborted");
134
+ const memoryMb = options.maxOldSpaceSizeMb ?? DEFAULT_PARSE_MAX_OLD_SPACE_SIZE_MB;
135
+ const timeoutMs = options.timeoutMs ?? DEFAULT_PARSE_TIMEOUT_MS;
136
+ if (!Number.isSafeInteger(memoryMb) || memoryMb < 1 || !Number.isFinite(timeoutMs) || timeoutMs <= 0) {
137
+ throw new ParseHostError("parse_failed");
138
+ }
139
+ const childPath = childModulePath();
140
+ const execArgv = [
141
+ ...path.extname(childPath).endsWith("mts") ? ["--experimental-strip-types"] : [],
142
+ "--experimental-sqlite",
143
+ `--max-old-space-size=${memoryMb}`
144
+ ];
145
+ const startedAt = performance.now();
146
+ const child = fork(childPath, [], {
147
+ execArgv,
148
+ stdio: ["ignore", "ignore", "ignore", "ipc"]
149
+ });
150
+ liveChildren.add(child);
151
+ return new Promise((resolve, reject) => {
152
+ let settled = false;
153
+ let pendingError;
154
+ let childResult;
155
+ let forkMs;
156
+ let requestSent = false;
157
+ let timeout;
158
+ let hardKillTimer;
159
+ let drainTimer;
160
+ const requestId = randomUUID();
161
+ const request = { type: "parse", requestId, filePath, namespace, ...mediaHint === void 0 ? {} : { mediaHint } };
162
+ const cleanupRun = () => {
163
+ clearTimeout(timeout);
164
+ signal?.removeEventListener("abort", onAbort);
165
+ };
166
+ const cleanupChild = () => {
167
+ if (hardKillTimer) clearTimeout(hardKillTimer);
168
+ if (drainTimer) clearTimeout(drainTimer);
169
+ liveChildren.delete(child);
170
+ };
171
+ const failAndKill = (error) => {
172
+ if (pendingError || settled) return;
173
+ pendingError = error;
174
+ hardKillTimer = terminate(child);
175
+ };
176
+ const onAbort = () => failAndKill(new ParseHostError("parse_aborted"));
177
+ const onChildError = () => failAndKill(new ParseHostError("parse_failed"));
178
+ const settleResult = (result) => {
179
+ if (pendingError) return;
180
+ if (forkMs === void 0 || settled) {
181
+ failAndKill(new ParseHostError("parse_invalid_result"));
182
+ return;
183
+ }
184
+ settled = true;
185
+ cleanupRun();
186
+ resolve({ ...result, forkMs });
187
+ drainTimer = setTimeout(() => {
188
+ if (!isRunning(child)) return;
189
+ try {
190
+ if (child.connected) child.disconnect();
191
+ } catch {
192
+ forceKill(child);
193
+ }
194
+ hardKillTimer = setTimeout(() => forceKill(child), CHILD_FORCE_KILL_MS);
195
+ hardKillTimer.unref();
196
+ }, CHILD_DRAIN_GRACE_MS);
197
+ };
198
+ const onMessage = (rawMessage) => {
199
+ if (!isChildMessage(rawMessage)) {
200
+ failAndKill(new ParseHostError("parse_invalid_result"));
201
+ return;
202
+ }
203
+ if (rawMessage.type === "terminated") {
204
+ if (!pendingError && !settled) {
205
+ pendingError = new ParseHostError("parse_terminated");
206
+ hardKillTimer = setTimeout(() => forceKill(child), CHILD_FORCE_KILL_MS);
207
+ hardKillTimer.unref();
208
+ }
209
+ return;
210
+ }
211
+ if (rawMessage.type === "ready") {
212
+ if (requestSent || pendingError) return;
213
+ forkMs = performance.now() - startedAt;
214
+ requestSent = true;
215
+ try {
216
+ options.onRequest?.(request);
217
+ } catch {
218
+ failAndKill(new ParseHostError("parse_failed"));
219
+ return;
220
+ }
221
+ child.send(request, (error) => {
222
+ if (error) failAndKill(new ParseHostError("parse_failed"));
223
+ });
224
+ return;
225
+ }
226
+ if (rawMessage.requestId !== requestId) {
227
+ failAndKill(new ParseHostError("parse_invalid_result"));
228
+ return;
229
+ }
230
+ if (rawMessage.type === "failure") {
231
+ childResult = rawMessage;
232
+ return;
233
+ }
234
+ childResult = rawMessage;
235
+ settleResult(rawMessage.result);
236
+ };
237
+ timeout = setTimeout(() => failAndKill(new ParseHostError("parse_timeout")), timeoutMs);
238
+ child.on("error", onChildError);
239
+ child.on("message", onMessage);
240
+ child.once("close", (code, signalCode) => {
241
+ cleanupRun();
242
+ cleanupChild();
243
+ if (settled) return;
244
+ settled = true;
245
+ if (pendingError) {
246
+ reject(pendingError);
247
+ } else if (code !== 0 || signalCode !== null) {
248
+ reject(new ParseHostError("parse_crashed", { exitCode: code, signal: signalCode }));
249
+ } else if (!childResult || childResult.type === "ready" || childResult.type === "terminated") {
250
+ reject(new ParseHostError("parse_failed"));
251
+ } else if (childResult.type === "failure") {
252
+ reject(childFailure(filePath, mediaHint, childResult));
253
+ } else {
254
+ reject(new ParseHostError("parse_invalid_result"));
255
+ }
256
+ });
257
+ signal?.addEventListener("abort", onAbort, { once: true });
258
+ if (signal?.aborted) onAbort();
259
+ try {
260
+ options.onChild?.(child);
261
+ } catch {
262
+ failAndKill(new ParseHostError("parse_failed"));
263
+ }
264
+ });
265
+ }
266
+ export {
267
+ ParseHostError,
268
+ isChildMessage,
269
+ parseDocument
270
+ };