typia 15.4.0 → 15.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,92 @@
1
+ package main
2
+
3
+ import (
4
+ "fmt"
5
+ "io"
6
+ "sync"
7
+
8
+ shimast "github.com/microsoft/typescript-go/shim/ast"
9
+ shimcompiler "github.com/microsoft/typescript-go/shim/compiler"
10
+ shimcore "github.com/microsoft/typescript-go/shim/core"
11
+ shimprinter "github.com/microsoft/typescript-go/shim/printer"
12
+ "github.com/samchon/ttsc/packages/ttsc/driver"
13
+ nativecontext "github.com/samchon/typia/packages/typia/native/core/context"
14
+ schemametadata "github.com/samchon/typia/packages/typia/native/core/schemas/metadata"
15
+ nativetransform "github.com/samchon/typia/packages/typia/native/transform"
16
+ )
17
+
18
+ // analyzeTypiaProgram answers an analysis-only run over a Program whose own
19
+ // diagnostics were clean: the linked program hooks' outcome, then typia's
20
+ // transform diagnostics. Its status is 3 when either fails and 0 otherwise.
21
+ //
22
+ // The emit lane learns the same answer by printing every file. Here typia's
23
+ // transformer runs over exactly the files that lane transforms, each in its own
24
+ // EmitContext, and its output is discarded unprinted. Neither the builtin script
25
+ // transformers, the linked emit transforms nor the printer report a TypeScript
26
+ // or typia diagnostic, so skipping them leaves the answer unchanged; the
27
+ // linked emit transforms are left out as ttsc's own analysis-only check leaves
28
+ // them out.
29
+ //
30
+ // typia's transformer rebuilds every ancestor of a rewritten call through the
31
+ // EmitContext's factory and writes nothing into a node it was given, so the
32
+ // Program's parsed ASTs stay as parsed and a resident host may keep the Program
33
+ // for its next request. Linked ProgramPlugins are different: ApplyLinkedPlugins
34
+ // rewrites those ASTs in place before typia reads them.
35
+ //
36
+ // The cost is one typia traversal per emitted source file over the Program the
37
+ // caller already loaded and diagnosed; the default-library classifier is
38
+ // registered for this call only.
39
+ func analyzeTypiaProgram(prog *driver.Program, settings buildSettings, out, errOut io.Writer) int {
40
+ registerTypiaDefaultLibraryClassifier(prog)
41
+ defer schemametadata.MetadataDefaultLibrary_release(prog.Checker)
42
+ if !settings.quiet {
43
+ writeTypiaBuildSummary(out, settings, false)
44
+ }
45
+ // The emit lane reports a hook failure through the emit funnel, so its text
46
+ // stays the same here.
47
+ if err := prog.ApplyLinkedPlugins(); err != nil {
48
+ fmt.Fprintf(errOut, "ttsc-typia build: emit failed: %v\n", err)
49
+ return 3
50
+ }
51
+ if settings.rewriteMode != "typia" {
52
+ return 0
53
+ }
54
+ diagnostics := []typiaTransformDiagnostic{}
55
+ extras := nativecontext.ITypiaContext_Extras{
56
+ Shared: &sync.Map{},
57
+ AddDiagnostic: func(diag *nativecontext.ITypiaDiagnostic) int {
58
+ diagnostics = append(diagnostics, typiaTransformDiagnosticFrom(diag))
59
+ return len(diagnostics)
60
+ },
61
+ }
62
+ for _, file := range typiaAnalysisFiles(prog) {
63
+ nativetransform.Transform(prog, &settings.transformOptions, extras, shimprinter.NewEmitContext())(file)
64
+ }
65
+ if len(diagnostics) > 0 {
66
+ writeTypiaTransformDiagnostics(errOut, diagnostics, settings.cwd)
67
+ return 3
68
+ }
69
+ return 0
70
+ }
71
+
72
+ // typiaAnalysisFiles lists, in Program order, the files whose JavaScript the
73
+ // emit lane passes through typia's transformer: the compiler's emit selection
74
+ // with a JavaScript output path.
75
+ //
76
+ // The emit lane runs on a Program loaded with emitDeclarationOnly cleared, so
77
+ // the paths are computed with it cleared too; noEmit itself does not enter the
78
+ // selection. The lane's outDir containment guard is not repeated: an output can
79
+ // leave outDir only for a source outside rootDir, which TypeScript reports as
80
+ // TS6059, and this lane runs only on a Program without diagnostics.
81
+ func typiaAnalysisFiles(prog *driver.Program) []*shimast.SourceFile {
82
+ program := prog.TSProgram
83
+ options := program.Options().Clone()
84
+ options.EmitDeclarationOnly = shimcore.TSFalse
85
+ files := []*shimast.SourceFile{}
86
+ for _, file := range shimcompiler.SourceFilesToEmit(program) {
87
+ if shimcompiler.OutputPathsFor(file, options, program).JsFilePath() != "" {
88
+ files = append(files, file)
89
+ }
90
+ }
91
+ return files
92
+ }
@@ -0,0 +1,318 @@
1
+ //go:build !js
2
+
3
+ package main
4
+
5
+ import (
6
+ "bufio"
7
+ "bytes"
8
+ "encoding/json"
9
+ "fmt"
10
+ "io"
11
+ "os"
12
+ "path/filepath"
13
+ "strings"
14
+
15
+ "github.com/samchon/ttsc/packages/ttsc/driver"
16
+ )
17
+
18
+ // checkServeRequest is one analysis watch cycle: the filesystem transitions
19
+ // since the previous cycle. Project, plugin and compiler options are fixed by
20
+ // the command line the host was started with.
21
+ type checkServeRequest struct {
22
+ // Invalidate drops the resident Program before answering.
23
+ Invalidate bool `json:"invalidate,omitempty"`
24
+
25
+ // Changed lists the local files changed since the previous cycle.
26
+ Changed []string `json:"changed,omitempty"`
27
+
28
+ // External is the subset of Changed declared by a project-input snapshot.
29
+ External []string `json:"external,omitempty"`
30
+ }
31
+
32
+ // checkServeTelemetry reports how the resident Program served the cycle.
33
+ type checkServeTelemetry struct {
34
+ // PID identifies the resident host process.
35
+ PID int `json:"pid"`
36
+
37
+ // ProgramLoads counts initial loads and full Program reconstructions.
38
+ ProgramLoads int `json:"programLoads"`
39
+
40
+ // ProgramUpdates counts incremental updates that reused the Program graph.
41
+ ProgramUpdates int `json:"programUpdates"`
42
+
43
+ // Reused reports whether this cycle was answered without a new load.
44
+ Reused bool `json:"reused"`
45
+ }
46
+
47
+ // checkServeResponse is one cycle's answer in the shape ttsc's resident check
48
+ // protocol reads: what one-shot `check` would print and return for the same
49
+ // files, plus the residency report.
50
+ type checkServeResponse struct {
51
+ // Status is one-shot check's exit status for the same files.
52
+ Status int `json:"status"`
53
+
54
+ // Stdout is what one-shot check would print to stdout.
55
+ Stdout string `json:"stdout"`
56
+
57
+ // Stderr is what one-shot check would print to stderr.
58
+ Stderr string `json:"stderr"`
59
+
60
+ // Telemetry reports the resident Program's loads and updates.
61
+ Telemetry checkServeTelemetry `json:"telemetry"`
62
+
63
+ // ProgramFiles names the checked Program's files, default libraries under
64
+ // their `bundled:///libs/` names, so the launcher needs no listing.
65
+ ProgramFiles []string `json:"programFiles,omitempty"`
66
+
67
+ // TypeScriptDiagnosticsReported acknowledges that Stderr holds the loaded
68
+ // Program's complete diagnostic batch. Absent when loading failed.
69
+ TypeScriptDiagnosticsReported bool `json:"typeScriptDiagnosticsReported,omitempty"`
70
+ }
71
+
72
+ // checkServeState owns at most one resident Program and the answer it gave.
73
+ //
74
+ // A Program stays resident only while no linked ProgramPlugin is selected:
75
+ // such a hook rewrites the parsed ASTs in place before typia reads them, so a
76
+ // reused Program would show the next cycle source an earlier cycle already
77
+ // rewrote. typia's own transformer leaves the ASTs untouched (see
78
+ // analyzeTypiaProgram), which is what lets every other Program stay.
79
+ type checkServeState struct {
80
+ settings buildSettings
81
+ outDir string
82
+ session *driver.Session
83
+
84
+ // answer is the response for the resident generation. A cycle that applies
85
+ // no change returns it, so the checker that served typia's type queries
86
+ // never answers a second diagnostic request.
87
+ answer *checkServeResponse
88
+
89
+ loads int
90
+ updates int
91
+ }
92
+
93
+ // runCheckServe is typia's resident analysis check for `ttsc --noEmit --watch`.
94
+ // ttsc starts it in place of `check`, with check's arguments, once the
95
+ // descriptor declares `capabilities.residentCheck`. It reads one JSON request
96
+ // per line from in and writes one JSON response per request to out until in
97
+ // reaches EOF.
98
+ //
99
+ // Each response holds what one-shot `check` prints and returns for the same
100
+ // files. A known changed source is applied to the resident Program through
101
+ // driver.Session; an unknown path, an unreadable change or an invalidation
102
+ // loads it again. Exit status 2 reports a startup, read or response-write
103
+ // failure; check failures travel in each response.
104
+ //
105
+ // Membership comes from Session.Contains, which runs no linked hook, and
106
+ // updates go through the upstream UpdateProgram. The state holds at most one
107
+ // Program, its overlay of applied edits and one answer; invalidation, reload
108
+ // and stream end close the Program. Request and response buffers are per line,
109
+ // without a byte cap.
110
+ func runCheckServe(in io.Reader, out io.Writer, args []string) int {
111
+ flags, ok := parseBuildFlags("check-serve", args)
112
+ if !ok {
113
+ return 2
114
+ }
115
+ if flags.observationsPath != "" || flags.provenancePath != "" {
116
+ fmt.Fprintln(stderr, "ttsc-typia check-serve: private result paths belong to a one-shot build")
117
+ return 2
118
+ }
119
+ flags.noEmit = true
120
+ settings, code := prepareBuild("ttsc-typia check-serve", flags)
121
+ if code != 0 {
122
+ return code
123
+ }
124
+ // driver.Session anchors its incremental updates on an absolute project root.
125
+ if !filepath.IsAbs(settings.cwd) {
126
+ absolute, err := filepath.Abs(settings.cwd)
127
+ if err != nil {
128
+ fmt.Fprintf(stderr, "ttsc-typia check-serve: cwd: %v\n", err)
129
+ return 2
130
+ }
131
+ settings.cwd = absolute
132
+ }
133
+ state := &checkServeState{settings: settings, outDir: flags.outDir}
134
+ defer state.close()
135
+ encoder := json.NewEncoder(out)
136
+ reader := bufio.NewReader(in)
137
+ for {
138
+ raw, readErr := reader.ReadString('\n')
139
+ if line := strings.TrimSpace(raw); line != "" {
140
+ if err := encoder.Encode(state.handle(line)); err != nil {
141
+ fmt.Fprintf(stderr, "ttsc-typia check-serve: write error: %v\n", err)
142
+ return 2
143
+ }
144
+ }
145
+ if readErr != nil {
146
+ if readErr != io.EOF {
147
+ fmt.Fprintf(stderr, "ttsc-typia check-serve: read error: %v\n", readErr)
148
+ return 2
149
+ }
150
+ return 0
151
+ }
152
+ }
153
+ }
154
+
155
+ func (s *checkServeState) close() {
156
+ if s.session != nil {
157
+ _ = s.session.Close()
158
+ s.session = nil
159
+ }
160
+ s.answer = nil
161
+ }
162
+
163
+ // handle answers one request line; a panic drops the resident Program.
164
+ func (s *checkServeState) handle(line string) (response checkServeResponse) {
165
+ response = checkServeResponse{Status: 2}
166
+ defer func() {
167
+ if recovered := recover(); recovered != nil {
168
+ s.close()
169
+ response = checkServeResponse{
170
+ Status: 2,
171
+ Stderr: fmt.Sprintf("ttsc-typia check-serve: request panicked: %v\n", recovered),
172
+ }
173
+ }
174
+ response.Telemetry.PID = os.Getpid()
175
+ response.Telemetry.ProgramLoads = s.loads
176
+ response.Telemetry.ProgramUpdates = s.updates
177
+ }()
178
+ var req checkServeRequest
179
+ if err := json.Unmarshal([]byte(line), &req); err != nil {
180
+ response.Stderr = fmt.Sprintf("ttsc-typia check-serve: invalid request: %v\n", err)
181
+ return response
182
+ }
183
+ reused := s.apply(req)
184
+ return s.check(reused)
185
+ }
186
+
187
+ // apply moves the resident Program to the request's filesystem state, or drops
188
+ // it when only a fresh load can: an invalidation, a path that is not a Program
189
+ // member and not a declared external input, or a change that cannot be read.
190
+ func (s *checkServeState) apply(req checkServeRequest) bool {
191
+ if req.Invalidate {
192
+ s.close()
193
+ return false
194
+ }
195
+ if s.session == nil {
196
+ return false
197
+ }
198
+ external := map[string]struct{}{}
199
+ for _, location := range req.External {
200
+ if resolved, err := filepath.Abs(location); err == nil {
201
+ external[filepath.Clean(resolved)] = struct{}{}
202
+ }
203
+ }
204
+ reused := true
205
+ for _, location := range req.Changed {
206
+ resolved, err := filepath.Abs(location)
207
+ if err != nil {
208
+ s.close()
209
+ return false
210
+ }
211
+ resolved = filepath.Clean(resolved)
212
+ if !s.session.Contains(resolved) {
213
+ if _, declared := external[resolved]; declared {
214
+ continue
215
+ }
216
+ s.close()
217
+ return false
218
+ }
219
+ content, err := os.ReadFile(resolved)
220
+ if err != nil {
221
+ s.close()
222
+ return false
223
+ }
224
+ s.answer = nil
225
+ if s.session.Apply(resolved, string(content)) {
226
+ s.updates++
227
+ } else {
228
+ // UpdateProgram reconstructed the Program: a real load, not a reuse.
229
+ s.loads++
230
+ reused = false
231
+ }
232
+ }
233
+ return reused
234
+ }
235
+
236
+ // check answers the current generation as one-shot check does, loading it
237
+ // first when no resident Program survived apply, and decides whether the
238
+ // Program stays for the next request.
239
+ func (s *checkServeState) check(reused bool) checkServeResponse {
240
+ if s.session != nil && s.answer != nil {
241
+ // Nothing the resident generation was built from changed, so a cold check
242
+ // of the same files gives the same answer.
243
+ response := *s.answer
244
+ response.Telemetry.Reused = true
245
+ return response
246
+ }
247
+ var out, errOut bytes.Buffer
248
+ var prog *driver.Program
249
+ var overlay *driver.OverlayFS
250
+ if s.session != nil {
251
+ prog = s.session.Program()
252
+ } else {
253
+ overlay = driver.NewOverlayFS(driver.DefaultFS())
254
+ loaded, status := loadTypiaProgram(s.settings, driver.LoadProgramOptions{
255
+ ForceNoEmit: true,
256
+ OutDir: s.outDir,
257
+ FS: overlay,
258
+ }, &errOut)
259
+ if status != 0 {
260
+ if loaded != nil {
261
+ _ = loaded.Close()
262
+ }
263
+ return checkServeResponse{Status: status, Stdout: out.String(), Stderr: errOut.String()}
264
+ }
265
+ s.loads++
266
+ reused = false
267
+ prog = loaded
268
+ // A Program that does not become resident below, or a panic before that,
269
+ // still releases its checker lease.
270
+ defer func() {
271
+ if s.session == nil {
272
+ _ = loaded.Close()
273
+ }
274
+ }()
275
+ }
276
+ status := reportTypiaProgramDiagnostics(prog, s.settings.cwd, &errOut)
277
+ if status == 0 {
278
+ status = analyzeTypiaProgram(prog, s.settings, &out, &errOut)
279
+ }
280
+ response := checkServeResponse{
281
+ Status: status,
282
+ Stdout: out.String(),
283
+ Stderr: errOut.String(),
284
+ ProgramFiles: programFileNames(prog),
285
+ TypeScriptDiagnosticsReported: true,
286
+ }
287
+ response.Telemetry.Reused = reused
288
+ // ApplyLinkedPlugins is latched per Program: after an analysis it returns
289
+ // that outcome, and after failing Program diagnostics it only settles the
290
+ // registry check, since no ProgramPlugin is linked when it is asked. A
291
+ // latched failure would enter every later Diagnostics of this Program, which
292
+ // a cold check never sees, so such a Program is not kept either.
293
+ if prog.HasLinkedProgramPlugins() || prog.ApplyLinkedPlugins() != nil {
294
+ s.close()
295
+ } else {
296
+ if s.session == nil {
297
+ s.session = driver.NewSessionFromProgram(s.settings.cwd, overlay, prog)
298
+ }
299
+ answer := response
300
+ s.answer = &answer
301
+ }
302
+ return response
303
+ }
304
+
305
+ // programFileNames lists a Program's files as the compiler names them.
306
+ func programFileNames(prog *driver.Program) []string {
307
+ if prog == nil || prog.TSProgram == nil {
308
+ return nil
309
+ }
310
+ files := prog.TSProgram.SourceFiles()
311
+ names := make([]string, 0, len(files))
312
+ for _, file := range files {
313
+ if file != nil {
314
+ names = append(names, string(file.FileName()))
315
+ }
316
+ }
317
+ return names
318
+ }
@@ -0,0 +1,234 @@
1
+ package main
2
+
3
+ import (
4
+ "bufio"
5
+ "encoding/json"
6
+ "io"
7
+ "os"
8
+ "path/filepath"
9
+ "strings"
10
+ "testing"
11
+ )
12
+
13
+ // TestCheckServeMatchesColdCheck verifies typia's resident check keeps one
14
+ // Program across compatible edits and answers exactly what one-shot `check`
15
+ // answers for the same files.
16
+ //
17
+ // The watch launcher trusts each reply's status, output, file list and
18
+ // completeness acknowledgement in place of a cold check, so every reply must
19
+ // equal a cold check run after the same edit.
20
+ //
21
+ // 1. Start check-serve over pipes and answer a typia transform failure with
22
+ // one load, the acknowledgement and the project files.
23
+ // 2. Fix the call, then break the TypeScript, requiring incremental updates
24
+ // whose answers equal a cold check each time, then drop the import and
25
+ // require the reconstruction to count as a load.
26
+ // 3. Send a cycle without changes and one naming only a declared external
27
+ // input, requiring the same answer without new work.
28
+ // 4. Add a root, invalidate, and send a malformed line, requiring a reload for
29
+ // the first two and a protocol error for the last.
30
+ // 5. Close stdin and require a clean exit.
31
+ //
32
+ // @evidence contracts/testing.md#behavioral-verification runCheckServe answers framed requests over real pipes; each answer's status, stdout and stderr must equal a captured cold `check`, with telemetry and file lists following the protocol, so a stale Program, a lost transform diagnostic, a missing reload or broken framing fails an assertion.
33
+ // @evidence contracts/testing.md#independent-expectations Cold `check` of the same files is the differential oracle; the expected statuses follow from the authored sources (a generic typia.is call fails the transform, a string assigned to number fails TypeScript) and the protocol fixes the load and update counts.
34
+ // @evidence contracts/testing.md#distinguishing-cases Transform failure, success and TypeScript failure cycles, an edit UpdateProgram must reconstruct, an unchanged and an external-only cycle, an unknown root, an invalidation and a malformed request; TestCheckServeReloadsWithProgramPlugin owns the linked ProgramPlugin case.
35
+ // @evidence contracts/testing.md#execution-ownership The native Go runner discovers this unit test; it runs runCheckServe in a goroutine of the test process and starts no daemon or built binary.
36
+ func TestCheckServeMatchesColdCheck(t *testing.T) {
37
+ root := checkServeProject(t)
38
+ main := filepath.Join(root, "src", "main.ts")
39
+ args := []string{"--tsconfig=" + filepath.Join(root, "tsconfig.json"), "--cwd=" + root}
40
+ serve := startCheckServe(t, args)
41
+
42
+ first := serve.send(t, `{}`)
43
+ if first.Status != 3 || !first.TypeScriptDiagnosticsReported ||
44
+ first.Telemetry.ProgramLoads != 1 || first.Telemetry.ProgramUpdates != 0 || first.Telemetry.Reused ||
45
+ first.Telemetry.PID != os.Getpid() {
46
+ t.Fatalf("first cycle = %#v", first)
47
+ }
48
+ if !strings.Contains(filepath.ToSlash(first.Stderr), "src/main.ts:3:9 - error TS(typia.is):") {
49
+ t.Fatalf("first cycle lost the transform diagnostic:\n%s", first.Stderr)
50
+ }
51
+ checkServeAssertFiles(t, first.ProgramFiles, main, filepath.Join(root, "src", "other.ts"))
52
+ checkServeAssertCold(t, args, first)
53
+
54
+ for index, cycle := range []struct {
55
+ source string
56
+ status int
57
+ reused bool
58
+ loads int
59
+ updates int
60
+ }{
61
+ {typiaCheckValidSource, 0, true, 1, 1},
62
+ {typiaCheckValidSource + "export const value: number = \"text\";\n", 2, true, 1, 2},
63
+ // Dropping the import changes the file's references, so UpdateProgram
64
+ // reconstructs the Program: a load, not a reuse.
65
+ {"export const value: number = \"text\";\n", 2, false, 2, 2},
66
+ } {
67
+ typiaCheckWrite(t, main, cycle.source)
68
+ answer := serve.send(t, checkServeChanged(t, main))
69
+ if answer.Status != cycle.status || answer.Telemetry.Reused != cycle.reused || !answer.TypeScriptDiagnosticsReported ||
70
+ answer.Telemetry.ProgramLoads != cycle.loads || answer.Telemetry.ProgramUpdates != cycle.updates {
71
+ t.Fatalf("edited cycle %d = %#v", index, answer)
72
+ }
73
+ checkServeAssertCold(t, args, answer)
74
+ }
75
+
76
+ unchanged := serve.send(t, `{}`)
77
+ external := filepath.Join(root, "lint.config.json")
78
+ typiaCheckWrite(t, external, "{}\n")
79
+ declared, _ := json.Marshal(checkServeRequest{Changed: []string{external}, External: []string{external}})
80
+ externalOnly := serve.send(t, string(declared))
81
+ for _, answer := range []checkServeResponse{unchanged, externalOnly} {
82
+ if answer.Status != 2 || !answer.Telemetry.Reused ||
83
+ answer.Telemetry.ProgramLoads != 2 || answer.Telemetry.ProgramUpdates != 2 {
84
+ t.Fatalf("no-change cycle = %#v", answer)
85
+ }
86
+ checkServeAssertCold(t, args, answer)
87
+ }
88
+
89
+ added := filepath.Join(root, "src", "added.ts")
90
+ typiaCheckWrite(t, added, typiaCheckValidSource)
91
+ reloaded := serve.send(t, checkServeChanged(t, added))
92
+ if reloaded.Telemetry.Reused || reloaded.Telemetry.ProgramLoads != 3 {
93
+ t.Fatalf("new root cycle = %#v", reloaded)
94
+ }
95
+ checkServeAssertFiles(t, reloaded.ProgramFiles, added)
96
+ checkServeAssertCold(t, args, reloaded)
97
+
98
+ typiaCheckWrite(t, main, typiaCheckValidSource)
99
+ invalidated := serve.send(t, `{"invalidate":true}`)
100
+ if invalidated.Status != 0 || invalidated.Telemetry.Reused || invalidated.Telemetry.ProgramLoads != 4 {
101
+ t.Fatalf("invalidated cycle = %#v", invalidated)
102
+ }
103
+ checkServeAssertCold(t, args, invalidated)
104
+
105
+ malformed := serve.send(t, `not json`)
106
+ if malformed.Status != 2 || malformed.TypeScriptDiagnosticsReported ||
107
+ !strings.Contains(malformed.Stderr, "invalid request") {
108
+ t.Fatalf("malformed request = %#v", malformed)
109
+ }
110
+ if code := serve.stop(); code != 0 {
111
+ t.Fatalf("check-serve exited with %d after stdin closed", code)
112
+ }
113
+ }
114
+
115
+ // checkServeHost is a check-serve command running in the test process.
116
+ type checkServeHost struct {
117
+ in *io.PipeWriter
118
+ lines *bufio.Scanner
119
+ done chan int
120
+ }
121
+
122
+ func startCheckServe(t *testing.T, args []string) *checkServeHost {
123
+ t.Helper()
124
+ inReader, inWriter := io.Pipe()
125
+ outReader, outWriter := io.Pipe()
126
+ done := make(chan int, 1)
127
+ go func() {
128
+ code := runCheckServe(inReader, outWriter, args)
129
+ _ = inReader.Close()
130
+ _ = outWriter.Close()
131
+ done <- code
132
+ }()
133
+ // A failed assertion leaves the host waiting on a pipe; closing both ends
134
+ // lets it return.
135
+ t.Cleanup(func() {
136
+ _ = inWriter.Close()
137
+ _ = outReader.Close()
138
+ })
139
+ lines := bufio.NewScanner(outReader)
140
+ lines.Buffer(make([]byte, 0, 64*1024), 64*1024*1024)
141
+ return &checkServeHost{in: inWriter, lines: lines, done: done}
142
+ }
143
+
144
+ func (h *checkServeHost) send(t *testing.T, request string) checkServeResponse {
145
+ t.Helper()
146
+ if _, err := io.WriteString(h.in, request+"\n"); err != nil {
147
+ t.Fatalf("write request: %v", err)
148
+ }
149
+ if !h.lines.Scan() {
150
+ t.Fatalf("no response to %s: %v", request, h.lines.Err())
151
+ }
152
+ var response checkServeResponse
153
+ if err := json.Unmarshal(h.lines.Bytes(), &response); err != nil {
154
+ t.Fatalf("decode response %s: %v", h.lines.Text(), err)
155
+ }
156
+ return response
157
+ }
158
+
159
+ func (h *checkServeHost) stop() int {
160
+ _ = h.in.Close()
161
+ return <-h.done
162
+ }
163
+
164
+ func checkServeChanged(t *testing.T, files ...string) string {
165
+ t.Helper()
166
+ line, err := json.Marshal(checkServeRequest{Changed: files})
167
+ if err != nil {
168
+ t.Fatal(err)
169
+ }
170
+ return string(line)
171
+ }
172
+
173
+ // checkServeAssertCold requires a resident answer to equal a one-shot `check`
174
+ // of the files as they are now.
175
+ func checkServeAssertCold(t *testing.T, args []string, resident checkServeResponse) {
176
+ t.Helper()
177
+ out, errText, code := ttscTypiaTestCapture(func() int {
178
+ return run(append([]string{"check"}, args...))
179
+ })
180
+ if code != resident.Status || out != resident.Stdout || errText != resident.Stderr {
181
+ t.Fatalf("resident/cold mismatch\nresident=%#v\ncold=(%d, %q, %q)", resident, code, out, errText)
182
+ }
183
+ }
184
+
185
+ // checkServeAssertFiles requires every listed file to be absolute or an
186
+ // embedded default library, and the wanted files to be listed. Slash spellings
187
+ // are compared without case, since a Windows drive letter may be spelled
188
+ // differently by the temporary-directory API.
189
+ func checkServeAssertFiles(t *testing.T, files []string, want ...string) {
190
+ t.Helper()
191
+ for _, file := range files {
192
+ if !filepath.IsAbs(file) && !strings.HasPrefix(file, "bundled:///libs/") {
193
+ t.Fatalf("program file %q is neither absolute nor a bundled library", file)
194
+ }
195
+ }
196
+ for _, wanted := range want {
197
+ found := false
198
+ for _, file := range files {
199
+ if strings.EqualFold(filepath.ToSlash(file), filepath.ToSlash(wanted)) {
200
+ found = true
201
+ break
202
+ }
203
+ }
204
+ if !found {
205
+ t.Fatalf("program files omit %s: %v", wanted, files)
206
+ }
207
+ }
208
+ }
209
+
210
+ func checkServeProject(t *testing.T) string {
211
+ t.Helper()
212
+ root := t.TempDir()
213
+ transformDiagnosticWriteTypiaStub(t, root)
214
+ typiaCheckWrite(t, filepath.Join(root, "tsconfig.json"), `{
215
+ "compilerOptions": {
216
+ "target": "ES2022",
217
+ "module": "commonjs",
218
+ "moduleResolution": "bundler",
219
+ "ignoreDeprecations": "6.0",
220
+ "types": ["*"],
221
+ "strict": true,
222
+ "skipLibCheck": true,
223
+ "noEmit": true
224
+ },
225
+ "include": ["src"]
226
+ }
227
+ `)
228
+ typiaCheckWrite(t, filepath.Join(root, "src", "main.ts"), transformDiagnosticSource)
229
+ typiaCheckWrite(t, filepath.Join(root, "src", "other.ts"), `import typia from "typia";
230
+ export const isName = (input: unknown): input is { name: string } =>
231
+ typia.is<{ name: string }>(input);
232
+ `)
233
+ return root
234
+ }