symnav 0.0.0 → 1.0.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,1051 @@
1
+ var __getOwnPropNames = Object.getOwnPropertyNames;
2
+ var __esm = (fn, res) => function __init() {
3
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
4
+ };
5
+
6
+ // ../../packages/daemon/dist/state-write-errors.js
7
+ var DaemonStateWriteError, DaemonStateWriteErrors;
8
+ var init_state_write_errors = __esm({
9
+ "../../packages/daemon/dist/state-write-errors.js"() {
10
+ "use strict";
11
+ DaemonStateWriteError = class extends Error {
12
+ failure;
13
+ code;
14
+ path;
15
+ syscall;
16
+ constructor(failure, cause) {
17
+ super(cause instanceof Error ? cause.message : "Required state write failed", { cause });
18
+ this.failure = failure;
19
+ this.code = failure.osCode;
20
+ this.path = failure.path;
21
+ this.syscall = cause?.syscall;
22
+ }
23
+ };
24
+ DaemonStateWriteErrors = class {
25
+ static from(error, fallbackPath) {
26
+ const seen = /* @__PURE__ */ new Set();
27
+ let current = error;
28
+ while (typeof current === "object" && current !== null && !seen.has(current)) {
29
+ seen.add(current);
30
+ if (current instanceof DaemonStateWriteError)
31
+ return current.failure;
32
+ const failure = current;
33
+ if (failure.syscall !== void 0 && /^(mkdir|write|rename|unlink|rmdir|chmod|fsync)/u.test(failure.syscall)) {
34
+ const path = failure.path ?? fallbackPath;
35
+ if (path !== void 0)
36
+ return { path, ...failure.code === void 0 ? {} : { osCode: failure.code } };
37
+ }
38
+ current = "cause" in current ? current.cause : void 0;
39
+ }
40
+ return void 0;
41
+ }
42
+ static failedWrite(path, error) {
43
+ const failure = error;
44
+ const osCode = failure?.code;
45
+ return new DaemonStateWriteError({ path: failure?.path ?? path, ...typeof osCode === "string" ? { osCode } : {} }, error);
46
+ }
47
+ static isFailure(value) {
48
+ if (typeof value !== "object" || value === null || Array.isArray(value))
49
+ return false;
50
+ const failure = value;
51
+ const keys = Object.keys(failure);
52
+ return typeof failure.path === "string" && failure.path.length > 0 && keys.every((key) => key === "path" || key === "osCode") && (failure.osCode === void 0 || typeof failure.osCode === "string");
53
+ }
54
+ };
55
+ }
56
+ });
57
+
58
+ // ../../packages/daemon/dist/diagnostics/failure-recorder.js
59
+ import { randomUUID } from "node:crypto";
60
+ var DaemonFailureRecorder;
61
+ var init_failure_recorder = __esm({
62
+ "../../packages/daemon/dist/diagnostics/failure-recorder.js"() {
63
+ "use strict";
64
+ init_state_write_errors();
65
+ DaemonFailureRecorder = class _DaemonFailureRecorder {
66
+ journal;
67
+ workspaceRoot;
68
+ clock;
69
+ stateWriteFailed;
70
+ constructor(journal, workspaceRoot, clock, stateWriteFailed) {
71
+ this.journal = journal;
72
+ this.workspaceRoot = workspaceRoot;
73
+ this.clock = clock;
74
+ this.stateWriteFailed = stateWriteFailed;
75
+ }
76
+ async record(kind, phase, reason, error, instanceId, requestId) {
77
+ try {
78
+ await this.journal.record({
79
+ schemaVersion: 1,
80
+ eventId: `${kind}:${kind === "fallback" ? requestId ?? randomUUID() : instanceId ?? randomUUID()}`,
81
+ workspaceRoot: this.workspaceRoot,
82
+ ...instanceId === void 0 ? {} : { instanceId },
83
+ ...requestId === void 0 ? {} : { requestId },
84
+ kind,
85
+ failure: _DaemonFailureRecorder.failure(this.clock.wallNowMs(), phase, reason, error)
86
+ });
87
+ } catch (writeError) {
88
+ const failure = DaemonStateWriteErrors.from(writeError);
89
+ if (failure !== void 0)
90
+ this.stateWriteFailed?.(failure);
91
+ }
92
+ }
93
+ static failure(timestamp, phase, reason, error) {
94
+ const osCode = this.osCode(error);
95
+ return {
96
+ phase,
97
+ reason: phase === "endpoint connect" && osCode === "ECONNRESET" ? "daemon-connection-reset" : reason,
98
+ timestamp,
99
+ ...osCode === void 0 ? {} : { osCode }
100
+ };
101
+ }
102
+ static osCode(error) {
103
+ const seen = /* @__PURE__ */ new Set();
104
+ let current = error;
105
+ while (typeof current === "object" && current !== null && !seen.has(current)) {
106
+ seen.add(current);
107
+ if ("code" in current && typeof current.code === "string" && /^(?:E[A-Z0-9_]{1,63}|ERR_[A-Z0-9_]{1,60})$/u.test(current.code))
108
+ return current.code;
109
+ current = "cause" in current ? current.cause : void 0;
110
+ }
111
+ return void 0;
112
+ }
113
+ };
114
+ }
115
+ });
116
+
117
+ // ../../packages/daemon/dist/daemon-command-name.js
118
+ var commandNames, DAEMON_COMMAND_NAMES;
119
+ var init_daemon_command_name = __esm({
120
+ "../../packages/daemon/dist/daemon-command-name.js"() {
121
+ "use strict";
122
+ commandNames = [
123
+ "overview",
124
+ "resolve",
125
+ "def",
126
+ "refs",
127
+ "context",
128
+ "graph",
129
+ "stats",
130
+ "help",
131
+ "version",
132
+ "unknown"
133
+ ];
134
+ DAEMON_COMMAND_NAMES = Object.freeze(commandNames);
135
+ }
136
+ });
137
+
138
+ // ../../packages/daemon/dist/daemon-policy.js
139
+ var MEBIBYTE, DaemonPolicy, DaemonPolicyCodec;
140
+ var init_daemon_policy = __esm({
141
+ "../../packages/daemon/dist/daemon-policy.js"() {
142
+ "use strict";
143
+ MEBIBYTE = 1024 * 1024;
144
+ DaemonPolicy = class _DaemonPolicy {
145
+ values;
146
+ constructor(values) {
147
+ this.values = _DaemonPolicy.freeze(values);
148
+ Object.freeze(this);
149
+ }
150
+ static currentSystem() {
151
+ const runtimeProcess = globalThis.process;
152
+ const constrainedBytes = runtimeProcess.constrainedMemory?.();
153
+ return _DaemonPolicy.fromSystemMemory({
154
+ totalBytes: runtimeProcess.binding("os").getTotalMem(),
155
+ ...constrainedBytes === void 0 ? {} : { constrainedBytes }
156
+ });
157
+ }
158
+ static fromSystemMemory(memory) {
159
+ const effectiveMemoryBytes = memory.constrainedBytes !== void 0 && memory.constrainedBytes > 0 && memory.constrainedBytes < memory.totalBytes ? memory.constrainedBytes : memory.totalBytes;
160
+ const effectiveMemoryMiB = Math.max(1, Math.floor(effectiveMemoryBytes / MEBIBYTE));
161
+ const hardProcessRssMiB = _DaemonPolicy.clamp(Math.floor(effectiveMemoryMiB / 2), 256, 8192);
162
+ const workerMaxOldGenerationSizeMiB = _DaemonPolicy.clamp(Math.floor(effectiveMemoryMiB / 4), 128, 4096);
163
+ return new _DaemonPolicy({
164
+ transport: {
165
+ singleResponseTimeoutMs: 250,
166
+ statusResponseTimeoutMs: 100,
167
+ executionAdmissionTimeoutMs: 5e3,
168
+ maximumJsonPayloadBytes: 8 * MEBIBYTE,
169
+ maximumExecutionControlPayloadBytes: 256 * 1024
170
+ },
171
+ startup: {
172
+ coordinationGraceMs: 15e3,
173
+ heartbeatIntervalMs: 100,
174
+ authorizationPollIntervalMs: 10,
175
+ observationPollIntervalMs: 20,
176
+ previousInstanceTerminationTimeoutMs: 5 * 6e4,
177
+ childFailureRetryLimit: 1
178
+ },
179
+ shutdown: {
180
+ idleTimeoutMs: 30 * 6e4,
181
+ stopTimeoutMs: 5e3,
182
+ forcedTerminationReserveMaximumMs: 500,
183
+ controllerPollIntervalMs: 20,
184
+ processSignalExitTimeoutMs: 500,
185
+ processExitPollIntervalMs: 20,
186
+ resourceDrainAcknowledgementGraceMs: 250,
187
+ resourceDrainAcknowledgementPollIntervalMs: 5
188
+ },
189
+ delivery: {
190
+ postAcceptanceExecutionReattachmentLimit: 1,
191
+ resultTransferResumeLimitPerExecutionAttempt: 1
192
+ },
193
+ output: {
194
+ maximumChunkRawBytes: 64 * 1024,
195
+ inlineRawBytes: 256 * 1024,
196
+ maximumResultRawBytes: 256 * MEBIBYTE,
197
+ maximumAggregateSpoolRawBytes: 512 * MEBIBYTE
198
+ },
199
+ resources: {
200
+ effectiveMemoryBytes,
201
+ hardProcessRssBytes: hardProcessRssMiB * MEBIBYTE,
202
+ softProcessRssBytes: Math.floor(hardProcessRssMiB * 0.8) * MEBIBYTE,
203
+ resumeProcessRssBytes: Math.floor(hardProcessRssMiB * 0.7) * MEBIBYTE,
204
+ workerMaxOldGenerationSizeMiB,
205
+ supervisionIntervalMs: 250,
206
+ replacementWindowMs: 10 * 6e4,
207
+ replacementLimit: 2,
208
+ workerHeapSampleIntervalMs: 25
209
+ },
210
+ diagnostics: {
211
+ logRotateBytes: 10 * MEBIBYTE,
212
+ logBackupCount: 4,
213
+ maximumQueuedEvents: 1024,
214
+ disconnectedTraceRetentionMs: 5 * 6e4,
215
+ maximumDisconnectedTraces: 1024
216
+ }
217
+ });
218
+ }
219
+ static clamp(value, minimum, maximum) {
220
+ return Math.max(minimum, Math.min(maximum, value));
221
+ }
222
+ static freeze(values) {
223
+ for (const section of Object.values(values))
224
+ Object.freeze(section);
225
+ return Object.freeze(values);
226
+ }
227
+ };
228
+ DaemonPolicyCodec = class _DaemonPolicyCodec {
229
+ static serialize(policy) {
230
+ return Object.freeze({ schemaVersion: 1, values: policy.values });
231
+ }
232
+ static parse(value) {
233
+ if (!_DaemonPolicyCodec.isRecord(value))
234
+ throw new Error("Invalid daemon policy");
235
+ _DaemonPolicyCodec.exactKeys(value, ["schemaVersion", "values"]);
236
+ if (value.schemaVersion !== 1 || !_DaemonPolicyCodec.isRecord(value.values)) {
237
+ throw new Error("Invalid daemon policy");
238
+ }
239
+ const values = value.values;
240
+ _DaemonPolicyCodec.validateValues(values);
241
+ return JSON.parse(JSON.stringify(values));
242
+ }
243
+ static deserialize(value) {
244
+ const PolicyConstructor = DaemonPolicy;
245
+ return new PolicyConstructor(_DaemonPolicyCodec.parse(value));
246
+ }
247
+ static validateValues(values) {
248
+ _DaemonPolicyCodec.exactKeys(values, [
249
+ "transport",
250
+ "startup",
251
+ "shutdown",
252
+ "delivery",
253
+ "output",
254
+ "resources",
255
+ "diagnostics"
256
+ ]);
257
+ const transport = _DaemonPolicyCodec.section(values, "transport", [
258
+ "singleResponseTimeoutMs",
259
+ "statusResponseTimeoutMs",
260
+ "executionAdmissionTimeoutMs",
261
+ "maximumJsonPayloadBytes",
262
+ "maximumExecutionControlPayloadBytes"
263
+ ]);
264
+ const startup = _DaemonPolicyCodec.section(values, "startup", [
265
+ "coordinationGraceMs",
266
+ "heartbeatIntervalMs",
267
+ "authorizationPollIntervalMs",
268
+ "observationPollIntervalMs",
269
+ "previousInstanceTerminationTimeoutMs",
270
+ "childFailureRetryLimit"
271
+ ]);
272
+ const shutdown = _DaemonPolicyCodec.section(values, "shutdown", [
273
+ "idleTimeoutMs",
274
+ "stopTimeoutMs",
275
+ "forcedTerminationReserveMaximumMs",
276
+ "controllerPollIntervalMs",
277
+ "processSignalExitTimeoutMs",
278
+ "processExitPollIntervalMs",
279
+ "resourceDrainAcknowledgementGraceMs",
280
+ "resourceDrainAcknowledgementPollIntervalMs"
281
+ ]);
282
+ const delivery = _DaemonPolicyCodec.section(values, "delivery", [
283
+ "postAcceptanceExecutionReattachmentLimit",
284
+ "resultTransferResumeLimitPerExecutionAttempt"
285
+ ]);
286
+ const output = _DaemonPolicyCodec.section(values, "output", [
287
+ "maximumChunkRawBytes",
288
+ "inlineRawBytes",
289
+ "maximumResultRawBytes",
290
+ "maximumAggregateSpoolRawBytes"
291
+ ]);
292
+ const resources = _DaemonPolicyCodec.section(values, "resources", [
293
+ "effectiveMemoryBytes",
294
+ "hardProcessRssBytes",
295
+ "softProcessRssBytes",
296
+ "resumeProcessRssBytes",
297
+ "workerMaxOldGenerationSizeMiB",
298
+ "supervisionIntervalMs",
299
+ "replacementWindowMs",
300
+ "replacementLimit",
301
+ "workerHeapSampleIntervalMs"
302
+ ]);
303
+ const diagnostics = _DaemonPolicyCodec.section(values, "diagnostics", [
304
+ "logRotateBytes",
305
+ "logBackupCount",
306
+ "maximumQueuedEvents",
307
+ "disconnectedTraceRetentionMs",
308
+ "maximumDisconnectedTraces"
309
+ ]);
310
+ for (const section of [
311
+ transport,
312
+ startup,
313
+ shutdown,
314
+ delivery,
315
+ output,
316
+ resources,
317
+ diagnostics
318
+ ]) {
319
+ for (const value of Object.values(section))
320
+ _DaemonPolicyCodec.nonnegativeInteger(value);
321
+ }
322
+ for (const [section, key] of [
323
+ [startup, "heartbeatIntervalMs"],
324
+ [startup, "authorizationPollIntervalMs"],
325
+ [startup, "observationPollIntervalMs"],
326
+ [shutdown, "controllerPollIntervalMs"],
327
+ [shutdown, "processExitPollIntervalMs"],
328
+ [shutdown, "resourceDrainAcknowledgementPollIntervalMs"],
329
+ [resources, "supervisionIntervalMs"],
330
+ [resources, "workerHeapSampleIntervalMs"]
331
+ ]) {
332
+ if (_DaemonPolicyCodec.integer(section, key) <= 0)
333
+ throw new Error("Invalid daemon policy");
334
+ }
335
+ const hardProcessRssBytes = _DaemonPolicyCodec.integer(resources, "hardProcessRssBytes");
336
+ const softProcessRssBytes = _DaemonPolicyCodec.integer(resources, "softProcessRssBytes");
337
+ const resumeProcessRssBytes = _DaemonPolicyCodec.integer(resources, "resumeProcessRssBytes");
338
+ if (hardProcessRssBytes <= softProcessRssBytes || softProcessRssBytes <= resumeProcessRssBytes) {
339
+ throw new Error("Invalid daemon policy");
340
+ }
341
+ const maximumChunkRawBytes = _DaemonPolicyCodec.integer(output, "maximumChunkRawBytes");
342
+ const inlineRawBytes = _DaemonPolicyCodec.integer(output, "inlineRawBytes");
343
+ const maximumResultRawBytes = _DaemonPolicyCodec.integer(output, "maximumResultRawBytes");
344
+ const maximumAggregateSpoolRawBytes = _DaemonPolicyCodec.integer(output, "maximumAggregateSpoolRawBytes");
345
+ if (maximumChunkRawBytes === 0 || maximumChunkRawBytes > inlineRawBytes || inlineRawBytes > maximumResultRawBytes || maximumResultRawBytes > maximumAggregateSpoolRawBytes) {
346
+ throw new Error("Invalid daemon policy");
347
+ }
348
+ }
349
+ static section(values, name, keys) {
350
+ const section = values[name];
351
+ if (!_DaemonPolicyCodec.isRecord(section))
352
+ throw new Error("Invalid daemon policy");
353
+ _DaemonPolicyCodec.exactKeys(section, keys);
354
+ return section;
355
+ }
356
+ static exactKeys(value, keys) {
357
+ const actual = Object.keys(value).sort();
358
+ const expected = [...keys].sort();
359
+ if (actual.length !== expected.length || actual.some((key, index) => key !== expected[index])) {
360
+ throw new Error("Invalid daemon policy");
361
+ }
362
+ }
363
+ static nonnegativeInteger(value) {
364
+ if (!Number.isSafeInteger(value) || value < 0) {
365
+ throw new Error("Invalid daemon policy");
366
+ }
367
+ }
368
+ static integer(section, key) {
369
+ const value = section[key];
370
+ _DaemonPolicyCodec.nonnegativeInteger(value);
371
+ return value;
372
+ }
373
+ static isRecord(value) {
374
+ return typeof value === "object" && value !== null && !Array.isArray(value);
375
+ }
376
+ };
377
+ }
378
+ });
379
+
380
+ // ../../packages/daemon/dist/client/daemon-client.js
381
+ var init_daemon_client = __esm({
382
+ "../../packages/daemon/dist/client/daemon-client.js"() {
383
+ "use strict";
384
+ }
385
+ });
386
+
387
+ // ../../packages/daemon/dist/client/daemon-controlled-failure-message.js
388
+ var init_daemon_controlled_failure_message = __esm({
389
+ "../../packages/daemon/dist/client/daemon-controlled-failure-message.js"() {
390
+ "use strict";
391
+ }
392
+ });
393
+
394
+ // ../../packages/daemon/dist/index.js
395
+ var init_dist = __esm({
396
+ "../../packages/daemon/dist/index.js"() {
397
+ "use strict";
398
+ init_daemon_command_name();
399
+ init_daemon_policy();
400
+ init_daemon_client();
401
+ init_daemon_controlled_failure_message();
402
+ }
403
+ });
404
+
405
+ // ../../packages/daemon/dist/diagnostics/failure-values.js
406
+ import { isAbsolute } from "node:path";
407
+ var DaemonFailureValues;
408
+ var init_failure_values = __esm({
409
+ "../../packages/daemon/dist/diagnostics/failure-values.js"() {
410
+ "use strict";
411
+ DaemonFailureValues = class {
412
+ static phases = /* @__PURE__ */ new Set([
413
+ "state location",
414
+ "endpoint create",
415
+ "endpoint bind",
416
+ "endpoint connect",
417
+ "process spawn",
418
+ "warm-up",
419
+ "worker",
420
+ "transfer"
421
+ ]);
422
+ static reasons = /* @__PURE__ */ new Set([
423
+ "state-write-failed",
424
+ "endpoint-create-failed",
425
+ "endpoint-bind-denied",
426
+ "endpoint-connect-failed",
427
+ "daemon-connection-reset",
428
+ "process-spawn-failed",
429
+ "startup-failed",
430
+ "worker-failed",
431
+ "transfer-failed",
432
+ "process-terminated",
433
+ "daemon-incompatible"
434
+ ]);
435
+ static isFailure(value) {
436
+ if (!this.isObject(value))
437
+ return false;
438
+ return this.exactKeys(value, ["phase", "reason", "timestamp"], ["osCode"]) && typeof value.phase === "string" && this.phases.has(value.phase) && typeof value.reason === "string" && this.reasons.has(value.reason) && typeof value.timestamp === "number" && Number.isFinite(value.timestamp) && value.timestamp >= 0 && (value.osCode === void 0 || this.isOsCode(value.osCode));
439
+ }
440
+ static isEvent(value) {
441
+ if (!this.isObject(value))
442
+ return false;
443
+ return this.exactKeys(value, ["schemaVersion", "eventId", "workspaceRoot", "kind", "failure"], ["instanceId", "requestId"]) && value.schemaVersion === 1 && this.isCorrelation(value.eventId) && typeof value.workspaceRoot === "string" && isAbsolute(value.workspaceRoot) && typeof value.kind === "string" && ["startup-failure", "fallback", "termination"].includes(value.kind) && this.isFailure(value.failure) && (value.instanceId === void 0 || this.isCorrelation(value.instanceId)) && (value.requestId === void 0 || this.isCorrelation(value.requestId));
444
+ }
445
+ static isOsCode(value) {
446
+ return typeof value === "string" && /^(?:E[A-Z0-9_]{1,63}|ERR_[A-Z0-9_]{1,60})$/u.test(value);
447
+ }
448
+ static isCorrelation(value) {
449
+ return typeof value === "string" && /^[A-Za-z0-9:._-]{1,256}$/u.test(value);
450
+ }
451
+ static isObject(value) {
452
+ return typeof value === "object" && value !== null && !Array.isArray(value);
453
+ }
454
+ static exactKeys(value, required, optional) {
455
+ return required.every((key) => key in value) && Object.keys(value).every((key) => required.includes(key) || optional.includes(key));
456
+ }
457
+ };
458
+ }
459
+ });
460
+
461
+ // ../../packages/daemon/dist/process/runtime-values.js
462
+ var DaemonRuntimeValues;
463
+ var init_runtime_values = __esm({
464
+ "../../packages/daemon/dist/process/runtime-values.js"() {
465
+ "use strict";
466
+ init_dist();
467
+ DaemonRuntimeValues = class {
468
+ static isCommandName(value) {
469
+ return DAEMON_COMMAND_NAMES.includes(value);
470
+ }
471
+ static isRequestId(value) {
472
+ return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/.test(value);
473
+ }
474
+ };
475
+ }
476
+ });
477
+
478
+ // ../../packages/daemon/dist/lifecycle/daemon-clock.js
479
+ import { performance } from "node:perf_hooks";
480
+ var NodeDaemonClock;
481
+ var init_daemon_clock = __esm({
482
+ "../../packages/daemon/dist/lifecycle/daemon-clock.js"() {
483
+ "use strict";
484
+ NodeDaemonClock = class {
485
+ sources;
486
+ constructor(sources = {
487
+ wallNowMs: Date.now,
488
+ monotonicNowMs: () => performance.now()
489
+ }) {
490
+ this.sources = sources;
491
+ }
492
+ wallNowMs() {
493
+ return this.sources.wallNowMs();
494
+ }
495
+ monotonicNowMs() {
496
+ return this.sources.monotonicNowMs();
497
+ }
498
+ };
499
+ }
500
+ });
501
+
502
+ // ../../packages/daemon/dist/worker/navigation-worker-entry.js
503
+ init_failure_recorder();
504
+ init_dist();
505
+ import { parentPort, workerData } from "node:worker_threads";
506
+ import { getHeapStatistics } from "node:v8";
507
+
508
+ // ../../packages/daemon/dist/daemon-executor.js
509
+ init_state_write_errors();
510
+
511
+ // ../../packages/daemon/dist/daemon-diagnostics.js
512
+ var DaemonDiagnosticValues = class {
513
+ static isDiagnostics(value) {
514
+ return this.isObject(value, /* @__PURE__ */ new Set());
515
+ }
516
+ static isValue(value, ancestors) {
517
+ if (value === null || typeof value === "boolean" || typeof value === "string")
518
+ return true;
519
+ if (typeof value === "number")
520
+ return Number.isFinite(value);
521
+ if (Array.isArray(value))
522
+ return this.isArray(value, ancestors);
523
+ return this.isObject(value, ancestors);
524
+ }
525
+ static isArray(value, ancestors) {
526
+ if (ancestors.has(value))
527
+ return false;
528
+ const descendants = new Set(ancestors).add(value);
529
+ return value.every((entry) => this.isValue(entry, descendants));
530
+ }
531
+ static isObject(value, ancestors) {
532
+ if (typeof value !== "object" || value === null || Array.isArray(value))
533
+ return false;
534
+ const prototype = Object.getPrototypeOf(value);
535
+ if (prototype !== Object.prototype && prototype !== null)
536
+ return false;
537
+ if (ancestors.has(value))
538
+ return false;
539
+ const descendants = new Set(ancestors).add(value);
540
+ return Object.values(value).every((entry) => this.isValue(entry, descendants));
541
+ }
542
+ };
543
+
544
+ // ../../packages/daemon/dist/daemon-executor.js
545
+ var ValidatedDaemonExecutorOutput = class {
546
+ output;
547
+ constructor(output) {
548
+ this.output = output;
549
+ }
550
+ async *records() {
551
+ for await (const value of this.output.records()) {
552
+ if (!DaemonExecutorValidation.isOutputRecord(value)) {
553
+ throw new Error("Invalid daemon executor output record");
554
+ }
555
+ yield value;
556
+ }
557
+ }
558
+ dispose() {
559
+ return this.output.dispose();
560
+ }
561
+ };
562
+ var ValidatedDaemonExecutor = class {
563
+ executor;
564
+ constructor(executor) {
565
+ this.executor = executor;
566
+ }
567
+ async initialize(workspaceRoot) {
568
+ const result = await this.executor.initialize(workspaceRoot);
569
+ if (!DaemonExecutorValidation.isInitializationResult(result)) {
570
+ throw new Error("Invalid daemon executor initialization result");
571
+ }
572
+ return result;
573
+ }
574
+ async execute(request) {
575
+ const result = await this.executor.execute(request);
576
+ if (!DaemonExecutorValidation.isExecutionResult(result)) {
577
+ throw new Error("Invalid daemon executor execution result");
578
+ }
579
+ return { ...result, output: new ValidatedDaemonExecutorOutput(result.output) };
580
+ }
581
+ releaseTransientResources() {
582
+ return this.executor.releaseTransientResources();
583
+ }
584
+ };
585
+ var DaemonExecutorModuleImporter = class {
586
+ static hostImporterModuleUrl = [
587
+ "data:text/javascript",
588
+ "export default moduleUrl => import(moduleUrl)"
589
+ ].join(",");
590
+ static async load(moduleUrl) {
591
+ const importer = await import(this.hostImporterModuleUrl);
592
+ return importer.default(moduleUrl);
593
+ }
594
+ };
595
+ var DaemonExecutorModuleLoader = class {
596
+ static async load(moduleUrl, options) {
597
+ if (!DaemonExecutorValidation.isFileUrl(moduleUrl)) {
598
+ throw new Error("Daemon executor module must use a file URL");
599
+ }
600
+ const loaded = await DaemonExecutorModuleImporter.load(moduleUrl);
601
+ if (!DaemonExecutorValidation.isRecord(loaded) || typeof loaded.createDaemonExecutor !== "function") {
602
+ throw new Error("Daemon executor module has no createDaemonExecutor factory");
603
+ }
604
+ const executor = await loaded.createDaemonExecutor(options);
605
+ if (!DaemonExecutorValidation.isExecutor(executor)) {
606
+ throw new Error("Daemon executor factory returned an invalid executor");
607
+ }
608
+ return new ValidatedDaemonExecutor(executor);
609
+ }
610
+ };
611
+ var DaemonExecutorValidation = class {
612
+ static isInitializationResult(value) {
613
+ if (!this.isRecord(value))
614
+ return false;
615
+ return this.hasExactKeys(value, this.keysWithDiagnostics(["fileCount"], value)) && this.isCount(value.fileCount) && this.isDiagnostics(value.diagnostics);
616
+ }
617
+ static isExecutionResult(value) {
618
+ if (!this.isRecord(value))
619
+ return false;
620
+ return this.hasExactKeys(value, this.keysWithDiagnostics(value.stateWriteFailure === void 0 ? ["exitCode", "output"] : ["exitCode", "output", "stateWriteFailure"], value)) && this.isCount(value.exitCode) && this.isOutput(value.output) && (value.stateWriteFailure === void 0 || DaemonStateWriteErrors.isFailure(value.stateWriteFailure)) && this.isDiagnostics(value.diagnostics);
621
+ }
622
+ static isOutputRecord(value) {
623
+ return this.isRecord(value) && this.hasExactKeys(value, ["stream", "bytes"]) && (value.stream === "stdout" || value.stream === "stderr") && value.bytes instanceof Uint8Array;
624
+ }
625
+ static isFileUrl(value) {
626
+ return typeof value === "string" && value.startsWith("file://");
627
+ }
628
+ static isExecutor(value) {
629
+ return this.isRecord(value) && typeof value.initialize === "function" && typeof value.execute === "function" && typeof value.releaseTransientResources === "function";
630
+ }
631
+ static isOutput(value) {
632
+ return this.isRecord(value) && typeof value.records === "function" && typeof value.dispose === "function";
633
+ }
634
+ static isDiagnostics(value) {
635
+ return value === void 0 || DaemonDiagnosticValues.isDiagnostics(value);
636
+ }
637
+ static keysWithDiagnostics(keys, value) {
638
+ return value.diagnostics === void 0 ? keys : [...keys, "diagnostics"];
639
+ }
640
+ static hasExactKeys(value, keys) {
641
+ const actual = Object.keys(value).sort();
642
+ const expected = [...keys].sort();
643
+ return actual.length === expected.length && actual.every((key, index) => key === expected[index]);
644
+ }
645
+ static isCount(value) {
646
+ return Number.isSafeInteger(value) && Number(value) >= 0;
647
+ }
648
+ static isRecord(value) {
649
+ return typeof value === "object" && value !== null && !Array.isArray(value);
650
+ }
651
+ };
652
+
653
+ // ../../packages/daemon/dist/worker/navigation-worker-entry.js
654
+ init_daemon_policy();
655
+
656
+ // ../../packages/daemon/dist/worker/worker-protocol.js
657
+ init_failure_values();
658
+ init_state_write_errors();
659
+ init_dist();
660
+ init_runtime_values();
661
+ var DaemonNavigationWorkerProtocol = class {
662
+ static request(value) {
663
+ if (!this.isRecord(value) || !this.isGeneration(value.generation)) {
664
+ throw new Error("Invalid daemon navigation worker request");
665
+ }
666
+ if (value.kind === "initialize" && this.hasKeys(value, ["kind", "generation", "workspaceRoot"]) && this.isNonEmptyString(value.workspaceRoot)) {
667
+ return value;
668
+ }
669
+ if (value.kind === "execute" && this.hasKeys(value, ["kind", "generation", "requestId", "commandName", "request"]) && this.isNonEmptyString(value.requestId) && DaemonRuntimeValues.isCommandName(value.commandName) && this.isExecutionRequest(value.request)) {
670
+ return value;
671
+ }
672
+ if (value.kind === "output-ack" && this.hasKeys(value, ["kind", "generation", "requestId", "sequence"]) && this.isNonEmptyString(value.requestId) && this.isCount(value.sequence)) {
673
+ return value;
674
+ }
675
+ if (value.kind === "release-transient" && this.hasKeys(value, ["kind", "generation", "operationId"]) && this.isNonEmptyString(value.operationId)) {
676
+ return value;
677
+ }
678
+ if (value.kind === "close" && this.hasKeys(value, ["kind", "generation"])) {
679
+ return value;
680
+ }
681
+ throw new Error("Invalid daemon navigation worker request");
682
+ }
683
+ static response(value, maximumChunkRawBytes) {
684
+ if (!this.isRecord(value) || !this.isGeneration(value.generation)) {
685
+ throw new Error("Invalid daemon navigation worker response");
686
+ }
687
+ if (value.kind === "ready" && this.hasKeys(value, this.keysWithDiagnostics(["kind", "generation", "fileCount", "refresh", "startupDurations"], value)) && this.isCount(value.fileCount) && this.isRefresh(value.refresh) && this.isDurations(value.startupDurations, ["discoveryMs", "indexingMs", "totalMs"]) && this.isDiagnostics(value.diagnostics)) {
688
+ return value;
689
+ }
690
+ if (value.kind === "output-chunk" && this.hasKeys(value, ["kind", "generation", "requestId", "sequence", "stream", "bytes"]) && this.isNonEmptyString(value.requestId) && this.isCount(value.sequence) && (value.stream === "stdout" || value.stream === "stderr") && value.bytes instanceof Uint8Array && value.bytes.byteLength <= maximumChunkRawBytes) {
691
+ return value;
692
+ }
693
+ if (value.kind === "result" && this.hasKeys(value, this.keysWithDiagnostics(["kind", "generation", "requestId", "result", "refresh", "durations", "resources"], value)) && this.isNonEmptyString(value.requestId) && this.isExecutionResult(value.result) && this.isRefresh(value.refresh) && this.isDurations(value.durations, ["freshnessMs", "navigationMs", "renderMs", "outputMs"]) && this.isDiagnostics(value.diagnostics) && this.isWorkerResources(value.resources)) {
694
+ return value;
695
+ }
696
+ if (value.kind === "failed" && this.isFailed(value)) {
697
+ return value;
698
+ }
699
+ if (value.kind === "heap" && this.hasKeys(value, [
700
+ "kind",
701
+ "generation",
702
+ "operationId",
703
+ "usedHeapBytes",
704
+ "heapLimitBytes"
705
+ ]) && this.isNonEmptyString(value.operationId) && this.isCount(value.usedHeapBytes) && this.isCount(value.heapLimitBytes)) {
706
+ return value;
707
+ }
708
+ if (value.kind === "closed" && this.hasKeys(value, ["kind", "generation"])) {
709
+ return value;
710
+ }
711
+ throw new Error("Invalid daemon navigation worker response");
712
+ }
713
+ static isWorkerResources(value) {
714
+ return this.isRecord(value) && this.hasKeys(value, [
715
+ "workerHeapUsedBytes",
716
+ "peakWorkerHeapUsedBytes",
717
+ "workerHeapLimitBytes"
718
+ ]) && this.isCount(value.workerHeapUsedBytes) && this.isCount(value.peakWorkerHeapUsedBytes) && this.isCount(value.workerHeapLimitBytes) && value.peakWorkerHeapUsedBytes >= value.workerHeapUsedBytes;
719
+ }
720
+ static isExecutionRequest(value) {
721
+ if (!this.isRecord(value))
722
+ return false;
723
+ return this.hasKeys(value, ["argv", "cwd", "telemetryEnabled", "executionMode"]) && Array.isArray(value.argv) && value.argv.every((argument) => typeof argument === "string") && typeof value.cwd === "string" && typeof value.telemetryEnabled === "boolean" && (value.executionMode === "cold" || value.executionMode === "warm" || value.executionMode === "fallback");
724
+ }
725
+ static isDiagnostics(value) {
726
+ return value === void 0 || DaemonDiagnosticValues.isDiagnostics(value);
727
+ }
728
+ static keysWithDiagnostics(keys, value) {
729
+ return value.diagnostics === void 0 ? keys : [...keys, "diagnostics"];
730
+ }
731
+ static isExecutionResult(value) {
732
+ return this.isRecord(value) && this.hasKeys(value, value.stateWriteFailure === void 0 ? ["exitCode"] : ["exitCode", "stateWriteFailure"]) && this.isCount(value.exitCode) && (value.stateWriteFailure === void 0 || DaemonStateWriteErrors.isFailure(value.stateWriteFailure));
733
+ }
734
+ static isRefresh(value) {
735
+ return this.isRecord(value) && this.hasKeys(value, ["added", "changed", "removed", "unchanged"]) && this.isCount(value.added) && this.isCount(value.changed) && this.isCount(value.removed) && this.isCount(value.unchanged);
736
+ }
737
+ static isFailed(value) {
738
+ const keys = ["kind", "generation", "failureCode"];
739
+ if (value.requestId !== void 0)
740
+ keys.push("requestId");
741
+ if (value.operationId !== void 0)
742
+ keys.push("operationId");
743
+ if (value.errorName !== void 0)
744
+ keys.push("errorName");
745
+ if (value.osCode !== void 0)
746
+ keys.push("osCode");
747
+ return this.hasKeys(value, keys) && (value.requestId === void 0 || this.isNonEmptyString(value.requestId)) && (value.operationId === void 0 || this.isNonEmptyString(value.operationId)) && !(value.requestId !== void 0 && value.operationId !== void 0) && (value.failureCode === "initialization" || value.failureCode === "execution" || value.failureCode === "protocol" || value.failureCode === "resource") && (value.errorName === void 0 || this.isNonEmptyString(value.errorName)) && (value.osCode === void 0 || DaemonFailureValues.isOsCode(value.osCode));
748
+ }
749
+ static isDurations(value, keys) {
750
+ return this.isRecord(value) && this.hasKeys(value, keys) && keys.every((key) => this.isMetric(value[key]));
751
+ }
752
+ static hasKeys(value, keys) {
753
+ const actual = Object.keys(value).sort();
754
+ return actual.length === keys.length && actual.every((key, index) => key === [...keys].sort()[index]);
755
+ }
756
+ static isGeneration(value) {
757
+ return Number.isSafeInteger(value) && Number(value) >= 0;
758
+ }
759
+ static isCount(value) {
760
+ return Number.isSafeInteger(value) && Number(value) >= 0;
761
+ }
762
+ static isMetric(value) {
763
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
764
+ }
765
+ static isNonEmptyString(value) {
766
+ return typeof value === "string" && value.length > 0;
767
+ }
768
+ static isRecord(value) {
769
+ return typeof value === "object" && value !== null && !Array.isArray(value);
770
+ }
771
+ };
772
+
773
+ // ../../packages/daemon/dist/worker/navigation-worker-entry.js
774
+ init_daemon_clock();
775
+ var DaemonNavigationWorkerEntry = class {
776
+ port;
777
+ data;
778
+ executor;
779
+ activeHeapMonitor;
780
+ tail = Promise.resolve();
781
+ outputAcknowledgements = /* @__PURE__ */ new Map();
782
+ policy;
783
+ clock = new NodeDaemonClock();
784
+ constructor(port, data2) {
785
+ this.port = port;
786
+ this.data = data2;
787
+ this.policy = DaemonPolicyCodec.deserialize(data2.policy);
788
+ }
789
+ run() {
790
+ this.port.on("message", (value) => {
791
+ if (typeof value === "object" && value !== null && "kind" in value && value.kind === "output-ack") {
792
+ try {
793
+ const request = DaemonNavigationWorkerProtocol.request(value);
794
+ if (request.kind !== "output-ack")
795
+ throw new Error("Invalid output acknowledgement");
796
+ this.acknowledgeOutput(request.requestId, request.sequence);
797
+ return;
798
+ } catch (error) {
799
+ this.fail("protocol", error);
800
+ return;
801
+ }
802
+ }
803
+ this.tail = this.tail.then(() => this.handle(value));
804
+ });
805
+ }
806
+ async handle(value) {
807
+ let request;
808
+ try {
809
+ request = DaemonNavigationWorkerProtocol.request(value);
810
+ } catch (error) {
811
+ this.fail("protocol", error);
812
+ return;
813
+ }
814
+ if (request.generation !== this.data.generation)
815
+ return;
816
+ if (request.kind === "initialize") {
817
+ await this.initialize(request.workspaceRoot);
818
+ return;
819
+ }
820
+ if (request.kind === "execute") {
821
+ await this.execute(request);
822
+ return;
823
+ }
824
+ if (request.kind === "release-transient") {
825
+ await this.releaseTransientResources(request.operationId);
826
+ return;
827
+ }
828
+ await this.close();
829
+ }
830
+ async initialize(workspaceRoot) {
831
+ const startedAt = this.clock.monotonicNowMs();
832
+ try {
833
+ this.executor = await DaemonExecutorModuleLoader.load(this.data.executorModuleUrl, {
834
+ stateDirectory: this.data.stateDirectory,
835
+ productVersion: this.data.productVersion,
836
+ sampleResources: () => this.activeHeapMonitor?.sample()
837
+ });
838
+ const initialized = await this.executor.initialize(workspaceRoot);
839
+ const totalMs = this.clock.monotonicNowMs() - startedAt;
840
+ this.send({
841
+ kind: "ready",
842
+ generation: this.data.generation,
843
+ fileCount: initialized.fileCount,
844
+ refresh: DaemonWorkerDiagnosticProjection.refresh(initialized.diagnostics),
845
+ startupDurations: {
846
+ ...DaemonWorkerDiagnosticProjection.startupDurations(initialized.diagnostics),
847
+ totalMs
848
+ },
849
+ ...initialized.diagnostics === void 0 ? {} : { diagnostics: initialized.diagnostics }
850
+ });
851
+ } catch (error) {
852
+ this.fail("initialization", error);
853
+ }
854
+ }
855
+ async execute(request) {
856
+ const heapMonitor = new WorkerHeapHighWater(this.policy.values.resources.workerHeapSampleIntervalMs);
857
+ this.activeHeapMonitor = heapMonitor;
858
+ try {
859
+ if (this.executor === void 0)
860
+ throw new Error("Navigation worker is not ready");
861
+ const result = await this.executor.execute(request.request);
862
+ heapMonitor.sample();
863
+ const outputStartedAt = this.clock.monotonicNowMs();
864
+ let sequence = 0;
865
+ for await (const record of result.output.records()) {
866
+ sequence = await this.sendOutput(request.requestId, sequence, record);
867
+ heapMonitor.sample();
868
+ }
869
+ await result.output.dispose();
870
+ const outputMs = this.clock.monotonicNowMs() - outputStartedAt;
871
+ const resources = heapMonitor.finish();
872
+ this.send({
873
+ kind: "result",
874
+ generation: this.data.generation,
875
+ requestId: request.requestId,
876
+ result: {
877
+ exitCode: result.exitCode,
878
+ ...result.stateWriteFailure === void 0 ? {} : { stateWriteFailure: result.stateWriteFailure }
879
+ },
880
+ refresh: DaemonWorkerDiagnosticProjection.refresh(result.diagnostics),
881
+ durations: {
882
+ ...DaemonWorkerDiagnosticProjection.commandDurations(result.diagnostics),
883
+ outputMs
884
+ },
885
+ ...result.diagnostics === void 0 ? {} : { diagnostics: result.diagnostics },
886
+ resources
887
+ });
888
+ } catch (error) {
889
+ this.fail("execution", error, { requestId: request.requestId });
890
+ } finally {
891
+ heapMonitor.close();
892
+ this.activeHeapMonitor = void 0;
893
+ }
894
+ }
895
+ async releaseTransientResources(operationId) {
896
+ try {
897
+ await this.executor?.releaseTransientResources();
898
+ const heap = getHeapStatistics();
899
+ this.send({
900
+ kind: "heap",
901
+ generation: this.data.generation,
902
+ operationId,
903
+ usedHeapBytes: heap.used_heap_size,
904
+ heapLimitBytes: heap.heap_size_limit
905
+ });
906
+ } catch (error) {
907
+ this.fail("resource", error, { operationId });
908
+ }
909
+ }
910
+ async close() {
911
+ await this.executor?.releaseTransientResources();
912
+ this.send({ kind: "closed", generation: this.data.generation });
913
+ this.port.close();
914
+ }
915
+ fail(failureCode, error, correlation = void 0) {
916
+ this.send({
917
+ kind: "failed",
918
+ generation: this.data.generation,
919
+ ...correlation,
920
+ failureCode,
921
+ ...error instanceof Error ? { errorName: error.name } : {},
922
+ ...DaemonFailureRecorder.osCode(error) === void 0 ? {} : { osCode: DaemonFailureRecorder.osCode(error) }
923
+ });
924
+ }
925
+ send(response) {
926
+ const validated = DaemonNavigationWorkerProtocol.response(response, this.policy.values.output.maximumChunkRawBytes);
927
+ if (validated.kind === "output-chunk") {
928
+ this.port.postMessage(validated, [validated.bytes.buffer]);
929
+ return;
930
+ }
931
+ this.port.postMessage(validated);
932
+ }
933
+ sendOutput(requestId, initialSequence, record) {
934
+ return this.sendOutputChunks(requestId, initialSequence, record);
935
+ }
936
+ async sendOutputChunks(requestId, initialSequence, record) {
937
+ let sequence = initialSequence;
938
+ if (record.bytes.byteLength === 0) {
939
+ await this.sendOutputChunk(requestId, sequence, record.stream, new Uint8Array());
940
+ return sequence + 1;
941
+ }
942
+ for (let offset = 0; offset < record.bytes.byteLength; offset += this.policy.values.output.maximumChunkRawBytes) {
943
+ const bytes = Uint8Array.from(record.bytes.subarray(offset, offset + this.policy.values.output.maximumChunkRawBytes));
944
+ await this.sendOutputChunk(requestId, sequence, record.stream, bytes);
945
+ sequence += 1;
946
+ }
947
+ return sequence;
948
+ }
949
+ sendOutputChunk(requestId, sequence, stream, bytes) {
950
+ const key = `${requestId}:${sequence}`;
951
+ if (this.outputAcknowledgements.has(key)) {
952
+ return Promise.reject(new Error("Duplicate worker output sequence"));
953
+ }
954
+ const acknowledgement = new Promise((resolve) => {
955
+ this.outputAcknowledgements.set(key, resolve);
956
+ });
957
+ this.send({
958
+ kind: "output-chunk",
959
+ generation: this.data.generation,
960
+ requestId,
961
+ sequence,
962
+ stream,
963
+ bytes
964
+ });
965
+ return acknowledgement;
966
+ }
967
+ acknowledgeOutput(requestId, sequence) {
968
+ const key = `${requestId}:${sequence}`;
969
+ const resolve = this.outputAcknowledgements.get(key);
970
+ if (resolve === void 0)
971
+ throw new Error("Unexpected worker output acknowledgement");
972
+ this.outputAcknowledgements.delete(key);
973
+ resolve();
974
+ }
975
+ };
976
+ var DaemonWorkerDiagnosticProjection = class {
977
+ static emptyRefresh = {
978
+ added: 0,
979
+ changed: 0,
980
+ removed: 0,
981
+ unchanged: 0
982
+ };
983
+ static refresh(diagnostics) {
984
+ const refresh = this.record(diagnostics?.refresh);
985
+ if (refresh === void 0)
986
+ return this.emptyRefresh;
987
+ return {
988
+ added: this.count(refresh.added),
989
+ changed: this.count(refresh.changed),
990
+ removed: this.count(refresh.removed),
991
+ unchanged: this.count(refresh.unchanged)
992
+ };
993
+ }
994
+ static startupDurations(diagnostics) {
995
+ const durations = this.record(diagnostics?.durations);
996
+ return {
997
+ discoveryMs: this.duration(durations?.discoveryMs),
998
+ indexingMs: this.duration(durations?.indexingMs)
999
+ };
1000
+ }
1001
+ static commandDurations(diagnostics) {
1002
+ const durations = this.record(diagnostics?.durations);
1003
+ return {
1004
+ freshnessMs: this.duration(durations?.freshnessMs),
1005
+ navigationMs: this.duration(durations?.navigationMs),
1006
+ renderMs: this.duration(durations?.renderMs)
1007
+ };
1008
+ }
1009
+ static record(value) {
1010
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
1011
+ }
1012
+ static count(value) {
1013
+ return Number.isSafeInteger(value) && Number(value) >= 0 ? Number(value) : 0;
1014
+ }
1015
+ static duration(value) {
1016
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
1017
+ }
1018
+ };
1019
+ var WorkerHeapHighWater = class {
1020
+ currentUsedBytes = 0;
1021
+ peakUsedBytes = 0;
1022
+ heapLimitBytes = 0;
1023
+ timer;
1024
+ constructor(sampleIntervalMs) {
1025
+ this.sample();
1026
+ this.timer = setInterval(() => this.sample(), sampleIntervalMs);
1027
+ this.timer.unref?.();
1028
+ }
1029
+ sample() {
1030
+ const heap = getHeapStatistics();
1031
+ this.currentUsedBytes = heap.used_heap_size;
1032
+ this.peakUsedBytes = Math.max(this.peakUsedBytes, this.currentUsedBytes);
1033
+ this.heapLimitBytes = heap.heap_size_limit;
1034
+ }
1035
+ finish() {
1036
+ this.sample();
1037
+ this.close();
1038
+ return {
1039
+ workerHeapUsedBytes: this.currentUsedBytes,
1040
+ peakWorkerHeapUsedBytes: this.peakUsedBytes,
1041
+ workerHeapLimitBytes: this.heapLimitBytes
1042
+ };
1043
+ }
1044
+ close() {
1045
+ clearInterval(this.timer);
1046
+ }
1047
+ };
1048
+ if (parentPort === null)
1049
+ throw new Error("Daemon navigation worker requires a parent port");
1050
+ var data = workerData;
1051
+ new DaemonNavigationWorkerEntry(parentPort, data).run();