ctxtop 0.0.0-stage → 4.1.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/.antigravity-plugin/plugin.json +36 -0
- package/.claude-plugin/plugin.json +18 -0
- package/CHECKSUMS.sha256 +166 -0
- package/LICENSE +27 -0
- package/README.md +350 -2
- package/SECURITY.md +22 -0
- package/agents/ah-flash-scout.md +25 -0
- package/assets/advanced_view_loaded_420px.png +0 -0
- package/assets/hero-demo.svg +188 -0
- package/assets/logo.svg +19 -0
- package/assets/simple_view_lean_420px.png +0 -0
- package/assets/simple_view_loaded_420px.png +0 -0
- package/assets/social-preview.svg +72 -0
- package/assets/zone_c_step3_shield_full.png +0 -0
- package/bin/ah-statusline.mjs +175 -0
- package/bin/cli.mjs +3 -0
- package/bin/ctxtop.mjs +1799 -0
- package/commands/cost-radar.md +11 -0
- package/commands/evolve.md +10 -0
- package/commands/handoff.md +10 -0
- package/commands/horizon.md +10 -0
- package/commands/inspect.md +10 -0
- package/commands/precheck.md +10 -0
- package/config/default_flightcheck.json +133 -0
- package/config/modelCatalog.json +785 -0
- package/config/platformQuirks.json +19 -0
- package/hooks/handlers/compact-lifecycle.mjs +577 -0
- package/hooks/handlers/config-change.mjs +402 -0
- package/hooks/handlers/hookIo.mjs +311 -0
- package/hooks/handlers/hookIpcClient.mjs +83 -0
- package/hooks/handlers/post-model-switch.mjs +111 -0
- package/hooks/handlers/post-tool-use.mjs +366 -0
- package/hooks/handlers/pre-model-switch.mjs +1048 -0
- package/hooks/handlers/pre-tool-use.mjs +632 -0
- package/hooks/handlers/stop-gate.mjs +526 -0
- package/hooks/handlers/user-prompt-submit.mjs +367 -0
- package/hooks/hooks.json +131 -0
- package/hooks/post_invocation.mjs +13 -0
- package/hooks/post_tool_use.mjs +25 -0
- package/hooks/pre_invocation.mjs +14 -0
- package/hooks/pre_tool_use.mjs +97 -0
- package/hooks/register.js +726 -0
- package/hooks/session_start.mjs +24 -0
- package/hooks/stop.mjs +23 -0
- package/hooks.json +56 -0
- package/package.json +110 -4
- package/packages/antigravity/package.json +14 -0
- package/packages/antigravity/src/index.mjs +1 -0
- package/packages/claude-code/package.json +14 -0
- package/packages/claude-code/src/index.mjs +2 -0
- package/packages/core/package.json +14 -0
- package/packages/core/src/index.mjs +1 -0
- package/packages/engine-node/package.json +14 -0
- package/packages/engine-node/src/index.mjs +1 -0
- package/packages/mcp/package.json +17 -0
- package/packages/mcp/src/server.mjs +396 -0
- package/packages/pro/LICENSE-COMMERCIAL.md +19 -0
- package/packages/pro/README-SIGNING.md +30 -0
- package/packages/pro/package.json +16 -0
- package/packages/pro/src/index.mjs +3 -0
- package/packages/pro/src/team_finops_pack.mjs +241 -0
- package/packages/pro/workers/polar_webhook_worker.mjs +215 -0
- package/plugin.json +36 -0
- package/rules/AGENTS.md +10 -0
- package/sidecars/horizon-daemon/ipcServer.mjs +24 -0
- package/sidecars/horizon-daemon/server.mjs +2038 -0
- package/sidecars/horizon-daemon/sidecar.json +19 -0
- package/skills/cost-radar/SKILL.md +21 -0
- package/skills/evolve/SKILL.md +21 -0
- package/skills/handoff/SKILL.md +50 -0
- package/skills/horizon/SKILL.md +17 -0
- package/skills/inspect/SKILL.md +18 -0
- package/skills/precheck/SKILL.md +44 -0
- package/src/adapters/antigravity/index.mjs +109 -0
- package/src/adapters/claude-code/index.mjs +194 -0
- package/src/cli/cost_radar.mjs +70 -0
- package/src/cli/doctor.mjs +351 -0
- package/src/cli/horizon_hud.mjs +888 -0
- package/src/cli/init.mjs +425 -0
- package/src/cli/postmortem.mjs +515 -0
- package/src/coach/cacheGravityRouter.mjs +12 -0
- package/src/config/modelCatalog.json +704 -0
- package/src/config/platformQuirks.json +19 -0
- package/src/core/action_queue.mjs +264 -0
- package/src/core/ag_bridge.mjs +346 -0
- package/src/core/atomic_io.mjs +124 -0
- package/src/core/baseline.mjs +607 -0
- package/src/core/blindspot_sensors.mjs +399 -0
- package/src/core/bucket_b_runtime.mjs +1200 -0
- package/src/core/classifier.mjs +1757 -0
- package/src/core/coach/circuit_breakers.mjs +650 -0
- package/src/core/coach/contradiction_auditor.mjs +239 -0
- package/src/core/coach/effort_advisor.mjs +143 -0
- package/src/core/coach/handoff_hydrator.mjs +483 -0
- package/src/core/coach/progressive_checkpointer.mjs +551 -0
- package/src/core/coach/prompt_decomposer_coach.mjs +141 -0
- package/src/core/coach/reflector_queue.mjs +505 -0
- package/src/core/coach/saved_quota_ledger.mjs +615 -0
- package/src/core/coach/subagent_ipi_sanitizer.mjs +200 -0
- package/src/core/coach/subagent_phantom_auditor.mjs +261 -0
- package/src/core/coach/task_quota_router.mjs +955 -0
- package/src/core/coach/turn_zero_gate.mjs +574 -0
- package/src/core/compaction_coach.mjs +1126 -0
- package/src/core/config.mjs +214 -0
- package/src/core/constants.mjs +1987 -0
- package/src/core/detectors_det01_to_16.mjs +1523 -0
- package/src/core/doc_indexer.mjs +338 -0
- package/src/core/episodic_memory.mjs +135 -0
- package/src/core/fts5_output_compressor.mjs +359 -0
- package/src/core/git_ledger.mjs +189 -0
- package/src/core/handoff_audit.mjs +558 -0
- package/src/core/history.mjs +221 -0
- package/src/core/hook_diagnostics.mjs +158 -0
- package/src/core/horizon_classifier.mjs +326 -0
- package/src/core/horizon_config.mjs +802 -0
- package/src/core/host_watchdog.mjs +200 -0
- package/src/core/layer5_hygiene.mjs +1084 -0
- package/src/core/log_resolver.mjs +231 -0
- package/src/core/mcp_auditor.mjs +138 -0
- package/src/core/micro_skills_store.mjs +91 -0
- package/src/core/offenders.mjs +161 -0
- package/src/core/parser.mjs +1997 -0
- package/src/core/path_canonicalizer.mjs +73 -0
- package/src/core/paths.mjs +311 -0
- package/src/core/prefix_cache_shield.mjs +386 -0
- package/src/core/pro_license.mjs +385 -0
- package/src/core/prompt_rubric.mjs +518 -0
- package/src/core/pruner.mjs +433 -0
- package/src/core/quota.mjs +1860 -0
- package/src/core/rsi_instinct_engine.mjs +1197 -0
- package/src/core/rsl_clash_auditor.mjs +423 -0
- package/src/core/rsl_distiller.mjs +372 -0
- package/src/core/rsl_ledger.mjs +969 -0
- package/src/core/rsl_triage.mjs +909 -0
- package/src/core/sanitizer.mjs +121 -0
- package/src/core/session_auditor.mjs +658 -0
- package/src/core/session_forensics.mjs +303 -0
- package/src/core/session_timeline.mjs +358 -0
- package/src/core/settings.mjs +99 -0
- package/src/core/shared/detectors.mjs +1342 -0
- package/src/core/shared/fnv1a64.mjs +85 -0
- package/src/core/shared/handoff_schema.mjs +123 -0
- package/src/core/shared/index.mjs +5 -0
- package/src/core/shared/ipi_sanitizer.mjs +165 -0
- package/src/core/shared/micro_skills.mjs +1 -0
- package/src/core/shared/plugin_validator.mjs +202 -0
- package/src/core/shared/prompt_hygiene_governor.mjs +1 -0
- package/src/core/shield_manager.mjs +1417 -0
- package/src/core/sidecar_store.mjs +302 -0
- package/src/core/sprint_metrics.mjs +366 -0
- package/src/core/sqlite_client.mjs +283 -0
- package/src/core/storage_doctor.mjs +358 -0
- package/src/core/subagents.mjs +609 -0
- package/src/core/swarm_topology.mjs +360 -0
- package/src/core/task_quota_router.mjs +1656 -0
- package/src/core/telemetry/cache_ttl_watchdog.mjs +284 -0
- package/src/core/telemetry/scope_lock_registry.mjs +578 -0
- package/src/core/telemetry/shadow_file_detector.mjs +291 -0
- package/src/core/telemetry/trajectory_watcher.mjs +259 -0
- package/src/core/timeline_svg.mjs +236 -0
- package/src/core/tool_surgeon.mjs +305 -0
- package/src/core/trajectory_stitcher.mjs +645 -0
- package/src/core/u_shaped_optimizer.mjs +789 -0
- package/src/core/wal_hygiene.mjs +233 -0
- package/src/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
- package/src/core-isomorphic/catalog/index.mjs +1 -0
- package/src/core-isomorphic/coach/cacheGravityRouter.mjs +1547 -0
- package/src/core-isomorphic/coach/microSkills.mjs +1 -0
- package/src/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
- package/src/core-isomorphic/coach/repoCalibration.mjs +254 -0
- package/src/core-isomorphic/coach/resumeToolsetAuditor.mjs +321 -0
- package/src/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
- package/src/core-isomorphic/coach/smartCompactAdvisor.mjs +305 -0
- package/src/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
- package/src/core-isomorphic/coach/ttlWatchdog.mjs +464 -0
- package/src/core-isomorphic/config/anthropicModelCatalog.json +606 -0
- package/src/core-isomorphic/config/catalogLoader.mjs +1268 -0
- package/src/core-isomorphic/config/horizonConfig.mjs +1055 -0
- package/src/core-isomorphic/control/callTree.mjs +338 -0
- package/src/core-isomorphic/control/coachLatches.mjs +126 -0
- package/src/core-isomorphic/control/controlStateMachine.mjs +205 -0
- package/src/core-isomorphic/control/index.mjs +49 -0
- package/src/core-isomorphic/control/swarmWorktree.mjs +109 -0
- package/src/core-isomorphic/control/toolSuspension.mjs +197 -0
- package/src/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
- package/src/core-isomorphic/diagnostics/index.mjs +9 -0
- package/src/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
- package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +888 -0
- package/src/core-isomorphic/economics/billingBlocks.mjs +251 -0
- package/src/core-isomorphic/economics/cacheGravity.mjs +369 -0
- package/src/core-isomorphic/economics/cliffBreaker.mjs +256 -0
- package/src/core-isomorphic/economics/driftLatency.mjs +433 -0
- package/src/core-isomorphic/economics/dualTtl.mjs +198 -0
- package/src/core-isomorphic/economics/index.mjs +47 -0
- package/src/core-isomorphic/economics/retentionRadar.mjs +348 -0
- package/src/core-isomorphic/guards/bucketBAlphaBeta.mjs +860 -0
- package/src/core-isomorphic/guards/bucketBGamma.mjs +442 -0
- package/src/core-isomorphic/guards/bucketBHeuristics.mjs +37 -0
- package/src/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
- package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +1184 -0
- package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +572 -0
- package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +913 -0
- package/src/core-isomorphic/guards/docIndexCore.mjs +446 -0
- package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +317 -0
- package/src/core-isomorphic/guards/slopsquatGate.mjs +551 -0
- package/src/core-isomorphic/index.js +27 -0
- package/src/core-isomorphic/telemetry/otelExporter.mjs +187 -0
- package/src/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
- package/src/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
- package/src/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
- package/src/core-isomorphic/telemetry/telemetryBridge.mjs +1156 -0
- package/src/core-isomorphic/ui/brailleSparkline.mjs +142 -0
- package/src/core-isomorphic/ui/costRadarSvg.mjs +276 -0
- package/src/core-isomorphic/ui/horizonGrid.mjs +475 -0
- package/src/core-isomorphic/ui/horizonPanelHtml.mjs +1237 -0
- package/src/core-isomorphic/ui/modViews.mjs +1504 -0
- package/src/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
- package/src/core-isomorphic/ustf/index.mjs +7 -0
- package/src/core-isomorphic/ustf/normalizer.mjs +512 -0
- package/src/core-isomorphic/ustf/schema.mjs +186 -0
- package/src/core-isomorphic/utils/runtime.mjs +962 -0
- package/src/demo/synthetic_states.mjs +661 -0
- package/src/diagnostics/bugReportGenerator.mjs +253 -0
- package/src/diagnostics/claudeHookCapabilities.mjs +396 -0
- package/src/diagnostics/doctorEngine.mjs +295 -0
- package/src/engine-node/db/index.mjs +58 -0
- package/src/engine-node/db/jsonl_fallback.mjs +184 -0
- package/src/engine-node/db/probe.mjs +342 -0
- package/src/engine-node/db/sqlite_wrapper.mjs +122 -0
- package/src/engine-node/index.mjs +12 -0
- package/src/engine-node/ipc/client.mjs +447 -0
- package/src/engine-node/ipc/index.mjs +22 -0
- package/src/engine-node/ipc/protocol.mjs +177 -0
- package/src/engine-node/ipc/server.mjs +445 -0
- package/src/engine-node/offloader/index.mjs +6 -0
- package/src/engine-node/offloader/tool_offloader.mjs +241 -0
- package/src/engine-node/sensors/blindspots.mjs +376 -0
- package/src/engine-node/sensors/git_merge_tree.mjs +223 -0
- package/src/engine-node/sensors/index.mjs +7 -0
- package/src/hooks/antigravity_rsl_hook.mjs +250 -0
- package/src/hooks/claude_rsl_hook.mjs +288 -0
- package/src/hooks/portfolio_runtime.mjs +858 -0
- package/src/hooks/post_invocation.mjs +611 -0
- package/src/hooks/pre_invocation.mjs +1725 -0
- package/src/hooks/session_start.mjs +199 -0
- package/src/shims/agy_cli_compressor.mjs +705 -0
- package/src/shims/agy_git_guard.mjs +749 -0
- package/src/shims/ah_log_query.mjs +39 -0
- package/src/ui/costRadarSvg.mjs +6 -0
- package/src/ui/horizonGrid.mjs +1 -0
- package/src/ui/horizonPanelHtml.mjs +1 -0
- package/src/ui/horizon_panel.css +167 -0
- package/src/ui/horizon_panel.js +212 -0
- package/src/ui/modViews.mjs +1 -0
- package/src/utils/modelSwitchTelemetry.mjs +308 -0
- package/src/utils/nodeIo.mjs +59 -0
- package/src/utils/runtime.mjs +1 -0
- package/src/utils/sessionCalibration.mjs +657 -0
- package/src/webview/advanced_view.html +1808 -0
- package/src/webview/horizon_panel.html +12397 -0
- package/src/webview/registry.mjs +80 -0
- package/src/webview/simple_view.html +1370 -0
|
@@ -0,0 +1,962 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/utils/runtime.mjs
|
|
3
|
+
* 100% Pure JavaScript ES module runtime utilities for Highbeam.
|
|
4
|
+
*
|
|
5
|
+
* Architectural Invariants (ISS-032 & ISS-022):
|
|
6
|
+
* - ZERO `node:*` imports, ZERO `require()`, ZERO dynamic `import()`, ZERO `process.getBuiltinModule()`.
|
|
7
|
+
* - Safe to load inside sandboxed V8 Mod isolates where `globalThis.process` is `undefined`
|
|
8
|
+
* as well as all Node.js >= 20.0.0 versions (`20.0.0` through `24.x`).
|
|
9
|
+
* - Provides pure-JS cross-platform POSIX/Win32 path manipulation (`joinPath`, `dirnamePath`,
|
|
10
|
+
* `basenamePath`, `isAbsolutePath`, `resolvePath`, `relativePath`, `normalizeSlashes`) and
|
|
11
|
+
* pure-JS deterministic hashing (`fnv1aHex`, FIPS 180-4 `sha256Hex`).
|
|
12
|
+
* - Tier-2 Node CLI entrypoints register a Node I/O adapter via `registerNodeIo(...)` (from
|
|
13
|
+
* `src/utils/nodeIo.mjs`), enabling Windows-safe atomic disk writes (`writeTextAtomic`,
|
|
14
|
+
* `writeJsonAtomic`) with `'utf8'`, `fsyncSync`, 5x bounded `EPERM`/`EBUSY`/`EACCES` rename
|
|
15
|
+
* retries, and guaranteed `.tmp` unlink cleanup on error.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
let registeredNodeIo = null;
|
|
19
|
+
|
|
20
|
+
const RETRYABLE_RENAME_CODES = new Set(['EPERM', 'EBUSY', 'EACCES']);
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Registers (or clears when `null`) the Tier-2 Node.js host I/O provider.
|
|
24
|
+
* Never called in sandboxed V8 Mod isolates where persistence uses `$.store`.
|
|
25
|
+
*
|
|
26
|
+
* @param {object | null} ioProvider
|
|
27
|
+
* @returns {object | null}
|
|
28
|
+
*/
|
|
29
|
+
export function registerNodeIo(ioProvider) {
|
|
30
|
+
registeredNodeIo = ioProvider || null;
|
|
31
|
+
return registeredNodeIo;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Resolves the active I/O provider from `options.io` or the registered Tier-2 provider.
|
|
36
|
+
*
|
|
37
|
+
* @param {object} [options={}]
|
|
38
|
+
* @returns {object | null}
|
|
39
|
+
*/
|
|
40
|
+
export function getNodeIo(options = {}) {
|
|
41
|
+
if (options && Object.prototype.hasOwnProperty.call(options, 'io')) {
|
|
42
|
+
return options.io || null;
|
|
43
|
+
}
|
|
44
|
+
return registeredNodeIo;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Detects whether the host environment uses Windows path conventions.
|
|
49
|
+
* Safe when `globalThis.process` is `undefined`.
|
|
50
|
+
*
|
|
51
|
+
* @param {string} [samplePath='']
|
|
52
|
+
* @returns {boolean}
|
|
53
|
+
*/
|
|
54
|
+
function isWindowsEnv(samplePath = '') {
|
|
55
|
+
if (/^[A-Za-z]:[\\/]/.test(samplePath) || samplePath.includes('\\')) {
|
|
56
|
+
return true;
|
|
57
|
+
}
|
|
58
|
+
return globalThis.process?.platform === 'win32';
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Normalizes all backslashes to forward slashes.
|
|
63
|
+
*
|
|
64
|
+
* @param {string} [rawPath='']
|
|
65
|
+
* @returns {string}
|
|
66
|
+
*/
|
|
67
|
+
export function normalizeSlashes(rawPath = '') {
|
|
68
|
+
return String(rawPath ?? '').replace(/\\/g, '/');
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Checks whether a path is absolute on POSIX (`/foo`) or Windows (`C:/foo`, `C:\foo`, `\\server\share`).
|
|
73
|
+
*
|
|
74
|
+
* @param {string} [rawPath='']
|
|
75
|
+
* @returns {boolean}
|
|
76
|
+
*/
|
|
77
|
+
export function isAbsolutePath(rawPath = '') {
|
|
78
|
+
const str = String(rawPath ?? '');
|
|
79
|
+
return /^(?:\/|[A-Za-z]:[\\/]|[\\/]{2})/.test(str);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Internal pure-JS path normalizer handling `.` and `..` across POSIX and Windows roots.
|
|
84
|
+
*
|
|
85
|
+
* @param {string} rawPosix
|
|
86
|
+
* @param {boolean} useWinSep
|
|
87
|
+
* @returns {string}
|
|
88
|
+
*/
|
|
89
|
+
function normalizeInternal(rawPosix, useWinSep) {
|
|
90
|
+
const sep = useWinSep ? '\\' : '/';
|
|
91
|
+
if (!rawPosix) return '.';
|
|
92
|
+
|
|
93
|
+
let root = '';
|
|
94
|
+
let rest = rawPosix;
|
|
95
|
+
|
|
96
|
+
const uncMatch = rawPosix.match(/^\/\/([^/]+)\/([^/]+)(?:\/(.*))?$/);
|
|
97
|
+
const driveMatch = !uncMatch ? rawPosix.match(/^([A-Za-z]:)(?:\/(.*))?$/) : null;
|
|
98
|
+
|
|
99
|
+
if (uncMatch) {
|
|
100
|
+
root = `//${uncMatch[1]}/${uncMatch[2]}/`;
|
|
101
|
+
rest = uncMatch[3] || '';
|
|
102
|
+
} else if (driveMatch) {
|
|
103
|
+
const hasSlash = rawPosix.length > 2 && rawPosix[2] === '/';
|
|
104
|
+
root = hasSlash ? `${driveMatch[1]}/` : driveMatch[1];
|
|
105
|
+
rest = driveMatch[2] || '';
|
|
106
|
+
} else if (rawPosix.startsWith('/')) {
|
|
107
|
+
root = '/';
|
|
108
|
+
rest = rawPosix.replace(/^\/+/, '');
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const isAbs = root === '/' || root.endsWith('/');
|
|
112
|
+
const rawParts = rest.split('/');
|
|
113
|
+
const resolved = [];
|
|
114
|
+
|
|
115
|
+
for (const part of rawParts) {
|
|
116
|
+
if (!part || part === '.') continue;
|
|
117
|
+
if (part === '..') {
|
|
118
|
+
if (resolved.length > 0 && resolved[resolved.length - 1] !== '..') {
|
|
119
|
+
resolved.pop();
|
|
120
|
+
} else if (!isAbs) {
|
|
121
|
+
resolved.push('..');
|
|
122
|
+
}
|
|
123
|
+
} else {
|
|
124
|
+
resolved.push(part);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const joined = resolved.join('/');
|
|
129
|
+
let result = '';
|
|
130
|
+
if (root) {
|
|
131
|
+
if (root.endsWith('/')) {
|
|
132
|
+
result = joined ? `${root}${joined}` : root;
|
|
133
|
+
} else {
|
|
134
|
+
result = joined ? `${root}/${joined}` : `${root}.`;
|
|
135
|
+
}
|
|
136
|
+
} else {
|
|
137
|
+
result = joined || '.';
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
return useWinSep ? result.replace(/\//g, sep) : result;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Pure-JS cross-platform `path.join` implementation.
|
|
145
|
+
*
|
|
146
|
+
* @param {...string} parts
|
|
147
|
+
* @returns {string}
|
|
148
|
+
*/
|
|
149
|
+
export function joinPath(...parts) {
|
|
150
|
+
const valid = [];
|
|
151
|
+
let winHint = globalThis.process?.platform === 'win32';
|
|
152
|
+
for (const p of parts) {
|
|
153
|
+
if (p === undefined || p === null) continue;
|
|
154
|
+
const s = String(p);
|
|
155
|
+
if (!s) continue;
|
|
156
|
+
if (/^[A-Za-z]:[\\/]/.test(s) || s.includes('\\')) {
|
|
157
|
+
winHint = true;
|
|
158
|
+
}
|
|
159
|
+
valid.push(normalizeSlashes(s));
|
|
160
|
+
}
|
|
161
|
+
if (valid.length === 0) return '.';
|
|
162
|
+
|
|
163
|
+
let combined = valid[0];
|
|
164
|
+
for (let i = 1; i < valid.length; i++) {
|
|
165
|
+
const seg = valid[i].replace(/^\/+/, '');
|
|
166
|
+
if (!seg) continue;
|
|
167
|
+
combined = combined.endsWith('/') ? `${combined}${seg}` : `${combined}/${seg}`;
|
|
168
|
+
}
|
|
169
|
+
return normalizeInternal(combined, winHint);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Resolves the active working directory safely without throwing in V8 isolates.
|
|
174
|
+
*
|
|
175
|
+
* @param {object} [options={}]
|
|
176
|
+
* @returns {string}
|
|
177
|
+
*/
|
|
178
|
+
export function getCwd(options = {}) {
|
|
179
|
+
if (typeof options?.cwd === 'string' && options.cwd.trim()) {
|
|
180
|
+
return options.cwd.trim();
|
|
181
|
+
}
|
|
182
|
+
const io = getNodeIo(options);
|
|
183
|
+
if (typeof io?.cwd === 'function') {
|
|
184
|
+
const c = io.cwd();
|
|
185
|
+
if (c) return c;
|
|
186
|
+
}
|
|
187
|
+
if (typeof globalThis.process?.cwd === 'function') {
|
|
188
|
+
try {
|
|
189
|
+
return globalThis.process.cwd();
|
|
190
|
+
} catch {
|
|
191
|
+
return '.';
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
return '.';
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Resolves the user home directory safely when available.
|
|
199
|
+
*
|
|
200
|
+
* @param {object} [options={}]
|
|
201
|
+
* @returns {string}
|
|
202
|
+
*/
|
|
203
|
+
export function getHomeDir(options = {}) {
|
|
204
|
+
if (typeof options?.homeDir === 'string' && options.homeDir.trim()) {
|
|
205
|
+
return options.homeDir.trim();
|
|
206
|
+
}
|
|
207
|
+
const io = getNodeIo(options);
|
|
208
|
+
if (typeof io?.os?.homedir === 'function') {
|
|
209
|
+
try {
|
|
210
|
+
return io.os.homedir() || '';
|
|
211
|
+
} catch {
|
|
212
|
+
return '';
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
const env = globalThis.process?.env;
|
|
216
|
+
if (env) {
|
|
217
|
+
return env.HOME || env.USERPROFILE || '';
|
|
218
|
+
}
|
|
219
|
+
return '';
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Pure-JS cross-platform `path.resolve` implementation.
|
|
224
|
+
*
|
|
225
|
+
* @param {...string} parts
|
|
226
|
+
* @returns {string}
|
|
227
|
+
*/
|
|
228
|
+
export function resolvePath(...parts) {
|
|
229
|
+
let resolvedPosix = '';
|
|
230
|
+
let hitAbs = false;
|
|
231
|
+
let winHint = globalThis.process?.platform === 'win32';
|
|
232
|
+
|
|
233
|
+
for (let i = parts.length - 1; i >= 0; i--) {
|
|
234
|
+
const raw = parts[i];
|
|
235
|
+
if (raw === undefined || raw === null || raw === '') continue;
|
|
236
|
+
const s = String(raw);
|
|
237
|
+
if (/^[A-Za-z]:[\\/]/.test(s) || s.includes('\\')) {
|
|
238
|
+
winHint = true;
|
|
239
|
+
}
|
|
240
|
+
const norm = normalizeSlashes(s);
|
|
241
|
+
resolvedPosix = resolvedPosix ? `${norm}/${resolvedPosix}` : norm;
|
|
242
|
+
if (isAbsolutePath(s)) {
|
|
243
|
+
hitAbs = true;
|
|
244
|
+
break;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
if (!hitAbs) {
|
|
249
|
+
const cwd = getCwd();
|
|
250
|
+
if (/^[A-Za-z]:[\\/]/.test(cwd) || cwd.includes('\\')) {
|
|
251
|
+
winHint = true;
|
|
252
|
+
}
|
|
253
|
+
const normCwd = normalizeSlashes(cwd);
|
|
254
|
+
resolvedPosix = resolvedPosix ? `${normCwd}/${resolvedPosix}` : normCwd;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
return normalizeInternal(resolvedPosix, winHint);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Pure-JS cross-platform `path.dirname` implementation.
|
|
262
|
+
*
|
|
263
|
+
* @param {string} [targetPath='']
|
|
264
|
+
* @returns {string}
|
|
265
|
+
*/
|
|
266
|
+
export function dirnamePath(targetPath = '') {
|
|
267
|
+
const raw = String(targetPath ?? '');
|
|
268
|
+
if (!raw) return '.';
|
|
269
|
+
const win = isWindowsEnv(raw);
|
|
270
|
+
const sep = win ? '\\' : '/';
|
|
271
|
+
const norm = normalizeSlashes(raw).replace(/\/+$/, '');
|
|
272
|
+
|
|
273
|
+
if (!norm) {
|
|
274
|
+
return raw.startsWith('/') || raw.startsWith('\\') ? sep : '.';
|
|
275
|
+
}
|
|
276
|
+
if (/^[A-Za-z]:$/.test(norm)) {
|
|
277
|
+
return `${norm}${sep}`;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
const lastSlash = norm.lastIndexOf('/');
|
|
281
|
+
if (lastSlash === -1) return '.';
|
|
282
|
+
if (lastSlash === 0) return sep;
|
|
283
|
+
|
|
284
|
+
const parent = norm.slice(0, lastSlash);
|
|
285
|
+
if (/^[A-Za-z]:$/.test(parent)) {
|
|
286
|
+
return `${parent}${sep}`;
|
|
287
|
+
}
|
|
288
|
+
return win ? parent.replace(/\//g, sep) : parent;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* Pure-JS cross-platform `path.basename` implementation.
|
|
293
|
+
*
|
|
294
|
+
* @param {string} [targetPath='']
|
|
295
|
+
* @param {string} [ext='']
|
|
296
|
+
* @returns {string}
|
|
297
|
+
*/
|
|
298
|
+
export function basenamePath(targetPath = '', ext = '') {
|
|
299
|
+
const norm = normalizeSlashes(String(targetPath ?? '')).replace(/\/+$/, '');
|
|
300
|
+
if (!norm) return '';
|
|
301
|
+
const idx = norm.lastIndexOf('/');
|
|
302
|
+
const base = idx === -1 ? norm : norm.slice(idx + 1);
|
|
303
|
+
if (ext && base.endsWith(ext)) {
|
|
304
|
+
return base.slice(0, base.length - ext.length);
|
|
305
|
+
}
|
|
306
|
+
return base;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* Pure-JS cross-platform `path.relative` implementation.
|
|
311
|
+
*
|
|
312
|
+
* @param {string} [from='']
|
|
313
|
+
* @param {string} [to='']
|
|
314
|
+
* @returns {string}
|
|
315
|
+
*/
|
|
316
|
+
export function relativePath(from = '', to = '') {
|
|
317
|
+
const win = isWindowsEnv(from) || isWindowsEnv(to);
|
|
318
|
+
const sep = win ? '\\' : '/';
|
|
319
|
+
const absFrom = normalizeSlashes(resolvePath(from)).replace(/\/+$/, '');
|
|
320
|
+
const absTo = normalizeSlashes(resolvePath(to)).replace(/\/+$/, '');
|
|
321
|
+
|
|
322
|
+
const cmpFrom = win ? absFrom.toLowerCase() : absFrom;
|
|
323
|
+
const cmpTo = win ? absTo.toLowerCase() : absTo;
|
|
324
|
+
if (cmpFrom === cmpTo) return '';
|
|
325
|
+
|
|
326
|
+
const fromDrive = cmpFrom.match(/^[a-z]:/)?.[0] || '';
|
|
327
|
+
const toDrive = cmpTo.match(/^[a-z]:/)?.[0] || '';
|
|
328
|
+
if (fromDrive !== toDrive) {
|
|
329
|
+
return win ? absTo.replace(/\//g, sep) : absTo;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
const fromParts = absFrom.replace(/^[A-Za-z]:\/?|^\/+/, '').split('/').filter(Boolean);
|
|
333
|
+
const toParts = absTo.replace(/^[A-Za-z]:\/?|^\/+/, '').split('/').filter(Boolean);
|
|
334
|
+
const cmpFromParts = win ? fromParts.map((s) => s.toLowerCase()) : fromParts;
|
|
335
|
+
const cmpToParts = win ? toParts.map((s) => s.toLowerCase()) : toParts;
|
|
336
|
+
|
|
337
|
+
let common = 0;
|
|
338
|
+
while (
|
|
339
|
+
common < cmpFromParts.length &&
|
|
340
|
+
common < cmpToParts.length &&
|
|
341
|
+
cmpFromParts[common] === cmpToParts[common]
|
|
342
|
+
) {
|
|
343
|
+
common += 1;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
const upMoves = new Array(fromParts.length - common).fill('..');
|
|
347
|
+
const downMoves = toParts.slice(common);
|
|
348
|
+
return [...upMoves, ...downMoves].join(sep);
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* Pure-JS `file://` URL to filesystem path converter.
|
|
353
|
+
*
|
|
354
|
+
* @param {string} [fileUrl='']
|
|
355
|
+
* @param {object} [options={}]
|
|
356
|
+
* @returns {string | null}
|
|
357
|
+
*/
|
|
358
|
+
export function fileUrlToPathPure(fileUrl = '', options = {}) {
|
|
359
|
+
const io = getNodeIo(options);
|
|
360
|
+
if (typeof io?.url?.fileURLToPath === 'function') {
|
|
361
|
+
try {
|
|
362
|
+
return io.url.fileURLToPath(fileUrl);
|
|
363
|
+
} catch {
|
|
364
|
+
return null;
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
const str = String(fileUrl || '');
|
|
368
|
+
if (!str.startsWith('file://')) return null;
|
|
369
|
+
try {
|
|
370
|
+
let pathname = decodeURIComponent(str.slice('file://'.length));
|
|
371
|
+
if (/^\/[A-Za-z]:\//.test(pathname)) {
|
|
372
|
+
pathname = pathname.slice(1).replace(/\//g, '\\');
|
|
373
|
+
}
|
|
374
|
+
return pathname;
|
|
375
|
+
} catch {
|
|
376
|
+
return null;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* Pure-JS path namespace object providing drop-in `join`, `dirname`, `basename`,
|
|
382
|
+
* `isAbsolute`, `resolve`, and `relative` methods in every environment.
|
|
383
|
+
*/
|
|
384
|
+
export const path = Object.freeze({
|
|
385
|
+
join: joinPath,
|
|
386
|
+
dirname: dirnamePath,
|
|
387
|
+
basename: basenamePath,
|
|
388
|
+
isAbsolute: isAbsolutePath,
|
|
389
|
+
resolve: resolvePath,
|
|
390
|
+
relative: relativePath
|
|
391
|
+
});
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* Fast deterministic 32-bit FNV-1a hex digest (pure JS).
|
|
395
|
+
*
|
|
396
|
+
* @param {string} [input='']
|
|
397
|
+
* @returns {string}
|
|
398
|
+
*/
|
|
399
|
+
export function fnv1aHex(input = '') {
|
|
400
|
+
let h = 0x811c9dc5;
|
|
401
|
+
const s = String(input ?? '');
|
|
402
|
+
for (let i = 0; i < s.length; i++) {
|
|
403
|
+
h ^= s.charCodeAt(i);
|
|
404
|
+
h = Math.imul(h, 0x01000193);
|
|
405
|
+
}
|
|
406
|
+
return (h >>> 0).toString(16).padStart(8, '0');
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
const SHA256_K = new Uint32Array([
|
|
410
|
+
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
|
411
|
+
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
|
412
|
+
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
|
413
|
+
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
|
414
|
+
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
|
415
|
+
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
|
416
|
+
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
|
417
|
+
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
|
|
418
|
+
]);
|
|
419
|
+
|
|
420
|
+
/**
|
|
421
|
+
* Encodes a UTF-16 JS string into UTF-8 bytes without requiring Node `Buffer`.
|
|
422
|
+
*
|
|
423
|
+
* @param {string} str
|
|
424
|
+
* @returns {Uint8Array}
|
|
425
|
+
*/
|
|
426
|
+
function encodeUtf8Bytes(str) {
|
|
427
|
+
if (typeof TextEncoder === 'function') {
|
|
428
|
+
return new TextEncoder().encode(str);
|
|
429
|
+
}
|
|
430
|
+
const bytes = [];
|
|
431
|
+
for (let i = 0; i < str.length; i++) {
|
|
432
|
+
let code = str.charCodeAt(i);
|
|
433
|
+
if (code >= 0xd800 && code <= 0xdbff && i + 1 < str.length) {
|
|
434
|
+
const low = str.charCodeAt(i + 1);
|
|
435
|
+
if (low >= 0xdc00 && low <= 0xdfff) {
|
|
436
|
+
code = ((code - 0xd800) << 10) + (low - 0xdc00) + 0x10000;
|
|
437
|
+
i += 1;
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
if (code < 0x80) {
|
|
441
|
+
bytes.push(code);
|
|
442
|
+
} else if (code < 0x800) {
|
|
443
|
+
bytes.push(0xc0 | (code >> 6), 0x80 | (code & 0x3f));
|
|
444
|
+
} else if (code < 0x10000) {
|
|
445
|
+
bytes.push(0xe0 | (code >> 12), 0x80 | ((code >> 6) & 0x3f), 0x80 | (code & 0x3f));
|
|
446
|
+
} else {
|
|
447
|
+
bytes.push(
|
|
448
|
+
0xf0 | (code >> 18),
|
|
449
|
+
0x80 | ((code >> 12) & 0x3f),
|
|
450
|
+
0x80 | ((code >> 6) & 0x3f),
|
|
451
|
+
0x80 | (code & 0x3f)
|
|
452
|
+
);
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
return new Uint8Array(bytes);
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/**
|
|
459
|
+
* Computes an exact FIPS 180-4 SHA-256 hex digest in pure JavaScript (with optional acceleration
|
|
460
|
+
* when a Tier-2 Node `crypto` adapter is registered).
|
|
461
|
+
*
|
|
462
|
+
* @param {string} [content='']
|
|
463
|
+
* @param {object} [options={}]
|
|
464
|
+
* @returns {string}
|
|
465
|
+
*/
|
|
466
|
+
export function sha256Hex(content = '', options = {}) {
|
|
467
|
+
const str = String(content ?? '');
|
|
468
|
+
const io = getNodeIo(options);
|
|
469
|
+
if (typeof io?.crypto?.createHash === 'function') {
|
|
470
|
+
return io.crypto.createHash('sha256').update(str, 'utf8').digest('hex');
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
const msg = encodeUtf8Bytes(str);
|
|
474
|
+
const bitLenHi = Math.floor((msg.length * 8) / 0x100000000);
|
|
475
|
+
const bitLenLo = (msg.length * 8) >>> 0;
|
|
476
|
+
const padLen = ((msg.length + 9 + 63) & ~63);
|
|
477
|
+
const padded = new Uint8Array(padLen);
|
|
478
|
+
padded.set(msg);
|
|
479
|
+
padded[msg.length] = 0x80;
|
|
480
|
+
const view = new DataView(padded.buffer);
|
|
481
|
+
view.setUint32(padLen - 8, bitLenHi, false);
|
|
482
|
+
view.setUint32(padLen - 4, bitLenLo, false);
|
|
483
|
+
|
|
484
|
+
let h0 = 0x6a09e667;
|
|
485
|
+
let h1 = 0xbb67ae85;
|
|
486
|
+
let h2 = 0x3c6ef372;
|
|
487
|
+
let h3 = 0xa54ff53a;
|
|
488
|
+
let h4 = 0x510e527f;
|
|
489
|
+
let h5 = 0x9b05688c;
|
|
490
|
+
let h6 = 0x1f83d9ab;
|
|
491
|
+
let h7 = 0x5be0cd19;
|
|
492
|
+
|
|
493
|
+
const w = new Uint32Array(64);
|
|
494
|
+
const rotr = (x, n) => (x >>> n) | (x << (32 - n));
|
|
495
|
+
|
|
496
|
+
for (let offset = 0; offset < padLen; offset += 64) {
|
|
497
|
+
for (let i = 0; i < 16; i++) {
|
|
498
|
+
w[i] = view.getUint32(offset + i * 4, false);
|
|
499
|
+
}
|
|
500
|
+
for (let i = 16; i < 64; i++) {
|
|
501
|
+
const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >>> 3);
|
|
502
|
+
const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >>> 10);
|
|
503
|
+
w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0;
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
let a = h0;
|
|
507
|
+
let b = h1;
|
|
508
|
+
let c = h2;
|
|
509
|
+
let d = h3;
|
|
510
|
+
let e = h4;
|
|
511
|
+
let f = h5;
|
|
512
|
+
let g = h6;
|
|
513
|
+
let h = h7;
|
|
514
|
+
|
|
515
|
+
for (let i = 0; i < 64; i++) {
|
|
516
|
+
const S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
|
|
517
|
+
const ch = (e & f) ^ (~e & g);
|
|
518
|
+
const temp1 = (h + S1 + ch + SHA256_K[i] + w[i]) >>> 0;
|
|
519
|
+
const S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
|
|
520
|
+
const maj = (a & b) ^ (a & c) ^ (b & c);
|
|
521
|
+
const temp2 = (S0 + maj) >>> 0;
|
|
522
|
+
|
|
523
|
+
h = g;
|
|
524
|
+
g = f;
|
|
525
|
+
f = e;
|
|
526
|
+
e = (d + temp1) >>> 0;
|
|
527
|
+
d = c;
|
|
528
|
+
c = b;
|
|
529
|
+
b = a;
|
|
530
|
+
a = (temp1 + temp2) >>> 0;
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
h0 = (h0 + a) >>> 0;
|
|
534
|
+
h1 = (h1 + b) >>> 0;
|
|
535
|
+
h2 = (h2 + c) >>> 0;
|
|
536
|
+
h3 = (h3 + d) >>> 0;
|
|
537
|
+
h4 = (h4 + e) >>> 0;
|
|
538
|
+
h5 = (h5 + f) >>> 0;
|
|
539
|
+
h6 = (h6 + g) >>> 0;
|
|
540
|
+
h7 = (h7 + h) >>> 0;
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
return [h0, h1, h2, h3, h4, h5, h6, h7]
|
|
544
|
+
.map((v) => v.toString(16).padStart(8, '0'))
|
|
545
|
+
.join('');
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
/**
|
|
549
|
+
* Checks whether a file exists via the registered Tier-2 Node `fs` provider.
|
|
550
|
+
* Returns `false` cleanly in pure V8 Mod isolates.
|
|
551
|
+
*
|
|
552
|
+
* @param {string} targetPath
|
|
553
|
+
* @param {object} [options={}]
|
|
554
|
+
* @returns {boolean}
|
|
555
|
+
*/
|
|
556
|
+
export function fileExists(targetPath, options = {}) {
|
|
557
|
+
const fsMod = getNodeIo(options)?.fs;
|
|
558
|
+
if (!fsMod || !targetPath) return false;
|
|
559
|
+
try {
|
|
560
|
+
return Boolean(fsMod.existsSync(targetPath));
|
|
561
|
+
} catch {
|
|
562
|
+
return false;
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
/**
|
|
567
|
+
* Safely returns the byte size of a file on disk via the registered Tier-2 Node `fs` provider.
|
|
568
|
+
* Returns `0` cleanly in pure V8 Mod isolates or when the file does not exist (`ISS-024`).
|
|
569
|
+
*
|
|
570
|
+
* @param {string} targetPath
|
|
571
|
+
* @param {object} [options={}]
|
|
572
|
+
* @returns {number}
|
|
573
|
+
*/
|
|
574
|
+
export function getFileByteSizeSafe(targetPath, options = {}) {
|
|
575
|
+
const fsMod = getNodeIo(options)?.fs;
|
|
576
|
+
if (!fsMod || typeof fsMod.statSync !== 'function' || !targetPath) return 0;
|
|
577
|
+
try {
|
|
578
|
+
if (!fsMod.existsSync(targetPath)) return 0;
|
|
579
|
+
const st = fsMod.statSync(targetPath);
|
|
580
|
+
return st && st.isFile?.() !== false && Number(st.size) > 0 ? Number(st.size) : 0;
|
|
581
|
+
} catch {
|
|
582
|
+
return 0;
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
/**
|
|
587
|
+
* Safely returns the modification timestamp (`mtimeMs`) of a file on disk via the registered
|
|
588
|
+
* Tier-2 Node `fs` provider. Returns `0` cleanly in pure V8 Mod isolates or when missing.
|
|
589
|
+
*
|
|
590
|
+
* @param {string} targetPath
|
|
591
|
+
* @param {object} [options={}]
|
|
592
|
+
* @returns {number}
|
|
593
|
+
*/
|
|
594
|
+
export function getFileMtimeMsSafe(targetPath, options = {}) {
|
|
595
|
+
const fsMod = getNodeIo(options)?.fs;
|
|
596
|
+
if (!fsMod || typeof fsMod.statSync !== 'function' || !targetPath) return 0;
|
|
597
|
+
try {
|
|
598
|
+
if (!fsMod.existsSync(targetPath)) return 0;
|
|
599
|
+
const st = fsMod.statSync(targetPath);
|
|
600
|
+
return st && st.isFile?.() !== false && Number(st.mtimeMs) > 0 ? Number(st.mtimeMs) : 0;
|
|
601
|
+
} catch {
|
|
602
|
+
return 0;
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
/**
|
|
607
|
+
* Safely lists filenames inside a directory via the registered Tier-2 Node `fs` provider.
|
|
608
|
+
* Returns `[]` cleanly in pure V8 Mod isolates or when the directory does not exist.
|
|
609
|
+
*
|
|
610
|
+
* @param {string} dirPath
|
|
611
|
+
* @param {object} [options={}]
|
|
612
|
+
* @returns {string[]}
|
|
613
|
+
*/
|
|
614
|
+
export function readdirSafe(dirPath, options = {}) {
|
|
615
|
+
const fsMod = getNodeIo(options)?.fs;
|
|
616
|
+
if (!fsMod || typeof fsMod.readdirSync !== 'function' || !dirPath) return [];
|
|
617
|
+
try {
|
|
618
|
+
if (!fsMod.existsSync(dirPath)) return [];
|
|
619
|
+
const entries = fsMod.readdirSync(dirPath);
|
|
620
|
+
return Array.isArray(entries) ? entries.map((e) => String(e)) : [];
|
|
621
|
+
} catch {
|
|
622
|
+
return [];
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
/**
|
|
627
|
+
* Deletes a file safely if it exists.
|
|
628
|
+
*
|
|
629
|
+
* @param {string} targetPath
|
|
630
|
+
* @param {object} [options={}]
|
|
631
|
+
* @returns {boolean}
|
|
632
|
+
*/
|
|
633
|
+
export function unlinkSafe(targetPath, options = {}) {
|
|
634
|
+
const fsMod = getNodeIo(options)?.fs;
|
|
635
|
+
if (!fsMod) return false;
|
|
636
|
+
try {
|
|
637
|
+
if (fsMod.existsSync(targetPath)) {
|
|
638
|
+
fsMod.unlinkSync(targetPath);
|
|
639
|
+
}
|
|
640
|
+
return true;
|
|
641
|
+
} catch {
|
|
642
|
+
return false;
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
/**
|
|
647
|
+
* Safely reads UTF-8 text from disk via the registered Node `fs` provider.
|
|
648
|
+
*
|
|
649
|
+
* @param {string} targetPath
|
|
650
|
+
* @param {string | null} [fallback=null]
|
|
651
|
+
* @param {object} [options={}]
|
|
652
|
+
* @returns {string | null}
|
|
653
|
+
*/
|
|
654
|
+
export function readTextSafe(targetPath, fallback = null, options = {}) {
|
|
655
|
+
const fsMod = getNodeIo(options)?.fs;
|
|
656
|
+
if (!fsMod || !targetPath) return fallback;
|
|
657
|
+
try {
|
|
658
|
+
if (!fsMod.existsSync(targetPath)) return fallback;
|
|
659
|
+
return fsMod.readFileSync(targetPath, 'utf8');
|
|
660
|
+
} catch {
|
|
661
|
+
return fallback;
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
/**
|
|
666
|
+
* Atomically writes UTF-8 text to disk (`ISS-022`):
|
|
667
|
+
* - Uses `${targetPath}.tmp.${pid}.${Date.now()}.${rand}`
|
|
668
|
+
* - Explicit `'utf8'` encoding + `fs.fsyncSync(fd)` before `closeSync`
|
|
669
|
+
* - 5x bounded retry on Windows `EPERM` / `EBUSY` / `EACCES` lock contention
|
|
670
|
+
* - Guaranteed `unlinkSync(tempPath)` cleanup on any write/rename failure
|
|
671
|
+
*
|
|
672
|
+
* @param {string} targetPath
|
|
673
|
+
* @param {string} content
|
|
674
|
+
* @param {object} [options={}]
|
|
675
|
+
* @returns {boolean}
|
|
676
|
+
*/
|
|
677
|
+
export function writeTextAtomic(targetPath, content, options = {}) {
|
|
678
|
+
const fsMod = getNodeIo(options)?.fs;
|
|
679
|
+
if (!fsMod || !targetPath) return false;
|
|
680
|
+
|
|
681
|
+
const pid = globalThis.process?.pid || 0;
|
|
682
|
+
const rand = Math.random().toString(36).slice(2, 8);
|
|
683
|
+
const tempPath = `${targetPath}.tmp.${pid}.${Date.now()}.${rand}`;
|
|
684
|
+
|
|
685
|
+
try {
|
|
686
|
+
const dir = dirnamePath(targetPath);
|
|
687
|
+
if (dir && dir !== '.' && !fsMod.existsSync(dir)) {
|
|
688
|
+
fsMod.mkdirSync(dir, { recursive: true });
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
if (typeof fsMod.openSync === 'function' && typeof fsMod.fsyncSync === 'function') {
|
|
692
|
+
const fd = fsMod.openSync(tempPath, 'w');
|
|
693
|
+
try {
|
|
694
|
+
fsMod.writeFileSync(fd, String(content ?? ''), 'utf8');
|
|
695
|
+
fsMod.fsyncSync(fd);
|
|
696
|
+
} finally {
|
|
697
|
+
try {
|
|
698
|
+
fsMod.closeSync(fd);
|
|
699
|
+
} catch {
|
|
700
|
+
// Ignore close error
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
} else {
|
|
704
|
+
fsMod.writeFileSync(tempPath, String(content ?? ''), 'utf8');
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
for (let attempt = 0; attempt < 5; attempt++) {
|
|
708
|
+
try {
|
|
709
|
+
fsMod.renameSync(tempPath, targetPath);
|
|
710
|
+
return true;
|
|
711
|
+
} catch (err) {
|
|
712
|
+
if (!RETRYABLE_RENAME_CODES.has(err?.code) || attempt === 4) {
|
|
713
|
+
throw err;
|
|
714
|
+
}
|
|
715
|
+
try {
|
|
716
|
+
if (typeof SharedArrayBuffer === 'function' && typeof Atomics?.wait === 'function') {
|
|
717
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, (attempt + 1) * 4);
|
|
718
|
+
}
|
|
719
|
+
} catch {
|
|
720
|
+
// Ignore if SharedArrayBuffer is unavailable
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
return true;
|
|
725
|
+
} catch {
|
|
726
|
+
try {
|
|
727
|
+
if (fsMod.existsSync(tempPath)) {
|
|
728
|
+
fsMod.unlinkSync(tempPath);
|
|
729
|
+
}
|
|
730
|
+
} catch {
|
|
731
|
+
// Ignore temp cleanup error
|
|
732
|
+
}
|
|
733
|
+
return false;
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
/**
|
|
738
|
+
* Atomically writes a JSON payload to disk via `writeTextAtomic`.
|
|
739
|
+
*
|
|
740
|
+
* @param {string} targetPath
|
|
741
|
+
* @param {unknown} data
|
|
742
|
+
* @param {object} [options={}]
|
|
743
|
+
* @returns {boolean}
|
|
744
|
+
*/
|
|
745
|
+
export function writeJsonAtomic(targetPath, data, options = {}) {
|
|
746
|
+
try {
|
|
747
|
+
const serialized = JSON.stringify(data, null, 2);
|
|
748
|
+
return writeTextAtomic(targetPath, serialized, options);
|
|
749
|
+
} catch {
|
|
750
|
+
return false;
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
/**
|
|
755
|
+
* Safely reads and parses a JSON file from disk.
|
|
756
|
+
*
|
|
757
|
+
* @param {string} targetPath
|
|
758
|
+
* @param {any} [fallback=null]
|
|
759
|
+
* @param {object} [options={}]
|
|
760
|
+
* @returns {any}
|
|
761
|
+
*/
|
|
762
|
+
export function readJsonSafe(targetPath, fallback = null, options = {}) {
|
|
763
|
+
const raw = readTextSafe(targetPath, null, options);
|
|
764
|
+
if (raw === null) return fallback;
|
|
765
|
+
try {
|
|
766
|
+
return JSON.parse(raw);
|
|
767
|
+
} catch {
|
|
768
|
+
return fallback;
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
/**
|
|
773
|
+
* Safely appends a JSONL record to an append-only file using `'utf8'`.
|
|
774
|
+
*
|
|
775
|
+
* @param {string} targetPath
|
|
776
|
+
* @param {object} record
|
|
777
|
+
* @param {object} [options={}]
|
|
778
|
+
* @returns {boolean}
|
|
779
|
+
*/
|
|
780
|
+
export function appendJsonlSafe(targetPath, record, options = {}) {
|
|
781
|
+
const fsMod = getNodeIo(options)?.fs;
|
|
782
|
+
if (!fsMod || !targetPath) return false;
|
|
783
|
+
try {
|
|
784
|
+
const dir = dirnamePath(targetPath);
|
|
785
|
+
if (dir && dir !== '.' && !fsMod.existsSync(dir)) {
|
|
786
|
+
fsMod.mkdirSync(dir, { recursive: true });
|
|
787
|
+
}
|
|
788
|
+
fsMod.appendFileSync(targetPath, `${JSON.stringify(record)}\n`, 'utf8');
|
|
789
|
+
return true;
|
|
790
|
+
} catch {
|
|
791
|
+
return false;
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
export const MAX_RUNTIME_DIAGNOSTIC_ENTRIES = 50;
|
|
796
|
+
|
|
797
|
+
const inMemoryDiagnosticsRing = [];
|
|
798
|
+
|
|
799
|
+
/**
|
|
800
|
+
* Redacts the user home directory from diagnostic messages in pure JavaScript.
|
|
801
|
+
*
|
|
802
|
+
* @param {string} text
|
|
803
|
+
* @param {object} [options={}]
|
|
804
|
+
* @returns {string}
|
|
805
|
+
*/
|
|
806
|
+
function redactDiagnosticHomePath(text, options = {}) {
|
|
807
|
+
const raw = String(text ?? '');
|
|
808
|
+
const home = getHomeDir(options);
|
|
809
|
+
if (!home) return raw;
|
|
810
|
+
const escapeRx = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
811
|
+
const winHome = home.replace(/\//g, '\\');
|
|
812
|
+
const posixHome = home.replace(/\\/g, '/');
|
|
813
|
+
let out = raw;
|
|
814
|
+
if (winHome) {
|
|
815
|
+
out = out.replace(new RegExp(escapeRx(winHome), 'gi'), '~');
|
|
816
|
+
}
|
|
817
|
+
if (posixHome && posixHome !== winHome) {
|
|
818
|
+
out = out.replace(new RegExp(escapeRx(posixHome), 'gi'), '~');
|
|
819
|
+
}
|
|
820
|
+
return out;
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
/**
|
|
824
|
+
* Resolves `<cwd>/.claude/cache/ah_diagnostics.jsonl` (or `options.diagnosticsPath`).
|
|
825
|
+
*
|
|
826
|
+
* @param {object} [options={}]
|
|
827
|
+
* @returns {string}
|
|
828
|
+
*/
|
|
829
|
+
export function getDiagnosticsFilePath(options = {}) {
|
|
830
|
+
if (typeof options?.diagnosticsPath === 'string' && options.diagnosticsPath.trim()) {
|
|
831
|
+
return options.diagnosticsPath.trim();
|
|
832
|
+
}
|
|
833
|
+
const cwd = getCwd(options);
|
|
834
|
+
return joinPath(cwd, '.claude', 'cache', 'ah_diagnostics.jsonl');
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
/**
|
|
838
|
+
* Records a structured non-fatal runtime diagnostic into the bounded 50-entry in-memory ring
|
|
839
|
+
* buffer and (when Tier-2 disk I/O is active AND an explicit `cwd` or `diagnosticsPath` is
|
|
840
|
+
* supplied) atomically maintains a bounded 50-line JSONL ring buffer at
|
|
841
|
+
* `<cwd>/.claude/cache/ah_diagnostics.jsonl`. Never writes to `stdout` (`ISS-065`).
|
|
842
|
+
*
|
|
843
|
+
* @param {string} source
|
|
844
|
+
* @param {string} operation
|
|
845
|
+
* @param {any} err
|
|
846
|
+
* @param {object} [options={}]
|
|
847
|
+
* @returns {object | null}
|
|
848
|
+
*/
|
|
849
|
+
export function recordRuntimeDiagnostic(source, operation, err, options = {}) {
|
|
850
|
+
try {
|
|
851
|
+
const maxEntries = Math.max(1, Number(options?.maxEntries || MAX_RUNTIME_DIAGNOSTIC_ENTRIES));
|
|
852
|
+
const rawMsg =
|
|
853
|
+
typeof err === 'string'
|
|
854
|
+
? err
|
|
855
|
+
: err && typeof err.message === 'string'
|
|
856
|
+
? err.message
|
|
857
|
+
: String(err ?? 'unknown error');
|
|
858
|
+
const redactedMsg = redactDiagnosticHomePath(rawMsg, options).slice(0, 300);
|
|
859
|
+
|
|
860
|
+
const entry = {
|
|
861
|
+
timestamp:
|
|
862
|
+
typeof options?.timestamp === 'string'
|
|
863
|
+
? options.timestamp
|
|
864
|
+
: new Date(options?.nowMs ?? Date.now()).toISOString(),
|
|
865
|
+
source: String(source || 'unknown'),
|
|
866
|
+
operation: String(operation || 'unknown'),
|
|
867
|
+
name: String(err?.name || 'Error').slice(0, 80),
|
|
868
|
+
message: redactedMsg
|
|
869
|
+
};
|
|
870
|
+
|
|
871
|
+
inMemoryDiagnosticsRing.push(entry);
|
|
872
|
+
if (inMemoryDiagnosticsRing.length > MAX_RUNTIME_DIAGNOSTIC_ENTRIES) {
|
|
873
|
+
inMemoryDiagnosticsRing.splice(
|
|
874
|
+
0,
|
|
875
|
+
inMemoryDiagnosticsRing.length - MAX_RUNTIME_DIAGNOSTIC_ENTRIES
|
|
876
|
+
);
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
const explicitDiagPath =
|
|
880
|
+
typeof options?.diagnosticsPath === 'string' && options.diagnosticsPath.trim()
|
|
881
|
+
? options.diagnosticsPath.trim()
|
|
882
|
+
: typeof options?.cwd === 'string' && options.cwd.trim() && options.cwd.trim() !== '.'
|
|
883
|
+
? joinPath(options.cwd.trim(), '.claude', 'cache', 'ah_diagnostics.jsonl')
|
|
884
|
+
: null;
|
|
885
|
+
|
|
886
|
+
const fsMod = getNodeIo(options)?.fs;
|
|
887
|
+
if (fsMod && explicitDiagPath && options?.persistDisk !== false) {
|
|
888
|
+
const existingRaw = readTextSafe(explicitDiagPath, '', options) || '';
|
|
889
|
+
const lines = existingRaw
|
|
890
|
+
.split(/\r?\n/)
|
|
891
|
+
.map((line) => line.trim())
|
|
892
|
+
.filter(Boolean);
|
|
893
|
+
lines.push(JSON.stringify(entry));
|
|
894
|
+
const bounded = lines.length > maxEntries ? lines.slice(lines.length - maxEntries) : lines;
|
|
895
|
+
writeTextAtomic(explicitDiagPath, `${bounded.join('\n')}\n`, options);
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
return entry;
|
|
899
|
+
} catch {
|
|
900
|
+
return null;
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
/**
|
|
905
|
+
* Reads bounded structured runtime diagnostics from `<cwd>/.claude/cache/ah_diagnostics.jsonl`
|
|
906
|
+
* when Tier-2 disk I/O is available, or from the pure-JS in-memory ring buffer in V8 Mod isolates (`ISS-065`).
|
|
907
|
+
*
|
|
908
|
+
* @param {object} [options={}]
|
|
909
|
+
* @returns {Array<object>}
|
|
910
|
+
*/
|
|
911
|
+
export function readRuntimeDiagnostics(options = {}) {
|
|
912
|
+
const maxEntries = Math.max(1, Number(options?.maxEntries || MAX_RUNTIME_DIAGNOSTIC_ENTRIES));
|
|
913
|
+
const fsMod = getNodeIo(options)?.fs;
|
|
914
|
+
|
|
915
|
+
if (!fsMod) {
|
|
916
|
+
return inMemoryDiagnosticsRing.slice(-maxEntries);
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
const targetPath = getDiagnosticsFilePath(options);
|
|
920
|
+
const raw = readTextSafe(targetPath, null, options);
|
|
921
|
+
const diskEntries = [];
|
|
922
|
+
if (raw) {
|
|
923
|
+
const lines = raw.split(/\r?\n/).filter((line) => line.trim().length > 0);
|
|
924
|
+
for (const line of lines) {
|
|
925
|
+
try {
|
|
926
|
+
const parsed = JSON.parse(line);
|
|
927
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
928
|
+
diskEntries.push({
|
|
929
|
+
...parsed,
|
|
930
|
+
message: redactDiagnosticHomePath(parsed.message || '', options).slice(0, 300)
|
|
931
|
+
});
|
|
932
|
+
}
|
|
933
|
+
} catch {
|
|
934
|
+
// Ignore malformed diagnostic line
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
if (options?.includeMemory) {
|
|
940
|
+
const combined = [...diskEntries, ...inMemoryDiagnosticsRing];
|
|
941
|
+
return combined.slice(-maxEntries);
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
return diskEntries.slice(-maxEntries);
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
/**
|
|
948
|
+
* Returns a snapshot of the bounded in-memory runtime diagnostics ring buffer.
|
|
949
|
+
*
|
|
950
|
+
* @param {number} [maxEntries=MAX_RUNTIME_DIAGNOSTIC_ENTRIES]
|
|
951
|
+
* @returns {Array<object>}
|
|
952
|
+
*/
|
|
953
|
+
export function getInMemoryRuntimeDiagnostics(maxEntries = MAX_RUNTIME_DIAGNOSTIC_ENTRIES) {
|
|
954
|
+
return inMemoryDiagnosticsRing.slice(-Math.max(1, Number(maxEntries || MAX_RUNTIME_DIAGNOSTIC_ENTRIES)));
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
/**
|
|
958
|
+
* Clears the in-memory runtime diagnostics ring buffer (for deterministic unit testing).
|
|
959
|
+
*/
|
|
960
|
+
export function clearInMemoryRuntimeDiagnostics() {
|
|
961
|
+
inMemoryDiagnosticsRing.length = 0;
|
|
962
|
+
}
|