-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
Copy pathnative-plugin.test.ts
680 lines (594 loc) · 22.7 KB
/
native-plugin.test.ts
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
import { BunFile, Loader, plugin } from "bun";
import { afterEach, beforeAll, beforeEach, describe, expect, it } from "bun:test";
import path, { dirname, join, resolve } from "path";
import source from "./native_plugin.cc" with { type: "file" };
import notAPlugin from "./not_native_plugin.cc" with { type: "file" };
import bundlerPluginHeader from "../../packages/bun-native-bundler-plugin-api/bundler_plugin.h" with { type: "file" };
import { bunEnv, bunExe, makeTree, tempDirWithFiles } from "harness";
import { itBundled } from "bundler/expectBundled";
import os from "os";
import fs from "fs";
describe("native-plugins", async () => {
const cwd = process.cwd();
let tempdir: string = "";
let outdir: string = "";
beforeAll(async () => {
const files = {
"bun-native-bundler-plugin-api/bundler_plugin.h": await Bun.file(bundlerPluginHeader).text(),
"plugin.cc": await Bun.file(source).text(),
"not_a_plugin.cc": await Bun.file(notAPlugin).text(),
"package.json": JSON.stringify({
"name": "fake-plugin",
"module": "index.ts",
"type": "module",
"devDependencies": {
"@types/bun": "latest",
},
"peerDependencies": {
"typescript": "^5.0.0",
},
"scripts": {
"build:napi": "node-gyp configure && node-gyp build",
},
"dependencies": {
"node-gyp": "10.2.0",
},
}),
"index.ts": /* ts */ `import values from "./stuff.ts";
import json from "./lmao.json";
const many_foo = ["foo","foo","foo","foo","foo","foo","foo"]
const many_bar = ["bar","bar","bar","bar","bar","bar","bar"]
const many_baz = ["baz","baz","baz","baz","baz","baz","baz"]
console.log(JSON.stringify(json));
values;`,
"stuff.ts": `export default { foo: "bar", baz: "baz" }`,
"lmao.json": ``,
"binding.gyp": /* gyp */ `{
"targets": [
{
"target_name": "xXx123_foo_counter_321xXx",
"sources": [ "plugin.cc" ],
"include_dirs": [ "." ]
},
{
"target_name": "not_a_plugin",
"sources": [ "not_a_plugin.cc" ],
"include_dirs": [ "." ]
}
]
}`,
};
tempdir = tempDirWithFiles("native-plugins", files);
await makeTree(tempdir, files);
outdir = path.join(tempdir, "dist");
console.log("tempdir", tempdir);
process.chdir(tempdir);
await Bun.$`${bunExe()} i && ${bunExe()} build:napi`.env(bunEnv).cwd(tempdir);
});
afterEach(async () => {
await Bun.$`rm -rf ${outdir}`;
process.chdir(cwd);
});
it("works in a basic case", async () => {
await Bun.$`${bunExe()} i && ${bunExe()} build:napi`.env(bunEnv).cwd(tempdir);
const napiModule = require(path.join(tempdir, "build/Release/xXx123_foo_counter_321xXx.node"));
const external = napiModule.createExternal();
const result = await Bun.build({
outdir,
entrypoints: [path.join(tempdir, "index.ts")],
plugins: [
{
name: "xXx123_foo_counter_321xXx",
setup(build) {
build.onBeforeParse({ filter: /\.ts/ }, { napiModule, symbol: "plugin_impl", external });
build.onLoad({ filter: /lmao\.json/ }, async ({ defer }) => {
await defer();
const count = napiModule.getFooCount(external);
return {
contents: JSON.stringify({ fooCount: count }),
loader: "json",
};
});
},
},
],
});
if (!result.success) console.log(result);
expect(result.success).toBeTrue();
const output = await Bun.$`${bunExe()} run dist/index.js`.cwd(tempdir).json();
expect(output).toStrictEqual({ fooCount: 9 });
const compilationCtxFreedCount = await napiModule.getCompilationCtxFreedCount(external);
expect(compilationCtxFreedCount).toBe(2);
});
it("doesn't explode when there are a lot of concurrent files", async () => {
// Generate 100 json files
const files: [filepath: string, var_name: string][] = await Promise.all(
Array.from({ length: 100 }, async (_, i) => {
await Bun.write(path.join(tempdir, "json_files", `lmao${i}.json`), `{}`);
return [`import json${i} from "./json_files/lmao${i}.json"`, `json${i}`];
}),
);
// Append the imports to index.ts
const prelude = /* ts */ `import values from "./stuff.ts"
const many_foo = ["foo","foo","foo","foo","foo","foo","foo"]
`;
await Bun.$`echo ${prelude} > index.ts`;
await Bun.$`echo ${files.map(([fp]) => fp).join("\n")} >> index.ts`;
await Bun.$`echo ${files.map(([, varname]) => `console.log(JSON.stringify(${varname}))`).join("\n")} >> index.ts`;
const napiModule = require(path.join(tempdir, "build/Release/xXx123_foo_counter_321xXx.node"));
const external = napiModule.createExternal();
const result = await Bun.build({
outdir,
entrypoints: [path.join(tempdir, "index.ts")],
plugins: [
{
name: "xXx123_foo_counter_321xXx",
setup(build) {
build.onBeforeParse({ filter: /\.ts/ }, { napiModule, symbol: "plugin_impl", external });
build.onLoad({ filter: /\.json/ }, async ({ defer, path }) => {
await defer();
const count = napiModule.getFooCount(external);
return {
contents: JSON.stringify({ fooCount: count }),
loader: "json",
};
});
},
},
],
});
if (!result.success) console.log(result);
console.log(result);
expect(result.success).toBeTrue();
const output = await Bun.$`${bunExe()} run dist/index.js`.cwd(tempdir).text();
const outputJsons = output
.trim()
.split("\n")
.map(s => JSON.parse(s));
for (const json of outputJsons) {
expect(json).toStrictEqual({ fooCount: 9 });
}
const compilationCtxFreedCount = await napiModule.getCompilationCtxFreedCount(external);
expect(compilationCtxFreedCount).toBe(2);
});
// We clone the RegExp object in the C++ code so this test ensures that there
// is no funny business regarding the filter regular expression and multiple
// threads
it("doesn't explode when there are a lot of concurrent files AND the filter regex is used on the JS thread", async () => {
const filter = /\.ts/;
// Generate 100 json files
const files: [filepath: string, var_name: string][] = await Promise.all(
Array.from({ length: 100 }, async (_, i) => {
await Bun.write(path.join(tempdir, "json_files", `lmao${i}.json`), `{}`);
return [`import json${i} from "./json_files/lmao${i}.json"`, `json${i}`];
}),
);
// Append the imports to index.ts
const prelude = /* ts */ `import values from "./stuff.ts"
const many_foo = ["foo","foo","foo","foo","foo","foo","foo"]
`;
await Bun.$`echo ${prelude} > index.ts`;
await Bun.$`echo ${files.map(([fp]) => fp).join("\n")} >> index.ts`;
await Bun.$`echo ${files.map(([, varname]) => `console.log(JSON.stringify(${varname}))`).join("\n")} >> index.ts`;
await Bun.$`echo '(() => values)();' >> index.ts`;
const napiModule = require(path.join(tempdir, "build/Release/xXx123_foo_counter_321xXx.node"));
const external = napiModule.createExternal();
const resultPromise = Bun.build({
outdir,
entrypoints: [path.join(tempdir, "index.ts")],
plugins: [
{
name: "xXx123_foo_counter_321xXx",
setup(build) {
build.onBeforeParse({ filter }, { napiModule, symbol: "plugin_impl", external });
build.onLoad({ filter: /\.json/ }, async ({ defer, path }) => {
await defer();
const count = napiModule.getFooCount(external);
return {
contents: JSON.stringify({ fooCount: count }),
loader: "json",
};
});
},
},
],
});
// Now saturate this thread with uses of the filter regex to test that nothing bad happens
// when the JS thread and the bundler thread use regexes concurrently
let dummy = 0;
for (let i = 0; i < 10000; i++) {
// Match the filter regex on some dummy string
dummy += filter.test("foo") ? 1 : 0;
}
const result = await resultPromise;
if (!result.success) console.log(result);
expect(result.success).toBeTrue();
const output = await Bun.$`${bunExe()} run dist/index.js`.cwd(tempdir).text();
const outputJsons = output
.trim()
.split("\n")
.map(s => JSON.parse(s));
for (const json of outputJsons) {
expect(json).toStrictEqual({ fooCount: 9 });
}
const compilationCtxFreedCount = await napiModule.getCompilationCtxFreedCount(external);
expect(compilationCtxFreedCount).toBe(2);
});
it("doesn't explode when passing invalid external", async () => {
const filter = /\.ts/;
// Generate 100 json files
const files: [filepath: string, var_name: string][] = await Promise.all(
Array.from({ length: 100 }, async (_, i) => {
await Bun.write(path.join(tempdir, "json_files", `lmao${i}.json`), `{}`);
return [`import json${i} from "./json_files/lmao${i}.json"`, `json${i}`];
}),
);
// Append the imports to index.ts
const prelude = /* ts */ `import values from "./stuff.ts"
const many_foo = ["foo","foo","foo","foo","foo","foo","foo"]
`;
await Bun.$`echo ${prelude} > index.ts`;
await Bun.$`echo ${files.map(([fp]) => fp).join("\n")} >> index.ts`;
await Bun.$`echo ${files.map(([, varname]) => `console.log(JSON.stringify(${varname}))`).join("\n")} >> index.ts`;
const result = await Bun.build({
outdir,
entrypoints: [path.join(tempdir, "index.ts")],
plugins: [
{
name: "xXx123_foo_counter_321xXx",
setup(build) {
const napiModule = require(path.join(tempdir, "build/Release/xXx123_foo_counter_321xXx.node"));
const external = undefined;
build.onBeforeParse({ filter }, { napiModule, symbol: "plugin_impl", external });
build.onLoad({ filter: /\.json/ }, async ({ defer, path }) => {
await defer();
let count = 0;
try {
count = napiModule.getFooCount(external);
} catch (e) {}
return {
contents: JSON.stringify({ fooCount: count }),
loader: "json",
};
});
},
},
],
throw: true,
});
const output = await Bun.$`${bunExe()} run dist/index.js`.cwd(tempdir).text();
const outputJsons = output
.trim()
.split("\n")
.map(s => JSON.parse(s));
for (const json of outputJsons) {
expect(json).toStrictEqual({ fooCount: 0 });
}
});
it("works when logging an error", async () => {
const filter = /\.ts/;
const prelude = /* ts */ `import values from "./stuff.ts"
const many_foo = ["foo","foo","foo","foo","foo","foo","foo"]
`;
await Bun.$`echo ${prelude} > index.ts`;
const napiModule = require(path.join(tempdir, "build/Release/xXx123_foo_counter_321xXx.node"));
const external = napiModule.createExternal();
const resultPromise = Bun.build({
outdir,
entrypoints: [path.join(tempdir, "index.ts")],
plugins: [
{
name: "xXx123_foo_counter_321xXx",
setup(build) {
napiModule.setThrowsErrors(external, true);
build.onBeforeParse({ filter }, { napiModule, symbol: "plugin_impl", external });
build.onLoad({ filter: /\.json/ }, async ({ defer, path }) => {
await defer();
let count = 0;
try {
count = napiModule.getFooCount(external);
} catch (e) {}
return {
contents: JSON.stringify({ fooCount: count }),
loader: "json",
};
});
},
},
],
});
const result = await resultPromise;
if (result.success) console.log(result);
expect(result.success).toBeFalse();
const log = result.logs[0];
expect(log.message).toContain("Throwing an error");
expect(log.level).toBe("error");
const compilationCtxFreedCount = await napiModule.getCompilationCtxFreedCount(external);
expect(compilationCtxFreedCount).toBe(0);
});
it("works with versioning", async () => {
const filter = /\.ts/;
const prelude = /* ts */ `import values from "./stuff.ts"
const many_foo = ["foo","foo","foo","foo","foo","foo","foo"]
`;
await Bun.$`echo ${prelude} > index.ts`;
const napiModule = require(path.join(tempdir, "build/Release/xXx123_foo_counter_321xXx.node"));
const external = napiModule.createExternal();
const resultPromise = Bun.build({
outdir,
entrypoints: [path.join(tempdir, "index.ts")],
plugins: [
{
name: "xXx123_foo_counter_321xXx",
setup(build) {
build.onBeforeParse({ filter }, { napiModule, symbol: "incompatible_version_plugin_impl", external });
build.onLoad({ filter: /\.json/ }, async ({ defer, path }) => {
await defer();
let count = 0;
try {
count = napiModule.getFooCount(external);
} catch (e) {}
return {
contents: JSON.stringify({ fooCount: count }),
loader: "json",
};
});
},
},
],
});
const result = await resultPromise;
if (result.success) console.log(result);
expect(result.success).toBeFalse();
const log = result.logs[0];
expect(log.message).toContain("This plugin is built for a newer version of Bun than the one currently running.");
expect(log.level).toBe("error");
const compilationCtxFreedCount = await napiModule.getCompilationCtxFreedCount(external);
expect(compilationCtxFreedCount).toBe(0);
});
// don't know how to reliably test this on windows
it.skipIf(process.platform === "win32")("prints name when plugin crashes", async () => {
const prelude = /* ts */ `import values from "./stuff.ts"
const many_foo = ["foo","foo","foo","foo","foo","foo","foo"]
`;
await Bun.$`echo ${prelude} > index.ts`;
const build_code = /* ts */ `
import * as path from "path";
const tempdir = process.env.BUN_TEST_TEMP_DIR;
const filter = /\.ts/;
const resultPromise = await Bun.build({
outdir: "dist",
entrypoints: [path.join(tempdir, "index.ts")],
plugins: [
{
name: "xXx123_foo_counter_321xXx",
setup(build) {
const napiModule = require(path.join(tempdir, "build/Release/xXx123_foo_counter_321xXx.node"));
const external = napiModule.createExternal();
napiModule.setWillCrash(external, true);
build.onBeforeParse({ filter }, { napiModule, symbol: "plugin_impl", external });
build.onLoad({ filter: /\.json/ }, async ({ defer, path }) => {
await defer();
let count = 0;
try {
count = napiModule.getFooCount(external);
} catch (e) {}
return {
contents: JSON.stringify({ fooCount: count }),
loader: "json",
};
});
},
},
],
});
console.log(resultPromise);
`;
await Bun.$`echo ${build_code} > build.ts`;
const { stdout, stderr } = await Bun.$`BUN_TEST_TEMP_DIR=${tempdir} ${bunExe()} run build.ts`.throws(false);
const errorString = stderr.toString();
expect(errorString).toContain('\x1b[31m\x1b[2m"native_plugin_test"\x1b[0m');
});
it("detects when plugin sets function pointer but does not user context pointer", async () => {
const filter = /\.ts/;
const prelude = /* ts */ `import values from "./stuff.ts"
const many_foo = ["foo","foo","foo","foo","foo","foo","foo"]
`;
await Bun.$`echo ${prelude} > index.ts`;
const napiModule = require(path.join(tempdir, "build/Release/xXx123_foo_counter_321xXx.node"));
const external = napiModule.createExternal();
const resultPromise = Bun.build({
outdir,
entrypoints: [path.join(tempdir, "index.ts")],
plugins: [
{
name: "xXx123_foo_counter_321xXx",
setup(build) {
build.onBeforeParse({ filter }, { napiModule, symbol: "plugin_impl_bad_free_function_pointer", external });
build.onLoad({ filter: /\.json/ }, async ({ defer, path }) => {
await defer();
let count = 0;
try {
count = napiModule.getFooCount(external);
} catch (e) {}
return {
contents: JSON.stringify({ fooCount: count }),
loader: "json",
};
});
},
},
],
});
const result = await resultPromise;
if (result.success) console.log(result);
expect(result.success).toBeFalse();
const log = result.logs[0];
expect(log.message).toContain(
"Native plugin set the `free_plugin_source_code_context` field without setting the `plugin_source_code_context` field.",
);
expect(log.level).toBe("error");
const compilationCtxFreedCount = await napiModule.getCompilationCtxFreedCount(external);
expect(compilationCtxFreedCount).toBe(0);
});
it("should fail gracefully when passing something that is NOT a bunler plugin", async () => {
const not_plugins = [require(path.join(tempdir, "build/Release/not_a_plugin.node")), 420, "hi", {}];
for (const napiModule of not_plugins) {
try {
await Bun.build({
outdir,
entrypoints: [path.join(tempdir, "index.ts")],
plugins: [
{
name: "not_a_plugin",
setup(build) {
build.onBeforeParse({ filter: /\.ts/ }, { napiModule, symbol: "plugin_impl" });
},
},
],
});
expect.unreachable();
} catch (e) {
expect(e.toString()).toContain(
"onBeforeParse `napiModule` must be a Napi module which exports the `BUN_PLUGIN_NAME` symbol.",
);
}
}
});
it("should fail gracefully when can't find the symbol", async () => {
const napiModule = require(path.join(tempdir, "build/Release/xXx123_foo_counter_321xXx.node"));
try {
await Bun.build({
outdir,
entrypoints: [path.join(tempdir, "index.ts")],
plugins: [
{
name: "not_a_plugin",
setup(build) {
build.onBeforeParse({ filter: /\.ts/ }, { napiModule, symbol: "OOGA_BOOGA_420" });
},
},
],
});
expect.unreachable();
} catch (e) {
expect(e.toString()).toContain('TypeError: Could not find the symbol "OOGA_BOOGA_420" in the given napi module.');
}
});
it("should use result of the first plugin that runs and doesn't execute the others", async () => {
const filter = /\.ts/;
const prelude = /* ts */ `import values from "./stuff.ts"
import json from "./lmao.json";
const many_foo = ["foo","foo","foo","foo","foo","foo","foo"]
const many_bar = ["bar","bar","bar","bar","bar","bar","bar"]
const many_baz = ["baz","baz","baz","baz","baz","baz","baz"]
console.log(JSON.stringify(json))
`;
await Bun.$`echo ${prelude} > index.ts`;
const napiModule = require(path.join(tempdir, "build/Release/xXx123_foo_counter_321xXx.node"));
const external = napiModule.createExternal();
const resultPromise = Bun.build({
outdir,
entrypoints: [path.join(tempdir, "index.ts")],
plugins: [
{
name: "xXx123_foo_counter_321xXx",
setup(build) {
build.onBeforeParse({ filter }, { napiModule, symbol: "plugin_impl", external });
build.onBeforeParse({ filter }, { napiModule, symbol: "plugin_impl_bar", external });
build.onBeforeParse({ filter }, { napiModule, symbol: "plugin_impl_baz", external });
build.onLoad({ filter: /\.json/ }, async ({ defer, path }) => {
await defer();
let fooCount = 0;
let barCount = 0;
let bazCount = 0;
try {
fooCount = napiModule.getFooCount(external);
barCount = napiModule.getBarCount(external);
bazCount = napiModule.getBazCount(external);
} catch (e) {}
return {
contents: JSON.stringify({ fooCount, barCount, bazCount }),
loader: "json",
};
});
},
},
],
});
const result = await resultPromise;
if (result.success) console.log(result);
expect(result.success).toBeTrue();
const output = await Bun.$`${bunExe()} run dist/index.js`.cwd(tempdir).json();
expect(output).toStrictEqual({ fooCount: 9, barCount: 0, bazCount: 0 });
const compilationCtxFreedCount = await napiModule.getCompilationCtxFreedCount(external);
expect(compilationCtxFreedCount).toBe(2);
});
type AdditionalFile = {
name: string;
contents: BunFile | string;
loader: Loader;
};
const additional_files: AdditionalFile[] = [
{
name: "bun.png",
contents: await Bun.file(path.join(import.meta.dir, "../integration/sharp/bun.png")),
loader: "file",
},
{
name: "index.js",
contents: /* ts */ `console.log('HELLO FRIENDS')`,
loader: "js",
},
{
name: "index.ts",
contents: /* ts */ `console.log('HELLO FRIENDS')`,
loader: "ts",
},
{
name: "lmao.jsx",
contents: /* ts */ `console.log('HELLO FRIENDS')`,
loader: "jsx",
},
{
name: "lmao.tsx",
contents: /* ts */ `console.log('HELLO FRIENDS')`,
loader: "tsx",
},
{
name: "lmao.toml",
contents: /* toml */ `foo = "bar"`,
loader: "toml",
},
{
name: "lmao.text",
contents: "HELLO FRIENDS",
loader: "text",
},
];
for (const { name, contents, loader } of additional_files) {
it(`works with ${loader} loader`, async () => {
await Bun.$`echo ${contents} > ${name}`;
const source = /* ts */ `import foo from "./${name}";
console.log(foo);`;
await Bun.$`echo ${source} > index.ts`;
const result = await Bun.build({
outdir,
entrypoints: [path.join(tempdir, "index.ts")],
plugins: [
{
name: "test",
setup(build) {
const ext = name.split(".").pop()!;
const napiModule = require(path.join(tempdir, "build/Release/xXx123_foo_counter_321xXx.node"));
// Construct regexp to match the file extension
const filter = new RegExp(`\\.${ext}$`);
build.onBeforeParse({ filter }, { napiModule, symbol: "plugin_impl" });
},
},
],
});
expect(result.success).toBeTrue();
});
}
});