MCPcopy Create free account
hub / github.com/Sandpack/nodebox-runtime / setup

Function setup

internals/esbuild-plugins/inline-worker.ts:31–84  ·  view source on GitHub ↗
(build)

Source from the content-addressed store, hash-verified

29 return {
30 name: 'esbuild-worker-threads-plugin',
31 setup(build) {
32 // Links worker-content: calls to this namespace
33 build.onResolve({ filter }, (args) => {
34 const realPath = args.path.replace(filter, '');
35 return {
36 path: path.resolve(args.resolveDir, realPath),
37 namespace,
38 };
39 });
40
41 // Handles `worker-content:` values to bundle them and replace with new link
42 build.onLoad({ filter: /.*/, namespace }, async (args) => {
43 // console.log(args);
44 let workerPath = existingBundles.get(args.path);
45 if (!workerPath) {
46 const result = await bundle(args.path);
47 workerPath = await writeWorker(outDir, result);
48 existingBundles.set(args.path, workerPath);
49 }
50 return {
51 contents: workerPath,
52 loader: 'text',
53 };
54 });
55
56 // Gets called when loading files, extracts worker constructors and replaces them with worker-content:...
57 // to be handled by other onLoad
58 build.onLoad({ filter: /.*\.(js|ts|mjs|cjs)/ }, async (args) => {
59 const content = await fs.readFile(args.path, 'utf8');
60 if (WORKER_RE.test(content)) {
61 if (existingReplaces.has(args.path)) {
62 return {
63 contents: content,
64 loader: args.path.endsWith('.ts') ? 'ts' : 'js',
65 };
66 }
67 const result = content.replace(WORKER_RE, (...params) => {
68 const replacement = /StatefulWorker/.test(params[0])
69 ? `StatefulWorker(require("worker-content:${params[1]}"), { eval: true })`
70 : `new Worker(require("worker-content:${params[1]}"), { eval: true })`;
71
72 console.log(`Replacing: "${params[0]}" with "${replacement}"`);
73
74 return replacement;
75 });
76 existingReplaces.set(args.path, result);
77 // console.log(`Rewrote worker constructor for ${path.relative(process.cwd(), args.path)}`);
78 return {
79 contents: result,
80 loader: args.path.endsWith('.ts') ? 'ts' : 'js',
81 };
82 }
83 });
84 },
85 };
86}

Callers

nothing calls this directly

Calls 2

writeWorkerFunction · 0.85
readFileMethod · 0.80

Tested by

no test coverage detected