rspack-plugin-cloudflare 0.0.0-stage → 0.1.0
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.
- package/LICENSE +21 -0
- package/README.md +128 -2
- package/dist/assets.d.ts +31 -0
- package/dist/assets.js +112 -0
- package/dist/assets.js.map +1 -0
- package/dist/build.d.ts +216 -0
- package/dist/build.js +140 -0
- package/dist/build.js.map +1 -0
- package/dist/config.d.ts +19 -0
- package/dist/config.js +103 -0
- package/dist/config.js.map +1 -0
- package/dist/containers.d.ts +30 -0
- package/dist/containers.js +167 -0
- package/dist/containers.js.map +1 -0
- package/dist/dev-entry.d.ts +11 -0
- package/dist/dev-entry.js +44 -0
- package/dist/dev-entry.js.map +1 -0
- package/dist/dev-worker.d.ts +73 -0
- package/dist/dev-worker.js +247 -0
- package/dist/dev-worker.js.map +1 -0
- package/dist/dev.d.ts +28 -0
- package/dist/dev.js +422 -0
- package/dist/dev.js.map +1 -0
- package/dist/http.d.ts +23 -0
- package/dist/http.js +89 -0
- package/dist/http.js.map +1 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +139 -0
- package/dist/index.js.map +1 -0
- package/dist/inspector.d.ts +5 -0
- package/dist/inspector.js +41 -0
- package/dist/inspector.js.map +1 -0
- package/dist/miniflare.d.ts +1 -0
- package/dist/miniflare.js +6 -0
- package/dist/miniflare.js.map +1 -0
- package/dist/module-rules.d.ts +4 -0
- package/dist/module-rules.js +29 -0
- package/dist/module-rules.js.map +1 -0
- package/dist/nodejs-compat.d.ts +14 -0
- package/dist/nodejs-compat.js +46 -0
- package/dist/nodejs-compat.js.map +1 -0
- package/dist/options.d.ts +45 -0
- package/dist/options.js +2 -0
- package/dist/options.js.map +1 -0
- package/dist/routing.d.ts +12 -0
- package/dist/routing.js +40 -0
- package/dist/routing.js.map +1 -0
- package/dist/tunnel.d.ts +15 -0
- package/dist/tunnel.js +94 -0
- package/dist/tunnel.js.map +1 -0
- package/dist/worker-config.d.ts +42 -0
- package/dist/worker-config.js +194 -0
- package/dist/worker-config.js.map +1 -0
- package/package.json +91 -5
- package/runtime/dev-runtime.js +265 -0
- package/src/assets.ts +148 -0
- package/src/build.ts +153 -0
- package/src/config.ts +138 -0
- package/src/containers.ts +183 -0
- package/src/dev-entry.ts +50 -0
- package/src/dev-worker.ts +297 -0
- package/src/dev.ts +478 -0
- package/src/http.ts +102 -0
- package/src/index.ts +164 -0
- package/src/inspector.ts +44 -0
- package/src/miniflare.ts +7 -0
- package/src/module-rules.ts +36 -0
- package/src/nodejs-compat.ts +63 -0
- package/src/options.ts +46 -0
- package/src/routing.ts +48 -0
- package/src/tunnel.ts +106 -0
- package/src/worker-config.ts +237 -0
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import { isBuiltin } from 'node:module';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
|
|
6
|
+
import { getModuleTypes } from './module-rules.js';
|
|
7
|
+
import { getNodeJsCompat } from './nodejs-compat.js';
|
|
8
|
+
|
|
9
|
+
import type { ResolvedWorker } from './config.js';
|
|
10
|
+
import type { ModuleType } from './module-rules.js';
|
|
11
|
+
import type { NodeJsCompat } from './nodejs-compat.js';
|
|
12
|
+
import type { CloudflarePluginOptions } from './options.js';
|
|
13
|
+
import type { Compiler, RspackOptions, RspackPluginInstance } from '@rspack/core';
|
|
14
|
+
|
|
15
|
+
/** The rspack plugin that holds generated modules, which dev rewrites when the Worker's exports change. */
|
|
16
|
+
export type VirtualModules = InstanceType<Compiler['rspack']['experiments']['VirtualModulesPlugin']>;
|
|
17
|
+
|
|
18
|
+
const PLUGIN_NAME = 'rspack-plugin-cloudflare';
|
|
19
|
+
const TYPESCRIPT_RE = /\.[cm]?tsx?$/;
|
|
20
|
+
// the static asset types Vite also imports as URLs; .txt stays a Text module, as wrangler treats it
|
|
21
|
+
const ASSET_RE = /\.(?:apng|avif|bmp|cur|eot|flac|gif|ico|jfif|jpe?g|jxl|m4a|mov|mp3|mp4|ogg|opus|otf|pdf|pjp|pjpeg|png|svg|ttf|vtt|wav|webm|webmanifest|webp|woff2?|aac)$/i;
|
|
22
|
+
// `?url` imports any file as a URL, like Vite
|
|
23
|
+
const URL_QUERY_RE = /\?(?:[^#]*&)?url(?:[&=#]|$)/;
|
|
24
|
+
|
|
25
|
+
/** Output subdirectory for assets Worker code imports, laid out the way the assets directory serves them. */
|
|
26
|
+
export const IMPORTED_ASSETS_DIR = 'imported-assets';
|
|
27
|
+
|
|
28
|
+
interface AdditionalModule {
|
|
29
|
+
/** File name in the output directory, which is also how the bundle imports it. */
|
|
30
|
+
fileName: string;
|
|
31
|
+
type: 'CompiledWasm' | 'Data';
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Copies imported `.wasm`/`.bin` files next to the bundle, where workerd loads them as their own modules. */
|
|
35
|
+
export class AdditionalModulesPlugin implements RspackPluginInstance {
|
|
36
|
+
readonly #files = new Map<string, { sourcePath: string; type: AdditionalModule['type']; }>();
|
|
37
|
+
|
|
38
|
+
/** Every file emitted so far; dev passes these to Miniflare, since rspack's incremental asset list can leave them out. */
|
|
39
|
+
get modules(): AdditionalModule[] {
|
|
40
|
+
return [...this.#files].map(([fileName, { type }]) => {
|
|
41
|
+
return { fileName, type };
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Records a file to emit and returns the specifier the bundle should import it by. */
|
|
46
|
+
add(sourcePath: string, type: AdditionalModule['type']) {
|
|
47
|
+
const hash = createHash('sha1').update(fs.readFileSync(sourcePath)).digest('hex')
|
|
48
|
+
.slice(0, 16);
|
|
49
|
+
const fileName = `${hash}-${path.basename(sourcePath)}`;
|
|
50
|
+
this.#files.set(fileName, { sourcePath, type });
|
|
51
|
+
return `./${fileName}`;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
apply(compiler: Compiler) {
|
|
55
|
+
const { Compilation, sources } = compiler.rspack;
|
|
56
|
+
compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
|
|
57
|
+
compilation.hooks.processAssets.tap({ name: PLUGIN_NAME, stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL }, () => {
|
|
58
|
+
for (const [fileName, { sourcePath }] of this.#files) {
|
|
59
|
+
compilation.emitAsset(fileName, new sources.RawSource(fs.readFileSync(sourcePath)));
|
|
60
|
+
compilation.fileDependencies.add(sourcePath);
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function createExternals(nodeJsCompat: NodeJsCompat | undefined, moduleTypes: Map<string, ModuleType>, additionalModules: AdditionalModulesPlugin) {
|
|
68
|
+
type ExternalsCallback = (error?: Error, result?: string) => void;
|
|
69
|
+
return ({ request, context }: { request?: string; context?: string; }, callback: ExternalsCallback) => {
|
|
70
|
+
if (!request) {
|
|
71
|
+
callback();
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
if (request.startsWith('cloudflare:')) {
|
|
75
|
+
callback(undefined, request);
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
if (nodeJsCompat) {
|
|
79
|
+
const native = nodeJsCompat.externals.get(request);
|
|
80
|
+
if (native) {
|
|
81
|
+
callback(undefined, native);
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
// a builtin the preset doesn't know about yet; workerd only resolves the node: form
|
|
85
|
+
if (isBuiltin(request) && !nodeJsCompat.polyfills.has(request)) {
|
|
86
|
+
callback(undefined, request.startsWith('node:') ? request : `node:${request}`);
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
const filePath = request.replace(/\?.*$/, '');
|
|
91
|
+
const type = moduleTypes.get(path.extname(filePath));
|
|
92
|
+
const isModule = type === 'CompiledWasm' || type === 'Data';
|
|
93
|
+
if (isModule && !URL_QUERY_RE.test(request) && context && (filePath.startsWith('.') || path.isAbsolute(filePath))) {
|
|
94
|
+
callback(undefined, additionalModules.add(path.resolve(context, filePath), type));
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
callback();
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Text modules inline as strings; with an assets directory, static files and `?url` imports become URLs served from it. */
|
|
102
|
+
function getAssetRules(worker: ResolvedWorker, textExtensions: Set<string>) {
|
|
103
|
+
const textRule = { test: (file: string) => textExtensions.has(path.extname(file)), type: 'asset/source' };
|
|
104
|
+
if (!worker.assets) {
|
|
105
|
+
return [textRule];
|
|
106
|
+
}
|
|
107
|
+
const generator = {
|
|
108
|
+
filename: 'assets/[name].[contenthash:8][ext]',
|
|
109
|
+
outputPath: IMPORTED_ASSETS_DIR,
|
|
110
|
+
// served from the root of the assets directory, not the Worker's own public path
|
|
111
|
+
publicPath: '/',
|
|
112
|
+
};
|
|
113
|
+
return [
|
|
114
|
+
{ resourceQuery: URL_QUERY_RE, type: 'asset/resource', generator },
|
|
115
|
+
textRule,
|
|
116
|
+
{ test: ASSET_RE, type: 'asset/resource', generator },
|
|
117
|
+
];
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Builds the rspack config for the Worker bundle: a single ESM file workerd can load as-is. */
|
|
121
|
+
export function createWorkerConfig(options: {
|
|
122
|
+
compiler: Compiler;
|
|
123
|
+
worker: ResolvedWorker;
|
|
124
|
+
pluginOptions: CloudflarePluginOptions;
|
|
125
|
+
outputDir: string;
|
|
126
|
+
/** The module to bundle. */
|
|
127
|
+
entry: string;
|
|
128
|
+
/** Source for `entry` when it isn't a real file, like dev's wrapper around `main`. */
|
|
129
|
+
entrySource?: string;
|
|
130
|
+
mode: 'development' | 'production';
|
|
131
|
+
/** Builds in rspack's HMR runtime so dev can update the running Worker in place. */
|
|
132
|
+
hot?: boolean;
|
|
133
|
+
/** Where HMR imports update chunks from; workerd has no import.meta.url to derive it from. */
|
|
134
|
+
publicPath?: string;
|
|
135
|
+
}): { config: RspackOptions; virtualModules: VirtualModules; additionalModules: AdditionalModulesPlugin; } {
|
|
136
|
+
const { compiler, worker, pluginOptions, outputDir, entry, entrySource, mode, hot = false, publicPath = '/' } = options;
|
|
137
|
+
const { rspack } = compiler;
|
|
138
|
+
const moduleTypes = getModuleTypes(worker);
|
|
139
|
+
const textExtensions = new Set([...moduleTypes].filter(([, type]) => type === 'Text').map(([extension]) => extension));
|
|
140
|
+
const additionalModules = new AdditionalModulesPlugin();
|
|
141
|
+
const nodeJsCompat = getNodeJsCompat(worker);
|
|
142
|
+
|
|
143
|
+
const virtualModules: Record<string, string> = {};
|
|
144
|
+
const entries = [entry];
|
|
145
|
+
if (entrySource !== undefined) {
|
|
146
|
+
virtualModules[entry] = entrySource;
|
|
147
|
+
}
|
|
148
|
+
if (nodeJsCompat?.injectSource) {
|
|
149
|
+
// runs before the Worker so injected globals like `process` exist while its modules evaluate
|
|
150
|
+
const injectPath = path.join(worker.rootDir, '.wrangler', 'tmp', `rspack-${worker.name}`, 'nodejs-compat-inject.js');
|
|
151
|
+
virtualModules[injectPath] = nodeJsCompat.injectSource;
|
|
152
|
+
entries.unshift(injectPath);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const plugins: RspackPluginInstance[] = [
|
|
156
|
+
new rspack.DefinePlugin(worker.config.define),
|
|
157
|
+
// workerd loads a single module here, so keep dynamic imports in the entry chunk
|
|
158
|
+
new rspack.optimize.LimitChunkCountPlugin({ maxChunks: 1 }),
|
|
159
|
+
additionalModules,
|
|
160
|
+
];
|
|
161
|
+
const polyfills = nodeJsCompat?.polyfills;
|
|
162
|
+
if (polyfills && polyfills.size > 0) {
|
|
163
|
+
// rspack reads `node:` specifiers as a URL scheme that resolve.alias never sees, so swap polyfills in before resolving
|
|
164
|
+
plugins.push(new rspack.NormalModuleReplacementPlugin(/^(?:node:)?[a-z_]/, (resource: { request: string; }) => {
|
|
165
|
+
const polyfill = polyfills.get(resource.request);
|
|
166
|
+
if (polyfill) {
|
|
167
|
+
resource.request = polyfill;
|
|
168
|
+
}
|
|
169
|
+
}));
|
|
170
|
+
}
|
|
171
|
+
const virtualModulesPlugin = new rspack.experiments.VirtualModulesPlugin(virtualModules);
|
|
172
|
+
plugins.push(virtualModulesPlugin);
|
|
173
|
+
if (hot) {
|
|
174
|
+
plugins.push(new rspack.HotModuleReplacementPlugin());
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
let config: RspackOptions = {
|
|
178
|
+
name: `cloudflare:${worker.name}`,
|
|
179
|
+
mode,
|
|
180
|
+
context: worker.rootDir,
|
|
181
|
+
target: ['webworker', 'es2024'],
|
|
182
|
+
entry: { index: entries },
|
|
183
|
+
output: {
|
|
184
|
+
path: outputDir,
|
|
185
|
+
filename: 'index.js',
|
|
186
|
+
module: true,
|
|
187
|
+
chunkFormat: 'module',
|
|
188
|
+
library: { type: 'module' },
|
|
189
|
+
clean: true,
|
|
190
|
+
publicPath,
|
|
191
|
+
},
|
|
192
|
+
externalsType: 'module-import',
|
|
193
|
+
externals: [createExternals(nodeJsCompat, moduleTypes, additionalModules)],
|
|
194
|
+
resolve: {
|
|
195
|
+
extensions: ['.ts', '.tsx', '.mts', '.cts', '.js', '.mjs', '.cjs', '.json'],
|
|
196
|
+
extensionAlias: { '.js': ['.ts', '.tsx', '.js'], '.mjs': ['.mts', '.mjs'] },
|
|
197
|
+
conditionNames: ['workerd', 'worker', 'browser', 'module', 'import', 'default'],
|
|
198
|
+
alias: worker.config.alias,
|
|
199
|
+
},
|
|
200
|
+
module: {
|
|
201
|
+
rules: [
|
|
202
|
+
{
|
|
203
|
+
test: TYPESCRIPT_RE,
|
|
204
|
+
loader: 'builtin:swc-loader',
|
|
205
|
+
options: {
|
|
206
|
+
jsc: {
|
|
207
|
+
parser: { syntax: 'typescript', tsx: true, decorators: true },
|
|
208
|
+
target: 'es2024',
|
|
209
|
+
},
|
|
210
|
+
},
|
|
211
|
+
type: 'javascript/auto',
|
|
212
|
+
},
|
|
213
|
+
{ oneOf: getAssetRules(worker, textExtensions) },
|
|
214
|
+
],
|
|
215
|
+
},
|
|
216
|
+
devtool: 'source-map',
|
|
217
|
+
optimization: {
|
|
218
|
+
// wrangler doesn't minify by default either, and readable stack traces matter more on the server
|
|
219
|
+
minimize: false,
|
|
220
|
+
// a failed dev build must leave the last good bundle in place, since restarting another Worker reloads it from disk
|
|
221
|
+
emitOnErrors: false,
|
|
222
|
+
},
|
|
223
|
+
plugins,
|
|
224
|
+
performance: { hints: false },
|
|
225
|
+
watchOptions: {
|
|
226
|
+
// dev's generated entry is virtual and the bundle is written under .wrangler, so the watcher would see both as changes
|
|
227
|
+
ignored: /[/\\](?:\.git|node_modules|\.wrangler)[/\\]/,
|
|
228
|
+
},
|
|
229
|
+
stats: 'errors-warnings',
|
|
230
|
+
infrastructureLogging: compiler.options.infrastructureLogging,
|
|
231
|
+
};
|
|
232
|
+
|
|
233
|
+
if (pluginOptions.worker) {
|
|
234
|
+
config = pluginOptions.worker(config, { name: worker.name }) ?? config;
|
|
235
|
+
}
|
|
236
|
+
return { config, virtualModules: virtualModulesPlugin, additionalModules };
|
|
237
|
+
}
|