typia 15.3.1 → 15.4.1

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.
@@ -10,7 +10,9 @@ import type { ITtscPlugin, ITtscPluginFactoryContext } from "ttsc";
10
10
  * resolution, so an empty hostInputHashes declaration permits safe descriptor
11
11
  * replay. The native build host supplies generation-owned input observations
12
12
  * and compiler-owned output provenance for ttsc's checked runtime reuse
13
- * protocol.
13
+ * protocol. Its only variable reads outside ttsc's own namespace go through the
14
+ * program's recorded `Env`, so it declares `environmentInputs` and ttsc keys
15
+ * its outputs by the variables it read instead of the whole environment.
14
16
  *
15
17
  * @param context Plugin factory context of ttsc
16
18
  *
package/lib/transform.js CHANGED
@@ -17,7 +17,9 @@ const node_path_1 = __importDefault(require("node:path"));
17
17
  * resolution, so an empty hostInputHashes declaration permits safe descriptor
18
18
  * replay. The native build host supplies generation-owned input observations
19
19
  * and compiler-owned output provenance for ttsc's checked runtime reuse
20
- * protocol.
20
+ * protocol. Its only variable reads outside ttsc's own namespace go through the
21
+ * program's recorded `Env`, so it declares `environmentInputs` and ttsc keys
22
+ * its outputs by the variables it read instead of the whole environment.
21
23
  *
22
24
  * @param context Plugin factory context of ttsc
23
25
  *
@@ -41,6 +43,7 @@ function createTtscPlugin(context) {
41
43
  capabilities: {
42
44
  emitObservations: true,
43
45
  emitProvenance: true,
46
+ environmentInputs: true,
44
47
  },
45
48
  };
46
49
  }
@@ -1 +1 @@
1
- {"version":3,"file":"transform.js","sources":["../src/transform.ts"],"names":[],"mappings":";;;;;;AAAA,6CAA4C;AAC5C,0DAA6B;AAG7B;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,0BACE,OAAkC;IAElC,oEAAoE;IACpE,wEAAwE;IACxE,2EAA2E;IAC3E,MAAM,WAAW,GAAG,IAAA,2BAAa,EAC/B,mBAAI,CAAC,IAAI,CAAC,OAAO,CAAC,WAAW,EAAE,cAAc,CAAC,CAC/C,CAAC;IACF,MAAM,IAAI,GAAW,mBAAI,CAAC,OAAO,CAAC,WAAW,CAAC,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAAC;IAC7E,OAAO;QACL,IAAI,EAAE,OAAO;QACb,MAAM,EAAE,mBAAI,CAAC,OAAO,CAAC,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,YAAY,CAAC;QACzD,eAAe,EAAE,EAAE;QACnB,YAAY,EAAE;YACZ,gBAAgB,EAAE,IAAI;YACtB,cAAc,EAAE,IAAI;SACrB;KACF,CAAC;AACJ,CAAC;kBAEc,gBAAgB"}
1
+ {"version":3,"file":"transform.js","sources":["../src/transform.ts"],"names":[],"mappings":";;;;;;AAAA,6CAA4C;AAC5C,0DAA6B;AAG7B;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,0BACE,OAAkC;IAElC,oEAAoE;IACpE,wEAAwE;IACxE,2EAA2E;IAC3E,MAAM,WAAW,GAAG,IAAA,2BAAa,EAC/B,mBAAI,CAAC,IAAI,CAAC,OAAO,CAAC,WAAW,EAAE,cAAc,CAAC,CAC/C,CAAC;IACF,MAAM,IAAI,GAAW,mBAAI,CAAC,OAAO,CAAC,WAAW,CAAC,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAAC;IAC7E,OAAO;QACL,IAAI,EAAE,OAAO;QACb,MAAM,EAAE,mBAAI,CAAC,OAAO,CAAC,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,YAAY,CAAC;QACzD,eAAe,EAAE,EAAE;QACnB,YAAY,EAAE;YACZ,gBAAgB,EAAE,IAAI;YACtB,cAAc,EAAE,IAAI;YACpB,iBAAiB,EAAE,IAAI;SACxB;KACF,CAAC;AACJ,CAAC;kBAEc,gBAAgB"}
package/lib/transform.mjs CHANGED
@@ -12,7 +12,9 @@ import path from "node:path";
12
12
  * resolution, so an empty hostInputHashes declaration permits safe descriptor
13
13
  * replay. The native build host supplies generation-owned input observations
14
14
  * and compiler-owned output provenance for ttsc's checked runtime reuse
15
- * protocol.
15
+ * protocol. Its only variable reads outside ttsc's own namespace go through the
16
+ * program's recorded `Env`, so it declares `environmentInputs` and ttsc keys
17
+ * its outputs by the variables it read instead of the whole environment.
16
18
  *
17
19
  * @param context Plugin factory context of ttsc
18
20
  *
@@ -32,7 +34,8 @@ function createTtscPlugin(context) {
32
34
  hostInputHashes: {},
33
35
  capabilities: {
34
36
  emitObservations: true,
35
- emitProvenance: true
37
+ emitProvenance: true,
38
+ environmentInputs: true
36
39
  }
37
40
  };
38
41
  }
@@ -1 +1 @@
1
- {"version":3,"file":"transform.mjs","names":[],"sources":["../src/transform.ts"],"sourcesContent":["import { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport type { ITtscPlugin, ITtscPluginFactoryContext } from \"ttsc\";\n\n/**\n * Describe typia's native transform to ttsc.\n *\n * Ttsc loads this file as an ES module, where `require` is unavailable, so a\n * resolver is anchored on the consuming project to find typia's own package\n * root. The returned descriptor names the plugin and the Go command under\n * `native/cmd/ttsc-typia`; the transform itself is not written in TypeScript.\n * No file is read outside the module graph. Ttsc records the package\n * resolution, so an empty hostInputHashes declaration permits safe descriptor\n * replay. The native build host supplies generation-owned input observations\n * and compiler-owned output provenance for ttsc's checked runtime reuse\n * protocol.\n *\n * @param context Plugin factory context of ttsc\n *\n * @returns Plugin descriptor\n *\n * @evidence contracts/common.md#principled-implementation The ttsc loader runs this file as an ES module where `require` is absent, so the function builds a CommonJS resolver anchored at the consuming project and resolves typia's own `package.json`, whose directory holds the native sources. No external file is read; ttsc records that module lookup and invalidates descriptor replay when its module graph or factory inputs change. The descriptor names the plugin and Go command under `native/cmd/ttsc-typia`.\n * @evidence contracts/common.md#clear-and-simple-design One function returns the plugin name, Go source, supported native protocols and external-input declaration; the default export repeats the same function for loaders that read it.\n * @evidence contracts/common.md#prohibited-implementation-shortcuts The package root comes from the installed typia through the supported resolver and not from path substrings, so it works for npm consumers and workspaces alike; the transform itself stays in Go.\n * @evidence contracts/common.md#meaningful-documentation A comment explains the purpose, the ESM resolution reason and the descriptor.\n */\nexport function createTtscPlugin(\n context: ITtscPluginFactoryContext,\n): ITtscPlugin {\n // ttsc loads this descriptor as ESM, where the ambient `require` is\n // unavailable; anchor a CJS resolver on the consuming project to locate\n // typia's own package root (not the project root, which has no `native/`).\n const requireFrom = createRequire(\n path.join(context.projectRoot, \"package.json\"),\n );\n const root: string = path.dirname(requireFrom.resolve(\"typia/package.json\"));\n return {\n name: \"typia\",\n source: path.resolve(root, \"native\", \"cmd\", \"ttsc-typia\"),\n hostInputHashes: {},\n capabilities: {\n emitObservations: true,\n emitProvenance: true,\n },\n };\n}\n\nexport default createTtscPlugin;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,iBACd,SACa;CAIb,MAAM,cAAc,cAClB,KAAK,KAAK,QAAQ,aAAa,cAAc,CAC/C;CACA,MAAM,OAAe,KAAK,QAAQ,YAAY,QAAQ,oBAAoB,CAAC;CAC3E,OAAO;EACL,MAAM;EACN,QAAQ,KAAK,QAAQ,MAAM,UAAU,OAAO,YAAY;EACxD,iBAAiB,CAAC;EAClB,cAAc;GACZ,kBAAkB;GAClB,gBAAgB;EAClB;CACF;AACF"}
1
+ {"version":3,"file":"transform.mjs","names":[],"sources":["../src/transform.ts"],"sourcesContent":["import { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport type { ITtscPlugin, ITtscPluginFactoryContext } from \"ttsc\";\n\n/**\n * Describe typia's native transform to ttsc.\n *\n * Ttsc loads this file as an ES module, where `require` is unavailable, so a\n * resolver is anchored on the consuming project to find typia's own package\n * root. The returned descriptor names the plugin and the Go command under\n * `native/cmd/ttsc-typia`; the transform itself is not written in TypeScript.\n * No file is read outside the module graph. Ttsc records the package\n * resolution, so an empty hostInputHashes declaration permits safe descriptor\n * replay. The native build host supplies generation-owned input observations\n * and compiler-owned output provenance for ttsc's checked runtime reuse\n * protocol. Its only variable reads outside ttsc's own namespace go through the\n * program's recorded `Env`, so it declares `environmentInputs` and ttsc keys\n * its outputs by the variables it read instead of the whole environment.\n *\n * @param context Plugin factory context of ttsc\n *\n * @returns Plugin descriptor\n *\n * @evidence contracts/common.md#principled-implementation The ttsc loader runs this file as an ES module where `require` is absent, so the function builds a CommonJS resolver anchored at the consuming project and resolves typia's own `package.json`, whose directory holds the native sources. No external file is read; ttsc records that module lookup and invalidates descriptor replay when its module graph or factory inputs change. The descriptor names the plugin and Go command under `native/cmd/ttsc-typia`.\n * @evidence contracts/common.md#clear-and-simple-design One function returns the plugin name, Go source, supported native protocols and external-input declaration; the default export repeats the same function for loaders that read it.\n * @evidence contracts/common.md#prohibited-implementation-shortcuts The package root comes from the installed typia through the supported resolver and not from path substrings, so it works for npm consumers and workspaces alike; the transform itself stays in Go.\n * @evidence contracts/common.md#meaningful-documentation A comment explains the purpose, the ESM resolution reason and the descriptor.\n */\nexport function createTtscPlugin(\n context: ITtscPluginFactoryContext,\n): ITtscPlugin {\n // ttsc loads this descriptor as ESM, where the ambient `require` is\n // unavailable; anchor a CJS resolver on the consuming project to locate\n // typia's own package root (not the project root, which has no `native/`).\n const requireFrom = createRequire(\n path.join(context.projectRoot, \"package.json\"),\n );\n const root: string = path.dirname(requireFrom.resolve(\"typia/package.json\"));\n return {\n name: \"typia\",\n source: path.resolve(root, \"native\", \"cmd\", \"ttsc-typia\"),\n hostInputHashes: {},\n capabilities: {\n emitObservations: true,\n emitProvenance: true,\n environmentInputs: true,\n },\n };\n}\n\nexport default createTtscPlugin;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,SAAgB,iBACd,SACa;CAIb,MAAM,cAAc,cAClB,KAAK,KAAK,QAAQ,aAAa,cAAc,CAC/C;CACA,MAAM,OAAe,KAAK,QAAQ,YAAY,QAAQ,oBAAoB,CAAC;CAC3E,OAAO;EACL,MAAM;EACN,QAAQ,KAAK,QAAQ,MAAM,UAAU,OAAO,YAAY;EACxD,iBAAiB,CAAC;EAClB,cAAc;GACZ,kBAAkB;GAClB,gBAAgB;GAChB,mBAAmB;EACrB;CACF;AACF"}
@@ -0,0 +1,144 @@
1
+ package main
2
+
3
+ import (
4
+ "encoding/json"
5
+ "os"
6
+ "path/filepath"
7
+ "strings"
8
+ "testing"
9
+ )
10
+
11
+ // TestProjectTransformPublishesUntouchedSourceVerbatim verifies the transform
12
+ // envelope publishes a file typia did not change as its authored text, and a
13
+ // file typia changed with a source map back to its authored text.
14
+ //
15
+ // The consumer keeps a module only when the published text equals the text it
16
+ // read. A printed copy of an unchanged file differs from it in formatting, so a
17
+ // bundler took every module as transformed and served lines that no longer
18
+ // matched the file; under Bun, which ignores the map an `onLoad` returns,
19
+ // breakpoints broke in every module of a typia project (samchon/typia#2557).
20
+ //
21
+ // 1. Build a project whose `main.ts` calls `typia.is<Point>()`, whose
22
+ // `plain.ts` has no typia call and is formatted the way the printer would
23
+ // rewrite it, and whose `crlf.ts` has no typia call and CRLF line endings.
24
+ // 2. Run project transform mode and decode the JSON envelope.
25
+ // 3. Assert `plain.ts` and `crlf.ts` are published byte for byte as written,
26
+ // with no source map entry.
27
+ // 4. Assert `main.ts` is lowered and carries a version 3 map whose
28
+ // `sourcesContent` is its authored text.
29
+ // 5. Run single-file transform mode on `plain.ts` and assert it prints the
30
+ // authored text too.
31
+ //
32
+ // @evidence contracts/testing.md#behavioral-verification The decoded envelope publishes plain.ts and crlf.ts byte for byte without a map entry, lowers main.ts with a version 3 map naming main.ts, and single-file mode prints plain.ts as written.
33
+ // @evidence contracts/testing.md#independent-expectations The authored fixture strings are the oracle for the unchanged files and for the map's sourcesContent; the lowered main.ts is recognized by the absence of the `typia.is<Point>` call it replaces, not by output the implementation produced.
34
+ // @evidence contracts/testing.md#distinguishing-cases A transformed file is paired with two untransformed ones, one formatted unlike the printer's output and one with CRLF endings the printer would normalize, so a reprint fails either comparison and a missing or misattached map fails the main.ts checks.
35
+ // @evidence contracts/testing.md#execution-ownership The native Go runner discovers TestProjectTransformPublishesUntouchedSourceVerbatim as a unit test. Its fixture project and captured runTransform calls exercise the owning Go operation in process; no consumer installation or compiler subprocess is used.
36
+ func TestProjectTransformPublishesUntouchedSourceVerbatim(t *testing.T) {
37
+ project := projectTransformUntouchedSourceProject(t)
38
+ out, errText, code := ttscTypiaTestCapture(func() int {
39
+ return runTransform([]string{
40
+ "--cwd", project,
41
+ "--tsconfig", "tsconfig.json",
42
+ "--output", "ts",
43
+ })
44
+ })
45
+ if code != 0 {
46
+ t.Fatalf("project transform failed: code=%d stderr=\n%s", code, errText)
47
+ }
48
+ var envelope struct {
49
+ TypeScript map[string]string `json:"typescript"`
50
+ SourceMaps map[string]struct {
51
+ Version int `json:"version"`
52
+ File string `json:"file"`
53
+ Sources []string `json:"sources"`
54
+ SourcesContent []*string `json:"sourcesContent"`
55
+ Mappings string `json:"mappings"`
56
+ } `json:"sourceMaps"`
57
+ }
58
+ if err := json.Unmarshal([]byte(out), &envelope); err != nil {
59
+ t.Fatalf("decode envelope: %v\n%s", err, out)
60
+ }
61
+
62
+ for key, authored := range map[string]string{
63
+ "src/plain.ts": projectTransformUntouchedSourcePlain,
64
+ "src/crlf.ts": projectTransformUntouchedSourceCRLF,
65
+ } {
66
+ if text, ok := envelope.TypeScript[key]; !ok || text != authored {
67
+ t.Fatalf("%s has no typia call and must be published as written:\nwant %q\ngot %q", key, authored, text)
68
+ }
69
+ if _, ok := envelope.SourceMaps[key]; ok {
70
+ t.Fatalf("%s is published as written and must carry no source map", key)
71
+ }
72
+ }
73
+
74
+ main := envelope.TypeScript["src/main.ts"]
75
+ if main == "" || strings.Contains(main, "typia.is<Point>") {
76
+ t.Fatalf("src/main.ts must be published with its typia call lowered, got:\n%s", main)
77
+ }
78
+ sourceMap, ok := envelope.SourceMaps["src/main.ts"]
79
+ if !ok {
80
+ t.Fatalf("src/main.ts was changed and must carry a source map:\n%s", out)
81
+ }
82
+ if sourceMap.Version != 3 || sourceMap.Mappings == "" || sourceMap.File != "main.ts" {
83
+ t.Fatalf("src/main.ts must carry a version 3 map for main.ts with mappings: %+v", sourceMap)
84
+ }
85
+ if len(sourceMap.Sources) != 1 || sourceMap.Sources[0] != "main.ts" {
86
+ t.Fatalf("the src/main.ts map must name main.ts as its one source: %v", sourceMap.Sources)
87
+ }
88
+ if len(sourceMap.SourcesContent) != 1 || sourceMap.SourcesContent[0] == nil || *sourceMap.SourcesContent[0] != projectTransformUntouchedSourceMain {
89
+ t.Fatalf("the src/main.ts map must carry the authored text as its sourcesContent: %v", sourceMap.SourcesContent)
90
+ }
91
+
92
+ single, errText, code := ttscTypiaTestCapture(func() int {
93
+ return runTransform([]string{
94
+ "--cwd", project,
95
+ "--tsconfig", "tsconfig.json",
96
+ "--file", "src/plain.ts",
97
+ "--output", "ts",
98
+ })
99
+ })
100
+ if code != 0 {
101
+ t.Fatalf("single-file transform failed: code=%d stderr=\n%s", code, errText)
102
+ }
103
+ if single != projectTransformUntouchedSourcePlain {
104
+ t.Fatalf("single-file mode must print an untouched file as written:\nwant %q\ngot %q", projectTransformUntouchedSourcePlain, single)
105
+ }
106
+ }
107
+
108
+ func projectTransformUntouchedSourceProject(t *testing.T) string {
109
+ t.Helper()
110
+ dir := ttscTypiaTestFixtureDirectory(t, "project-transform-untouched-source-")
111
+ src := filepath.Join(dir, "src")
112
+ if err := os.MkdirAll(src, 0o755); err != nil {
113
+ t.Fatalf("mkdir fixture src: %v", err)
114
+ }
115
+ if err := os.WriteFile(filepath.Join(dir, "tsconfig.json"), []byte(projectDependenciesEnvelopeTSConfig), 0o644); err != nil {
116
+ t.Fatalf("write tsconfig: %v", err)
117
+ }
118
+ for name, body := range map[string]string{
119
+ "main.ts": projectTransformUntouchedSourceMain,
120
+ "plain.ts": projectTransformUntouchedSourcePlain,
121
+ "crlf.ts": projectTransformUntouchedSourceCRLF,
122
+ } {
123
+ if err := os.WriteFile(filepath.Join(src, name), []byte(body), 0o644); err != nil {
124
+ t.Fatalf("write %s: %v", name, err)
125
+ }
126
+ }
127
+ return dir
128
+ }
129
+
130
+ const projectTransformUntouchedSourceMain = `import typia from "typia";
131
+
132
+ import type { Point } from "./plain";
133
+
134
+ export const isPoint = (input: unknown) => typia.is<Point>(input);
135
+ `
136
+
137
+ const projectTransformUntouchedSourcePlain = `export interface Point { x: number; y: number }
138
+
139
+
140
+ export const origin: Point = {x:0,y:0};
141
+ export function add(a:Point,b:Point):Point{return {x:a.x+b.x,y:a.y+b.y}}
142
+ `
143
+
144
+ const projectTransformUntouchedSourceCRLF = "export const greeting: string = \"hello\";\r\n\r\nexport const twice = (value: string): string => value + value;\r\n"
@@ -25,7 +25,7 @@ import (
25
25
  // runTransform is the source-to-source host that drives the ttsc transform
26
26
  // stage. Unlike `build` (which emits .js), it returns
27
27
  // transformed TypeScript: typia's per-file node transformer runs in an
28
- // EmitContext and the result SourceFile is printed back as TS (no JS script
28
+ // EmitContext and a changed SourceFile is printed back as TS (no JS script
29
29
  // transformers), so injected namespace imports stay as ES imports the caller
30
30
  // can type-strip per file. With no --file it emits a JSON envelope of every
31
31
  // project source keyed by its cwd-relative path; with --file it prints one file.
@@ -41,7 +41,7 @@ func runTransform(args []string) int {
41
41
  cwdOverride := fs.String("cwd", "", "override the working directory")
42
42
  out := fs.String("out", "", "write single-file output to PATH instead of stdout")
43
43
  rewriteMode := fs.String("rewrite-mode", "typia", "native rewrite backend id")
44
- output := fs.String("output", defaultTransformOutput(), "single-file output kind: js or ts")
44
+ output := fs.String("output", "", "single-file output kind: js or ts (default: TYPIA_TTSC_TRANSFORM_OUTPUT, else ts)")
45
45
  pluginsJSON := fs.String("plugins-json", "", "ordered ttsc plugin payload")
46
46
  if err := fs.Parse(args); err != nil {
47
47
  return 2
@@ -50,7 +50,7 @@ func runTransform(args []string) int {
50
50
  fmt.Fprintf(stderr, "ttsc-typia transform: unknown --rewrite-mode value %q\n", *rewriteMode)
51
51
  return 2
52
52
  }
53
- if *output != "js" && *output != "ts" {
53
+ if *output != "" && *output != "js" && *output != "ts" {
54
54
  fmt.Fprintf(stderr, "ttsc-typia transform: unknown --output value %q\n", *output)
55
55
  return 2
56
56
  }
@@ -119,11 +119,16 @@ func runTransform(args []string) int {
119
119
  fmt.Fprintf(stderr, "ttsc-typia transform: source file is not in program: %s\n", absFile)
120
120
  return 2
121
121
  }
122
+ kind := *output
123
+ if kind == "" {
124
+ kind = defaultTransformOutput(prog)
125
+ }
122
126
  return runTransformSingle(cwd, *out, &transformDiags, func() (string, int) {
123
- if *output == "js" {
127
+ if kind == "js" {
124
128
  return transformSingleToJavaScript(prog, typiaTransform, target)
125
129
  }
126
- return transformFileToTypeScript(prog, typiaTransform, target), 0
130
+ text, _ := transformFileToTypeScript(prog, typiaTransform, target)
131
+ return text, 0
127
132
  })
128
133
  }
129
134
 
@@ -175,11 +180,12 @@ func runTransformSingle(
175
180
  return writeSingleOutput(text, outPath)
176
181
  }
177
182
 
178
- // runTransformProject prints every non-declaration project source as transformed
179
- // TypeScript and encodes the JSON envelope the ttsc host expects. Alongside the
180
- // transformed sources it reports two invalidation channels the ttsc consumer
181
- // registers with the bundler so persistent caches and watch mode invalidate
182
- // generated validators soundly:
183
+ // runTransformProject publishes every non-declaration project source as
184
+ // TypeScript, printed with a source map where it was changed and as its
185
+ // authored text where it was not, and encodes the JSON envelope the ttsc host
186
+ // expects. Alongside the sources it reports two invalidation channels the ttsc
187
+ // consumer registers with the bundler so persistent caches and watch mode
188
+ // invalidate generated validators soundly:
183
189
  //
184
190
  // - `graph`, the host-owned reference graph of the loaded program (direct
185
191
  // resolved edges, ambient globals, tsconfig extends chain) computed by the
@@ -256,7 +262,14 @@ func runTransformProject(
256
262
  continue
257
263
  }
258
264
  collector.Begin(key)
259
- out.TypeScript[key] = transformFileToTypeScript(prog, typiaTransform, sf)
265
+ text, sourceMap := transformFileToTypeScript(prog, typiaTransform, sf)
266
+ out.TypeScript[key] = text
267
+ if sourceMap != "" {
268
+ if out.SourceMaps == nil {
269
+ out.SourceMaps = map[string]json.RawMessage{}
270
+ }
271
+ out.SourceMaps[key] = json.RawMessage(sourceMap)
272
+ }
260
273
  collector.End()
261
274
  }
262
275
  out.Dependencies = collector.ToJSON()
@@ -281,24 +294,54 @@ func runTransformProject(
281
294
  }
282
295
 
283
296
  // transformFileToTypeScript runs typia's node transformer on one source file in
284
- // a fresh EmitContext and prints the result as TypeScript. It deliberately skips
285
- // the JS script transformers (type-erase, module-transform): the caller wants TS.
297
+ // a fresh EmitContext and returns the file's TypeScript with a source map back
298
+ // to the authored text. It deliberately skips the JS script transformers
299
+ // (type-erase, module-transform): the caller wants TS.
300
+ //
301
+ // A file typia left alone comes back as the parsed text itself, with no map.
302
+ // The transformer rebuilds a node only when it replaces something beneath it,
303
+ // so the original SourceFile coming back means nothing was replaced. Printing
304
+ // it anyway would hand the consumer the author's code in the printer's
305
+ // formatting, which a bundler then takes as a changed module and serves with
306
+ // lines that no longer match the file on disk; a host that ignores input maps,
307
+ // such as Bun's `onLoad`, loses breakpoints in every module (samchon/typia#2557).
308
+ //
309
+ // The parsed text is the authored text only while nothing else rewrote the
310
+ // file. A linked ProgramPlugin edits the tree in place without replacing the
311
+ // SourceFile, and a linked source preamble is inserted into the parsed text,
312
+ // so under either the file is printed like a changed one.
313
+ //
314
+ // A printed file carries a version 3 map back to the authored text, with that
315
+ // text as `sourcesContent`, so the consumer can check the map against the text
316
+ // it was handed before composing it. The driver moves a preamble-bearing map
317
+ // off the preamble; a map it cannot correct is dropped rather than published
318
+ // pointing at the wrong lines, and a printed text equal to the authored text
319
+ // needs no map.
286
320
  func transformFileToTypeScript(
287
321
  prog *driver.Program,
288
322
  typiaTransform driver.PluginTransform,
289
323
  sf *shimast.SourceFile,
290
- ) string {
291
- options := prog.TSProgram.Options()
324
+ ) (string, string) {
292
325
  ec := shimprinter.NewEmitContext()
293
326
  result := sf
294
327
  if next := typiaTransform(ec, result); next != nil {
295
328
  result = next
296
329
  }
330
+ if result == sf && prog.SourcePreamble == "" && !prog.HasLinkedProgramPlugins() {
331
+ return sf.Text(), ""
332
+ }
297
333
  shimast.SetParentInChildrenUnset(result.AsNode())
298
- writer := shimprinter.NewTextWriter(options.NewLine.GetNewLineCharacter(), 0)
299
- printer := shimprinter.NewPrinter(shimprinter.PrinterOptions{NewLine: options.NewLine}, shimprinter.PrintHandlers{}, ec)
300
- printer.Write(result.AsNode(), result, writer, nil)
301
- return writer.String()
334
+ text, sourceMap := shimprinter.EmitSourceFileWithSourceMap(
335
+ shimprinter.PrinterOptions{NewLine: prog.TSProgram.Options().NewLine, InlineSources: true},
336
+ shimprinter.PrintHandlers{},
337
+ ec,
338
+ result,
339
+ )
340
+ authored, corrected, ok := prog.AuthoredSourceMap(sf, sourceMap)
341
+ if !ok || text == authored {
342
+ return text, ""
343
+ }
344
+ return text, corrected
302
345
  }
303
346
 
304
347
  // transformSingleToJavaScript emits a single file's JS through the full node-path
@@ -377,8 +420,13 @@ func writeSingleOutput(text, outPath string) int {
377
420
  return 0
378
421
  }
379
422
 
380
- func defaultTransformOutput() string {
381
- if os.Getenv("TYPIA_TTSC_TRANSFORM_OUTPUT") == "js" {
423
+ // defaultTransformOutput is the single-file output kind when --output is not
424
+ // given: `TYPIA_TTSC_TRANSFORM_OUTPUT=js` selects JavaScript, anything else
425
+ // TypeScript. It is read through the program, which records the read as an
426
+ // input of this generation, so a host that reuses this output under another
427
+ // value sees the change; os.Getenv was recorded by nothing (samchon/ttsc#1852).
428
+ func defaultTransformOutput(prog *driver.Program) string {
429
+ if value, _ := prog.Env("TYPIA_TTSC_TRANSFORM_OUTPUT"); value == "js" {
382
430
  return "js"
383
431
  }
384
432
  return "ts"
@@ -387,6 +435,10 @@ func defaultTransformOutput() string {
387
435
  type transformProjectOutput struct {
388
436
  Diagnostics []transformCompilerDiagnostic `json:"diagnostics,omitempty"`
389
437
  TypeScript map[string]string `json:"typescript"`
438
+ // SourceMaps maps each printed TypeScript key whose text differs from the
439
+ // authored text to a version 3 map back to that text, keyed like TypeScript.
440
+ // A file published as its authored text has no entry.
441
+ SourceMaps map[string]json.RawMessage `json:"sourceMaps,omitempty"`
390
442
  // Graph is the host-owned reference graph of the loaded program produced by
391
443
  // the ttsc driver SDK (driver.NewTransformGraph): direct resolved reference
392
444
  // edges, ambient global-scope files, and the tsconfig extends chain, keyed
@@ -0,0 +1,67 @@
1
+ package main
2
+
3
+ import (
4
+ "os"
5
+ "path/filepath"
6
+ "strings"
7
+ "testing"
8
+ )
9
+
10
+ // TestTransformOutputDefaultFollowsTheRecordedVariable verifies the single-file
11
+ // output kind defaults to TYPIA_TTSC_TRANSFORM_OUTPUT read through the loaded
12
+ // program, and that an explicit --output still wins.
13
+ //
14
+ // The default was read with os.Getenv while flags were parsed, before any
15
+ // program existed, so nothing recorded it and a host reusing output across
16
+ // launches could not tell a changed value (samchon/ttsc#1852). The program's
17
+ // Env records the read as an input of the generation.
18
+ //
19
+ // 1. Transform one annotated declaration with the variable set to js and no
20
+ // --output: the annotation is gone.
21
+ // 2. Keep the variable at js and pass --output ts: the annotation stays.
22
+ // 3. Unset the variable: the annotation stays.
23
+ //
24
+ // @evidence contracts/testing.md#behavioral-verification The real transform command runs over a real program; the printed declaration shows which output kind ran.
25
+ // @evidence contracts/testing.md#independent-expectations TypeScript output keeps the authored `: number` annotation and JavaScript output drops it, independently of typia's rewriting.
26
+ // @evidence contracts/testing.md#distinguishing-cases The variable set, unset, and overridden by an explicit flag separate the default from the flag.
27
+ // @evidence contracts/testing.md#execution-ownership The native Go runner owns the temporary fixture and the in-process transform; t.Setenv restores the variable.
28
+ func TestTransformOutputDefaultFollowsTheRecordedVariable(t *testing.T) {
29
+ dir := ttscTypiaTestFixtureDirectory(t, "transform-output-default-")
30
+ src := filepath.Join(dir, "src")
31
+ if err := os.MkdirAll(src, 0o755); err != nil {
32
+ t.Fatalf("mkdir fixture src: %v", err)
33
+ }
34
+ if err := os.WriteFile(filepath.Join(dir, "tsconfig.json"), []byte(atomicIntersectionSchemaTSConfig), 0o644); err != nil {
35
+ t.Fatalf("write tsconfig: %v", err)
36
+ }
37
+ if err := os.WriteFile(filepath.Join(src, "main.ts"), []byte("export const answer: number = 42;\n"), 0o644); err != nil {
38
+ t.Fatalf("write source: %v", err)
39
+ }
40
+ transform := func(extra ...string) string {
41
+ t.Helper()
42
+ out, errText, code := ttscTypiaTestCapture(func() int {
43
+ return runTransform(append([]string{
44
+ "--cwd", dir,
45
+ "--tsconfig", "tsconfig.json",
46
+ "--file", "src/main.ts",
47
+ }, extra...))
48
+ })
49
+ if code != 0 {
50
+ t.Fatalf("transform failed: code=%d stderr=\n%s", code, errText)
51
+ }
52
+ return out
53
+ }
54
+ annotated := func(out string) bool { return strings.Contains(out, "answer: number") }
55
+
56
+ t.Setenv("TYPIA_TTSC_TRANSFORM_OUTPUT", "js")
57
+ if out := transform(); annotated(out) {
58
+ t.Fatalf("the variable selects JavaScript output:\n%s", out)
59
+ }
60
+ if out := transform("--output", "ts"); !annotated(out) {
61
+ t.Fatalf("an explicit --output ts wins over the variable:\n%s", out)
62
+ }
63
+ os.Unsetenv("TYPIA_TTSC_TRANSFORM_OUTPUT")
64
+ if out := transform(); !annotated(out) {
65
+ t.Fatalf("without the variable the output is TypeScript:\n%s", out)
66
+ }
67
+ }
@@ -0,0 +1,168 @@
1
+ package main
2
+
3
+ import (
4
+ "encoding/json"
5
+ "os"
6
+ "path/filepath"
7
+ "strings"
8
+ "testing"
9
+
10
+ shimast "github.com/microsoft/typescript-go/shim/ast"
11
+ shimcore "github.com/microsoft/typescript-go/shim/core"
12
+ shimprinter "github.com/microsoft/typescript-go/shim/printer"
13
+ "github.com/samchon/ttsc/packages/ttsc/driver"
14
+ )
15
+
16
+ // The driver pairs manifest entries with registrations by position. Go runs
17
+ // package init functions in file-name order, so this registration follows the
18
+ // one in build_emit_hook_observations_test.go and answers manifest entry 1.
19
+ func init() { driver.RegisterPlugin(transformLinkedEditPlugin{}) }
20
+
21
+ // TestTransformPrintsFilesRewrittenOutsideTypia verifies a file typia did not
22
+ // change is still printed, with a map back to its authored text, when its
23
+ // parsed text is not that authored text.
24
+ //
25
+ // The transform host publishes an untouched file as its parsed text instead of
26
+ // printing it (samchon/typia#2557). That holds only while nothing else rewrote
27
+ // the file: a linked source preamble is inserted into the parsed text, and a
28
+ // linked ProgramPlugin edits the tree in place, so publishing the parsed text
29
+ // would leak the preamble without a map or drop the plugin's edit.
30
+ //
31
+ // 1. Load a project with a source preamble and run the TypeScript printer on a
32
+ // file through a transform that changes nothing.
33
+ // 2. Assert the published text keeps the preamble and carries a map whose
34
+ // `sourcesContent` is the authored text without it.
35
+ // 3. Run project transform mode with a linked ProgramPlugin that rewrites a
36
+ // string literal in a file typia does not touch.
37
+ // 4. Assert the envelope publishes the rewritten literal, with a map back to
38
+ // the authored text.
39
+ //
40
+ // @evidence contracts/testing.md#behavioral-verification The preamble file is published with the preamble and a map whose sourcesContent is the authored text, and the linked plugin's in-place rewrite reaches the decoded project envelope with its map.
41
+ // @evidence contracts/testing.md#independent-expectations The authored fixture strings and the literal the fixture plugin writes are the oracles; no expected text is printed by the implementation under test.
42
+ // @evidence contracts/testing.md#distinguishing-cases A preamble with no tree edit and a tree edit with no preamble each leave typia's result pointer unchanged, so publishing the parsed text fails the preamble map check in one case and the rewritten literal check in the other.
43
+ // @evidence contracts/testing.md#execution-ownership The native Go runner discovers TestTransformPrintsFilesRewrittenOutsideTypia as a unit test. It loads fixture Programs through the driver and captured runTransform calls in process, selects the linked plugin with t.Setenv, and starts no consumer or compiler subprocess.
44
+ func TestTransformPrintsFilesRewrittenOutsideTypia(t *testing.T) {
45
+ t.Run("source preamble", func(t *testing.T) {
46
+ project := transformRewrittenOutsideTypiaProject(t, "transform-preamble-")
47
+ prog, diags, err := driver.LoadProgram(project, "tsconfig.json", driver.LoadProgramOptions{
48
+ ForceEmit: true,
49
+ SourcePreamble: transformRewrittenOutsideTypiaPreamble,
50
+ })
51
+ if err != nil || len(diags) != 0 {
52
+ t.Fatalf("load program: err=%v diagnostics=%#v", err, diags)
53
+ }
54
+ defer prog.Close()
55
+ sf := prog.SourceFile(filepath.ToSlash(filepath.Join(project, "src", "plain.ts")))
56
+ if sf == nil || !strings.Contains(sf.Text(), transformRewrittenOutsideTypiaPreamble) {
57
+ t.Fatalf("src/plain.ts must be parsed with the preamble")
58
+ }
59
+ unchanged := func(_ *shimprinter.EmitContext, file *shimast.SourceFile) *shimast.SourceFile { return file }
60
+ text, sourceMap := transformFileToTypeScript(prog, unchanged, sf)
61
+ if !strings.Contains(text, "// banner") || !strings.Contains(text, "spec") {
62
+ t.Fatalf("the preamble-bearing file must be printed with the preamble:\n%s", text)
63
+ }
64
+ transformRewrittenOutsideTypiaAssertMap(t, sourceMap)
65
+ })
66
+
67
+ t.Run("linked program plugin", func(t *testing.T) {
68
+ project := transformRewrittenOutsideTypiaProject(t, "transform-linked-edit-")
69
+ // Manifest entry 0 answers buildObservationPlugin, which records this file.
70
+ if err := os.WriteFile(filepath.Join(project, "external.txt"), []byte("consumed\n"), 0o644); err != nil {
71
+ t.Fatalf("write external input: %v", err)
72
+ }
73
+ payload, _ := json.Marshal([]driver.PluginEntry{
74
+ {Name: "observation-test", Stage: "transform", Config: map[string]any{"mode": "complete"}},
75
+ {Name: "linked-edit", Stage: "transform", Config: map[string]any{}},
76
+ })
77
+ t.Setenv(driver.LinkedPluginsEnv, string(payload))
78
+ out, errText, code := ttscTypiaTestCapture(func() int {
79
+ return runTransform([]string{
80
+ "--cwd", project,
81
+ "--tsconfig", "tsconfig.json",
82
+ "--output", "ts",
83
+ })
84
+ })
85
+ if code != 0 {
86
+ t.Fatalf("project transform failed: code=%d stderr=\n%s", code, errText)
87
+ }
88
+ var envelope struct {
89
+ TypeScript map[string]string `json:"typescript"`
90
+ SourceMaps map[string]json.RawMessage `json:"sourceMaps"`
91
+ }
92
+ if err := json.Unmarshal([]byte(out), &envelope); err != nil {
93
+ t.Fatalf("decode envelope: %v\n%s", err, out)
94
+ }
95
+ text := envelope.TypeScript["src/plain.ts"]
96
+ if !strings.Contains(text, "linked-applied") || strings.Contains(text, "linked-pending") {
97
+ t.Fatalf("src/plain.ts must be published with the linked plugin's edit:\n%s", text)
98
+ }
99
+ transformRewrittenOutsideTypiaAssertMap(t, string(envelope.SourceMaps["src/plain.ts"]))
100
+ })
101
+ }
102
+
103
+ func transformRewrittenOutsideTypiaAssertMap(t *testing.T, sourceMap string) {
104
+ t.Helper()
105
+ var decoded struct {
106
+ Version int `json:"version"`
107
+ Sources []string `json:"sources"`
108
+ SourcesContent []*string `json:"sourcesContent"`
109
+ Mappings string `json:"mappings"`
110
+ }
111
+ if err := json.Unmarshal([]byte(sourceMap), &decoded); err != nil {
112
+ t.Fatalf("src/plain.ts must carry a source map: %v\n%s", err, sourceMap)
113
+ }
114
+ if decoded.Version != 3 || decoded.Mappings == "" || len(decoded.Sources) != 1 || decoded.Sources[0] != "plain.ts" {
115
+ t.Fatalf("src/plain.ts must carry a version 3 map for plain.ts: %s", sourceMap)
116
+ }
117
+ if len(decoded.SourcesContent) != 1 || decoded.SourcesContent[0] == nil || *decoded.SourcesContent[0] != transformRewrittenOutsideTypiaPlain {
118
+ t.Fatalf("the src/plain.ts map must carry the authored text as its sourcesContent: %s", sourceMap)
119
+ }
120
+ }
121
+
122
+ func transformRewrittenOutsideTypiaProject(t *testing.T, prefix string) string {
123
+ t.Helper()
124
+ dir := ttscTypiaTestFixtureDirectory(t, prefix)
125
+ if err := os.MkdirAll(filepath.Join(dir, "src"), 0o755); err != nil {
126
+ t.Fatalf("mkdir fixture src: %v", err)
127
+ }
128
+ if err := os.WriteFile(filepath.Join(dir, "tsconfig.json"), []byte(projectDependenciesEnvelopeTSConfig), 0o644); err != nil {
129
+ t.Fatalf("write tsconfig: %v", err)
130
+ }
131
+ if err := os.WriteFile(filepath.Join(dir, "src", "plain.ts"), []byte(transformRewrittenOutsideTypiaPlain), 0o644); err != nil {
132
+ t.Fatalf("write plain.ts: %v", err)
133
+ }
134
+ return dir
135
+ }
136
+
137
+ const transformRewrittenOutsideTypiaPreamble = "// banner\n"
138
+
139
+ const transformRewrittenOutsideTypiaPlain = `export const spec = "linked-pending";
140
+ export const twice = (value: number): number => value * 2;
141
+ `
142
+
143
+ // transformLinkedEditPlugin is a linked ProgramPlugin shaped like @ttsc/paths:
144
+ // it rewrites a string literal in place, leaving every SourceFile pointer as
145
+ // it was.
146
+ type transformLinkedEditPlugin struct{}
147
+
148
+ func (transformLinkedEditPlugin) ApplyProgram(prog *driver.Program, _ driver.PluginContext) error {
149
+ for _, sf := range prog.SourceFiles() {
150
+ transformLinkedEditRewrite(sf.AsNode())
151
+ }
152
+ return nil
153
+ }
154
+
155
+ func transformLinkedEditRewrite(node *shimast.Node) {
156
+ if node == nil {
157
+ return
158
+ }
159
+ if node.Kind == shimast.KindStringLiteral && node.Text() == "linked-pending" {
160
+ node.AsStringLiteral().Text = "linked-applied"
161
+ node.Flags |= shimast.NodeFlagsSynthesized
162
+ node.Loc = shimcore.UndefinedTextRange()
163
+ }
164
+ node.ForEachChild(func(child *shimast.Node) bool {
165
+ transformLinkedEditRewrite(child)
166
+ return false
167
+ })
168
+ }
package/native/go.mod CHANGED
@@ -2,7 +2,7 @@ module github.com/samchon/typia/packages/typia/native
2
2
 
3
3
  go 1.26
4
4
 
5
- // The supported ttsc floor (>= 0.36.3, including negotiated emit observations)
5
+ // The supported ttsc floor (>= 0.37.0, including recorded environment inputs)
6
6
  // is enforced through typia's package.json peerDependency, not here: ttsc builds
7
7
  // this plugin from source on the user's machine and its buildSourcePlugin
8
8
  // generates `replace github.com/samchon/ttsc/packages/ttsc v0.0.0 =>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "typia",
3
- "version": "15.3.1",
3
+ "version": "15.4.1",
4
4
  "description": "Superfast runtime validators with only one line",
5
5
  "main": "lib/index.js",
6
6
  "exports": {
@@ -43,11 +43,11 @@
43
43
  "homepage": "https://typia.io",
44
44
  "dependencies": {
45
45
  "randexp": "^0.5.3",
46
- "@typia/interface": "^15.3.1",
47
- "@typia/utils": "^15.3.1"
46
+ "@typia/interface": "^15.4.1",
47
+ "@typia/utils": "^15.4.1"
48
48
  },
49
49
  "peerDependencies": {
50
- "ttsc": ">=0.36.3"
50
+ "ttsc": ">=0.37.0"
51
51
  },
52
52
  "peerDependenciesMeta": {
53
53
  "ttsc": {
@@ -58,7 +58,7 @@
58
58
  "@types/node": "^25.3.0",
59
59
  "rimraf": "^6.1.2",
60
60
  "rolldown": "^1.1.5",
61
- "ttsc": "^0.36.3",
61
+ "ttsc": "^0.37.0",
62
62
  "typescript": "7.1.0-dev.20261020.3"
63
63
  },
64
64
  "sideEffects": false,
package/src/transform.ts CHANGED
@@ -13,7 +13,9 @@ import type { ITtscPlugin, ITtscPluginFactoryContext } from "ttsc";
13
13
  * resolution, so an empty hostInputHashes declaration permits safe descriptor
14
14
  * replay. The native build host supplies generation-owned input observations
15
15
  * and compiler-owned output provenance for ttsc's checked runtime reuse
16
- * protocol.
16
+ * protocol. Its only variable reads outside ttsc's own namespace go through the
17
+ * program's recorded `Env`, so it declares `environmentInputs` and ttsc keys
18
+ * its outputs by the variables it read instead of the whole environment.
17
19
  *
18
20
  * @param context Plugin factory context of ttsc
19
21
  *
@@ -41,6 +43,7 @@ export function createTtscPlugin(
41
43
  capabilities: {
42
44
  emitObservations: true,
43
45
  emitProvenance: true,
46
+ environmentInputs: true,
44
47
  },
45
48
  };
46
49
  }