-
Notifications
You must be signed in to change notification settings - Fork 30.6k
/
Copy pathtest-esm-loader-hooks.mjs
842 lines (737 loc) Β· 30.5 KB
/
test-esm-loader-hooks.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
import { spawnPromisified } from '../common/index.mjs';
import * as fixtures from '../common/fixtures.mjs';
import assert from 'node:assert';
import { execPath } from 'node:process';
import { describe, it } from 'node:test';
describe('Loader hooks', { concurrency: !process.env.TEST_PARALLEL }, () => {
it('are called with all expected arguments', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--experimental-loader',
fixtures.fileURL('es-module-loaders/hooks-input.mjs'),
fixtures.path('es-modules/json-modules.mjs'),
]);
assert.strictEqual(stderr, '');
assert.strictEqual(code, 0);
assert.strictEqual(signal, null);
const lines = stdout.split('\n');
assert.match(lines[0], /{"url":"file:\/\/\/.*\/json-modules\.mjs","format":"test","shortCircuit":true}/);
assert.match(lines[1], /{"source":{"type":"Buffer","data":\[.*\]},"format":"module","shortCircuit":true}/);
assert.match(lines[2], /{"url":"file:\/\/\/.*\/experimental\.json","format":"test","shortCircuit":true}/);
assert.match(lines[3], /{"source":{"type":"Buffer","data":\[.*\]},"format":"json","shortCircuit":true}/);
assert.strictEqual(lines[4], '');
assert.strictEqual(lines.length, 5);
});
it('are called with all expected arguments using register function', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--experimental-loader=data:text/javascript,',
'--input-type=module',
'--eval',
"import { register } from 'node:module';" +
`register(${JSON.stringify(fixtures.fileURL('es-module-loaders/hooks-input.mjs'))});` +
`await import(${JSON.stringify(fixtures.fileURL('es-modules/json-modules.mjs'))});`,
]);
assert.strictEqual(stderr, '');
assert.strictEqual(code, 0);
assert.strictEqual(signal, null);
const lines = stdout.split('\n');
assert.match(lines[0], /{"url":"file:\/\/\/.*\/json-modules\.mjs","format":"test","shortCircuit":true}/);
assert.match(lines[1], /{"source":{"type":"Buffer","data":\[.*\]},"format":"module","shortCircuit":true}/);
assert.match(lines[2], /{"url":"file:\/\/\/.*\/experimental\.json","format":"test","shortCircuit":true}/);
assert.match(lines[3], /{"source":{"type":"Buffer","data":\[.*\]},"format":"json","shortCircuit":true}/);
assert.strictEqual(lines[4], '');
assert.strictEqual(lines.length, 5);
});
describe('should handle never-settling hooks in ESM files', { concurrency: !process.env.TEST_PARALLEL }, () => {
it('top-level await of a never-settling resolve without warning', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--experimental-loader',
fixtures.fileURL('es-module-loaders/never-settling-resolve-step/loader.mjs'),
fixtures.path('es-module-loaders/never-settling-resolve-step/never-resolve.mjs'),
]);
assert.strictEqual(stderr, '');
assert.match(stdout, /^should be output\r?\n$/);
assert.strictEqual(code, 13);
assert.strictEqual(signal, null);
});
it('top-level await of a never-settling resolve with warning', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--experimental-loader',
fixtures.fileURL('es-module-loaders/never-settling-resolve-step/loader.mjs'),
fixtures.path('es-module-loaders/never-settling-resolve-step/never-resolve.mjs'),
]);
assert.match(stderr, /Warning: Detected unsettled top-level await at.+never-resolve\.mjs:5/);
assert.match(stdout, /^should be output\r?\n$/);
assert.strictEqual(code, 13);
assert.strictEqual(signal, null);
});
it('top-level await of a never-settling load without warning', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--experimental-loader',
fixtures.fileURL('es-module-loaders/never-settling-resolve-step/loader.mjs'),
fixtures.path('es-module-loaders/never-settling-resolve-step/never-load.mjs'),
]);
assert.strictEqual(stderr, '');
assert.match(stdout, /^should be output\r?\n$/);
assert.strictEqual(code, 13);
assert.strictEqual(signal, null);
});
it('top-level await of a never-settling load with warning', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--experimental-loader',
fixtures.fileURL('es-module-loaders/never-settling-resolve-step/loader.mjs'),
fixtures.path('es-module-loaders/never-settling-resolve-step/never-load.mjs'),
]);
assert.match(stderr, /Warning: Detected unsettled top-level await at.+never-load\.mjs:5/);
assert.match(stdout, /^should be output\r?\n$/);
assert.strictEqual(code, 13);
assert.strictEqual(signal, null);
});
it('top-level await of a race of never-settling hooks', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--experimental-loader',
fixtures.fileURL('es-module-loaders/never-settling-resolve-step/loader.mjs'),
fixtures.path('es-module-loaders/never-settling-resolve-step/race.mjs'),
]);
assert.strictEqual(stderr, '');
assert.match(stdout, /^true\r?\n$/);
assert.strictEqual(code, 0);
assert.strictEqual(signal, null);
});
it('import.meta.resolve of a never-settling resolve', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--experimental-loader',
fixtures.fileURL('es-module-loaders/never-settling-resolve-step/loader.mjs'),
fixtures.path('es-module-loaders/never-settling-resolve-step/import.meta.never-resolve.mjs'),
]);
assert.strictEqual(stderr, '');
assert.match(stdout, /^should be output\r?\n$/);
assert.strictEqual(code, 13);
assert.strictEqual(signal, null);
});
});
describe('should handle never-settling hooks in CJS files', { concurrency: !process.env.TEST_PARALLEL }, () => {
it('never-settling resolve', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--experimental-loader',
fixtures.fileURL('es-module-loaders/never-settling-resolve-step/loader.mjs'),
fixtures.path('es-module-loaders/never-settling-resolve-step/never-resolve.cjs'),
]);
assert.strictEqual(stderr, '');
assert.match(stdout, /^should be output\r?\n$/);
assert.strictEqual(code, 0);
assert.strictEqual(signal, null);
});
it('never-settling load', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--experimental-loader',
fixtures.fileURL('es-module-loaders/never-settling-resolve-step/loader.mjs'),
fixtures.path('es-module-loaders/never-settling-resolve-step/never-load.cjs'),
]);
assert.strictEqual(stderr, '');
assert.match(stdout, /^should be output\r?\n$/);
assert.strictEqual(code, 0);
assert.strictEqual(signal, null);
});
it('race of never-settling hooks', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--experimental-loader',
fixtures.fileURL('es-module-loaders/never-settling-resolve-step/loader.mjs'),
fixtures.path('es-module-loaders/never-settling-resolve-step/race.cjs'),
]);
assert.strictEqual(stderr, '');
assert.match(stdout, /^true\r?\n$/);
assert.strictEqual(code, 0);
assert.strictEqual(signal, null);
});
});
it('should work without worker permission', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--experimental-permission',
'--allow-fs-read',
'*',
'--experimental-loader',
fixtures.fileURL('empty.js'),
fixtures.path('es-modules/esm-top-level-await.mjs'),
]);
assert.strictEqual(stderr, '');
assert.match(stdout, /^1\r?\n2\r?\n$/);
assert.strictEqual(code, 0);
assert.strictEqual(signal, null);
});
it('should allow loader hooks to spawn workers when allowed by the CLI flags', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--experimental-permission',
'--allow-worker',
'--allow-fs-read',
'*',
'--experimental-loader',
`data:text/javascript,import{Worker}from"worker_threads";new Worker(${encodeURIComponent(JSON.stringify(fixtures.path('empty.js')))}).unref()`,
fixtures.path('es-modules/esm-top-level-await.mjs'),
]);
assert.strictEqual(stderr, '');
assert.match(stdout, /^1\r?\n2\r?\n$/);
assert.strictEqual(code, 0);
assert.strictEqual(signal, null);
});
it('should not allow loader hooks to spawn workers if restricted by the CLI flags', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--experimental-permission',
'--allow-fs-read',
'*',
'--experimental-loader',
`data:text/javascript,import{Worker}from"worker_threads";new Worker(${encodeURIComponent(JSON.stringify(fixtures.path('empty.js')))}).unref()`,
fixtures.path('es-modules/esm-top-level-await.mjs'),
]);
assert.match(stderr, /code: 'ERR_ACCESS_DENIED'/);
assert.strictEqual(stdout, '');
assert.strictEqual(code, 1);
assert.strictEqual(signal, null);
});
it('should not leak internals or expose import.meta.resolve', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--experimental-loader',
fixtures.fileURL('es-module-loaders/loader-edge-cases.mjs'),
fixtures.path('empty.js'),
]);
assert.strictEqual(stderr, '');
assert.strictEqual(stdout, '');
assert.strictEqual(code, 0);
assert.strictEqual(signal, null);
});
it('should be fine to call `process.exit` from a custom async hook', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--experimental-loader',
'data:text/javascript,export function load(a,b,next){if(a==="data:exit")process.exit(42);return next(a,b)}',
'--input-type=module',
'--eval',
'import "data:exit"',
]);
assert.strictEqual(stderr, '');
assert.strictEqual(stdout, '');
assert.strictEqual(code, 42);
assert.strictEqual(signal, null);
});
it('should be fine to call `process.exit` from a custom sync hook', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--experimental-loader',
'data:text/javascript,export function resolve(a,b,next){if(a==="exit:")process.exit(42);return next(a,b)}',
'--input-type=module',
'--eval',
'import "data:text/javascript,import.meta.resolve(%22exit:%22)"',
]);
assert.strictEqual(stderr, '');
assert.strictEqual(stdout, '');
assert.strictEqual(code, 42);
assert.strictEqual(signal, null);
});
it('should be fine to call `process.exit` from the loader thread top-level', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--experimental-loader',
'data:text/javascript,process.exit(42)',
fixtures.path('empty.js'),
]);
assert.strictEqual(stderr, '');
assert.strictEqual(stdout, '');
assert.strictEqual(code, 42);
assert.strictEqual(signal, null);
});
describe('should handle a throwing top-level body', () => {
it('should handle regular Error object', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--experimental-loader',
'data:text/javascript,throw new Error("error message")',
fixtures.path('empty.js'),
]);
assert.match(stderr, /Error: error message\r?\n/);
assert.strictEqual(stdout, '');
assert.strictEqual(code, 1);
assert.strictEqual(signal, null);
});
it('should handle null', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--experimental-loader',
'data:text/javascript,throw null',
fixtures.path('empty.js'),
]);
assert.match(stderr, /\nnull\r?\n/);
assert.strictEqual(stdout, '');
assert.strictEqual(code, 1);
assert.strictEqual(signal, null);
});
it('should handle undefined', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--experimental-loader',
'data:text/javascript,throw undefined',
fixtures.path('empty.js'),
]);
assert.match(stderr, /\nundefined\r?\n/);
assert.strictEqual(stdout, '');
assert.strictEqual(code, 1);
assert.strictEqual(signal, null);
});
it('should handle boolean', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--experimental-loader',
'data:text/javascript,throw true',
fixtures.path('empty.js'),
]);
assert.match(stderr, /\ntrue\r?\n/);
assert.strictEqual(stdout, '');
assert.strictEqual(code, 1);
assert.strictEqual(signal, null);
});
it('should handle empty plain object', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--experimental-loader',
'data:text/javascript,throw {}',
fixtures.path('empty.js'),
]);
assert.match(stderr, /\n\{\}\r?\n/);
assert.strictEqual(stdout, '');
assert.strictEqual(code, 1);
assert.strictEqual(signal, null);
});
it('should handle plain object', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--experimental-loader',
'data:text/javascript,throw {fn(){},symbol:Symbol("symbol"),u:undefined}',
fixtures.path('empty.js'),
]);
assert.match(stderr, /\n\{ fn: \[Function: fn\], symbol: Symbol\(symbol\), u: undefined \}\r?\n/);
assert.strictEqual(stdout, '');
assert.strictEqual(code, 1);
assert.strictEqual(signal, null);
});
it('should handle number', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--experimental-loader',
'data:text/javascript,throw 1',
fixtures.path('empty.js'),
]);
assert.match(stderr, /\n1\r?\n/);
assert.strictEqual(stdout, '');
assert.strictEqual(code, 1);
assert.strictEqual(signal, null);
});
it('should handle bigint', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--experimental-loader',
'data:text/javascript,throw 1n',
fixtures.path('empty.js'),
]);
assert.match(stderr, /\n1\r?\n/);
assert.strictEqual(stdout, '');
assert.strictEqual(code, 1);
assert.strictEqual(signal, null);
});
it('should handle string', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--experimental-loader',
'data:text/javascript,throw "literal string"',
fixtures.path('empty.js'),
]);
assert.match(stderr, /\nliteral string\r?\n/);
assert.strictEqual(stdout, '');
assert.strictEqual(code, 1);
assert.strictEqual(signal, null);
});
it('should handle symbol', async () => {
const { code, signal, stdout } = await spawnPromisified(execPath, [
'--experimental-loader',
'data:text/javascript,throw Symbol("symbol descriptor")',
fixtures.path('empty.js'),
]);
// Throwing a symbol doesn't produce any output
assert.strictEqual(stdout, '');
assert.strictEqual(code, 1);
assert.strictEqual(signal, null);
});
it('should handle function', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--experimental-loader',
'data:text/javascript,throw function fnName(){}',
fixtures.path('empty.js'),
]);
assert.match(stderr, /\n\[Function: fnName\]\r?\n/);
assert.strictEqual(stdout, '');
assert.strictEqual(code, 1);
assert.strictEqual(signal, null);
});
});
describe('globalPreload', () => {
it('should emit warning', async () => {
const { stderr } = await spawnPromisified(execPath, [
'--experimental-loader',
'data:text/javascript,export function globalPreload(){}',
'--experimental-loader',
'data:text/javascript,export function globalPreload(){return""}',
fixtures.path('empty.js'),
]);
assert.strictEqual(stderr.match(/`globalPreload` has been removed; use `initialize` instead/g).length, 1);
});
it('should not emit warning when initialize is supplied', async () => {
const { stderr } = await spawnPromisified(execPath, [
'--experimental-loader',
'data:text/javascript,export function globalPreload(){}export function initialize(){}',
fixtures.path('empty.js'),
]);
assert.doesNotMatch(stderr, /`globalPreload` has been removed; use `initialize` instead/);
});
});
it('should be fine to call `process.removeAllListeners("beforeExit")` from the main thread', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--experimental-loader',
'data:text/javascript,export function load(a,b,c){return new Promise(d=>setTimeout(()=>d(c(a,b)),99))}',
'--input-type=module',
'--eval',
'setInterval(() => process.removeAllListeners("beforeExit"),1).unref();await import("data:text/javascript,")',
]);
assert.strictEqual(stderr, '');
assert.strictEqual(stdout, '');
assert.strictEqual(code, 0);
assert.strictEqual(signal, null);
});
describe('`initialize`/`register`', () => {
it('should invoke `initialize` correctly', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--experimental-loader',
fixtures.fileURL('es-module-loaders/hooks-initialize.mjs'),
'--input-type=module',
'--eval',
'import os from "node:os";',
]);
assert.strictEqual(stderr, '');
assert.deepStrictEqual(stdout.split('\n'), ['hooks initialize 1', '']);
assert.strictEqual(code, 0);
assert.strictEqual(signal, null);
});
it('should allow communicating with loader via `register` ports', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--input-type=module',
'--eval',
`
import {MessageChannel} from 'node:worker_threads';
import {register} from 'node:module';
import {once} from 'node:events';
const {port1, port2} = new MessageChannel();
port1.on('message', (msg) => {
console.log('message', msg);
});
const result = register(
${JSON.stringify(fixtures.fileURL('es-module-loaders/hooks-initialize-port.mjs'))},
{data: port2, transferList: [port2]},
);
console.log('register', result);
const timeout = setTimeout(() => {}, 2**31 - 1); // to keep the process alive.
await Promise.all([
once(port1, 'message').then(() => once(port1, 'message')),
import('node:os'),
]);
clearTimeout(timeout);
port1.close();
`,
]);
assert.strictEqual(stderr, '');
assert.deepStrictEqual(stdout.split('\n'), [ 'register undefined',
'message initialize',
'message resolve node:os',
'' ]);
assert.strictEqual(code, 0);
assert.strictEqual(signal, null);
});
it('should have `register` accept URL objects as `parentURL`', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--import',
`data:text/javascript,${encodeURIComponent(
'import{ register } from "node:module";' +
'import { pathToFileURL } from "node:url";' +
'register("./hooks-initialize.mjs", pathToFileURL("./"));'
)}`,
'--input-type=module',
'--eval',
`
import {register} from 'node:module';
register(
${JSON.stringify(fixtures.fileURL('es-module-loaders/loader-load-foo-or-42.mjs'))},
new URL('data:'),
);
import('node:os').then((result) => {
console.log(JSON.stringify(result));
});
`,
], { cwd: fixtures.fileURL('es-module-loaders/') });
assert.strictEqual(stderr, '');
assert.deepStrictEqual(stdout.split('\n').sort(), ['hooks initialize 1', '{"default":"foo"}', ''].sort());
assert.strictEqual(code, 0);
assert.strictEqual(signal, null);
});
it('should have `register` work with cjs', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--input-type=commonjs',
'--eval',
`
'use strict';
const {register} = require('node:module');
register(
${JSON.stringify(fixtures.fileURL('es-module-loaders/hooks-initialize.mjs'))},
);
register(
${JSON.stringify(fixtures.fileURL('es-module-loaders/loader-load-foo-or-42.mjs'))},
);
import('node:os').then((result) => {
console.log(JSON.stringify(result));
});
`,
]);
assert.strictEqual(stderr, '');
assert.deepStrictEqual(stdout.split('\n').sort(), ['hooks initialize 1', '{"default":"foo"}', ''].sort());
assert.strictEqual(code, 0);
assert.strictEqual(signal, null);
});
it('`register` should work with `require`', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--require',
fixtures.path('es-module-loaders/register-loader.cjs'),
'--input-type=module',
'--eval',
'import "node:os";',
]);
assert.strictEqual(stderr, '');
assert.deepStrictEqual(stdout.split('\n'), ['resolve passthru', 'resolve passthru', '']);
assert.strictEqual(code, 0);
assert.strictEqual(signal, null);
});
it('`register` should work with `import`', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--import',
fixtures.fileURL('es-module-loaders/register-loader.mjs'),
'--input-type=module',
'--eval',
'import "node:os"',
]);
assert.strictEqual(stderr, '');
assert.deepStrictEqual(stdout.split('\n'), ['resolve passthru', '']);
assert.strictEqual(code, 0);
assert.strictEqual(signal, null);
});
it('should execute `initialize` in sequence', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--input-type=module',
'--eval',
`
import {register} from 'node:module';
console.log('result 1', register(
${JSON.stringify(fixtures.fileURL('es-module-loaders/hooks-initialize.mjs'))}
));
console.log('result 2', register(
${JSON.stringify(fixtures.fileURL('es-module-loaders/hooks-initialize.mjs'))}
));
await import('node:os');
`,
]);
assert.strictEqual(stderr, '');
assert.deepStrictEqual(stdout.split('\n'), [ 'hooks initialize 1',
'result 1 undefined',
'hooks initialize 2',
'result 2 undefined',
'' ]);
assert.strictEqual(code, 0);
assert.strictEqual(signal, null);
});
it('should handle `initialize` returning never-settling promise', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--input-type=module',
'--eval',
`
import {register} from 'node:module';
register('data:text/javascript,export function initialize(){return new Promise(()=>{})}');
`,
]);
assert.strictEqual(stderr, '');
assert.strictEqual(stdout, '');
assert.strictEqual(code, 13);
assert.strictEqual(signal, null);
});
it('should handle `initialize` returning rejecting promise', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--input-type=module',
'--eval',
`
import {register} from 'node:module';
register('data:text/javascript,export function initialize(){return Promise.reject()}');
`,
]);
assert.match(stderr, /undefined\r?\n/);
assert.strictEqual(stdout, '');
assert.strictEqual(code, 1);
assert.strictEqual(signal, null);
});
it('should handle `initialize` throwing null', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--input-type=module',
'--eval',
`
import {register} from 'node:module';
register('data:text/javascript,export function initialize(){throw null}');
`,
]);
assert.match(stderr, /null\r?\n/);
assert.strictEqual(stdout, '');
assert.strictEqual(code, 1);
assert.strictEqual(signal, null);
});
it('should be fine to call `process.exit` from a initialize hook', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--input-type=module',
'--eval',
`
import {register} from 'node:module';
register('data:text/javascript,export function initialize(){process.exit(42);}');
`,
]);
assert.strictEqual(stderr, '');
assert.strictEqual(stdout, '');
assert.strictEqual(code, 42);
assert.strictEqual(signal, null);
});
});
it('should use CJS loader to respond to require.resolve calls by default', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--experimental-loader',
fixtures.fileURL('es-module-loaders/loader-resolve-passthru.mjs'),
fixtures.path('require-resolve.js'),
]);
assert.strictEqual(stderr, '');
assert.strictEqual(stdout, 'resolve passthru\n');
assert.strictEqual(code, 0);
assert.strictEqual(signal, null);
});
it('should use ESM loader to respond to require.resolve calls when opting in', async () => {
const readFile = async () => {};
const fileURLToPath = () => {};
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--experimental-loader',
`data:text/javascript,import{readFile}from"node:fs/promises";import{fileURLToPath}from"node:url";export ${
async function load(u, c, n) {
const r = await n(u, c);
if (u.endsWith('/common/index.js')) {
r.source = '"use strict";module.exports=require("node:module").createRequire(' +
`${JSON.stringify(u)})(${JSON.stringify(fileURLToPath(u))});\n`;
} else if (c.format === 'commonjs') {
r.source = await readFile(new URL(u));
}
return r;
}}`,
'--experimental-loader',
fixtures.fileURL('es-module-loaders/loader-resolve-passthru.mjs'),
fixtures.path('require-resolve.js'),
]);
assert.strictEqual(stderr, '');
assert.strictEqual(stdout, 'resolve passthru\n'.repeat(10));
assert.strictEqual(code, 0);
assert.strictEqual(signal, null);
});
it('should support source maps in commonjs translator', async () => {
const readFile = async () => {};
const hook = `
import { readFile } from 'node:fs/promises';
export ${
async function load(url, context, nextLoad) {
const resolved = await nextLoad(url, context);
if (context.format === 'commonjs') {
resolved.source = await readFile(new URL(url));
}
return resolved;
}
}`;
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--enable-source-maps',
'--import',
`data:text/javascript,${encodeURIComponent(`
import{ register } from "node:module";
register(${
JSON.stringify('data:text/javascript,' + encodeURIComponent(hook))
});
`)}`,
fixtures.path('source-map/throw-on-require.js'),
]);
assert.strictEqual(stdout, '');
assert.match(stderr, /throw-on-require\.ts:9:9/);
assert.strictEqual(code, 1);
assert.strictEqual(signal, null);
});
it('should handle mixed of opt-in modules and non-opt-in ones', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--experimental-loader',
`data:text/javascript,const fixtures=${JSON.stringify(fixtures.path('empty.js'))};export ${
encodeURIComponent(function resolve(s, c, n) {
if (s.endsWith('entry-point')) {
return {
shortCircuit: true,
url: 'file:///c:/virtual-entry-point',
format: 'commonjs',
};
}
return n(s, c);
})
}export ${
encodeURIComponent(async function load(u, c, n) {
if (u === 'file:///c:/virtual-entry-point') {
return {
shortCircuit: true,
source: `"use strict";require(${JSON.stringify(fixtures)});console.log("Hello");`,
format: 'commonjs',
};
}
return n(u, c);
})}`,
'entry-point',
]);
assert.strictEqual(stderr, '');
assert.strictEqual(stdout, 'Hello\n');
assert.strictEqual(code, 0);
assert.strictEqual(signal, null);
});
});