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
@@ -32,9 +32,15 @@ func tnRunBeforeExit(code float64) {
32
32
  }
33
33
  }
34
34
 
35
+ // Set by process.stdin.setRawMode: puts the terminal back as it was, as Node does at exit
36
+ var tnResetStdio func()
37
+
35
38
  // The end of main: exit with process.exitCode
36
39
  func TnProcessExit() {
37
40
  tnRunBeforeExit(tnExitCode)
41
+ if tnResetStdio != nil {
42
+ tnResetStdio()
43
+ }
38
44
  if tnExitCode != 0 {
39
45
  os.Exit(int(tnExitCode))
40
46
  }
@@ -46,6 +52,9 @@ func TnProcessExitWith(code ...float64) {
46
52
  tnExitCode = code[0]
47
53
  }
48
54
  tnRunBeforeExit(tnExitCode)
55
+ if tnResetStdio != nil {
56
+ tnResetStdio()
57
+ }
49
58
  os.Exit(int(tnExitCode))
50
59
  }
51
60
 
@@ -171,6 +180,197 @@ func TnHasEnv(name string) bool {
171
180
  _, ok := os.LookupEnv(name)
172
181
  return ok
173
182
  }`;
183
+ // Terminal size, raw mode and umask: one variant per target OS (nodeTtyOS@os)
184
+ const ttyHelper = `var tnStdinRaw bool
185
+
186
+ // process.stdout.columns / rows: 0 when the stream is not a terminal
187
+ func TnTtyColumns(f *os.File) float64 {
188
+ cols, _, _ := tnTerminalSize(f)
189
+ return float64(cols)
190
+ }
191
+
192
+ func TnTtyRows(f *os.File) float64 {
193
+ _, rows, _ := tnTerminalSize(f)
194
+ return float64(rows)
195
+ }
196
+
197
+ func TnTtyWindowSize(f *os.File) []float64 {
198
+ cols, rows, _ := tnTerminalSize(f)
199
+ return []float64{float64(cols), float64(rows)}
200
+ }
201
+
202
+ // process.stdin.setRawMode(mode): libuv's raw mode; throws when stdin is not a terminal
203
+ func TnTtySetRawMode(mode bool) {
204
+ if !tnSetRawMode(os.Stdin, mode) {
205
+ panic(TnNodeError("Error", "EINVAL", "setRawMode EINVAL"))
206
+ }
207
+ tnStdinRaw = mode
208
+ tnResetStdio = func() { tnSetRawMode(os.Stdin, false) }
209
+ }
210
+
211
+ // process.umask(mask?): the previous mask (a number or an octal string)
212
+ func TnProcessUmask(mask ...interface{}) float64 {
213
+ if len(mask) == 0 || mask[0] == nil {
214
+ old := tnUmask(0)
215
+ tnUmask(old)
216
+ return float64(old)
217
+ }
218
+ var m int
219
+ switch x := mask[0].(type) {
220
+ case string:
221
+ n, err := strconv.ParseInt(x, 8, 32)
222
+ if err != nil {
223
+ panic(TnNodeError("TypeError", "ERR_INVALID_ARG_VALUE", "The argument 'mask' must be a 32-bit unsigned integer or an octal string. Received '" + x + "'"))
224
+ }
225
+ m = int(n)
226
+ default:
227
+ m = int(TnNumber(x))
228
+ }
229
+ return float64(tnUmask(m & 0o777))
230
+ }`;
231
+ // Linux: the asm-generic termios ioctls and flags (std syscall only has them
232
+ // for some architectures); PowerPC and MIPS number them differently
233
+ const linuxTtyHelper = `type tnWinsize struct {
234
+ Row, Col, X, Y uint16
235
+ }
236
+
237
+ func tnTerminalSize(f *os.File) (int, int, bool) {
238
+ var ws tnWinsize
239
+ _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, f.Fd(), uintptr(syscall.TIOCGWINSZ), uintptr(unsafe.Pointer(&ws)))
240
+ if errno != 0 || ws.Col == 0 {
241
+ return 0, 0, false
242
+ }
243
+ return int(ws.Col), int(ws.Row), true
244
+ }
245
+
246
+ var tnSavedTermios *syscall.Termios
247
+
248
+ func tnSetRawMode(f *os.File, raw bool) bool {
249
+ if strings.HasPrefix(runtime.GOARCH, "ppc") || strings.HasPrefix(runtime.GOARCH, "mips") {
250
+ return false
251
+ }
252
+ var t syscall.Termios
253
+ if _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, f.Fd(), 0x5401, uintptr(unsafe.Pointer(&t))); errno != 0 {
254
+ return false
255
+ }
256
+ if raw {
257
+ if tnSavedTermios == nil {
258
+ saved := t
259
+ tnSavedTermios = &saved
260
+ }
261
+ t.Iflag &^= 0x2 | 0x100 | 0x10 | 0x20 | 0x400
262
+ t.Oflag |= 0x4
263
+ t.Cflag |= 0x30
264
+ t.Lflag &^= 0x8 | 0x2 | 0x8000 | 0x1
265
+ t.Cc[6], t.Cc[5] = 1, 0
266
+ } else if tnSavedTermios != nil {
267
+ t = *tnSavedTermios
268
+ }
269
+ _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, f.Fd(), 0x5402, uintptr(unsafe.Pointer(&t)))
270
+ return errno == 0
271
+ }
272
+
273
+ func tnUmask(mask int) int {
274
+ return syscall.Umask(mask)
275
+ }`;
276
+ // macOS and FreeBSD: TIOCGETA / TIOCSETA
277
+ const bsdTtyHelper = `type tnWinsize struct {
278
+ Row, Col, X, Y uint16
279
+ }
280
+
281
+ func tnTerminalSize(f *os.File) (int, int, bool) {
282
+ var ws tnWinsize
283
+ _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, f.Fd(), uintptr(syscall.TIOCGWINSZ), uintptr(unsafe.Pointer(&ws)))
284
+ if errno != 0 || ws.Col == 0 {
285
+ return 0, 0, false
286
+ }
287
+ return int(ws.Col), int(ws.Row), true
288
+ }
289
+
290
+ var tnSavedTermios *syscall.Termios
291
+
292
+ func tnSetRawMode(f *os.File, raw bool) bool {
293
+ var t syscall.Termios
294
+ if _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, f.Fd(), uintptr(syscall.TIOCGETA), uintptr(unsafe.Pointer(&t))); errno != 0 {
295
+ return false
296
+ }
297
+ if raw {
298
+ if tnSavedTermios == nil {
299
+ saved := t
300
+ tnSavedTermios = &saved
301
+ }
302
+ t.Iflag &^= syscall.BRKINT | syscall.ICRNL | syscall.INPCK | syscall.ISTRIP | syscall.IXON
303
+ t.Oflag |= syscall.ONLCR
304
+ t.Cflag |= syscall.CS8
305
+ t.Lflag &^= syscall.ECHO | syscall.ICANON | syscall.IEXTEN | syscall.ISIG
306
+ t.Cc[syscall.VMIN], t.Cc[syscall.VTIME] = 1, 0
307
+ } else if tnSavedTermios != nil {
308
+ t = *tnSavedTermios
309
+ }
310
+ _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, f.Fd(), uintptr(syscall.TIOCSETA), uintptr(unsafe.Pointer(&t)))
311
+ return errno == 0
312
+ }
313
+
314
+ func tnUmask(mask int) int {
315
+ return syscall.Umask(mask)
316
+ }`;
317
+ // Windows: the console API (there is no umask; Node returns 0)
318
+ const windowsTtyHelper = `var (
319
+ tnTtyKernel32 = syscall.NewLazyDLL("kernel32.dll")
320
+ tnGetConsoleScreenBufferInfo = tnTtyKernel32.NewProc("GetConsoleScreenBufferInfo")
321
+ tnSetConsoleMode = tnTtyKernel32.NewProc("SetConsoleMode")
322
+ tnSavedConsoleMode uint32
323
+ tnConsoleModeSaved bool
324
+ )
325
+
326
+ type tnConsoleScreenBufferInfo struct {
327
+ Size, CursorPosition [2]int16
328
+ Attributes uint16
329
+ Left, Top, Right, Bottom int16
330
+ MaximumWindowSize [2]int16
331
+ }
332
+
333
+ func tnTerminalSize(f *os.File) (int, int, bool) {
334
+ var info tnConsoleScreenBufferInfo
335
+ ok, _, _ := tnGetConsoleScreenBufferInfo.Call(f.Fd(), uintptr(unsafe.Pointer(&info)))
336
+ if ok == 0 {
337
+ return 0, 0, false
338
+ }
339
+ return int(info.Right-info.Left) + 1, int(info.Bottom-info.Top) + 1, true
340
+ }
341
+
342
+ func tnSetRawMode(f *os.File, raw bool) bool {
343
+ var mode uint32
344
+ if syscall.GetConsoleMode(syscall.Handle(f.Fd()), &mode) != nil {
345
+ return false
346
+ }
347
+ if raw {
348
+ if !tnConsoleModeSaved {
349
+ tnSavedConsoleMode, tnConsoleModeSaved = mode, true
350
+ }
351
+ // no ENABLE_ECHO_INPUT / LINE_INPUT / PROCESSED_INPUT; ENABLE_VIRTUAL_TERMINAL_INPUT
352
+ mode = mode&^(0x4|0x2|0x1) | 0x200
353
+ } else if tnConsoleModeSaved {
354
+ mode = tnSavedConsoleMode
355
+ }
356
+ ok, _, _ := tnSetConsoleMode.Call(f.Fd(), uintptr(mode))
357
+ return ok != 0
358
+ }
359
+
360
+ func tnUmask(mask int) int {
361
+ return 0
362
+ }`;
363
+ const otherTtyHelper = `func tnTerminalSize(f *os.File) (int, int, bool) {
364
+ return 0, 0, false
365
+ }
366
+
367
+ func tnSetRawMode(f *os.File, raw bool) bool {
368
+ return false
369
+ }
370
+
371
+ func tnUmask(mask int) int {
372
+ return 0
373
+ }`;
174
374
  export function registerProcess(r) {
175
375
  defineModule(r, 'process');
176
376
  r.globals['process'] = 'process';
@@ -182,6 +382,13 @@ export function registerProcess(r) {
182
382
  defineHelper(r, 'nodeProcess', ['fmt', 'math/big', 'os', 'runtime', 'strings', 'syscall', 'time'], ['error', 'orderedMap'], processHelper);
183
383
  defineClass(r, 'process.MemoryUsage', '*TnMemoryUsage', 'class', '', 'rss=float64; heapTotal=float64; heapUsed=float64; external=float64; arrayBuffers=float64', '', '');
184
384
  const use = () => r.helper('nodeProcess');
385
+ defineHelper(r, 'nodeTtyOS@linux', ['os', 'runtime', 'strings', 'syscall', 'unsafe'], [], linuxTtyHelper);
386
+ for (const goos of ['darwin', 'freebsd'])
387
+ defineHelper(r, `nodeTtyOS@${goos}`, ['os', 'syscall', 'unsafe'], [], bsdTtyHelper);
388
+ defineHelper(r, 'nodeTtyOS@windows', ['os', 'syscall', 'unsafe'], [], windowsTtyHelper);
389
+ defineHelper(r, 'nodeTtyOS@other', ['os'], [], otherTtyHelper);
390
+ defineHelper(r, 'nodeTty', ['os', 'strconv'], ['nodeTtyOS@os', 'nodeProcess', 'error', 'dynamic'], ttyHelper);
391
+ const tty = () => r.helper('nodeTty');
185
392
  const value = (name, type, emit) => {
186
393
  r.values[`process.${name}`] = (_c) => emit();
187
394
  r.valueTypes[`process.${name}`] = type;
@@ -241,6 +448,26 @@ export function registerProcess(r) {
241
448
  use();
242
449
  return 'TnIsTTY(os.Stdin)';
243
450
  });
451
+ value('stdout.columns', 'float64', () => {
452
+ tty();
453
+ return 'TnTtyColumns(os.Stdout)';
454
+ });
455
+ value('stdout.rows', 'float64', () => {
456
+ tty();
457
+ return 'TnTtyRows(os.Stdout)';
458
+ });
459
+ value('stderr.columns', 'float64', () => {
460
+ tty();
461
+ return 'TnTtyColumns(os.Stderr)';
462
+ });
463
+ value('stderr.rows', 'float64', () => {
464
+ tty();
465
+ return 'TnTtyRows(os.Stderr)';
466
+ });
467
+ value('stdin.isRaw', 'bool', () => {
468
+ tty();
469
+ return 'tnStdinRaw';
470
+ });
244
471
  value('stdout.fd', 'float64', () => 'float64(1)');
245
472
  value('stderr.fd', 'float64', () => 'float64(2)');
246
473
  value('stdin.fd', 'float64', () => 'float64(0)');
@@ -292,6 +519,21 @@ export function registerProcess(r) {
292
519
  use();
293
520
  return `TnProcessWrite(os.Stderr, ${call.args[0]})`;
294
521
  });
522
+ for (const stream of ['stdout', 'stderr']) {
523
+ const f = stream === 'stdout' ? 'os.Stdout' : 'os.Stderr';
524
+ fn(`${stream}.getWindowSize`, '[]float64', (_c) => {
525
+ tty();
526
+ return `TnTtyWindowSize(${f})`;
527
+ });
528
+ }
529
+ fn('stdin.setRawMode', '', (call) => {
530
+ tty();
531
+ return `TnTtySetRawMode(${call.args[0]})`;
532
+ });
533
+ fn('umask', 'float64', (call) => {
534
+ tty();
535
+ return `TnProcessUmask(${call.args.slice(0, 1).join(', ')})`;
536
+ });
295
537
  fn('nextTick', '', (call) => {
296
538
  r.helper('timerWait');
297
539
  const rest = call.args.slice(1).join(', ');
@@ -228,6 +228,270 @@ func TnClearLine(stream interface{}, dir float64, rest ...interface{}) bool {
228
228
  func TnClearScreenDown(stream interface{}, rest ...interface{}) bool {
229
229
  return tnCursorWrite(stream, "\\x1b[0J", tnCursorCallback(rest))
230
230
  }`;
231
+ // readline.emitKeypressEvents(stream): 'keypress' (str, key) events decoded
232
+ // from the stream's data, a port of Node's emitKeys
233
+ const keypressHelper = `// A decoded key; "" stands for undefined
234
+ type TnKey struct {
235
+ sequence string
236
+ name string
237
+ ctrl bool
238
+ meta bool
239
+ shift bool
240
+ code string
241
+ }
242
+
243
+ type tnKeyDecoder struct {
244
+ buf []rune // -1 is the escape timeout ('' in Node)
245
+ timer *TnTimeout
246
+ }
247
+
248
+ var tnKeyDecoders = map[*TnStream]*tnKeyDecoder{}
249
+
250
+ func TnEmitKeypressEvents(stream interface{}, rest ...interface{}) {
251
+ sl, ok := stream.(tnStreamLike)
252
+ if !ok || TnIsNil(stream) {
253
+ return
254
+ }
255
+ s := sl.tnStream()
256
+ if tnKeyDecoders[s] != nil {
257
+ return
258
+ }
259
+ d := &tnKeyDecoder{}
260
+ tnKeyDecoders[s] = d
261
+ var pending []byte
262
+ s.TnEventEmitter.on("data", func(chunk interface{}) {
263
+ if s.listenerCount("keypress") == 0 {
264
+ return
265
+ }
266
+ switch c := chunk.(type) {
267
+ case string:
268
+ pending = append(pending, c...)
269
+ case []byte:
270
+ pending = append(pending, c...)
271
+ default:
272
+ pending = append(pending, TnJSString(chunk)...)
273
+ }
274
+ // whole UTF-8 characters only, as a StringDecoder would
275
+ text := []rune{}
276
+ for len(pending) > 0 && utf8.FullRune(pending) {
277
+ r, size := utf8.DecodeRune(pending)
278
+ text = append(text, r)
279
+ pending = pending[size:]
280
+ }
281
+ if len(text) == 0 {
282
+ return
283
+ }
284
+ if d.timer != nil {
285
+ TnClearTimeout(d.timer)
286
+ d.timer = nil
287
+ }
288
+ for _, r := range text {
289
+ d.feed(s, r)
290
+ }
291
+ // a lone ESC at the end is the Escape key unless more follows soon
292
+ if text[len(text)-1] == 0x1b {
293
+ d.timer = TnSetTimeout(500, func() {
294
+ d.timer = nil
295
+ if len(d.buf) > 0 {
296
+ d.feed(s, -1)
297
+ }
298
+ })
299
+ }
300
+ })
301
+ s.listening("data")
302
+ }
303
+
304
+ func (d *tnKeyDecoder) feed(s *TnStream, r rune) {
305
+ d.buf = append(d.buf, r)
306
+ for len(d.buf) > 0 {
307
+ key, str, emit, n := tnDecodeKey(d.buf)
308
+ if n == 0 {
309
+ return
310
+ }
311
+ d.buf = d.buf[n:]
312
+ if emit {
313
+ s.emit("keypress", str, key)
314
+ }
315
+ }
316
+ }
317
+
318
+ type tnKeyNeedMore struct{}
319
+
320
+ var tnKeyTilde = regexp.MustCompile("^(?:(\\\\d\\\\d?)(?:;(\\\\d))?([~^$])|(\\\\d{3}~))$")
321
+ var tnKeyLetter = regexp.MustCompile("^((\\\\d;)?(\\\\d))?([A-Za-z])$")
322
+
323
+ var tnKeyCodes = map[string]string{
324
+ "[P": "f1", "[Q": "f2", "[R": "f3", "[S": "f4",
325
+ "OP": "f1", "OQ": "f2", "OR": "f3", "OS": "f4",
326
+ "[11~": "f1", "[12~": "f2", "[13~": "f3", "[14~": "f4",
327
+ "[200~": "paste-start", "[201~": "paste-end",
328
+ "[[A": "f1", "[[B": "f2", "[[C": "f3", "[[D": "f4", "[[E": "f5",
329
+ "[15~": "f5", "[17~": "f6", "[18~": "f7", "[19~": "f8", "[20~": "f9", "[21~": "f10", "[23~": "f11", "[24~": "f12",
330
+ "[A": "up", "[B": "down", "[C": "right", "[D": "left", "[E": "clear", "[F": "end", "[H": "home",
331
+ "OA": "up", "OB": "down", "OC": "right", "OD": "left", "OE": "clear", "OF": "end", "OH": "home",
332
+ "[1~": "home", "[2~": "insert", "[3~": "delete", "[4~": "end", "[5~": "pageup", "[6~": "pagedown",
333
+ "[[5~": "pageup", "[[6~": "pagedown", "[7~": "home", "[8~": "end",
334
+ "[a": "up shift", "[b": "down shift", "[c": "right shift", "[d": "left shift", "[e": "clear shift",
335
+ "[2$": "insert shift", "[3$": "delete shift", "[5$": "pageup shift", "[6$": "pagedown shift", "[7$": "home shift", "[8$": "end shift",
336
+ "Oa": "up ctrl", "Ob": "down ctrl", "Oc": "right ctrl", "Od": "left ctrl", "Oe": "clear ctrl",
337
+ "[2^": "insert ctrl", "[3^": "delete ctrl", "[5^": "pageup ctrl", "[6^": "pagedown ctrl", "[7^": "home ctrl", "[8^": "end ctrl",
338
+ "[Z": "tab shift",
339
+ }
340
+
341
+ // One key from the start of in: n is how many characters it used (0 when
342
+ // it needs more input)
343
+ func tnDecodeKey(in []rune) (key *TnKey, str string, emit bool, n int) {
344
+ defer func() {
345
+ if x := recover(); x != nil {
346
+ if _, ok := x.(tnKeyNeedMore); !ok {
347
+ panic(x)
348
+ }
349
+ key, str, emit, n = nil, "", false, 0
350
+ }
351
+ }()
352
+ i := 0
353
+ s := ""
354
+ next := func() rune {
355
+ if i >= len(in) {
356
+ panic(tnKeyNeedMore{})
357
+ }
358
+ r := in[i]
359
+ i++
360
+ if r >= 0 {
361
+ s += string(r)
362
+ }
363
+ return r
364
+ }
365
+ isDigit := func(r rune) bool { return r >= '0' && r <= '9' }
366
+ k := &TnKey{}
367
+ ch := next()
368
+ escaped := false
369
+ if ch == 0x1b {
370
+ escaped = true
371
+ ch = next()
372
+ if ch == 0x1b {
373
+ ch = next()
374
+ }
375
+ }
376
+ if escaped && (ch == 'O' || ch == '[') {
377
+ code := string(ch)
378
+ modifier := 0
379
+ if ch == 'O' {
380
+ ch = next()
381
+ if isDigit(ch) {
382
+ modifier = int(ch-'0') - 1
383
+ ch = next()
384
+ }
385
+ if ch >= 0 {
386
+ code += string(ch)
387
+ }
388
+ } else {
389
+ ch = next()
390
+ if ch == '[' {
391
+ code += "["
392
+ ch = next()
393
+ }
394
+ // the command starts at ch (Node: s.length - 1)
395
+ cmdStart := len(s) - 1
396
+ if ch >= 0 {
397
+ cmdStart = len(s) - utf8.RuneLen(ch)
398
+ }
399
+ if isDigit(ch) {
400
+ ch = next()
401
+ if isDigit(ch) {
402
+ ch = next()
403
+ if isDigit(ch) {
404
+ ch = next()
405
+ }
406
+ }
407
+ }
408
+ if ch == ';' {
409
+ ch = next()
410
+ if isDigit(ch) {
411
+ next()
412
+ }
413
+ }
414
+ cmd := s[cmdStart:]
415
+ if m := tnKeyTilde.FindStringSubmatch(cmd); m != nil {
416
+ if m[4] != "" {
417
+ code += m[4]
418
+ } else {
419
+ code += m[1] + m[3]
420
+ modifier = 0
421
+ if m[2] != "" {
422
+ modifier, _ = strconv.Atoi(m[2])
423
+ modifier--
424
+ }
425
+ }
426
+ } else if m := tnKeyLetter.FindStringSubmatch(cmd); m != nil {
427
+ code += m[4]
428
+ modifier = 0
429
+ if m[3] != "" {
430
+ modifier, _ = strconv.Atoi(m[3])
431
+ modifier--
432
+ }
433
+ } else {
434
+ code += cmd
435
+ }
436
+ }
437
+ k.ctrl = modifier&4 != 0
438
+ k.meta = modifier&10 != 0
439
+ k.shift = modifier&1 != 0
440
+ k.code = code
441
+ if named, ok := tnKeyCodes[code]; ok {
442
+ parts := strings.SplitN(named, " ", 2)
443
+ k.name = parts[0]
444
+ if len(parts) == 2 && parts[1] == "shift" {
445
+ k.shift = true
446
+ } else if len(parts) == 2 {
447
+ k.ctrl = true
448
+ }
449
+ } else {
450
+ k.name = "undefined"
451
+ }
452
+ } else {
453
+ named := true
454
+ switch {
455
+ case ch == '\\r':
456
+ k.name, k.meta = "return", escaped
457
+ case ch == '\\n':
458
+ k.name, k.meta = "enter", escaped
459
+ case ch == '\\t':
460
+ k.name, k.meta = "tab", escaped
461
+ case ch == '\\b' || ch == 0x7f:
462
+ k.name, k.meta = "backspace", escaped
463
+ case ch == 0x1b:
464
+ k.name, k.meta = "escape", escaped
465
+ case ch == ' ':
466
+ k.name, k.meta = "space", escaped
467
+ case !escaped && ch >= 0 && ch <= 0x1a:
468
+ k.name, k.ctrl = string(rune(ch+'a'-1)), true
469
+ case isDigit(ch) || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'):
470
+ k.name = strings.ToLower(string(ch))
471
+ k.shift = ch >= 'A' && ch <= 'Z'
472
+ k.meta = escaped
473
+ case escaped:
474
+ if ch < 0 {
475
+ k.name = "escape"
476
+ } else {
477
+ named = false
478
+ }
479
+ k.meta = true
480
+ default:
481
+ named = false
482
+ }
483
+ if !named && !escaped {
484
+ k.sequence = s
485
+ // a single unnamed character, e.g. "."
486
+ return k, s, utf8.RuneCountInString(s) == 1, i
487
+ }
488
+ }
489
+ k.sequence = s
490
+ if escaped {
491
+ return k, "", s != "", i
492
+ }
493
+ return k, s, s != "", i
494
+ }`;
231
495
  export function registerReadline(r) {
232
496
  defineModule(r, 'readline');
233
497
  defineModule(r, 'readline/promises');
@@ -280,6 +544,13 @@ export function registerReadline(r) {
280
544
  return event && event.kind === 'StringLiteral' && event.text === 'line' ? ['string'] : [];
281
545
  };
282
546
  r.paramTypers['readline.Interface#once'] = r.paramTypers['readline.Interface#on'];
547
+ defineHelper(r, 'nodeKeypress', ['regexp', 'strconv', 'strings', 'unicode/utf8'], ['nodeStream', 'nodeEvents', 'timerWait'], keypressHelper);
548
+ defineClass(r, 'readline.Key', '*TnKey', 'class', '', 'sequence=string; name=string; ctrl=bool; meta=bool; shift=bool; code=string', '', '');
549
+ r.functions['readline.emitKeypressEvents'] = (call) => {
550
+ r.helper('nodeKeypress');
551
+ return `TnEmitKeypressEvents(${call.args.join(', ')})`;
552
+ };
553
+ r.results['readline.emitKeypressEvents'] = '';
283
554
  defineHelper(r, 'nodeReadlineCursor', [], ['nodeStream', 'nodeInvoke', 'eventLoop'], cursorHelper);
284
555
  const cursorFns = {
285
556
  cursorTo: 'TnCursorTo',
@@ -40,7 +40,8 @@ export function createNodeRegistry() {
40
40
  typeOf: (_node) => '',
41
41
  visit: (_node) => '',
42
42
  categoryOf: (_node) => '',
43
- isArrayBuffer: (_node) => false
43
+ isArrayBuffer: (_node) => false,
44
+ entryPoint: (_node) => ''
44
45
  };
45
46
  return registry;
46
47
  }
@@ -24,7 +24,9 @@ type TnSqliteDb struct {
24
24
  allowUnknown bool
25
25
  defensive bool
26
26
  limitOptions interface{}
27
- stmts []*TnSqliteStmt
27
+ // prepared statements not finalized yet; the JS objects are not kept, so
28
+ // one that becomes unreachable is finalized on the event loop
29
+ live map[*sqlite3.Stmt]bool
28
30
  limits *TnSqliteLimits
29
31
  // A JS throw inside a user-defined function, rethrown after the statement
30
32
  pending interface{}
@@ -361,13 +363,10 @@ func (db *TnSqliteDb) setAuthorizer(callback interface{}) {
361
363
 
362
364
  func (db *TnSqliteDb) close() {
363
365
  db.requireOpen()
364
- for _, st := range db.stmts {
365
- if st.s != nil {
366
- st.s.Close()
367
- st.s = nil
368
- }
366
+ for s := range db.live {
367
+ s.Close()
369
368
  }
370
- db.stmts = nil
369
+ db.live = nil
371
370
  err := db.conn.Close()
372
371
  db.conn = nil
373
372
  if err != nil {
@@ -417,7 +416,18 @@ func (db *TnSqliteDb) prepare(sql string, opts ...interface{}) *TnSqliteStmt {
417
416
  st.allowBare = tnSqliteFlag(opts[0], "allowBareNamedParameters", st.allowBare)
418
417
  st.allowUnknown = tnSqliteFlag(opts[0], "allowUnknownNamedParameters", st.allowUnknown)
419
418
  }
420
- db.stmts = append(db.stmts, st)
419
+ if db.live == nil {
420
+ db.live = map[*sqlite3.Stmt]bool{}
421
+ }
422
+ db.live[s] = true
423
+ runtime.AddCleanup(st, func(s *sqlite3.Stmt) {
424
+ TnLoopPost(func() {
425
+ if db.live[s] {
426
+ delete(db.live, s)
427
+ s.Close()
428
+ }
429
+ })
430
+ }, s)
421
431
  return st
422
432
  }
423
433
 
@@ -622,18 +632,56 @@ func (db *TnSqliteDb) applyChangeset(changeset []byte, options ...interface{}) b
622
632
  panic(TnNodeError("Error", "ERR_SQLITE_ERROR", "Changesets are not supported: the bundled SQLite has no session extension"))
623
633
  }
624
634
 
635
+ // serialize(dbName = 'main') / deserialize(buffer, { dbName }): the database
636
+ // image goes through a temporary file and SQLite's backup API (the driver
637
+ // has no sqlite3_serialize binding)
638
+ func tnSqliteTempFile() string {
639
+ f, err := os.CreateTemp("", "tnsqlite-*.db")
640
+ if err != nil {
641
+ panic(tnSqliteError(err))
642
+ }
643
+ f.Close()
644
+ return f.Name()
645
+ }
646
+
625
647
  func (db *TnSqliteDb) serialize(name ...interface{}) []byte {
626
648
  db.requireOpen()
627
- panic(TnNodeError("Error", "ERR_SQLITE_ERROR", "serialize() is not supported: the bundled SQLite driver has no sqlite3_serialize binding"))
649
+ schema := "main"
650
+ if len(name) > 0 {
651
+ if s, ok := name[0].(string); ok {
652
+ schema = s
653
+ }
654
+ }
655
+ path := tnSqliteTempFile()
656
+ defer os.Remove(path)
657
+ os.Remove(path)
658
+ db.check(db.conn.Backup(schema, path))
659
+ data, err := os.ReadFile(path)
660
+ if err != nil {
661
+ panic(tnSqliteError(err))
662
+ }
663
+ return data
628
664
  }
629
665
 
630
666
  func (db *TnSqliteDb) deserialize(data []byte, options ...interface{}) {
631
667
  db.requireOpen()
632
- panic(TnNodeError("Error", "ERR_SQLITE_ERROR", "deserialize() is not supported: the bundled SQLite driver has no sqlite3_deserialize binding"))
668
+ schema := "main"
669
+ if len(options) > 0 && options[0] != nil {
670
+ if s, ok := TnGet(options[0], "dbName").(string); ok {
671
+ schema = s
672
+ }
673
+ }
674
+ path := tnSqliteTempFile()
675
+ defer os.Remove(path)
676
+ if err := os.WriteFile(path, data, 0o600); err != nil {
677
+ panic(tnSqliteError(err))
678
+ }
679
+ db.check(db.conn.Restore(schema, path))
633
680
  }
634
681
 
635
682
  func (st *TnSqliteStmt) requireLive() {
636
- if st.s == nil {
683
+ // db.close() (or a reopen) finalized it
684
+ if st.s == nil || !st.db.live[st.s] {
637
685
  panic(tnSqliteState("statement has been finalized"))
638
686
  }
639
687
  st.db.requireOpen()
@@ -1063,7 +1111,7 @@ func TnSqliteBackup(db *TnSqliteDb, path string, opts ...interface{}) chan float
1063
1111
  }`;
1064
1112
  export function registerSqlite(r) {
1065
1113
  defineModule(r, 'sqlite');
1066
- defineHelper(r, 'nodeSqlite', ['github.com/ncruces/go-sqlite3', 'errors', 'fmt', 'math', 'math/big', 'reflect', 'sort', 'strconv', 'strings', 'time', 'unsafe'], ['dynamic', 'orderedMap', 'nodeInvoke', 'eventLoop', 'promise'], sqliteHelper);
1114
+ defineHelper(r, 'nodeSqlite', ['github.com/ncruces/go-sqlite3', 'errors', 'fmt', 'math', 'math/big', 'os', 'reflect', 'runtime', 'sort', 'strconv', 'strings', 'time', 'unsafe'], ['dynamic', 'orderedMap', 'nodeInvoke', 'eventLoop', 'promise'], sqliteHelper);
1067
1115
  const use = () => r.helper('nodeSqlite');
1068
1116
  defineClass(r, 'sqlite.DatabaseSync', '*TnSqliteDb', 'class', 'open=; close=; exec=; prepare=*TnSqliteStmt; location=*string; function=; aggregate=; enableLoadExtension=; enableDefensive=; loadExtension=; setAuthorizer=; createTagStore=*TnSqliteTagStore; createSession=interface{}; applyChangeset=bool; serialize=[]byte; deserialize=', '', 'isOpen=bool; isTransaction=bool; limits=*TnSqliteLimits', '');
1069
1117
  defineClass(r, 'sqlite.StatementSync', '*TnSqliteStmt', 'class', 'run=*TnSqliteRunResult; get=interface{}; all=[]interface{}; iterate=*TnSqliteIterator; columns=[]interface{}; setReadBigInts=; setReturnArrays=; setAllowBareNamedParameters=; setAllowUnknownNamedParameters=', '', 'sourceSQL=string; expandedSQL=string', '');