ttsc 0.34.2 → 0.35.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 (76) hide show
  1. package/driver/compileraliases/names.go +69 -0
  2. package/driver/compileraliases/names_test.go +57 -0
  3. package/lib/compiler/internal/build/BuildExecution.d.ts +26 -0
  4. package/lib/compiler/internal/build/BuildExecution.js +13 -3
  5. package/lib/compiler/internal/build/BuildExecution.js.map +1 -1
  6. package/lib/compiler/internal/build/RunBuildOptions.d.ts +2 -0
  7. package/lib/compiler/internal/build/RuntimeBuildCache.d.ts +47 -0
  8. package/lib/compiler/internal/build/RuntimeBuildCache.js +235 -0
  9. package/lib/compiler/internal/build/RuntimeBuildCache.js.map +1 -0
  10. package/lib/compiler/internal/build/RuntimeBuildInputs.d.ts +44 -0
  11. package/lib/compiler/internal/build/RuntimeBuildInputs.js +282 -0
  12. package/lib/compiler/internal/build/RuntimeBuildInputs.js.map +1 -0
  13. package/lib/compiler/internal/build/RuntimeInputProof.d.ts +50 -0
  14. package/lib/compiler/internal/build/RuntimeInputProof.js +315 -0
  15. package/lib/compiler/internal/build/RuntimeInputProof.js.map +1 -0
  16. package/lib/compiler/internal/build/TsgoArguments.d.ts +5 -4
  17. package/lib/compiler/internal/build/TsgoArguments.js +11 -5
  18. package/lib/compiler/internal/build/TsgoArguments.js.map +1 -1
  19. package/lib/compiler/internal/build/runBuild.d.ts +3 -3
  20. package/lib/compiler/internal/build/runBuild.js +17 -4
  21. package/lib/compiler/internal/build/runBuild.js.map +1 -1
  22. package/lib/compiler/internal/resolveNativeTypeScriptPackage.d.ts +27 -0
  23. package/lib/compiler/internal/resolveNativeTypeScriptPackage.js +103 -0
  24. package/lib/compiler/internal/resolveNativeTypeScriptPackage.js.map +1 -0
  25. package/lib/compiler/internal/resolveTsgo.d.ts +7 -6
  26. package/lib/compiler/internal/resolveTsgo.js +16 -35
  27. package/lib/compiler/internal/resolveTsgo.js.map +1 -1
  28. package/lib/compiler/internal/runNativeCheckWithObservations.d.ts +18 -14
  29. package/lib/compiler/internal/runNativeCheckWithObservations.js +42 -18
  30. package/lib/compiler/internal/runNativeCheckWithObservations.js.map +1 -1
  31. package/lib/flags/FLAG_SCHEMA.js +7 -0
  32. package/lib/flags/FLAG_SCHEMA.js.map +1 -1
  33. package/lib/internal/nativeBinary.d.ts +4 -0
  34. package/lib/internal/nativeBinary.js +6 -1
  35. package/lib/internal/nativeBinary.js.map +1 -1
  36. package/lib/launcher/internal/parseTtsxCLI.d.ts +1 -0
  37. package/lib/launcher/internal/parseTtsxCLI.js +1 -0
  38. package/lib/launcher/internal/parseTtsxCLI.js.map +1 -1
  39. package/lib/launcher/internal/prepareExecution.d.ts +2 -0
  40. package/lib/launcher/internal/prepareExecution.js +11 -2
  41. package/lib/launcher/internal/prepareExecution.js.map +1 -1
  42. package/lib/launcher/internal/runTtsx.js +5 -0
  43. package/lib/launcher/internal/runTtsx.js.map +1 -1
  44. package/lib/launcher/internal/runtime/installRuntimeHooks.js +7 -0
  45. package/lib/launcher/internal/runtime/installRuntimeHooks.js.map +1 -1
  46. package/lib/plugin/internal/load/loadProjectPlugins.js +1 -0
  47. package/lib/plugin/internal/load/loadProjectPlugins.js.map +1 -1
  48. package/lib/plugin/internal/source/SourceBuildCacheLayout.d.ts +2 -0
  49. package/lib/plugin/internal/source/SourceBuildCacheLayout.js +3 -0
  50. package/lib/plugin/internal/source/SourceBuildCacheLayout.js.map +1 -1
  51. package/lib/plugin/internal/source/pluginBuildVersions.d.ts +8 -7
  52. package/lib/plugin/internal/source/pluginBuildVersions.js +13 -13
  53. package/lib/plugin/internal/source/pluginBuildVersions.js.map +1 -1
  54. package/lib/structures/ITtscPluginCapabilities.d.ts +13 -2
  55. package/package.json +9 -9
  56. package/src/compiler/internal/build/BuildExecution.ts +32 -16
  57. package/src/compiler/internal/build/RunBuildOptions.ts +3 -0
  58. package/src/compiler/internal/build/RuntimeBuildCache.ts +252 -0
  59. package/src/compiler/internal/build/RuntimeBuildInputs.ts +349 -0
  60. package/src/compiler/internal/build/RuntimeInputProof.ts +346 -0
  61. package/src/compiler/internal/build/TsgoArguments.ts +11 -5
  62. package/src/compiler/internal/build/runBuild.ts +20 -5
  63. package/src/compiler/internal/resolveNativeTypeScriptPackage.ts +110 -0
  64. package/src/compiler/internal/resolveTsgo.ts +17 -36
  65. package/src/compiler/internal/runNativeCheckWithObservations.ts +41 -18
  66. package/src/flags/FLAG_SCHEMA.ts +7 -0
  67. package/src/internal/nativeBinary.ts +4 -0
  68. package/src/launcher/internal/parseTtsxCLI.ts +1 -0
  69. package/src/launcher/internal/prepareExecution.ts +20 -2
  70. package/src/launcher/internal/runTtsx.ts +5 -0
  71. package/src/launcher/internal/runtime/installRuntimeHooks.ts +11 -0
  72. package/src/plugin/internal/load/loadProjectPlugins.ts +1 -0
  73. package/src/plugin/internal/source/SourceBuildCacheLayout.ts +4 -0
  74. package/src/plugin/internal/source/pluginBuildVersions.ts +13 -15
  75. package/src/structures/ITtscPluginCapabilities.ts +14 -2
  76. package/utility/host.go +22 -1
@@ -0,0 +1,346 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+
5
+ import type { ITtscCompilerTransformation } from "../../../structures/ITtscCompilerTransformation";
6
+ import type { TtscBuildResult } from "../../../structures/internal/TtscBuildResult";
7
+
8
+ /**
9
+ * Replay the compiler and native input witnesses of a completed runtime build.
10
+ * Read predicates keep their original text or raw-byte codec; absence, entry
11
+ * kind, physical target and directory membership remain independent predicates.
12
+ * Failed or unsupported observations withhold reuse.
13
+ *
14
+ * @evidence contracts/common.md#principled-implementation Replay compares generation witnesses with current existence, stat, decoded text, physical identity and directory membership. Native version-one file, optional-file, entry and directory codecs use explicit tags, raw file/link bytes and sorted nul-delimited records. Compiler text strips UTF-8 BOM or decodes even UTF-16LE/BE bytes before SHA-256; host directory presence uses its separate domain marker.
15
+ * @evidence contracts/common.md#clear-and-simple-design One namespace separates result admission, declared host inputs, compiler predicates and the native version-one codec. Private physical/absence and SHA-256 helpers serve the codecs without merging their meanings.
16
+ * @evidence contracts/common.md#prohibited-implementation-shortcuts Unknown codecs, failed reads and producer proof failures decline admission. Only ENOENT/ENOTDIR prove absence; other physical-resolution errors remain unavailable. Following stat classifies compiler views while lstat retains native link kinds; only the producer private output subtree is excluded.
17
+ * @evidence contracts/common.md#meaningful-documentation Native prose identifies generation proof, codec ownership and refusal semantics; private helper comments identify query, byte, decoded-text and null/error boundaries.
18
+ * @evidence contracts/portability.md#os-neutral-implementation Native stat, lstat and realpath retain actual kinds, targets and spellings without case assumptions. POSIX directory names/link targets stay raw bytes, Windows names follow the producer UTF-8 codec, and compiler directory entries sort by UTF-8 bytes.
19
+ * @evidence contracts/performance.md#efficient-algorithms Replay visits recorded predicates and their bytes or immediate directory entries rather than unrelated trees. Hashing and BOM decoding cost O(bytes), including a big-endian copy; directory codecs cost O(N log N) sorting plus encoded bytes and link queries. Physical resolution follows native path/link traversal.
20
+ * @evidence contracts/performance.md#reuse-equivalent-work Every retained predicate is observed anew to authorize completed-result reuse. Host capture and admission share the producer codec; no path memo, watcher silence or historical hash independently grants authority.
21
+ * @evidence contracts/performance.md#bound-retention-and-release-resources Read buffers, decoded text, paths and sorted directory members are call-local and have no proof-reader byte or entry cap. Synchronous calls retain no handle, watcher, process or historical population; only returned proof values escape.
22
+ */
23
+ export namespace RuntimeInputProof {
24
+ /**
25
+ * Validate result-level host witnesses and every reported compiler predicate.
26
+ * The caller independently proves the selected compiler, project membership
27
+ * and plugin selection; an absent graph alone grants no completeness.
28
+ *
29
+ * @evidence contracts/common.md#principled-implementation Explicit incomplete observations and any graph failure reject reuse; host paths require both content and physical witnesses, and rich compiler predicates are replayed under their own codec.
30
+ * @evidence contracts/common.md#clear-and-simple-design One admission pass delegates individual compiler observations and native codecs.
31
+ * @evidence contracts/common.md#prohibited-implementation-shortcuts Missing witness fields never become an empty successful observation, and only the caller-owned private output subtree is excluded.
32
+ * @evidence contracts/common.md#meaningful-documentation Native prose identifies result admission and the caller's separate completeness obligations.
33
+ * @evidence contracts/portability.md#os-neutral-implementation Native path resolution anchors producer-relative graph keys, and current physical paths come from native realpath.
34
+ * @evidence contracts/performance.md#efficient-algorithms Input and predicate populations drive replay; each read hashes its actual bytes and directories sort immediate entry records.
35
+ * @evidence contracts/performance.md#reuse-equivalent-work Generation witnesses, rather than an identity-key match, decide whether a completed build remains reusable.
36
+ * @evidence contracts/performance.md#bound-retention-and-release-resources Temporary path and predicate records are invocation-owned without retained handles or history.
37
+ */
38
+ export function holds(
39
+ result: TtscBuildResult,
40
+ projectRoot: string,
41
+ emitDir: string,
42
+ ): boolean {
43
+ if (
44
+ result.observationsComplete === false ||
45
+ Object.keys(result.graph?.inputProofFailures ?? {}).length !== 0
46
+ )
47
+ return false;
48
+ try {
49
+ for (const file of result.hostInputs ?? []) {
50
+ const [currentPhysical, hash] = observeHostInput(file);
51
+ if (
52
+ !Object.hasOwn(result.hostInputHashes ?? {}, file) ||
53
+ !Object.hasOwn(result.hostInputRealpaths ?? {}, file) ||
54
+ currentPhysical !== result.hostInputRealpaths![file] ||
55
+ hash !== result.hostInputHashes![file]
56
+ )
57
+ return false;
58
+ }
59
+ const graph = result.graph;
60
+ for (const [name, observed] of Object.entries(
61
+ graph?.inputObservations ?? {},
62
+ )) {
63
+ const file = path.resolve(projectRoot, name);
64
+ const relative = path.relative(emitDir, file);
65
+ if (
66
+ relative === "" ||
67
+ (!path.isAbsolute(relative) &&
68
+ relative !== ".." &&
69
+ !relative.startsWith(".." + path.sep))
70
+ )
71
+ continue;
72
+ if (!observationHolds(file, observed)) return false;
73
+ }
74
+ for (const [name, expected] of Object.entries(graph?.inputHashes ?? {})) {
75
+ if (Object.hasOwn(graph?.inputObservations ?? {}, name)) continue;
76
+ const file = path.resolve(projectRoot, name);
77
+ if (physical(file) !== graph?.inputRealpaths?.[name]) return false;
78
+ let current: string | null = null;
79
+ try {
80
+ if (fs.statSync(file).isFile())
81
+ current = textHash(fs.readFileSync(file));
82
+ } catch (error) {
83
+ if (!missing(error)) return false;
84
+ }
85
+ if (current !== expected) return false;
86
+ }
87
+ return true;
88
+ } catch {
89
+ return false;
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Observe a declared host input under its existing raw-file or directory-kind
95
+ * codec. Descriptor resolution can declare directories as presence inputs;
96
+ * those are distinct from compiler source reads and directory enumeration.
97
+ * Native identity and metadata bracket the observation. Missing paths carry
98
+ * null witnesses, while unavailable or changing observations throw.
99
+ *
100
+ * @evidence contracts/common.md#principled-implementation Raw file bytes and the existing ttsc:host-input:directory domain marker reproduce the descriptor/native host-input contract, with physical identity and full native metadata checked before and after.
101
+ * @evidence contracts/common.md#clear-and-simple-design One observer supplies the same declared-host codec to input capture and retained-result admission, independently of compiler text and enumeration predicates.
102
+ * @evidence contracts/common.md#prohibited-implementation-shortcuts Only ENOENT/ENOTDIR establish absence; unsupported entry kinds, read failures and changing witnesses refuse reuse instead of becoming empty content.
103
+ * @evidence contracts/common.md#meaningful-documentation Native prose distinguishes directory presence from directory membership, states the producer codec and explains failure semantics.
104
+ * @evidence contracts/portability.md#os-neutral-implementation Native following stat, realpath and byte reads retain actual host links and physical spellings without OS-name or separator guesses.
105
+ * @evidence contracts/performance.md#efficient-algorithms File observations hash their complete byte buffer and bracket native metadata; directory presence hashes a fixed marker without scanning members.
106
+ * @evidence contracts/performance.md#reuse-equivalent-work Capture and admission share the producer's codec, but every invocation observes current witnesses and retains no path-only truth.
107
+ * @evidence contracts/performance.md#bound-retention-and-release-resources Read buffers and stat records are call-local; synchronous filesystem calls leave no retained handle or watcher.
108
+ */
109
+ export function observeHostInput(
110
+ file: string,
111
+ ): readonly [string | null, string | null] {
112
+ const beforePhysical = physical(file);
113
+ let before: fs.BigIntStats;
114
+ try {
115
+ before = fs.statSync(file, { bigint: true });
116
+ } catch (error) {
117
+ if (!missing(error)) throw error;
118
+ if (beforePhysical !== null || physical(file) !== null)
119
+ throw new Error("Host input changed during absence observation.");
120
+ return [null, null];
121
+ }
122
+ if (!before.isFile() && !before.isDirectory())
123
+ throw new Error("Unsupported runtime host input kind.");
124
+ const hash = before.isDirectory()
125
+ ? digest("ttsc:host-input:directory\0")
126
+ : digest(fs.readFileSync(file));
127
+ const after = fs.statSync(file, { bigint: true });
128
+ const signature = (stat: fs.BigIntStats): string =>
129
+ [stat.dev, stat.ino, stat.size, stat.mtimeNs, stat.ctimeNs].join(":");
130
+ if (
131
+ signature(before) !== signature(after) ||
132
+ beforePhysical !== physical(file)
133
+ )
134
+ throw new Error("Host input changed during observation.");
135
+ return [beforePhysical, hash];
136
+ }
137
+
138
+ /** Compare one compiler query record with the corresponding current queries. */
139
+ function observationHolds(
140
+ file: string,
141
+ observed: ITtscCompilerTransformation.IInputObservation,
142
+ ): boolean {
143
+ for (const predicate of observed.nativePredicates ?? [])
144
+ if (
145
+ predicate.version !== 1 ||
146
+ !predicate.identityStable ||
147
+ physical(file) !== predicate.realpath ||
148
+ nativeDigest(file, predicate.kind) !== predicate.digest
149
+ )
150
+ return false;
151
+ let kind: "file" | "directory" | "missing" = "missing";
152
+ try {
153
+ const stat = fs.statSync(file);
154
+ kind = stat.isDirectory() ? "directory" : "file";
155
+ } catch (error) {
156
+ if (!missing(error)) return false;
157
+ }
158
+ if (
159
+ observed.fileExists !== undefined &&
160
+ observed.fileExists !== (kind === "file")
161
+ )
162
+ return false;
163
+ if (
164
+ observed.directoryExists !== undefined &&
165
+ observed.directoryExists !== (kind === "directory")
166
+ )
167
+ return false;
168
+ if (observed.stat !== undefined && observed.stat !== kind) return false;
169
+ if (observed.readFile !== undefined) {
170
+ let hash: string | null = null;
171
+ try {
172
+ if (kind !== "directory") hash = textHash(fs.readFileSync(file));
173
+ } catch {
174
+ /* Compiler read failed. */
175
+ }
176
+ if (
177
+ observed.readFile.ok ? hash !== observed.readFile.hash : hash !== null
178
+ )
179
+ return false;
180
+ }
181
+ if (observed.realpath !== undefined) {
182
+ const current = physical(file);
183
+ if (
184
+ observed.realpath.ok
185
+ ? current !== observed.realpath.path
186
+ : current !== null
187
+ )
188
+ return false;
189
+ }
190
+ if (observed.accessibleEntries !== undefined) {
191
+ const directories: string[] = [];
192
+ const files: string[] = [];
193
+ let entries: fs.Dirent[] = [];
194
+ try {
195
+ entries = fs.readdirSync(file, { withFileTypes: true });
196
+ } catch {
197
+ /* Compiler enumeration returns an empty view. */
198
+ }
199
+ for (const entry of entries) {
200
+ try {
201
+ const stat = entry.isSymbolicLink()
202
+ ? fs.statSync(path.join(file, entry.name))
203
+ : entry;
204
+ if (stat.isDirectory()) directories.push(entry.name);
205
+ else if (stat.isFile()) files.push(entry.name);
206
+ } catch {
207
+ /* Compiler enumeration omits inaccessible link targets. */
208
+ }
209
+ }
210
+ const compare = (a: string, b: string): number =>
211
+ Buffer.compare(Buffer.from(a), Buffer.from(b));
212
+ if (
213
+ JSON.stringify({
214
+ directories: directories.sort(compare),
215
+ files: files.sort(compare),
216
+ }) !== JSON.stringify(observed.accessibleEntries)
217
+ )
218
+ return false;
219
+ }
220
+ return true;
221
+ }
222
+
223
+ /**
224
+ * Reproduce native version-one file, optional-file, entry and directory
225
+ * bytes.
226
+ */
227
+ function nativeDigest(file: string, kind: string): string {
228
+ if (kind === "file") return digest(fs.readFileSync(file));
229
+ if (kind === "optional-file") {
230
+ try {
231
+ return fs.statSync(file).isFile()
232
+ ? digest(
233
+ Buffer.concat([Buffer.from("file\0"), fs.readFileSync(file)]),
234
+ )
235
+ : digest("missing\0");
236
+ } catch (error) {
237
+ if (missing(error)) return digest("missing\0");
238
+ throw error;
239
+ }
240
+ }
241
+ if (kind === "entry") {
242
+ try {
243
+ const entry = fs.lstatSync(file);
244
+ return entry.isSymbolicLink()
245
+ ? digest(
246
+ Buffer.concat([
247
+ Buffer.from("symlink\0"),
248
+ fs.readlinkSync(file, { encoding: "buffer" }),
249
+ ]),
250
+ )
251
+ : digest(
252
+ (entry.isDirectory()
253
+ ? "directory"
254
+ : entry.isFile()
255
+ ? "file"
256
+ : "other") + "\0",
257
+ );
258
+ } catch (error) {
259
+ if (missing(error)) return digest("missing\0");
260
+ throw error;
261
+ }
262
+ }
263
+ if (kind !== "directory") throw new Error("unsupported native input codec");
264
+ const records: Buffer[] = [];
265
+ const names =
266
+ process.platform === "win32"
267
+ ? fs.readdirSync(file).map((name) => Buffer.from(name))
268
+ : fs.readdirSync(file, { encoding: "buffer" });
269
+ for (const name of names) {
270
+ const target =
271
+ process.platform === "win32"
272
+ ? path.join(file, name.toString())
273
+ : Buffer.concat([Buffer.from(file + path.sep), name]);
274
+ const entry = fs.lstatSync(target);
275
+ const entryKind = entry.isDirectory()
276
+ ? "directory"
277
+ : entry.isFile()
278
+ ? "file"
279
+ : entry.isSymbolicLink()
280
+ ? "symlink"
281
+ : "other";
282
+ const link = entry.isSymbolicLink()
283
+ ? fs.readlinkSync(target, { encoding: "buffer" })
284
+ : Buffer.alloc(0);
285
+ records.push(
286
+ Buffer.concat([name, Buffer.from("\0" + entryKind + "\0"), link]),
287
+ );
288
+ }
289
+ records.sort(Buffer.compare);
290
+ return digest(
291
+ Buffer.concat(
292
+ records.flatMap((record, index) =>
293
+ index === 0 ? [record] : [Buffer.from([0]), record],
294
+ ),
295
+ ),
296
+ );
297
+ }
298
+
299
+ /** Hash compiler-decoded text, retaining the BOM and UTF-16 producer policy. */
300
+ function textHash(bytes: Buffer): string {
301
+ if (
302
+ bytes.length >= 2 &&
303
+ ((bytes[0] === 0xff && bytes[1] === 0xfe) ||
304
+ (bytes[0] === 0xfe && bytes[1] === 0xff))
305
+ ) {
306
+ const text = Buffer.from(
307
+ bytes.subarray(2, 2 + Math.floor((bytes.length - 2) / 2) * 2),
308
+ );
309
+ if (bytes[0] === 0xfe) text.swap16();
310
+ return digest(Buffer.from(text.toString("utf16le"), "utf8"));
311
+ }
312
+ return digest(
313
+ bytes.length >= 3 &&
314
+ bytes[0] === 0xef &&
315
+ bytes[1] === 0xbb &&
316
+ bytes[2] === 0xbf
317
+ ? bytes.subarray(3)
318
+ : bytes,
319
+ );
320
+ }
321
+
322
+ /** Obtain a current physical coordinate, with null only for native absence. */
323
+ function physical(file: string): string | null {
324
+ try {
325
+ return fs.realpathSync.native(file);
326
+ } catch (error) {
327
+ if (missing(error)) return null;
328
+ throw error;
329
+ }
330
+ }
331
+
332
+ /** Classify only native absent-path errors. */
333
+ function missing(error: unknown): boolean {
334
+ return (
335
+ typeof error === "object" &&
336
+ error !== null &&
337
+ "code" in error &&
338
+ (error.code === "ENOENT" || error.code === "ENOTDIR")
339
+ );
340
+ }
341
+
342
+ /** SHA-256 of supplied text or raw bytes. */
343
+ function digest(bytes: string | Buffer): string {
344
+ return crypto.createHash("sha256").update(bytes).digest("hex");
345
+ }
346
+ }
@@ -195,11 +195,12 @@ export namespace TsgoArguments {
195
195
  /**
196
196
  * The forwarded-tsgo payload for a native `build`/`check` emit invocation.
197
197
  *
198
- * The sidecar builds its Program in-process, so the pinned `rootDir` has to
199
- * travel the same channel every other tsgo option takes to it — the host flag
200
- * set does not declare `--rootDir`, and `filterHostArgs` would strip it.
198
+ * The sidecar builds its Program in-process, so runtime source-map defaults
199
+ * and the pinned `rootDir` travel the same channel as other tsgo options —
200
+ * the host flag set does not declare `--rootDir`, and `filterHostArgs` would
201
+ * strip it.
201
202
  *
202
- * @evidence contracts/common.md#principled-implementation The same private layout root used by direct builds is placed in the sidecar compiler-option channel, preserving declared/composite containment while avoiding a new ordinary config-directory restriction without a new host flag.
203
+ * @evidence contracts/common.md#principled-implementation The same private layout root and forced runtime source-map default used by direct builds precede user arguments in the sidecar compiler-option channel, preserving explicit overrides and declared/composite containment without a new host flag.
203
204
  * @evidence contracts/common.md#clear-and-simple-design Root pinning stays in one helper and general payload ordering/serialization stays in createNativeTsgoArgs.
204
205
  * @evidence contracts/common.md#prohibited-implementation-shortcuts The supported environment payload carries compiler options instead of injecting unknown flags into strict foreign host parsers.
205
206
  * @evidence contracts/common.md#meaningful-documentation Native prose explains why rootDir travels with compiler options rather than through the host flag set.
@@ -215,7 +216,12 @@ export namespace TsgoArguments {
215
216
  ): string | undefined {
216
217
  return createNativeTsgoArgs(
217
218
  options,
218
- pinnedRootDirArgs(execution, options),
219
+ [
220
+ ...(options.forceRuntimeSourceMap === true
221
+ ? ["--sourceMap", "true"]
222
+ : []),
223
+ ...pinnedRootDirArgs(execution, options),
224
+ ],
219
225
  false,
220
226
  );
221
227
  }
@@ -2,6 +2,8 @@ import type { TtscBuildResult } from "../../../structures/internal/TtscBuildResu
2
2
  import { BuildExecution } from "./BuildExecution";
3
3
  import { BuildTiming } from "./BuildTiming";
4
4
  import type { RunBuildOptions } from "./RunBuildOptions";
5
+ import { RuntimeBuildCache } from "./RuntimeBuildCache";
6
+ import { RuntimeBuildInputs } from "./RuntimeBuildInputs";
5
7
  import { WatchInputPublication } from "./WatchInputPublication";
6
8
 
7
9
  /**
@@ -21,7 +23,7 @@ import { WatchInputPublication } from "./WatchInputPublication";
21
23
  * @evidence contracts/common.md#meaningful-documentation Native prose distinguishes returned exit failures from thrown setup/launch errors and explains the project-free branch.
22
24
  * @evidence contracts/portability.md#os-neutral-implementation Execution selection and spawning use the shared native path/process boundaries with cwd and separate argv, rather than constructing a shell command here.
23
25
  * @evidence contracts/performance.md#efficient-algorithms Timing creation and terminal selection make their own flag projections before the selected preparation/execution path. Delegated configuration, plugin, native/provenance and diagnostic work follows its actual input/report sizes; timing formatting scans ledger labels and output. No measured dominance or duration/output ceiling is established by this wrapper.
24
- * @evidence contracts/performance.md#reuse-equivalent-work A resolved execution context is carried through preparation and execution, so this build does not reload its plugin selection between phases.
26
+ * @evidence contracts/performance.md#reuse-equivalent-work A resolved execution context is carried through preparation and execution without another plugin load; private runtime requests delegate verified completed-emission reuse to RuntimeBuildCache with current input and producer proofs.
25
27
  * @evidence contracts/performance.md#bound-retention-and-release-resources The ledger and execution state are build-owned, while returned output/proof/diagnostic records transfer to the caller; no resident handle or historical build is stored here. Delegated native/probe/artifact acquisition and cleanup may be best effort, and thrown setup can precede some cleanup boundaries. This wrapper supplies no duration/output bound or descendant-release certification.
26
28
  */
27
29
  export function runBuild(options: RunBuildOptions = {}): TtscBuildResult {
@@ -36,8 +38,8 @@ export function runBuild(options: RunBuildOptions = {}): TtscBuildResult {
36
38
  * @evidence contracts/common.md#prohibited-implementation-shortcuts Awaiting changes only publication completion, preserves compiler/plugin selection and project-free terminal behavior, and sends publication failure through existing setup and cleanup rather than bypassing a pending baseline.
37
39
  * @evidence contracts/common.md#meaningful-documentation Entry prose states the publication barrier, order before compilation and internal callers' obligation to complete the sequence and deliver rejection.
38
40
  * @evidence contracts/portability.md#os-neutral-implementation BuildExecution retains native cwd, path identity and argument-array ownership across suspension; the namespace adds no independent native boundary.
39
- * @evidence contracts/performance.md#efficient-algorithms Each selected terminal, context, discovery, preparation and compile phase runs once; each publication adds one await and constant sequence state.
40
- * @evidence contracts/performance.md#reuse-equivalent-work One resolved execution context serves preparation and compilation without reloading plugins; the namespace retains no completed build or in-flight cache.
41
+ * @evidence contracts/performance.md#efficient-algorithms Each selected terminal, context, discovery and preparation phase runs once; eligible runtime requests add native source/configuration queries and content proofs before restoring or compiling. Each publication adds one await and constant sequence state.
42
+ * @evidence contracts/performance.md#reuse-equivalent-work One resolved execution context serves preparation and compilation without reloading plugins; the delegated runtime store reuses completed bytes only under current equal input snapshots and valid producer witnesses, with ordinary compilation on any miss.
41
43
  * @evidence contracts/performance.md#bound-retention-and-release-resources The invocation owns its sequence, ledger, context and current handoff while callbacks settle. Selected results transfer to the caller, delegated resource ownership and cleanup stay unchanged, and no resident history is retained.
42
44
  */
43
45
  export namespace runBuild {
@@ -72,14 +74,27 @@ export namespace runBuild {
72
74
  execution,
73
75
  setupStartedAt,
74
76
  );
75
- const result =
76
- prepared.result ??
77
+ const build = () =>
77
78
  BuildExecution.runPreparedBuild(
78
79
  options,
79
80
  timing,
80
81
  execution,
81
82
  prepared.buildOptions,
82
83
  );
84
+ const proof =
85
+ prepared.result === undefined
86
+ ? RuntimeBuildInputs.create(prepared.buildOptions, execution)
87
+ : undefined;
88
+ const result =
89
+ prepared.result ??
90
+ (proof === undefined
91
+ ? build()
92
+ : RuntimeBuildCache.run({
93
+ directory: options.runtimeCacheDir,
94
+ emitDir: options.isolateOutputsTo!,
95
+ ...proof,
96
+ build,
97
+ }));
83
98
  return BuildTiming.appendTimingOutput(result, timing);
84
99
  }
85
100
  }
@@ -0,0 +1,110 @@
1
+ import fs from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import path from "node:path";
4
+
5
+ /**
6
+ * Find native TypeScript from a filename used as a Node resolution anchor.
7
+ *
8
+ * The nearest ancestor manifest declaring TypeScript or its npm aliases owns
9
+ * discovery. Its aliases targeting `typescript` precede the ordinary name. A
10
+ * manifest reporting a compiler major below 7 belongs to the JavaScript
11
+ * compiler and is skipped. Missing or nonnumeric version metadata retains the
12
+ * existing path-discovery behavior; executable availability is the caller's
13
+ * responsibility. Alias candidates must report the actual package name
14
+ * `typescript` and a native major. Multiple distinct native alias installs are
15
+ * ambiguous and require an explicit binary. Read and parse errors propagate,
16
+ * except a disappeared manifest is treated as an absent candidate.
17
+ *
18
+ * @evidence contracts/common.md#principled-implementation Project and ancestor dependency maps supply npm aliases by their declared target; Node resolves those arbitrary names from the caller's filename, and installed name/version metadata verifies native identity. Distinct native alias installs are rejected as ambiguous rather than selected by spelling or declaration order.
19
+ * @evidence contracts/common.md#clear-and-simple-design One owner selects manifest metadata for executable resolution and plugin version keys so they cannot choose different package names.
20
+ * @evidence contracts/common.md#prohibited-implementation-shortcuts The real package identity and npm alias syntax define discovery; no particular alias, consumer identity or guessed executable is embedded.
21
+ * @evidence contracts/common.md#meaningful-documentation The comment defines anchor semantics, alias precedence, legacy rejection, incomplete metadata behavior and propagated read failures.
22
+ * @evidence contracts/portability.md#os-neutral-implementation createRequire follows native Node package resolution and synchronous filesystem reads without shell commands or path case assumptions.
23
+ * @evidence contracts/performance.md#efficient-algorithms The ancestor walk parses its manifests and visits their declared dependency entries once, then resolves and reads only A distinct aliases plus the ordinary name. Sorting alias names costs O(A log A); Node lookup, realpath and manifest bytes contribute delegated costs. Installed dependency trees are never scanned.
24
+ *
25
+ * @evidenceExclude contracts/performance.md#reuse-equivalent-work Project installations can change between calls, and this operation owns no invalidation source that would justify a retained result.
26
+ * @evidenceExclude contracts/performance.md#bound-retention-and-release-resources Synchronous reads retain no open handles and the caller owns the returned metadata.
27
+ */
28
+ export function resolveNativeTypeScriptPackage(
29
+ from: string,
30
+ ): { packageJson: string; manifest: Record<string, unknown> } | undefined {
31
+ const requireFrom = createRequire(from);
32
+ const aliases = new Set<string>();
33
+ for (
34
+ let directory = path.dirname(from);
35
+ ;
36
+ directory = path.dirname(directory)
37
+ ) {
38
+ const project = readManifest(path.join(directory, "package.json"));
39
+ let declaresTypeScript = false;
40
+ for (const field of [
41
+ "dependencies",
42
+ "devDependencies",
43
+ "optionalDependencies",
44
+ ]) {
45
+ const dependencies = project?.[field];
46
+ if (dependencies === null || typeof dependencies !== "object") continue;
47
+ declaresTypeScript ||= Object.hasOwn(dependencies, "typescript");
48
+ for (const [name, specifier] of Object.entries(dependencies))
49
+ if (
50
+ name !== "typescript" &&
51
+ typeof specifier === "string" &&
52
+ /^npm:typescript(?:@|$)/.test(specifier)
53
+ )
54
+ aliases.add(name);
55
+ }
56
+ if (declaresTypeScript || aliases.size) break;
57
+ if (path.dirname(directory) === directory) break;
58
+ }
59
+ let selected:
60
+ | { packageJson: string; manifest: Record<string, unknown> }
61
+ | undefined;
62
+ for (const name of [...aliases].sort().concat("typescript")) {
63
+ if (name === "typescript" && selected) return selected;
64
+ let packageJson: string;
65
+ try {
66
+ packageJson = requireFrom.resolve(`${name}/package.json`);
67
+ } catch {
68
+ continue;
69
+ }
70
+ const manifest = readManifest(packageJson);
71
+ if (!manifest) continue;
72
+ const majorText =
73
+ typeof manifest.version === "string"
74
+ ? manifest.version.split(".")[0]!
75
+ : "";
76
+ const major = /^\d+$/.test(majorText) ? Number(majorText) : NaN;
77
+ if (major < 7) continue;
78
+ if (
79
+ name !== "typescript" &&
80
+ (manifest.name !== "typescript" || !Number.isFinite(major))
81
+ )
82
+ continue;
83
+ const candidate = { packageJson, manifest };
84
+ if (name === "typescript") return candidate;
85
+ if (
86
+ selected &&
87
+ fs.realpathSync(selected.packageJson) !== fs.realpathSync(packageJson)
88
+ )
89
+ throw new Error(
90
+ "ttsc: multiple native TypeScript aliases are installed; select one with --binary or TTSC_TSGO_BINARY.",
91
+ );
92
+ selected = candidate;
93
+ }
94
+ return selected;
95
+ }
96
+
97
+ /** Read current manifest bytes, including after Node cached an older path. */
98
+ function readManifest(file: string): Record<string, unknown> | undefined {
99
+ try {
100
+ return JSON.parse(fs.readFileSync(file, "utf8")) as Record<string, unknown>;
101
+ } catch (error) {
102
+ if (
103
+ ["ENOENT", "ENOTDIR"].includes(
104
+ (error as NodeJS.ErrnoException).code ?? "",
105
+ )
106
+ )
107
+ return undefined;
108
+ throw error;
109
+ }
110
+ }
@@ -2,6 +2,7 @@ import fs from "node:fs";
2
2
  import { createRequire } from "node:module";
3
3
  import path from "node:path";
4
4
 
5
+ import { resolveNativeTypeScriptPackage } from "./resolveNativeTypeScriptPackage";
5
6
  import { SidecarEnvironment } from "./sharedHost/SidecarEnvironment";
6
7
 
7
8
  /**
@@ -12,13 +13,14 @@ import { SidecarEnvironment } from "./sharedHost/SidecarEnvironment";
12
13
  * 1. Select `opts.binary`, or consult `TTSC_TSGO_BINARY` only when it is absent. A
13
14
  * nonempty override must be an existing absolute path; returns `{ binary,
14
15
  * packageJson: "", packageRoot, version: "custom" }`.
15
- * 2. `typescript` resolved from the project `cwd`.
16
- * 3. `typescript` resolved from `opts.resolveFrom` (for test harnesses and
17
- * embedders that anchor to a different directory).
16
+ * 2. Declared npm aliases targeting TypeScript, then native `typescript`, from
17
+ * `cwd`.
18
+ * 3. The same discovery from `opts.resolveFrom` (for test harnesses and embedders
19
+ * that anchor to a different directory).
18
20
  *
19
21
  * Throws a descriptive error when the package or platform path is missing.
20
22
  * Manifest read/parse failures can propagate directly. Existence does not
21
- * certify a regular executable, native ABI or compiler version compatibility;
23
+ * certify a regular executable, native ABI or compiler-target compatibility;
22
24
  * this operation selects paths and metadata without executing them. Platform
23
25
  * package resolution is anchored at the chosen TypeScript manifest and can
24
26
  * follow Node's ancestor search, rather than proving both packages occupy one
@@ -29,7 +31,7 @@ import { SidecarEnvironment } from "./sharedHost/SidecarEnvironment";
29
31
  * @evidence contracts/common.md#prohibited-implementation-shortcuts Package names and lib/tsc suffixes follow the native TypeScript distribution contract. Missing dependencies remain descriptive errors rather than invented compiler paths or fixture-specific substitutes.
30
32
  * @evidence contracts/common.md#meaningful-documentation Ordered precedence, custom metadata and failures are documented separately, and the fallback anchor member explains its filename semantics following the documentation skill.
31
33
  * @evidence contracts/portability.md#os-neutral-implementation Native path APIs validate absolute overrides and select the Windows executable suffix; createRequire anchors resolution to actual package files without shell quoting or OS-derived case policy.
32
- * @evidence contracts/performance.md#efficient-algorithms A precedence sequence makes at most two TypeScript resolution attempts, one platform resolution and one manifest parse of M bytes. Node ancestor/package lookup, native existence checks and path text work have delegated costs; Windows environment override selection scans environment keys through SidecarEnvironment. Returned metadata does not retain the full parsed manifest.
34
+ * @evidence contracts/performance.md#efficient-algorithms Up to two anchors delegate ancestor manifest and alias discovery before one platform lookup. Dependency declaration counts, alias lookups, manifest bytes and path work determine cost; Windows environment selection scans environment keys through SidecarEnvironment. Returned metadata does not retain parsed manifests.
33
35
  *
34
36
  * @evidenceExclude contracts/performance.md#reuse-equivalent-work Overrides and consumer installations are mutable filesystem authority; this resolver owns no dependency invalidation source that could justify retaining a custom result across calls.
35
37
  * @evidenceExclude contracts/performance.md#bound-retention-and-release-resources Synchronous package reads retain no handles or tasks; returned path and version strings transfer to the caller without a historical metadata table.
@@ -39,7 +41,7 @@ export function resolveTsgo(
39
41
  /** Explicit path to a native `tsc` binary; bypasses package resolution. */
40
42
  binary?: string;
41
43
 
42
- /** Directory from which to discover `typescript`. */
44
+ /** Directory from which to discover native TypeScript. */
43
45
  cwd?: string;
44
46
 
45
47
  /**
@@ -75,26 +77,23 @@ export function resolveTsgo(
75
77
  }
76
78
 
77
79
  const cwd = path.resolve(opts.cwd ?? process.cwd());
78
- // Resolve the package.json of typescript.
79
- // Try cwd first, then the optional resolveFrom anchor.
80
- let packageJson: string;
81
- packageJson =
82
- resolveTypeScriptPackageJson(path.join(cwd, "package.json")) ??
80
+ const selected =
81
+ resolveNativeTypeScriptPackage(path.join(cwd, "package.json")) ??
83
82
  (opts.resolveFrom
84
- ? resolveTypeScriptPackageJson(opts.resolveFrom)
85
- : undefined) ??
86
- "";
87
- if (!packageJson) {
83
+ ? resolveNativeTypeScriptPackage(opts.resolveFrom)
84
+ : undefined);
85
+ if (!selected) {
88
86
  throw new Error(
89
87
  [
90
- "ttsc: typescript is required.",
88
+ "ttsc: native TypeScript 7 or newer is required.",
91
89
  "Install the native TypeScript compiler in the consuming project:",
92
90
  " npm i -D typescript",
91
+ "For legacy tooling, declare an npm:typescript@^7 alias in package.json.",
93
92
  ].join("\n"),
94
93
  );
95
94
  }
96
95
 
97
- const manifest = readPackageJson(packageJson);
96
+ const { packageJson, manifest } = selected;
98
97
  const packageRoot = path.dirname(packageJson);
99
98
  const platformPackage = `@typescript/typescript-${process.platform}-${process.arch}`;
100
99
  const platformResolver = createRequire(packageJson);
@@ -107,7 +106,7 @@ export function resolveTsgo(
107
106
  throw new Error(
108
107
  [
109
108
  `ttsc: platform-specific TypeScript binary not found (${platformPackage}).`,
110
- "Reinstall typescript with optional dependencies enabled.",
109
+ "Reinstall the selected native TypeScript package with optional dependencies enabled.",
111
110
  ].join("\n"),
112
111
  );
113
112
  }
@@ -132,21 +131,3 @@ export function resolveTsgo(
132
131
  typeof manifest.version === "string" ? manifest.version : "unknown",
133
132
  };
134
133
  }
135
-
136
- /**
137
- * Resolve TypeScript relative to an absolute filename accepted by
138
- * createRequire. Returns undefined when the anchor or package cannot be
139
- * resolved.
140
- */
141
- function resolveTypeScriptPackageJson(from: string): string | undefined {
142
- try {
143
- return createRequire(from).resolve("typescript/package.json");
144
- } catch {
145
- return undefined;
146
- }
147
- }
148
-
149
- /** Parse a JSON file and return the result as a plain object. */
150
- function readPackageJson(file: string): Record<string, unknown> {
151
- return JSON.parse(fs.readFileSync(file, "utf8")) as Record<string, unknown>;
152
- }