ttsc 0.31.4 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/cmd/ttsc/compiler_argument_cwd_test.go +38 -38
  2. package/cmd/ttscserver/main.go +2 -12
  3. package/cmd/ttscserver/resolve_launch_uses_native_flag_authority_test.go +7 -7
  4. package/driver/lsp.go +4 -43
  5. package/driver/rewrite.go +1 -1
  6. package/internal/e2etrace/completion_hints.go +3 -3
  7. package/internal/e2etrace/completion_hints_test.go +26 -12
  8. package/internal/graph/build.go +5 -6
  9. package/internal/graph/graph.go +3 -3
  10. package/internal/graph/line_model.go +2 -35
  11. package/internal/lspserver/lsp_clean_didopen_refreshes_compiler_state_test.go +13 -36
  12. package/internal/lspserver/lsp_hints_refresh_ignores_a_superseded_generation_test.go +9 -3
  13. package/internal/lspserver/lsp_plugin.go +19 -0
  14. package/internal/lspserver/lsp_proxy.go +9 -129
  15. package/internal/lspserver/lsp_server.go +0 -8
  16. package/internal/lspserver/lsp_watched_file_changes_reach_compiler_caches_test.go +6 -36
  17. package/internal/sourceprocess/windows_target_owns_suspended_admission_test.go +5 -5
  18. package/lib/compiler/internal/build/BuildExecution.js +11 -3
  19. package/lib/compiler/internal/build/BuildExecution.js.map +1 -1
  20. package/lib/compiler/internal/build/TsgoArguments.js.map +1 -1
  21. package/lib/compiler/internal/project/CompilerProjectSelection.d.ts +9 -8
  22. package/lib/compiler/internal/project/CompilerProjectSelection.js +11 -9
  23. package/lib/compiler/internal/project/CompilerProjectSelection.js.map +1 -1
  24. package/lib/compiler/internal/project/resolveOwningProjectConfig.d.ts +20 -8
  25. package/lib/compiler/internal/project/resolveOwningProjectConfig.js +21 -12
  26. package/lib/compiler/internal/project/resolveOwningProjectConfig.js.map +1 -1
  27. package/lib/compiler/internal/runSingleFileEmit.d.ts +5 -4
  28. package/lib/compiler/internal/runSingleFileEmit.js +5 -4
  29. package/lib/compiler/internal/runSingleFileEmit.js.map +1 -1
  30. package/lib/flags/ParseOptions.d.ts +2 -2
  31. package/lib/internal/E2ETrace.d.ts +1 -0
  32. package/lib/internal/E2ETrace.js.map +1 -1
  33. package/lib/internal/OwnedNativeProcess.d.ts +2 -2
  34. package/lib/internal/OwnedNativeProcess.js +2 -2
  35. package/lib/internal/SourceNativeRetirement.d.ts +8 -7
  36. package/lib/internal/SourceNativeRetirement.js +19 -10
  37. package/lib/internal/SourceNativeRetirement.js.map +1 -1
  38. package/lib/internal/TtsxNodeOptions.d.ts +79 -0
  39. package/lib/internal/TtsxNodeOptions.js +121 -0
  40. package/lib/internal/TtsxNodeOptions.js.map +1 -0
  41. package/lib/internal/javascriptRuntimeCapabilities.js +4 -1
  42. package/lib/internal/javascriptRuntimeCapabilities.js.map +1 -1
  43. package/lib/internal/parseWindowsDirectoryCaseSensitivity.d.ts +5 -5
  44. package/lib/internal/parseWindowsDirectoryCaseSensitivity.js +5 -5
  45. package/lib/internal/pathIdentity/createCaseSensitivityObservations.d.ts +35 -0
  46. package/lib/internal/pathIdentity/createCaseSensitivityObservations.js +209 -0
  47. package/lib/internal/pathIdentity/createCaseSensitivityObservations.js.map +1 -0
  48. package/lib/internal/pathIdentity/createFilesystemPathIdentityContext.js +2 -143
  49. package/lib/internal/pathIdentity/createFilesystemPathIdentityContext.js.map +1 -1
  50. package/lib/internal/probeLocalProcess.d.ts +5 -1
  51. package/lib/internal/probeLocalProcess.js +9 -7
  52. package/lib/internal/probeLocalProcess.js.map +1 -1
  53. package/lib/internal/projectInputPathIdentity.d.ts +1 -0
  54. package/lib/internal/projectInputPathIdentity.js +1 -0
  55. package/lib/internal/projectInputPathIdentity.js.map +1 -1
  56. package/lib/launcher/internal/parseTtsxCLI.d.ts +5 -4
  57. package/lib/launcher/internal/parseTtsxCLI.js +5 -4
  58. package/lib/launcher/internal/parseTtsxCLI.js.map +1 -1
  59. package/lib/launcher/internal/prepareExecution.js.map +1 -1
  60. package/lib/launcher/internal/resolveSingleFileOutput.d.ts +8 -9
  61. package/lib/launcher/internal/resolveSingleFileOutput.js +8 -9
  62. package/lib/launcher/internal/resolveSingleFileOutput.js.map +1 -1
  63. package/lib/launcher/internal/runTtsc.js +5 -5
  64. package/lib/launcher/internal/runTtsx.js +5 -2
  65. package/lib/launcher/internal/runTtsx.js.map +1 -1
  66. package/lib/launcher/internal/runtime/ProcessOwnedDirectory.d.ts +2 -0
  67. package/lib/launcher/internal/runtime/ProcessOwnedDirectory.js +2 -1
  68. package/lib/launcher/internal/runtime/ProcessOwnedDirectory.js.map +1 -1
  69. package/lib/launcher/internal/runtime/RuntimeEntrySources.d.ts +40 -0
  70. package/lib/launcher/internal/runtime/RuntimeEntrySources.js +57 -0
  71. package/lib/launcher/internal/runtime/RuntimeEntrySources.js.map +1 -0
  72. package/lib/launcher/internal/runtime/RuntimeProjectOwnership.d.ts +5 -4
  73. package/lib/launcher/internal/runtime/RuntimeProjectOwnership.js +8 -6
  74. package/lib/launcher/internal/runtime/RuntimeProjectOwnership.js.map +1 -1
  75. package/lib/launcher/internal/runtime/commonJsExportNames.d.ts +2 -1
  76. package/lib/launcher/internal/runtime/commonJsExportNames.js +2 -1
  77. package/lib/launcher/internal/runtime/commonJsExportNames.js.map +1 -1
  78. package/lib/launcher/internal/runtime/installRuntimeHooks.js +35 -9
  79. package/lib/launcher/internal/runtime/installRuntimeHooks.js.map +1 -1
  80. package/lib/launcher/internal/runtime/isLocalProcessGone.d.ts +1 -1
  81. package/lib/launcher/internal/runtime/isLocalProcessGone.js +4 -4
  82. package/lib/launcher/internal/runtime/isLocalProcessGone.js.map +1 -1
  83. package/lib/launcher/internal/runtime/resolveRuntimeCleanTargets.js +3 -1
  84. package/lib/launcher/internal/runtime/resolveRuntimeCleanTargets.js.map +1 -1
  85. package/lib/launcher/internal/watch/FseventsStreams.d.ts +2 -0
  86. package/lib/launcher/internal/watch/FseventsStreams.js +19 -0
  87. package/lib/launcher/internal/watch/FseventsStreams.js.map +1 -1
  88. package/lib/launcher/internal/watch/WatchTopology.d.ts +74 -12
  89. package/lib/launcher/internal/watch/WatchTopology.js +301 -92
  90. package/lib/launcher/internal/watch/WatchTopology.js.map +1 -1
  91. package/lib/launcher/internal/watch/projectInputReloadEventShouldNotify.d.ts +4 -1
  92. package/lib/launcher/internal/watch/projectInputReloadEventShouldNotify.js +3 -2
  93. package/lib/launcher/internal/watch/projectInputReloadEventShouldNotify.js.map +1 -1
  94. package/lib/plugin/internal/load/loadProjectPlugins.js +17 -9
  95. package/lib/plugin/internal/load/loadProjectPlugins.js.map +1 -1
  96. package/lib/plugin/internal/load/resolveNativeSource.js +2 -3
  97. package/lib/plugin/internal/load/resolveNativeSource.js.map +1 -1
  98. package/lib/plugin/internal/source/pluginModuleReplaceDirectories.d.ts +4 -1
  99. package/lib/plugin/internal/source/pluginModuleReplaceDirectories.js +9 -2
  100. package/lib/plugin/internal/source/pluginModuleReplaceDirectories.js.map +1 -1
  101. package/lib/structures/internal/TtscCommonOptions.d.ts +2 -2
  102. package/package.json +9 -9
  103. package/src/compiler/internal/build/BuildExecution.ts +15 -6
  104. package/src/compiler/internal/build/TsgoArguments.ts +4 -1
  105. package/src/compiler/internal/project/CompilerProjectSelection.ts +14 -14
  106. package/src/compiler/internal/project/resolveOwningProjectConfig.ts +29 -14
  107. package/src/compiler/internal/runSingleFileEmit.ts +11 -7
  108. package/src/flags/ParseOptions.ts +2 -2
  109. package/src/internal/E2ETrace.ts +5 -1
  110. package/src/internal/OwnedNativeProcess.ts +2 -2
  111. package/src/internal/SourceNativeRetirement.ts +42 -19
  112. package/src/internal/TtsxNodeOptions.ts +124 -0
  113. package/src/internal/javascriptRuntimeCapabilities.ts +6 -1
  114. package/src/internal/parseWindowsDirectoryCaseSensitivity.ts +5 -5
  115. package/src/internal/pathIdentity/createCaseSensitivityObservations.ts +242 -0
  116. package/src/internal/pathIdentity/createFilesystemPathIdentityContext.ts +2 -169
  117. package/src/internal/probeLocalProcess.ts +13 -8
  118. package/src/internal/projectInputPathIdentity.ts +1 -0
  119. package/src/launcher/internal/parseTtsxCLI.ts +5 -4
  120. package/src/launcher/internal/prepareExecution.ts +4 -1
  121. package/src/launcher/internal/resolveSingleFileOutput.ts +8 -9
  122. package/src/launcher/internal/runTtsc.ts +5 -5
  123. package/src/launcher/internal/runTtsx.ts +17 -8
  124. package/src/launcher/internal/runtime/ProcessOwnedDirectory.ts +5 -1
  125. package/src/launcher/internal/runtime/RuntimeEntrySources.ts +57 -0
  126. package/src/launcher/internal/runtime/RuntimeProjectOwnership.ts +23 -10
  127. package/src/launcher/internal/runtime/commonJsExportNames.ts +11 -4
  128. package/src/launcher/internal/runtime/installRuntimeHooks.ts +55 -13
  129. package/src/launcher/internal/runtime/isLocalProcessGone.ts +5 -3
  130. package/src/launcher/internal/runtime/resolveRuntimeCleanTargets.ts +17 -5
  131. package/src/launcher/internal/watch/FseventsStreams.ts +22 -0
  132. package/src/launcher/internal/watch/WatchTopology.ts +387 -99
  133. package/src/launcher/internal/watch/projectInputReloadEventShouldNotify.ts +14 -9
  134. package/src/plugin/internal/load/loadProjectPlugins.ts +17 -3
  135. package/src/plugin/internal/load/resolveNativeSource.ts +10 -4
  136. package/src/plugin/internal/source/pluginModuleReplaceDirectories.ts +10 -1
  137. package/src/structures/internal/TtscCommonOptions.ts +2 -2
  138. package/internal/graphsymbols/position_helpers_follow_ecma_line_terminators_test.go +0 -78
  139. package/internal/graphsymbols/provider.go +0 -650
  140. package/internal/lspserver/lsp_symbols.go +0 -212
@@ -20,10 +20,11 @@ import { readEffectiveCompilerOptions } from "./readEffectiveCompilerOptions";
20
20
  * failure propagates on success and is aggregated with an earlier operation
21
21
  * failure rather than replacing it.
22
22
  *
23
- * A launcher-supplied selection shares its project and original compiler argument
24
- * cwd with public output planning. Response freshness is checked before native
25
- * work and publication; these sequential checks do not pin bytes atomically.
26
- * Callers without that record retain explicit config/nearest-file discovery.
23
+ * A launcher-supplied selection shares its project and original compiler
24
+ * argument cwd with public output planning. Response freshness is checked
25
+ * before native work and publication; these sequential checks do not pin bytes
26
+ * atomically. Callers without that record retain explicit config/nearest-file
27
+ * discovery.
27
28
  *
28
29
  * @returns The transformed JavaScript source text.
29
30
  * @throws When the build exits non-zero, proves no JavaScript for the requested
@@ -59,7 +60,8 @@ export function runSingleFileEmit(
59
60
  });
60
61
  const tsconfig = project.path;
61
62
  const compilerArgsCwd = selection?.compilerArgsCwd ?? project.root;
62
- if (selection !== undefined) CompilerProjectSelection.assertCurrent(selection);
63
+ if (selection !== undefined)
64
+ CompilerProjectSelection.assertCurrent(selection);
63
65
  // The root tsgo lays the outputs against: a `--rootDir` forwarded on the
64
66
  // command line, which reaches it after the config; otherwise the declared
65
67
  // one, which `readProjectConfig` already absolutized; otherwise the project's
@@ -75,7 +77,8 @@ export function runSingleFileEmit(
75
77
  typeof effective === "string"
76
78
  ? path.resolve(compilerArgsCwd, effective)
77
79
  : project.root;
78
- if (selection !== undefined) CompilerProjectSelection.assertCurrent(selection);
80
+ if (selection !== undefined)
81
+ CompilerProjectSelection.assertCurrent(selection);
79
82
  const outDir = createCanonicalTempDirectory("ttsc-single-file-");
80
83
  let failed = false;
81
84
  let failure: unknown;
@@ -119,7 +122,8 @@ export function runSingleFileEmit(
119
122
  );
120
123
  }
121
124
  const transformed = fs.readFileSync(emitted, "utf8");
122
- if (selection !== undefined) CompilerProjectSelection.assertCurrent(selection);
125
+ if (selection !== undefined)
126
+ CompilerProjectSelection.assertCurrent(selection);
123
127
  if (options.out) {
124
128
  const target = path.isAbsolute(options.out)
125
129
  ? options.out
@@ -29,8 +29,8 @@ export interface ParseOptions {
29
29
  readonly errorPrefix: string;
30
30
 
31
31
  /**
32
- * Observe a validated launcher assignment at its compiler-frame position.
33
- * The canonical schema name and parsed value retain alias/value semantics;
32
+ * Observe a validated launcher assignment at its compiler-frame position. The
33
+ * canonical schema name and parsed value retain alias/value semantics;
34
34
  * passthroughIndex counts compiler tokens already forwarded at this point.
35
35
  * Exceptions propagate from the caller's observer.
36
36
  *
@@ -51,7 +51,9 @@ export namespace E2ETrace {
51
51
  export function runtimeCleanup(
52
52
  directory: string,
53
53
  runtimeCacheDir: string,
54
- origin: "ttsx-runtime-cleanup" | "runtime-clean-selection" = "ttsx-runtime-cleanup",
54
+ origin:
55
+ | "ttsx-runtime-cleanup"
56
+ | "runtime-clean-selection" = "ttsx-runtime-cleanup",
55
57
  ):
56
58
  | ((
57
59
  phase: string,
@@ -62,6 +64,7 @@ export namespace E2ETrace {
62
64
  owner?: { hostname: string; pid: number };
63
65
  result: string;
64
66
  errorCode?: string;
67
+ state?: string;
65
68
  },
66
69
  ) => void)
67
70
  | undefined {
@@ -86,6 +89,7 @@ export namespace E2ETrace {
86
89
  owner?: { hostname: string; pid: number };
87
90
  result: string;
88
91
  errorCode?: string;
92
+ state?: string;
89
93
  },
90
94
  ): void => {
91
95
  try {
@@ -42,8 +42,8 @@ export namespace OwnedNativeProcess {
42
42
  *
43
43
  * Enabled private tracing may receive a frozen scalar copy of an accepted
44
44
  * receipt through the existing retirement observer. The original helper has
45
- * closed before that copy is made. It contains no command or environment
46
- * data and cannot grant closure authority. Trace IO can change scheduling.
45
+ * closed before that copy is made. It contains no command or environment data
46
+ * and cannot grant closure authority. Trace IO can change scheduling.
47
47
  *
48
48
  * @evidence contracts/common.md#principled-implementation A private request carries exact command/options and a structurally checked native receipt is required after helper close; cancellation returns only after joined and empty-boundary proof.
49
49
  * @evidence contracts/common.md#clear-and-simple-design Control stdin is separate from target input, target output streams remain unchanged, and one finally owns listeners and private protocol storage.
@@ -417,17 +417,18 @@ export namespace SourceNativeRetirement {
417
417
  * still exists. Cleanup can then remove that root without another realpath.
418
418
  * Only successful cleanup drops the exact captured registration; a failed
419
419
  * cleanup or a replacement registration remains owned. Unknown boundaries
420
- * defer the same callback and identity through the original release protocol.
420
+ * defer the same callback and identity through the original release
421
+ * protocol.
421
422
  *
422
- * The optional task failure distinguishes an earlier thrown undefined from
423
- * no earlier failure. It is combined with a cleanup refusal, never rethrown
423
+ * The optional task failure distinguishes an earlier thrown undefined from no
424
+ * earlier failure. It is combined with a cleanup refusal, never rethrown
424
425
  * after successful cleanup or deferred recovery. Ordinary unscoped callers
425
426
  * perform cleanup without observing or inventing a registration.
426
427
  *
427
- * Enabled private tracing observes the original callback's execution, not
428
- * its deferral. Scalar own error properties are read without invoking
429
- * getters; reflection or sink failures leave the original outcome intact.
430
- * Synchronous trace writes can change scheduling and prove only that run.
428
+ * Enabled private tracing observes the original callback's execution, not its
429
+ * deferral. Scalar own error properties are read without invoking getters;
430
+ * reflection or sink failures leave the original outcome intact. Synchronous
431
+ * trace writes can change scheduling and prove only that run.
431
432
  *
432
433
  * @evidence contracts/common.md#principled-implementation Physical identity and the exact resource object are captured before destruction; only successful cleanup removes that identical registration from the original scope, while failure and replacement retain ownership.
433
434
  * @evidence contracts/common.md#clear-and-simple-design One operation combines destructive cleanup with registration release, using the existing release/recover protocol instead of making each caller order physical lookup around removal.
@@ -460,15 +461,31 @@ export namespace SourceNativeRetirement {
460
461
  OwnedSynchronousProcess.reportFailure(combined);
461
462
  throw combined;
462
463
  }
463
- const resource = root === undefined ? undefined : scope!.resources.get(root);
464
+ const resource =
465
+ root === undefined ? undefined : scope!.resources.get(root);
464
466
  const observe = !process.env.TTSC_E2E_TRACE
465
467
  ? undefined
466
468
  : (phase: string, error?: unknown): void => {
467
469
  try {
468
- const detail: Record<string, string | number | boolean | null | undefined> = {};
469
- if (error !== null && (typeof error === "object" || typeof error === "function"))
470
- for (const field of ["code", "errno", "syscall", "path", "dest"]) {
471
- const descriptor = Object.getOwnPropertyDescriptor(error, field);
470
+ const detail: Record<
471
+ string,
472
+ string | number | boolean | null | undefined
473
+ > = {};
474
+ if (
475
+ error !== null &&
476
+ (typeof error === "object" || typeof error === "function")
477
+ )
478
+ for (const field of [
479
+ "code",
480
+ "errno",
481
+ "syscall",
482
+ "path",
483
+ "dest",
484
+ ]) {
485
+ const descriptor = Object.getOwnPropertyDescriptor(
486
+ error,
487
+ field,
488
+ );
472
489
  const value: unknown = descriptor?.value;
473
490
  if (typeof value === "string" || typeof value === "number")
474
491
  detail[field] = value;
@@ -478,14 +495,20 @@ export namespace SourceNativeRetirement {
478
495
  resourceRoot: root ?? fenceRoot,
479
496
  ...detail,
480
497
  });
481
- if (phase === "source-resource-cleanup-started" && scope !== undefined)
498
+ if (
499
+ phase === "source-resource-cleanup-started" &&
500
+ scope !== undefined
501
+ )
482
502
  for (const [boundary, state] of scope.boundaries)
483
- E2ETrace.capabilityResolution("source-resource-cleanup-boundary", {
484
- taskToken: scope.taskToken,
485
- resourceRoot: root,
486
- boundary,
487
- retirement: state.state,
488
- });
503
+ E2ETrace.capabilityResolution(
504
+ "source-resource-cleanup-boundary",
505
+ {
506
+ taskToken: scope.taskToken,
507
+ resourceRoot: root,
508
+ boundary,
509
+ retirement: state.state,
510
+ },
511
+ );
489
512
  } catch {
490
513
  // Diagnostic reflection and IO cannot replace original cleanup.
491
514
  }
@@ -0,0 +1,124 @@
1
+ import { SidecarEnvironment } from "../compiler/internal/sharedHost/SidecarEnvironment";
2
+
3
+ /**
4
+ * The `NODE_OPTIONS` a ttsx run received, beside the value it gave its program
5
+ * after appending its own preloads.
6
+ *
7
+ * Ttsx appends its runtime preloads (`register.js`, `runtimeOwnerPreload.js`,
8
+ * `runtimeHookPreload.js`) to the program's `NODE_OPTIONS`, so every process
9
+ * the program starts inherits the source loader. ttsc's own helper processes,
10
+ * the runtime capability probe and the plugin descriptor evaluator, are not the
11
+ * program's. They must neither run those preloads nor count them as a user's
12
+ * startup code: both helpers refuse their caches for any non-empty
13
+ * `NODE_OPTIONS`, so ttsx's own preloads re-probed Node and re-evaluated every
14
+ * descriptor on every plugin load of a run (samchon/ttsc#1740). A user's own
15
+ * `NODE_OPTIONS` still reaches the helpers and still disables both caches.
16
+ *
17
+ * The record travels to every descendant of the program, and a descendant may
18
+ * set its own `NODE_OPTIONS`. So the received value is restored only while
19
+ * `NODE_OPTIONS` is still exactly the value ttsx gave; any other value is the
20
+ * process's own and reaches its helpers unchanged.
21
+ *
22
+ * @evidence contracts/common.md#principled-implementation The received and given values are recorded together before the program starts, and the received value is restored only while the given one is still in force, so helpers see exactly the options their process was started with by its user.
23
+ * @evidence contracts/common.md#clear-and-simple-design One channel, one producer for launchers, one reader for nested launchers and one environment projection for helpers.
24
+ * @evidence contracts/common.md#prohibited-implementation-shortcuts No option string is parsed or filtered; values are carried and compared verbatim.
25
+ * @evidence contracts/common.md#meaningful-documentation Native prose names the preloads, the helpers, the cache refusals, the descendant case and the user case that stays conservative.
26
+ * @evidence contracts/portability.md#os-neutral-implementation Reads and writes go through SidecarEnvironment, which applies Windows' case-insensitive variable identity.
27
+ * @evidence contracts/performance.md#efficient-algorithms Each call reads at most two variables, decodes one short JSON pair and copies one environment.
28
+ * @evidence contracts/performance.md#reuse-equivalent-work Restoring the user's options is what lets the helpers' existing caches serve a ttsx run.
29
+ * @evidenceExclude contracts/performance.md#bound-retention-and-release-resources Nothing is retained; the returned environment belongs to the caller.
30
+ */
31
+ export namespace TtsxNodeOptions {
32
+ /** The channel carrying `[received, given]` as JSON. */
33
+ export const RECORD = "TTSX_NODE_OPTIONS_RECORD";
34
+
35
+ /**
36
+ * The variables a ttsx run gives its program: `given` as `NODE_OPTIONS` and
37
+ * the record of what it received from `env`.
38
+ *
39
+ * @evidence contracts/common.md#principled-implementation The record pairs the value received before any preload with the exact value given, so later readers can tell whether ttsx's value is still in force.
40
+ * @evidence contracts/common.md#clear-and-simple-design One call returns both variables a launcher spreads into its child environment.
41
+ * @evidence contracts/common.md#prohibited-implementation-shortcuts Both values are recorded verbatim; nothing is parsed or filtered.
42
+ * @evidence contracts/common.md#meaningful-documentation Native prose names both returned variables and where the received value comes from.
43
+ * @evidence contracts/portability.md#os-neutral-implementation The received value is read through `received`, which uses SidecarEnvironment's Windows-aware variable identity.
44
+ * @evidence contracts/performance.md#efficient-algorithms One read through `received` and one JSON encoding of two strings.
45
+ * @evidenceExclude contracts/performance.md#reuse-equivalent-work A launcher calls it once per child; there is no work to share.
46
+ * @evidenceExclude contracts/performance.md#bound-retention-and-release-resources The returned variables belong to the caller; nothing is retained.
47
+ */
48
+ export function give(
49
+ env: NodeJS.ProcessEnv,
50
+ given: string,
51
+ ): { NODE_OPTIONS: string; [RECORD]: string } {
52
+ return {
53
+ NODE_OPTIONS: given,
54
+ [RECORD]: JSON.stringify([received(env), given]),
55
+ };
56
+ }
57
+
58
+ /**
59
+ * The `NODE_OPTIONS` a process received from its user: an enclosing ttsx
60
+ * run's received value while its given value is still in force, else the
61
+ * process's own.
62
+ *
63
+ * @evidence contracts/common.md#principled-implementation The enclosing record answers only while its given value equals the current one; any other value is the process's own.
64
+ * @evidence contracts/common.md#clear-and-simple-design One comparison selects between the record and the current value.
65
+ * @evidence contracts/common.md#prohibited-implementation-shortcuts A malformed record is ignored rather than repaired.
66
+ * @evidence contracts/common.md#meaningful-documentation Native prose states both outcomes.
67
+ * @evidence contracts/portability.md#os-neutral-implementation Variables are read through SidecarEnvironment, which applies Windows' case-insensitive variable identity.
68
+ * @evidence contracts/performance.md#efficient-algorithms Two variable reads and one JSON decode of a short pair.
69
+ * @evidenceExclude contracts/performance.md#reuse-equivalent-work Each call answers from the given environment; there is nothing to share.
70
+ * @evidenceExclude contracts/performance.md#bound-retention-and-release-resources Nothing is retained.
71
+ */
72
+ export function received(env: NodeJS.ProcessEnv): string {
73
+ const current = SidecarEnvironment.read(env, "NODE_OPTIONS") ?? "";
74
+ const record = readRecord(env);
75
+ return record !== undefined && record.given === current
76
+ ? record.received
77
+ : current;
78
+ }
79
+
80
+ /**
81
+ * The environment for a ttsc helper process: `NODE_OPTIONS` restored to the
82
+ * received value while an enclosing ttsx run's given value is in force,
83
+ * unchanged anywhere else.
84
+ *
85
+ * @evidence contracts/common.md#principled-implementation Only ttsx's own appended preloads are withdrawn, and only while ttsx's value is in force; a user's or descendant's value reaches the helper.
86
+ * @evidence contracts/common.md#clear-and-simple-design One projection returns either the input environment or one copy with a single variable replaced.
87
+ * @evidence contracts/common.md#prohibited-implementation-shortcuts No option string is edited; the received value replaces the given one whole.
88
+ * @evidence contracts/common.md#meaningful-documentation Native prose states when the environment is changed and when it is returned unchanged.
89
+ * @evidence contracts/portability.md#os-neutral-implementation SidecarEnvironment reads and writes the variable under Windows' case-insensitive identity.
90
+ * @evidence contracts/performance.md#efficient-algorithms Two variable reads, one JSON decode and at most one environment copy.
91
+ * @evidence contracts/performance.md#reuse-equivalent-work Restoring the user's options lets the probe and descriptor caches serve a ttsx run.
92
+ * @evidenceExclude contracts/performance.md#bound-retention-and-release-resources The returned environment belongs to the caller; nothing is retained.
93
+ */
94
+ export function forHelpers(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
95
+ const record = readRecord(env);
96
+ const current = SidecarEnvironment.read(env, "NODE_OPTIONS") ?? "";
97
+ if (record === undefined || record.given !== current) return env;
98
+ const helper = { ...env };
99
+ SidecarEnvironment.write(
100
+ helper,
101
+ "NODE_OPTIONS",
102
+ record.received.trim() === "" ? undefined : record.received,
103
+ );
104
+ return helper;
105
+ }
106
+
107
+ function readRecord(
108
+ env: NodeJS.ProcessEnv,
109
+ ): { given: string; received: string } | undefined {
110
+ const text = SidecarEnvironment.read(env, RECORD);
111
+ if (text === undefined) return undefined;
112
+ try {
113
+ const value: unknown = JSON.parse(text);
114
+ return Array.isArray(value) &&
115
+ value.length === 2 &&
116
+ typeof value[0] === "string" &&
117
+ typeof value[1] === "string"
118
+ ? { given: value[1], received: value[0] }
119
+ : undefined;
120
+ } catch {
121
+ return undefined;
122
+ }
123
+ }
124
+ }
@@ -9,6 +9,7 @@ import { PluginLoadAnswers } from "../plugin/internal/source/PluginLoadAnswers";
9
9
  import { E2ETrace } from "./E2ETrace";
10
10
  import type { IJavaScriptRuntimeCapabilities } from "./IJavaScriptRuntimeCapabilities";
11
11
  import { OwnedSynchronousProcess } from "./OwnedSynchronousProcess";
12
+ import { TtsxNodeOptions } from "./TtsxNodeOptions";
12
13
  import { isSpawnSyncFdExhaustion } from "./isSpawnSyncFdExhaustion";
13
14
  import { runtimeExecutableIdentity } from "./runtimeExecutableIdentity";
14
15
  import { spawnSyncWithLowDescriptors } from "./spawnSyncWithLowDescriptors";
@@ -45,7 +46,11 @@ export function javascriptRuntimeCapabilities(
45
46
  cwd: string,
46
47
  identities?: PluginContentIdentities.Store,
47
48
  ): IJavaScriptRuntimeCapabilities {
48
- const effectiveEnv = SidecarEnvironment.merge(process.env, env);
49
+ // Inside a ttsx run this is the user's NODE_OPTIONS, not ttsx's preloads,
50
+ // which would refuse the cache and run in the probe (#1740).
51
+ const effectiveEnv = TtsxNodeOptions.forHelpers(
52
+ SidecarEnvironment.merge(process.env, env),
53
+ );
49
54
  const cacheKey = runtimeCapabilityCacheKey(runtime, effectiveEnv);
50
55
  const beforeIdentity =
51
56
  cacheKey === undefined
@@ -2,11 +2,11 @@
2
2
  * Interpret fsutil's case-sensitivity query without assuming a display
3
3
  * language.
4
4
  *
5
- * English messages identify the state in the final field of the complete
6
- * native message. The echoed directory path supplies no status evidence. For
7
- * every other locale, the volume-root query supplies the raw localized suffix
8
- * for the ordinary disabled state. A target with that suffix is insensitive;
9
- * a different successful message is the enabled state.
5
+ * English messages identify the state in the final field of the complete native
6
+ * message. The echoed directory path supplies no status evidence. For every
7
+ * other locale, the volume-root query supplies the raw localized suffix for the
8
+ * ordinary disabled state. A target with that suffix is insensitive; a
9
+ * different successful message is the enabled state.
10
10
  *
11
11
  * Inputs must be successful fsutil query responses. The opaque comparison
12
12
  * assumes the volume-root response represents the ordinary disabled state;
@@ -0,0 +1,242 @@
1
+ import childProcess from "node:child_process";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+
5
+ import { E2ETrace } from "../E2ETrace";
6
+ import { OwnedSynchronousProcess } from "../OwnedSynchronousProcess";
7
+ import { parseWindowsDirectoryCaseSensitivity } from "../parseWindowsDirectoryCaseSensitivity";
8
+ import type { FilesystemPathIdentityOperations } from "./FilesystemPathIdentityOperations";
9
+ import { resolveFilesystemPath } from "./resolveFilesystemPath";
10
+
11
+ /**
12
+ * Create one unit of work's directory case-policy observations: a function that
13
+ * answers whether a directory's names are case-sensitive, asking the filesystem
14
+ * once per directory for as long as the unit keeps it.
15
+ *
16
+ * An identity context memoizes case answers for itself, but a unit of work that
17
+ * creates several contexts, such as one watch decision, asked each directory
18
+ * once per context. On Windows an inconclusive directory, one that is empty or
19
+ * whose names carry no ASCII case, costs an `fsutil` process per question, and
20
+ * one decision asked the same directory up to seventeen times
21
+ * (samchon/ttsc#1742). Contexts created with this function as their
22
+ * `caseSensitive` operation share its answers.
23
+ *
24
+ * The answers are observations of the moment they were asked, like a context's
25
+ * own. The unit's owner chooses their lifetime; a later unit creates new
26
+ * observations rather than reusing these. A directory's flag can change while
27
+ * it is empty, so an answer outliving its unit could be stale.
28
+ *
29
+ * Unavailable evidence is `undefined`: an unreadable directory, a failed query,
30
+ * or a platform without a read-only probe for an inconclusive directory. Only
31
+ * observed insensitivity permits ASCII folding.
32
+ *
33
+ * @param operations Replaceable filesystem primitives; omitted members use the
34
+ * host's own.
35
+ * @evidence contracts/common.md#principled-implementation Alternate-name observations decide first; a rejected alternate is conclusive only while its original exists. Darwin walks same-device names for its volume-wide policy and Windows asks fsutil's read-only per-directory flag. Failed observation stays unknown.
36
+ * @evidence contracts/common.md#clear-and-simple-design One returned function owns the probe and its per-unit memo; identity resolution stays with the contexts that call it.
37
+ * @evidence contracts/common.md#prohibited-implementation-shortcuts No answer is inferred from the OS name, and no answer is carried beyond the unit that observed it.
38
+ * @evidence contracts/common.md#meaningful-documentation Native paragraphs explain sharing, lifetime, the empty-directory hazard and unknown evidence, with tags separated.
39
+ * @evidence contracts/portability.md#os-neutral-implementation Native realpath, lstat and readdir observe alternate names; darwin and win32 select their read-only volume or directory probes, and the platform's path dialect keys the memo.
40
+ * @evidence contracts/performance.md#efficient-algorithms A miss enumerates the directory's immediate entries and stops at the first conclusive alternate; darwin can walk same-device ancestors and Windows can launch directory and volume fsutil queries. A hit is one map lookup.
41
+ * @evidence contracts/performance.md#reuse-equivalent-work Every context of one unit shares each directory's answer, so a unit asks the filesystem once per directory instead of once per context.
42
+ * @evidence contracts/performance.md#bound-retention-and-release-resources The memo holds one entry per queried directory without eviction for the unit's lifetime; releasing the returned function releases it. Probes hold no handle after returning, and a Windows query has no explicit timeout.
43
+ */
44
+ export function createCaseSensitivityObservations(
45
+ operations: Partial<
46
+ Pick<
47
+ FilesystemPathIdentityOperations,
48
+ "lstat" | "platform" | "readdir" | "realpath"
49
+ >
50
+ > = {},
51
+ ): (directory: string) => boolean | undefined {
52
+ const platform = operations.platform ?? process.platform;
53
+ const probes = {
54
+ lstat: operations.lstat ?? fs.lstatSync,
55
+ readdir: operations.readdir ?? fs.readdirSync,
56
+ realpath: operations.realpath ?? physicalRealpath,
57
+ };
58
+ const answers = new Map<string, boolean | undefined>();
59
+ return (directory) => {
60
+ const key = resolveFilesystemPath(directory, platform);
61
+ if (answers.has(key)) return answers.get(key);
62
+ let answer: boolean | undefined;
63
+ try {
64
+ answer = filesystemDirectoryIsCaseSensitive(key, platform, probes);
65
+ } catch {
66
+ // A failed capability observation is unknown. This does not suppress
67
+ // strict physical identity errors in a context's realpath resolver.
68
+ answer = undefined;
69
+ }
70
+ answers.set(key, answer);
71
+ return answer;
72
+ };
73
+ }
74
+
75
+ function physicalRealpath(location: string): string {
76
+ return fs.realpathSync.native?.(location) ?? fs.realpathSync(location);
77
+ }
78
+
79
+ function filesystemDirectoryIsCaseSensitive(
80
+ directory: string,
81
+ platform: NodeJS.Platform,
82
+ operations: {
83
+ lstat(location: string): fs.Stats | fs.BigIntStats;
84
+ readdir(directory: string): string[];
85
+ realpath(location: string): string;
86
+ },
87
+ ): boolean | undefined {
88
+ const pathApi = platform === "win32" ? path.win32 : path.posix;
89
+ let entries: string[];
90
+ try {
91
+ entries = operations.readdir(directory);
92
+ } catch {
93
+ return undefined;
94
+ }
95
+ const foldedNames = new Map<string, string>();
96
+ for (const name of entries) {
97
+ const folded = foldAsciiCase(name);
98
+ const previous = foldedNames.get(folded);
99
+ if (previous !== undefined && previous !== name) return true;
100
+ foldedNames.set(folded, name);
101
+ }
102
+ for (const name of entries) {
103
+ const alternate = alternateCase(name);
104
+ if (alternate === name) continue;
105
+ try {
106
+ operations.lstat(pathApi.join(directory, alternate));
107
+ } catch (error) {
108
+ if (isMissingFilesystemEntry(error)) {
109
+ // Enumeration is not an atomic snapshot. An absent alternate proves
110
+ // sensitivity only if the original spelling still names an entry.
111
+ try {
112
+ operations.lstat(pathApi.join(directory, name));
113
+ return true;
114
+ } catch (originalError) {
115
+ if (isMissingFilesystemEntry(originalError) === false)
116
+ throw originalError;
117
+ }
118
+ continue;
119
+ }
120
+ throw error;
121
+ }
122
+ try {
123
+ const actual = resolveFilesystemPath(
124
+ operations.realpath(pathApi.join(directory, name)),
125
+ platform,
126
+ );
127
+ const alias = resolveFilesystemPath(
128
+ operations.realpath(pathApi.join(directory, alternate)),
129
+ platform,
130
+ );
131
+ return actual !== alias;
132
+ } catch (error) {
133
+ if (isMissingFilesystemEntry(error) === false) throw error;
134
+ }
135
+ }
136
+ if (platform === "darwin") {
137
+ // APFS/HFS case semantics are volume-wide. An empty directory has no child
138
+ // name to probe, so ask the same read-only question of its existing name in
139
+ // the parent and walk upward until a name with ASCII case is available.
140
+ // This avoids a write probe while still distinguishing default APFS from a
141
+ // case-sensitive volume.
142
+ let current = resolveFilesystemPath(directory, platform);
143
+ while (true) {
144
+ const parent = pathApi.dirname(current);
145
+ if (parent === current) break;
146
+ // Names are interpreted by their parent; another mount is not evidence
147
+ // of the directory's own volume case policy.
148
+ if (operations.lstat(current).dev !== operations.lstat(parent).dev)
149
+ return undefined;
150
+ const name = pathApi.basename(current);
151
+ const alternate = alternateCase(name);
152
+ if (alternate !== name) {
153
+ try {
154
+ const actual = resolveFilesystemPath(
155
+ operations.realpath(current),
156
+ platform,
157
+ );
158
+ const alias = resolveFilesystemPath(
159
+ operations.realpath(pathApi.join(parent, alternate)),
160
+ platform,
161
+ );
162
+ return actual !== alias;
163
+ } catch (error) {
164
+ if (isMissingFilesystemEntry(error) === false) throw error;
165
+ }
166
+ }
167
+ current = parent;
168
+ }
169
+ return undefined;
170
+ }
171
+ if (platform !== "win32") return undefined;
172
+ // Node does not expose the Windows per-directory flag. Prefer fsutil's
173
+ // read-only answer; unavailable capability remains unknown.
174
+ const queried = queryWindowsDirectoryCaseSensitivity(directory);
175
+ if (queried !== undefined) return queried;
176
+ return undefined;
177
+ }
178
+
179
+ /**
180
+ * Read the per-directory flag without depending on fsutil's display language.
181
+ *
182
+ * English output is cheap to recognize directly. Other Windows locales write
183
+ * console-code-page bytes that Node cannot reliably decode, so their raw
184
+ * message is interpreted against the volume-root query.
185
+ */
186
+ function queryWindowsDirectoryCaseSensitivity(
187
+ directory: string,
188
+ ): boolean | undefined {
189
+ const result = queryWindowsDirectoryCaseSensitivityBytes(directory);
190
+ if (result === undefined) return undefined;
191
+ const volumeRoot = path.win32.parse(directory).root;
192
+ const direct = parseWindowsDirectoryCaseSensitivity(
193
+ result,
194
+ undefined,
195
+ volumeRoot,
196
+ );
197
+ if (direct !== undefined) return direct;
198
+ const volume = queryWindowsDirectoryCaseSensitivityBytes(volumeRoot);
199
+ return parseWindowsDirectoryCaseSensitivity(result, volume, volumeRoot);
200
+ }
201
+
202
+ function queryWindowsDirectoryCaseSensitivityBytes(
203
+ directory: string,
204
+ ): Buffer | undefined {
205
+ const args = ["file", "queryCaseSensitiveInfo", directory];
206
+ const result = E2ETrace.synchronous(
207
+ "fsutil.exe",
208
+ args,
209
+ {},
210
+ "path-case-probe",
211
+ () =>
212
+ OwnedSynchronousProcess.launch("fsutil.exe", args, {
213
+ windowsHide: true,
214
+ }) ?? childProcess.spawnSync("fsutil.exe", args, { windowsHide: true }),
215
+ );
216
+ return result.error === undefined &&
217
+ result.status === 0 &&
218
+ Buffer.isBuffer(result.stdout)
219
+ ? result.stdout
220
+ : undefined;
221
+ }
222
+
223
+ function alternateCase(value: string): string {
224
+ return value.replace(/[A-Za-z]/g, (character) =>
225
+ character === character.toLowerCase()
226
+ ? character.toUpperCase()
227
+ : character.toLowerCase(),
228
+ );
229
+ }
230
+
231
+ /** ASCII folding is the case equivalence observed by the read-only probes. */
232
+ function foldAsciiCase(value: string): string {
233
+ return value.replace(/[A-Z]/g, (character) => character.toLowerCase());
234
+ }
235
+
236
+ function isMissingFilesystemEntry(error: unknown): boolean {
237
+ return (
238
+ error instanceof Error &&
239
+ "code" in error &&
240
+ (error.code === "ENOENT" || error.code === "ENOTDIR")
241
+ );
242
+ }