typenative 0.4.0 → 0.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.
Files changed (44) hide show
  1. package/.github/workflows/ci.yml +2 -0
  2. package/CHANGELOG.md +201 -0
  3. package/CONTRIBUTION.md +1 -1
  4. package/bin/cli.js +1 -0
  5. package/bin/go/bridge.js +74 -14
  6. package/bin/go/convert.js +48 -0
  7. package/bin/go/metadata.js +13 -4
  8. package/bin/go/overrides.js +4 -6
  9. package/bin/go/stdlib.generated.js +2 -0
  10. package/bin/index.js +117 -0
  11. package/bin/main.js +1 -0
  12. package/bin/node/child_process.js +51 -3
  13. package/bin/node/cluster.js +41 -3
  14. package/bin/node/core.js +1 -1
  15. package/bin/node/crypto.js +205 -4
  16. package/bin/node/dgram.js +230 -6
  17. package/bin/node/dns.js +470 -7
  18. package/bin/node/errno_tables.js +445 -0
  19. package/bin/node/fs.js +21 -14
  20. package/bin/node/http.js +128 -30
  21. package/bin/node/http2.js +4 -1
  22. package/bin/node/module_v8.js +142 -0
  23. package/bin/node/net.js +9 -6
  24. package/bin/node/process.js +242 -0
  25. package/bin/node/readline.js +271 -0
  26. package/bin/node/registry.js +2 -1
  27. package/bin/node/sqlite.js +60 -12
  28. package/bin/node/stream.js +139 -7
  29. package/bin/node/test.js +311 -19
  30. package/bin/node/url.js +23 -5
  31. package/bin/node/util.js +18 -1
  32. package/bin/node/util_extra.js +6 -30
  33. package/bin/node/worker_threads.js +79 -19
  34. package/bin/transpiler.js +4019 -497
  35. package/bin/typecheck-node.js +1 -0
  36. package/bin/version.js +1 -1
  37. package/conformance.md +1025 -884
  38. package/examples/README.md +5 -5
  39. package/examples/json-server/README.md +31 -29
  40. package/examples/json-server/bench.mjs +130 -38
  41. package/package.json +1 -1
  42. package/types/typenative-go.d.ts +23 -0
  43. package/types/typenative-npm.d.ts +169 -5
  44. package/types/typenative.d.ts +185 -11
@@ -29,6 +29,8 @@ type TnStream struct {
29
29
  readEnded bool
30
30
  endEmitted bool
31
31
  flowing int
32
+ // a 'readable' listener: paused mode, the consumer pulls with read()
33
+ readableListening bool
32
34
  reading bool
33
35
  flowScheduled bool
34
36
  source func(s *TnStream)
@@ -170,7 +172,11 @@ func (s *TnStream) toChunk(chunk interface{}, enc string) interface{} {
170
172
  }
171
173
 
172
174
  func (s *TnStream) push(chunk interface{}, encoding ...string) bool {
173
- if chunk == nil {
175
+ // nullable strings (cond ? text : null) and typed nils
176
+ if p, ok := chunk.(*string); ok && p != nil {
177
+ chunk = *p
178
+ }
179
+ if chunk == nil || TnIsNil(chunk) {
174
180
  s.readEnded = true
175
181
  if s.decoder != nil {
176
182
  if rest := s.decoder.end(); rest != "" {
@@ -216,6 +222,10 @@ func (s *TnStream) flow() {
216
222
  if s.destroyed {
217
223
  return
218
224
  }
225
+ if s.readableListening && s.flowing != 1 {
226
+ s.flowReadable()
227
+ return
228
+ }
219
229
  for s.flowing == 1 && len(s.queue) > 0 {
220
230
  chunk := s.queue[0]
221
231
  s.queue = s.queue[1:]
@@ -230,6 +240,32 @@ func (s *TnStream) flow() {
230
240
  }
231
241
  }
232
242
 
243
+ // Paused mode: 'readable' while there is data, then one last 'readable' (read()
244
+ // gives null) before 'end', as in Node
245
+ func (s *TnStream) flowReadable() {
246
+ for !s.endEmitted && (len(s.queue) > 0 || s.readEnded) {
247
+ before := len(s.queue)
248
+ s.emit("readable")
249
+ if s.destroyed || s.flowing == 1 {
250
+ return
251
+ }
252
+ if len(s.queue) == 0 && s.readEnded {
253
+ if before == 0 {
254
+ s.emitEnd()
255
+ return
256
+ }
257
+ continue
258
+ }
259
+ // the consumer left data buffered: wait for read() or more data
260
+ if len(s.queue) >= before {
261
+ return
262
+ }
263
+ }
264
+ if len(s.queue) == 0 {
265
+ s.requestRead()
266
+ }
267
+ }
268
+
233
269
  func (s *TnStream) requestRead() {
234
270
  if s.reading || s.readEnded || s.destroyed {
235
271
  return
@@ -293,6 +329,13 @@ func (s *TnStream) once(event string, fn interface{}) *TnEventEmitter {
293
329
  }
294
330
 
295
331
  func (s *TnStream) listening(event string) {
332
+ if event == "readable" && s.readableSide {
333
+ s.readableListening = true
334
+ s.flowing = 0
335
+ s.requestRead()
336
+ s.scheduleFlow()
337
+ return
338
+ }
296
339
  if event == "data" && s.flowing != 0 && s.readableSide {
297
340
  s.resume()
298
341
  }
@@ -314,7 +357,10 @@ func (s *TnStream) pause() *TnStream {
314
357
 
315
358
  func (s *TnStream) isPaused() bool { return s.flowing == 0 }
316
359
 
317
- // read(): paused-mode pull of the next buffered chunk (null when none)
360
+ // read(size?): paused-mode pull (null when nothing is buffered). As in Node,
361
+ // without a size it returns everything buffered as one Buffer / string, and
362
+ // with one it waits for that many bytes (characters with an encoding) unless
363
+ // the stream has ended; object mode returns one object
318
364
  func (s *TnStream) read(size ...float64) interface{} {
319
365
  if len(s.queue) == 0 {
320
366
  s.requestRead()
@@ -323,9 +369,83 @@ func (s *TnStream) read(size ...float64) interface{} {
323
369
  }
324
370
  return nil
325
371
  }
326
- chunk := s.queue[0]
327
- s.queue = s.queue[1:]
328
- return chunk
372
+ if s.objectMode {
373
+ chunk := s.queue[0]
374
+ s.queue = s.queue[1:]
375
+ s.emit("data", chunk)
376
+ return chunk
377
+ }
378
+ n := -1
379
+ if len(size) > 0 && size[0] >= 0 {
380
+ n = int(size[0])
381
+ }
382
+ total := 0
383
+ for _, c := range s.queue {
384
+ total += tnChunkLen(c)
385
+ }
386
+ if n == 0 || (n > total && !s.readEnded) {
387
+ s.requestRead()
388
+ return nil
389
+ }
390
+ if n < 0 || n > total {
391
+ n = total
392
+ }
393
+ var text []rune
394
+ var data []byte
395
+ isText := false
396
+ // (empty chunks, such as a split UTF-8 sequence, go along with the rest)
397
+ for len(s.queue) > 0 && (n > 0 || tnChunkLen(s.queue[0]) == 0) {
398
+ switch c := s.queue[0].(type) {
399
+ case string:
400
+ isText = true
401
+ r := []rune(c)
402
+ if len(r) > n {
403
+ text = append(text, r[:n]...)
404
+ s.queue[0] = string(r[n:])
405
+ n = 0
406
+ continue
407
+ }
408
+ text = append(text, r...)
409
+ n -= len(r)
410
+ case []byte:
411
+ if len(c) > n {
412
+ data = append(data, c[:n]...)
413
+ s.queue[0] = c[n:]
414
+ n = 0
415
+ continue
416
+ }
417
+ data = append(data, c...)
418
+ n -= len(c)
419
+ default:
420
+ n--
421
+ }
422
+ s.queue = s.queue[1:]
423
+ }
424
+ if len(s.queue) == 0 && !s.readEnded {
425
+ s.requestRead()
426
+ }
427
+ var out interface{}
428
+ if isText && len(text) > 0 {
429
+ out = string(text)
430
+ } else if len(data) > 0 {
431
+ out = data
432
+ }
433
+ // what read() returns is also a 'data' event, as in Node
434
+ if out != nil {
435
+ s.emit("data", out)
436
+ }
437
+ return out
438
+ }
439
+
440
+ // The length read(size) counts: bytes, or characters of decoded strings
441
+ func tnChunkLen(c interface{}) int {
442
+ switch x := c.(type) {
443
+ case string:
444
+ return utf8.RuneCountInString(x)
445
+ case []byte:
446
+ return len(x)
447
+ }
448
+ return 1
329
449
  }
330
450
 
331
451
  func (s *TnStream) setEncoding(enc string) *TnStream {
@@ -1054,7 +1174,7 @@ export function registerStream(r) {
1054
1174
  defineModule(r, mod);
1055
1175
  r.namespaces['stream.promises'] = 'stream/promises';
1056
1176
  r.namespaces['stream.default'] = 'stream.Stream';
1057
- defineHelper(r, 'nodeStream', ['encoding/json', 'os', 'reflect'], ['nodeEvents', 'buffer', 'stringDecoder', 'eventLoop', 'promise', 'dynamic', 'nodeInvoke', 'stdinReader'], streamHelper);
1177
+ defineHelper(r, 'nodeStream', ['encoding/json', 'os', 'reflect', 'unicode/utf8'], ['nodeEvents', 'buffer', 'stringDecoder', 'eventLoop', 'promise', 'dynamic', 'nodeInvoke', 'stdinReader'], streamHelper);
1058
1178
  defineHelper(r, 'stdinReader', ['bufio', 'os'], [], `// One buffered reader shared by process.stdin, readline and question()
1059
1179
  var tnStdinBuffered *bufio.Reader
1060
1180
 
@@ -1109,6 +1229,7 @@ func tnStdin() *bufio.Reader {
1109
1229
  r.hookParams[`_${hook}`] = STREAM_HOOK_PARAMS[hook];
1110
1230
  r.methods['stream.Duplex#pipe'] = (c) => {
1111
1231
  use();
1232
+ useHashStream(r, c.types);
1112
1233
  return `TnPipe(${c.recv}, ${c.args.join(', ')})`;
1113
1234
  };
1114
1235
  r.typers['stream.Duplex#pipe'] = (c) => c.types[0] || '*TnStream';
@@ -1121,6 +1242,7 @@ func tnStdin() *bufio.Reader {
1121
1242
  r.results['stream.Readable.from'] = '*TnStream';
1122
1243
  const pipeline = (call) => {
1123
1244
  use();
1245
+ useHashStream(r, call.types);
1124
1246
  const last = call.nodes.length - 1;
1125
1247
  const hasCallback = last >= 0 && (call.nodes[last].kind === 'ArrowFunction' || call.nodes[last].kind === 'FunctionExpression');
1126
1248
  const streams = hasCallback ? call.args.slice(0, last) : call.args;
@@ -1136,6 +1258,7 @@ func tnStdin() *bufio.Reader {
1136
1258
  r.paramTypers['stream.finished'] = (_n) => ['interface{}'];
1137
1259
  r.functions['stream/promises.pipeline'] = (call) => {
1138
1260
  use();
1261
+ useHashStream(r, call.types);
1139
1262
  return `TnPipelinePromise(${call.args.join(', ')})`;
1140
1263
  };
1141
1264
  r.functions['stream/promises.finished'] = (call) => {
@@ -1202,8 +1325,10 @@ func tnStdin() *bufio.Reader {
1202
1325
  for (const method of ['on', 'once', 'resume', 'pause', 'setEncoding', 'pipe', 'read', 'destroy']) {
1203
1326
  r.functions[`process.stdin.${method}`] = (call) => {
1204
1327
  use();
1205
- if (method === 'pipe')
1328
+ if (method === 'pipe') {
1329
+ useHashStream(r, call.types);
1206
1330
  return `TnPipe(TnStdin(), ${call.args.join(', ')})`;
1331
+ }
1207
1332
  const refCall = method === 'destroy' ? '; TnStdin().stdinRef(false)' : '; TnStdin().stdinRef(TnStdin().flowing == 1)';
1208
1333
  return `func() *TnStream { TnStdin().${method}(${call.args.join(', ')})${refCall}; return TnStdin() }()`;
1209
1334
  };
@@ -1212,6 +1337,11 @@ func tnStdin() *bufio.Reader {
1212
1337
  r.paramTypers['process.stdin.on'] = (nodes) => streamListenerTypes(nodes);
1213
1338
  r.paramTypers['process.stdin.once'] = r.paramTypers['process.stdin.on'];
1214
1339
  }
1340
+ // Pulls in crypto's hashStream when a Hash is passed to pipe() / pipeline()
1341
+ function useHashStream(r, types) {
1342
+ if (types.indexOf('*TnHash') >= 0)
1343
+ r.helper('hashStream');
1344
+ }
1215
1345
  // Listener parameters of stream events
1216
1346
  export function streamListenerTypes(nodes) {
1217
1347
  const event = nodes[0];
@@ -1220,5 +1350,7 @@ export function streamListenerTypes(nodes) {
1220
1350
  return ['interface{}'];
1221
1351
  if (name === 'error')
1222
1352
  return ['interface{}'];
1353
+ if (name === 'keypress')
1354
+ return ['string', '*TnKey'];
1223
1355
  return [];
1224
1356
  }
package/bin/node/test.js CHANGED
@@ -14,6 +14,7 @@ type TnTestNode struct {
14
14
  skipMsg string
15
15
  todo bool
16
16
  todoMsg string
17
+ only bool
17
18
  timeoutMs float64
18
19
  parent *TnTestNode
19
20
  children []*TnTestNode
@@ -37,6 +38,8 @@ var tnTestCurrent = tnTestRoot
37
38
  var tnTestRunning *TnTestNode
38
39
  var tnTestScheduled bool
39
40
  var tnTestSpec bool
41
+ var tnTestTap bool
42
+ var tnTestReporter string
40
43
  var tnTestColor bool
41
44
  var tnTestStart time.Time
42
45
  var tnTestCounts = map[string]int{}
@@ -145,6 +148,9 @@ func tnTestNew(suite bool, args []interface{}) *TnTestNode {
145
148
  if ms, ok := TnGet(a, "timeout").(float64); ok {
146
149
  n.timeoutMs = ms
147
150
  }
151
+ if only, ok := TnGet(a, "only").(bool); ok {
152
+ n.only = only
153
+ }
148
154
  }
149
155
  }
150
156
  return n
@@ -171,9 +177,16 @@ func TnTestRegister(variant string, args ...interface{}) chan struct{} {
171
177
  n.skip = true
172
178
  case "todo":
173
179
  n.todo = true
180
+ case "only":
181
+ n.only = true
174
182
  }
175
183
  if tnTestRunning != nil && tnTestCurrent == tnTestRoot && tnTestRunning.ctx != nil {
176
184
  n.parent = tnTestRunning
185
+ // subtests go through the same filters
186
+ if tnTestFilters().active() && !tnTestSelected(n) {
187
+ n.done <- struct{}{}
188
+ return n.done
189
+ }
177
190
  tnTestRunning.children = append(tnTestRunning.children, n)
178
191
  tnRunTestNode(n, tnTestDepth(n))
179
192
  return n.done
@@ -192,6 +205,8 @@ func TnSuiteRegister(variant string, args ...interface{}) chan struct{} {
192
205
  n.skip = true
193
206
  case "todo":
194
207
  n.todo = true
208
+ case "only":
209
+ n.only = true
195
210
  }
196
211
  n.parent = tnTestCurrent
197
212
  tnTestCurrent.children = append(tnTestCurrent.children, n)
@@ -340,14 +355,174 @@ func tnTestAncestors(n *TnTestNode) []*TnTestNode {
340
355
  return chain
341
356
  }
342
357
 
358
+ // The test runner's flags, from NODE_OPTIONS as Node reads them:
359
+ // --test-name-pattern / --test-skip-pattern (repeatable, "/re/flags" or a
360
+ // plain regular expression), --test-only and --test-reporter
361
+ type tnTestConfig struct {
362
+ names []*regexp.Regexp
363
+ skips []*regexp.Regexp
364
+ only bool
365
+ reporter string
366
+ }
367
+
368
+ func (c *tnTestConfig) active() bool { return len(c.names) > 0 || len(c.skips) > 0 || c.only }
369
+
370
+ var tnTestCfg *tnTestConfig
371
+
372
+ // NODE_OPTIONS words: spaces separate them, double quotes group
373
+ func tnNodeOptionWords(s string) []string {
374
+ words := []string{}
375
+ cur := strings.Builder{}
376
+ inQuote, has := false, false
377
+ for _, r := range s {
378
+ switch {
379
+ case r == '"':
380
+ inQuote = !inQuote
381
+ has = true
382
+ case r == ' ' && !inQuote:
383
+ if has {
384
+ words = append(words, cur.String())
385
+ cur.Reset()
386
+ has = false
387
+ }
388
+ default:
389
+ cur.WriteRune(r)
390
+ has = true
391
+ }
392
+ }
393
+ if has {
394
+ words = append(words, cur.String())
395
+ }
396
+ return words
397
+ }
398
+
399
+ func tnTestPattern(s string) *regexp.Regexp {
400
+ if len(s) > 2 && s[0] == '/' {
401
+ if i := strings.LastIndexByte(s, '/'); i > 0 {
402
+ prefix := ""
403
+ if strings.Contains(s[i+1:], "i") {
404
+ prefix = "(?i)"
405
+ }
406
+ if re, err := regexp.Compile(prefix + s[1:i]); err == nil {
407
+ return re
408
+ }
409
+ }
410
+ }
411
+ re, err := regexp.Compile(s)
412
+ if err != nil {
413
+ return regexp.MustCompile(regexp.QuoteMeta(s))
414
+ }
415
+ return re
416
+ }
417
+
418
+ func tnTestFilters() *tnTestConfig {
419
+ if tnTestCfg != nil {
420
+ return tnTestCfg
421
+ }
422
+ c := &tnTestConfig{}
423
+ words := tnNodeOptionWords(os.Getenv("NODE_OPTIONS"))
424
+ for i := 0; i < len(words); i++ {
425
+ name, value, hasValue := strings.Cut(words[i], "=")
426
+ takesValue := name == "--test-name-pattern" || name == "--test-skip-pattern" || name == "--test-reporter"
427
+ if takesValue && !hasValue && i+1 < len(words) {
428
+ i++
429
+ value = words[i]
430
+ }
431
+ switch name {
432
+ case "--test-name-pattern":
433
+ c.names = append(c.names, tnTestPattern(value))
434
+ case "--test-skip-pattern":
435
+ c.skips = append(c.skips, tnTestPattern(value))
436
+ case "--test-only":
437
+ c.only = true
438
+ case "--test-reporter":
439
+ c.reporter = value
440
+ }
441
+ }
442
+ tnTestCfg = c
443
+ return c
444
+ }
445
+
446
+ // A pattern matches a test's name, an ancestor's, or the names joined with spaces
447
+ func tnTestNameMatches(n *TnTestNode, patterns []*regexp.Regexp) bool {
448
+ names := []string{}
449
+ for p := n; p != nil && p.parent != nil; p = p.parent {
450
+ for _, re := range patterns {
451
+ if re.MatchString(p.name) {
452
+ return true
453
+ }
454
+ }
455
+ names = append([]string{p.name}, names...)
456
+ }
457
+ full := strings.Join(names, " ")
458
+ for _, re := range patterns {
459
+ if re.MatchString(full) {
460
+ return true
461
+ }
462
+ }
463
+ return false
464
+ }
465
+
466
+ func tnTestSelected(n *TnTestNode) bool {
467
+ c := tnTestFilters()
468
+ if len(c.names) > 0 && !tnTestNameMatches(n, c.names) {
469
+ return false
470
+ }
471
+ if len(c.skips) > 0 && tnTestNameMatches(n, c.skips) {
472
+ return false
473
+ }
474
+ if c.only {
475
+ for p := n; p != nil; p = p.parent {
476
+ if p.only {
477
+ return true
478
+ }
479
+ }
480
+ return false
481
+ }
482
+ return true
483
+ }
484
+
485
+ // Drops the tests the filters leave out, and the suites left empty (Node
486
+ // does not report them)
487
+ func tnTestPrune(n *TnTestNode) bool {
488
+ kept := []*TnTestNode{}
489
+ for _, child := range n.children {
490
+ if child.suite {
491
+ if tnTestPrune(child) {
492
+ kept = append(kept, child)
493
+ }
494
+ } else if tnTestSelected(child) {
495
+ kept = append(kept, child)
496
+ }
497
+ }
498
+ n.children = kept
499
+ return len(kept) > 0
500
+ }
501
+
343
502
  func tnRunRoot() {
344
503
  tnTestStart = time.Now()
345
- tnTestSpec = TnIsTTY(os.Stdout)
346
- tnTestColor = tnTestSpec && os.Getenv("NO_COLOR") == ""
347
- if !tnTestSpec {
504
+ cfg := tnTestFilters()
505
+ tnTestReporter = cfg.reporter
506
+ if tnTestReporter != "spec" && tnTestReporter != "dot" && tnTestReporter != "junit" && tnTestReporter != "tap" {
507
+ tnTestReporter = "tap"
508
+ if TnIsTTY(os.Stdout) {
509
+ tnTestReporter = "spec"
510
+ }
511
+ }
512
+ tnTestSpec = tnTestReporter == "spec"
513
+ tnTestTap = tnTestReporter == "tap"
514
+ tnTestColor = (tnTestSpec || tnTestReporter == "dot") && TnIsTTY(os.Stdout) && os.Getenv("NO_COLOR") == ""
515
+ if tnTestTap {
348
516
  fmt.Println("TAP version 13")
349
517
  }
518
+ if tnTestReporter == "junit" {
519
+ fmt.Println("<?xml version=\\"1.0\\" encoding=\\"utf-8\\"?>")
520
+ fmt.Println("<testsuites>")
521
+ }
350
522
  root := tnTestRoot
523
+ if cfg.active() {
524
+ tnTestPrune(root)
525
+ }
351
526
  ctx := &TnTestContext{node: root}
352
527
  failedHook := tnRunHooks(root.before, ctx)
353
528
  for i := 0; i < len(root.children); i++ {
@@ -365,9 +540,13 @@ func tnRunTestNode(n *TnTestNode, depth int) {
365
540
  n.started = true
366
541
  tnTestShowParents(n)
367
542
  indent := strings.Repeat(" ", depth)
368
- if !tnTestSpec {
543
+ if tnTestTap {
369
544
  fmt.Println(indent + "# Subtest: " + n.name)
370
545
  }
546
+ // .only without --test-only: Node's notice, as the test's diagnostic
547
+ if n.only && !tnTestFilters().only {
548
+ n.diagnostics = append(n.diagnostics, "'only' and 'runOnly' require the --test-only command-line option.")
549
+ }
371
550
  start := time.Now()
372
551
  ctx := &TnTestContext{node: n, mock: TnNewMockTracker(), signal: TnNewAbortSignal()}
373
552
  n.ctx = ctx
@@ -548,9 +727,19 @@ func tnTestYamlString(s string, indent string) string {
548
727
  }
549
728
 
550
729
  func tnTestReport(n *TnTestNode, depth int) {
551
- if tnTestSpec {
730
+ switch tnTestReporter {
731
+ case "spec":
552
732
  tnTestReportSpec(n, depth)
553
733
  return
734
+ case "dot":
735
+ mark := "."
736
+ if n.status == "fail" {
737
+ mark = tnTestColorize("31", "X")
738
+ }
739
+ fmt.Print(mark)
740
+ return
741
+ case "junit":
742
+ return
554
743
  }
555
744
  indent := strings.Repeat(" ", depth)
556
745
  if len(n.children) > 0 {
@@ -650,9 +839,117 @@ func tnTestReportSpec(n *TnTestNode, depth int) {
650
839
  }
651
840
  }
652
841
 
842
+ // dot: the failures after the line of dots, in the spec reporter's format
843
+ func tnTestFailureLines(n *TnTestNode) {
844
+ fmt.Println("\\n" + tnTestColorize("31", "\\u2716 "+n.name+" ("+tnTestDuration(n.duration)+"ms)"))
845
+ name := TnJSString(tnTestErrorField(n.err, "name"))
846
+ head := name
847
+ if code, ok := tnTestErrorField(n.err, "code").(string); ok && code != "" {
848
+ head += " [" + code + "]"
849
+ }
850
+ for _, l := range strings.Split(head+": "+TnJSString(tnTestErrorField(n.err, "message")), "\\n") {
851
+ fmt.Println(" " + l)
852
+ }
853
+ }
854
+
855
+ func tnXMLEscape(s string, attr bool) string {
856
+ s = strings.ReplaceAll(s, "&", "&amp;")
857
+ s = strings.ReplaceAll(s, "<", "&lt;")
858
+ if attr {
859
+ s = strings.ReplaceAll(s, "\\"", "&quot;")
860
+ s = strings.ReplaceAll(s, "\\n", "")
861
+ }
862
+ return s
863
+ }
864
+
865
+ // junit: Node's layout (testcase / testsuite elements, diagnostics and the
866
+ // counters as comments); failure bodies show the error, without a stack
867
+ func tnTestJunit(n *TnTestNode, depth int) {
868
+ indent := strings.Repeat("\\t", depth+1)
869
+ dur := strconv.FormatFloat(n.duration/1000, 'f', 6, 64)
870
+ if n.suite {
871
+ tests, failures, skipped := 0, 0, 0
872
+ for _, c := range n.children {
873
+ if !c.suite {
874
+ tests++
875
+ if c.status == "fail" {
876
+ failures++
877
+ }
878
+ if c.status == "skip" || c.status == "todo" {
879
+ skipped++
880
+ }
881
+ }
882
+ }
883
+ host, _ := os.Hostname()
884
+ fmt.Printf("%s<testsuite name=\\"%s\\" time=\\"%s\\" disabled=\\"0\\" errors=\\"0\\" tests=\\"%d\\" failures=\\"%d\\" skipped=\\"%d\\" hostname=\\"%s\\">\\n", indent, tnXMLEscape(n.name, true), dur, tests, failures, skipped, tnXMLEscape(host, true))
885
+ for _, c := range n.children {
886
+ tnTestJunit(c, depth+1)
887
+ }
888
+ fmt.Println(indent + "</testsuite>")
889
+ } else {
890
+ open := fmt.Sprintf("%s<testcase name=\\"%s\\" time=\\"%s\\" classname=\\"test\\"", indent, tnXMLEscape(n.name, true), dur)
891
+ switch {
892
+ case n.status == "fail":
893
+ msg := tnXMLEscape(TnJSString(tnTestErrorField(n.err, "message")), true)
894
+ fmt.Printf("%s failure=\\"%s\\">\\n", open, msg)
895
+ fmt.Printf("%s\\t<failure type=\\"%s\\" message=\\"%s\\">\\n", indent, n.failureType, msg)
896
+ // Node wraps the error in an ERR_TEST_FAILURE whose cause it is
897
+ cause := strings.ReplaceAll(TnInspect(n.err), "\\n", "\\n ")
898
+ raw := strings.TrimSuffix(TnJSString(tnTestErrorField(n.err, "message")), "\\n")
899
+ fmt.Println(tnXMLEscape("[Error [ERR_TEST_FAILURE]: "+raw+"\\n] {\\n code: 'ERR_TEST_FAILURE',\\n failureType: '"+n.failureType+"',\\n cause: "+cause+"\\n}", false))
900
+ fmt.Println(indent + "\\t</failure>")
901
+ fmt.Println(indent + "</testcase>")
902
+ case n.status == "skip" || n.status == "todo":
903
+ kind := "skipped"
904
+ msg := n.skipMsg
905
+ if n.status == "todo" {
906
+ kind, msg = "todo", n.todoMsg
907
+ }
908
+ if msg == "" {
909
+ msg = "true"
910
+ }
911
+ fmt.Println(open + ">")
912
+ fmt.Printf("%s\\t<skipped type=\\"%s\\" message=\\"%s\\"/>\\n", indent, kind, tnXMLEscape(msg, true))
913
+ fmt.Println(indent + "</testcase>")
914
+ default:
915
+ fmt.Println(open + "/>")
916
+ }
917
+ for _, c := range n.children {
918
+ tnTestJunit(c, depth+1)
919
+ }
920
+ }
921
+ for _, d := range n.diagnostics {
922
+ fmt.Println(indent + "<!-- " + d + " -->")
923
+ }
924
+ }
925
+
653
926
  func tnTestFinish() {
654
927
  stats := []string{"tests", "suites", "pass", "fail", "cancelled", "skipped", "todo"}
655
- if !tnTestSpec {
928
+ duration := "duration_ms " + tnTestDuration(float64(time.Since(tnTestStart).Nanoseconds())/1e6)
929
+ switch tnTestReporter {
930
+ case "dot":
931
+ fmt.Println()
932
+ if len(tnTestFailures) > 0 {
933
+ fmt.Println("\\n" + tnTestColorize("31", "Failed tests:"))
934
+ for _, n := range tnTestFailures {
935
+ tnTestFailureLines(n)
936
+ }
937
+ }
938
+ tnTestExitCode()
939
+ return
940
+ case "junit":
941
+ for _, n := range tnTestRoot.children {
942
+ tnTestJunit(n, 0)
943
+ }
944
+ for _, key := range stats {
945
+ fmt.Println("\\t<!-- " + key + " " + strconv.Itoa(tnTestCounts[key]) + " -->")
946
+ }
947
+ fmt.Println("\\t<!-- " + duration + " -->")
948
+ fmt.Println("</testsuites>")
949
+ tnTestExitCode()
950
+ return
951
+ }
952
+ if tnTestTap {
656
953
  fmt.Println("1.." + strconv.Itoa(len(tnTestRoot.children)))
657
954
  }
658
955
  for _, key := range stats {
@@ -663,26 +960,21 @@ func tnTestFinish() {
663
960
  fmt.Println("# " + line)
664
961
  }
665
962
  }
666
- duration := "duration_ms " + tnTestDuration(float64(time.Since(tnTestStart).Nanoseconds())/1e6)
667
963
  if tnTestSpec {
668
964
  fmt.Println(tnTestColorize("34", "\\u2139 "+duration))
669
965
  if len(tnTestFailures) > 0 {
670
966
  fmt.Println("\\n" + tnTestColorize("31", "\\u2716 failing tests:"))
671
967
  for _, n := range tnTestFailures {
672
- fmt.Println("\\n" + tnTestColorize("31", "\\u2716 "+n.name+" ("+tnTestDuration(n.duration)+"ms)"))
673
- name := TnJSString(tnTestErrorField(n.err, "name"))
674
- head := name
675
- if code, ok := tnTestErrorField(n.err, "code").(string); ok && code != "" {
676
- head += " [" + code + "]"
677
- }
678
- for _, l := range strings.Split(head+": "+TnJSString(tnTestErrorField(n.err, "message")), "\\n") {
679
- fmt.Println(" " + l)
680
- }
968
+ tnTestFailureLines(n)
681
969
  }
682
970
  }
683
971
  } else {
684
972
  fmt.Println("# " + duration)
685
973
  }
974
+ tnTestExitCode()
975
+ }
976
+
977
+ func tnTestExitCode() {
686
978
  if tnTestCounts["fail"] > 0 || tnTestCounts["cancelled"] > 0 {
687
979
  TnSetExitCode(1)
688
980
  }
@@ -972,7 +1264,7 @@ function eventFn(nodes) {
972
1264
  }
973
1265
  export function registerTest(r) {
974
1266
  defineModule(r, 'test');
975
- defineHelper(r, 'nodeTest', ['fmt', 'math', 'os', 'reflect', 'strconv', 'strings', 'time'], ['eventLoop', 'promise', 'nodeInvoke', 'dynamic', 'nodeEvents', 'nodeProcess', 'nodeUtil', 'error', 'timerWait', 'clock'], testHelper);
1267
+ defineHelper(r, 'nodeTest', ['fmt', 'math', 'os', 'reflect', 'regexp', 'strconv', 'strings', 'time'], ['eventLoop', 'promise', 'nodeInvoke', 'dynamic', 'nodeEvents', 'nodeProcess', 'nodeUtil', 'error', 'timerWait', 'clock'], testHelper);
976
1268
  const use = () => r.helper('nodeTest');
977
1269
  defineClass(r, 'test.TestContext', '*TnTestContext', 'class', 'skip=; todo=; diagnostic=; plan=; runOnly=; test=chan struct{}; before=; after=; beforeEach=; afterEach=', '', 'name=string; fullName=string; mock=*TnMockTracker; signal=*TnAbortSignal; filePath=string; assert=*TnTestAssert', '');
978
1270
  r.classes['test.SuiteContext'] = r.classes['test.TestContext'];
@@ -1011,13 +1303,13 @@ export function registerTest(r) {
1011
1303
  register(name, 'TnTestRegister', '');
1012
1304
  register(`${name}.skip`, 'TnTestRegister', 'skip');
1013
1305
  register(`${name}.todo`, 'TnTestRegister', 'todo');
1014
- register(`${name}.only`, 'TnTestRegister', '');
1306
+ register(`${name}.only`, 'TnTestRegister', 'only');
1015
1307
  }
1016
1308
  for (const name of ['describe', 'suite']) {
1017
1309
  register(name, 'TnSuiteRegister', '');
1018
1310
  register(`${name}.skip`, 'TnSuiteRegister', 'skip');
1019
1311
  register(`${name}.todo`, 'TnSuiteRegister', 'todo');
1020
- register(`${name}.only`, 'TnSuiteRegister', '');
1312
+ register(`${name}.only`, 'TnSuiteRegister', 'only');
1021
1313
  }
1022
1314
  for (const variant of ['', '.skip', '.todo', '.only']) {
1023
1315
  r.functions[`test.default${variant}`] = r.functions[`test.test${variant}`];