rspack-plugin-cloudflare 0.1.0 → 0.2.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/README.md +8 -5
- package/THIRD_PARTY_NOTICES.txt +139 -0
- package/dist/index.d.ts +51 -7
- package/dist/index.js +3591 -131
- package/dist/index.js.map +1 -1
- package/dist/workers/asset-worker/index.js +5783 -0
- package/dist/workers/asset-worker/index.js.map +1 -0
- package/dist/workers/router-worker/index.js +6245 -0
- package/dist/workers/router-worker/index.js.map +1 -0
- package/package.json +13 -11
- package/dist/assets.d.ts +0 -31
- package/dist/assets.js +0 -112
- package/dist/assets.js.map +0 -1
- package/dist/build.d.ts +0 -216
- package/dist/build.js +0 -140
- package/dist/build.js.map +0 -1
- package/dist/config.d.ts +0 -19
- package/dist/config.js +0 -103
- package/dist/config.js.map +0 -1
- package/dist/containers.d.ts +0 -30
- package/dist/containers.js +0 -167
- package/dist/containers.js.map +0 -1
- package/dist/dev-entry.d.ts +0 -11
- package/dist/dev-entry.js +0 -44
- package/dist/dev-entry.js.map +0 -1
- package/dist/dev-worker.d.ts +0 -73
- package/dist/dev-worker.js +0 -247
- package/dist/dev-worker.js.map +0 -1
- package/dist/dev.d.ts +0 -28
- package/dist/dev.js +0 -422
- package/dist/dev.js.map +0 -1
- package/dist/http.d.ts +0 -23
- package/dist/http.js +0 -89
- package/dist/http.js.map +0 -1
- package/dist/inspector.d.ts +0 -5
- package/dist/inspector.js +0 -41
- package/dist/inspector.js.map +0 -1
- package/dist/miniflare.d.ts +0 -1
- package/dist/miniflare.js +0 -6
- package/dist/miniflare.js.map +0 -1
- package/dist/module-rules.d.ts +0 -4
- package/dist/module-rules.js +0 -29
- package/dist/module-rules.js.map +0 -1
- package/dist/nodejs-compat.d.ts +0 -14
- package/dist/nodejs-compat.js +0 -46
- package/dist/nodejs-compat.js.map +0 -1
- package/dist/options.d.ts +0 -45
- package/dist/options.js +0 -2
- package/dist/options.js.map +0 -1
- package/dist/routing.d.ts +0 -12
- package/dist/routing.js +0 -40
- package/dist/routing.js.map +0 -1
- package/dist/tunnel.d.ts +0 -15
- package/dist/tunnel.js +0 -94
- package/dist/tunnel.js.map +0 -1
- package/dist/worker-config.d.ts +0 -42
- package/dist/worker-config.js +0 -194
- package/dist/worker-config.js.map +0 -1
- package/src/assets.ts +0 -148
- package/src/build.ts +0 -153
- package/src/config.ts +0 -138
- package/src/containers.ts +0 -183
- package/src/dev-entry.ts +0 -50
- package/src/dev-worker.ts +0 -297
- package/src/dev.ts +0 -478
- package/src/http.ts +0 -102
- package/src/index.ts +0 -164
- package/src/inspector.ts +0 -44
- package/src/miniflare.ts +0 -7
- package/src/module-rules.ts +0 -36
- package/src/nodejs-compat.ts +0 -63
- package/src/options.ts +0 -46
- package/src/routing.ts +0 -48
- package/src/tunnel.ts +0 -106
- package/src/worker-config.ts +0 -237
package/src/assets.ts
DELETED
|
@@ -1,148 +0,0 @@
|
|
|
1
|
-
import fs from 'node:fs';
|
|
2
|
-
import path from 'node:path';
|
|
3
|
-
|
|
4
|
-
import { lookup } from 'mrmime';
|
|
5
|
-
|
|
6
|
-
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
7
|
-
|
|
8
|
-
/** The slice of rspack's output filesystem we read from; the dev server swaps in an in-memory one. */
|
|
9
|
-
export interface ReadableFileSystem {
|
|
10
|
-
readFile: (filePath: string, callback: (error: NodeJS.ErrnoException | null, data?: Buffer | string) => void) => void;
|
|
11
|
-
stat: (filePath: string, callback: (error: NodeJS.ErrnoException | null, stats?: { isFile: () => boolean; }) => void) => void;
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
interface AssetsConfig {
|
|
15
|
-
html_handling?: string;
|
|
16
|
-
not_found_handling?: string;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
export interface AssetServer {
|
|
20
|
-
/** Whether a request path matches a file, applying the configured html_handling. */
|
|
21
|
-
exists: (pathname: string) => Promise<boolean>;
|
|
22
|
-
/** Serves a request from the assets directory, applying not_found_handling when nothing matches. */
|
|
23
|
-
handle: (req: IncomingMessage, res: ServerResponse) => Promise<void>;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
function statFile(fileSystem: ReadableFileSystem, filePath: string) {
|
|
27
|
-
return new Promise<boolean>((resolve) => {
|
|
28
|
-
fileSystem.stat(filePath, (error, stats) => {
|
|
29
|
-
resolve(!error && Boolean(stats?.isFile()));
|
|
30
|
-
});
|
|
31
|
-
});
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
function readFile(fileSystem: ReadableFileSystem, filePath: string) {
|
|
35
|
-
return new Promise<Buffer>((resolve, reject) => {
|
|
36
|
-
fileSystem.readFile(filePath, (error, data) => {
|
|
37
|
-
if (error || data === undefined) {
|
|
38
|
-
reject(error ?? new Error(`Could not read ${filePath}`));
|
|
39
|
-
return;
|
|
40
|
-
}
|
|
41
|
-
resolve(Buffer.from(data));
|
|
42
|
-
});
|
|
43
|
-
});
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
function htmlCandidates(pathname: string, htmlHandling: string | undefined) {
|
|
47
|
-
if (htmlHandling === 'none') {
|
|
48
|
-
return [pathname];
|
|
49
|
-
}
|
|
50
|
-
if (pathname.endsWith('/')) {
|
|
51
|
-
return [`${pathname}index.html`];
|
|
52
|
-
}
|
|
53
|
-
return [pathname, `${pathname}.html`, `${pathname}/index.html`];
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
/**
|
|
57
|
-
* Serves the Worker's assets directory the way the asset Worker does, reading the compiler's output filesystem first so
|
|
58
|
-
* files only emitted in memory by the dev server are visible.
|
|
59
|
-
*/
|
|
60
|
-
export function createAssetServer(options: {
|
|
61
|
-
directory: string;
|
|
62
|
-
config: AssetsConfig | undefined;
|
|
63
|
-
getOutputFileSystem: () => ReadableFileSystem | undefined;
|
|
64
|
-
waitUntilValid: () => Promise<void>;
|
|
65
|
-
/** More directories served at the root, checked after `directory`. */
|
|
66
|
-
extraDirectories?: string[];
|
|
67
|
-
}): AssetServer {
|
|
68
|
-
const { directory, config } = options;
|
|
69
|
-
const roots = [directory, ...options.extraDirectories ?? []];
|
|
70
|
-
|
|
71
|
-
async function findFile(filePath: string) {
|
|
72
|
-
const outputFileSystem = options.getOutputFileSystem();
|
|
73
|
-
if (outputFileSystem && await statFile(outputFileSystem, filePath)) {
|
|
74
|
-
return { fileSystem: outputFileSystem, filePath };
|
|
75
|
-
}
|
|
76
|
-
if (await statFile(fs, filePath)) {
|
|
77
|
-
return { fileSystem: fs, filePath };
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
function toFilePath(root: string, pathname: string) {
|
|
82
|
-
const filePath = path.join(root, decodeURIComponent(pathname));
|
|
83
|
-
// path.join normalizes `..`, so anything still escaping the directory is a traversal attempt
|
|
84
|
-
if (filePath !== root && !filePath.startsWith(root + path.sep)) {
|
|
85
|
-
return;
|
|
86
|
-
}
|
|
87
|
-
return filePath;
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
async function resolveFile(pathname: string) {
|
|
91
|
-
await options.waitUntilValid();
|
|
92
|
-
for (const candidate of htmlCandidates(pathname, config?.html_handling)) {
|
|
93
|
-
for (const root of roots) {
|
|
94
|
-
const filePath = toFilePath(root, candidate);
|
|
95
|
-
const found = filePath && await findFile(filePath);
|
|
96
|
-
if (found) {
|
|
97
|
-
return found;
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
async function resolveNotFound(pathname: string) {
|
|
104
|
-
if (config?.not_found_handling === 'single-page-application') {
|
|
105
|
-
return { status: 200, file: await resolveFile('/index.html') };
|
|
106
|
-
}
|
|
107
|
-
if (config?.not_found_handling === '404-page') {
|
|
108
|
-
// the nearest 404.html walking up from the requested path
|
|
109
|
-
const segments = pathname.split('/').slice(0, -1);
|
|
110
|
-
while (segments.length > 0) {
|
|
111
|
-
const file = await resolveFile(`${segments.join('/')}/404.html`);
|
|
112
|
-
if (file) {
|
|
113
|
-
return { status: 404, file };
|
|
114
|
-
}
|
|
115
|
-
segments.pop();
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
return { status: 404, file: undefined };
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
return {
|
|
122
|
-
async exists(pathname) {
|
|
123
|
-
const file = await resolveFile(pathname);
|
|
124
|
-
return file !== undefined;
|
|
125
|
-
},
|
|
126
|
-
async handle(req, res) {
|
|
127
|
-
const { pathname } = new URL(req.url ?? '/', 'http://localhost');
|
|
128
|
-
let status = 200;
|
|
129
|
-
let file = await resolveFile(pathname);
|
|
130
|
-
if (!file) {
|
|
131
|
-
({ status, file } = await resolveNotFound(pathname));
|
|
132
|
-
}
|
|
133
|
-
if (!file) {
|
|
134
|
-
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
135
|
-
res.end('Not Found');
|
|
136
|
-
return;
|
|
137
|
-
}
|
|
138
|
-
const body = await readFile(file.fileSystem, file.filePath);
|
|
139
|
-
res.writeHead(status, {
|
|
140
|
-
'Content-Type': lookup(file.filePath) ?? 'application/octet-stream',
|
|
141
|
-
'Content-Length': body.length,
|
|
142
|
-
// dev output changes on every rebuild, so never let the browser reuse it without asking
|
|
143
|
-
'Cache-Control': 'no-cache',
|
|
144
|
-
});
|
|
145
|
-
res.end(req.method === 'HEAD' ? undefined : body);
|
|
146
|
-
},
|
|
147
|
-
};
|
|
148
|
-
}
|
package/src/build.ts
DELETED
|
@@ -1,153 +0,0 @@
|
|
|
1
|
-
import { existsSync } from 'node:fs';
|
|
2
|
-
import fs from 'node:fs/promises';
|
|
3
|
-
import path from 'node:path';
|
|
4
|
-
|
|
5
|
-
import { unstable_getVarsForDev } from 'wrangler';
|
|
6
|
-
|
|
7
|
-
import { IMPORTED_ASSETS_DIR, createWorkerConfig } from './worker-config.js';
|
|
8
|
-
|
|
9
|
-
import type { ResolvedWorker } from './config.js';
|
|
10
|
-
import type { CloudflarePluginOptions } from './options.js';
|
|
11
|
-
import type { Compiler, Stats } from '@rspack/core';
|
|
12
|
-
|
|
13
|
-
// readConfig bookkeeping and bundling settings that rspack has already applied, so deploy must not apply them again
|
|
14
|
-
const OMITTED_CONFIG_KEYS = new Set([
|
|
15
|
-
'configPath',
|
|
16
|
-
'userConfigPath',
|
|
17
|
-
'topLevelName',
|
|
18
|
-
'definedEnvironments',
|
|
19
|
-
'targetEnvironment',
|
|
20
|
-
'build',
|
|
21
|
-
'define',
|
|
22
|
-
'alias',
|
|
23
|
-
'tsconfig',
|
|
24
|
-
'find_additional_modules',
|
|
25
|
-
'base_dir',
|
|
26
|
-
'preserve_file_names',
|
|
27
|
-
]);
|
|
28
|
-
|
|
29
|
-
/** The Wrangler config `wrangler deploy` reads for the built Worker, with every path rebased onto the output directory. */
|
|
30
|
-
export function createOutputConfig(worker: ResolvedWorker) {
|
|
31
|
-
const rebase = (filePath: string) => path.relative(worker.outputDir, path.resolve(worker.rootDir, filePath)).replaceAll('\\', '/') || '.';
|
|
32
|
-
const config = Object.fromEntries(Object.entries(worker.config).filter(([key]) => !OMITTED_CONFIG_KEYS.has(key)));
|
|
33
|
-
// readConfig always fills in `unsafe`, and wrangler warns about it being experimental even when empty
|
|
34
|
-
if (worker.config.unsafe && Object.keys(worker.config.unsafe).length === 0) {
|
|
35
|
-
delete config.unsafe;
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
// wrangler's defaults already cover .wasm and .bin beside the bundle; custom binary rules have to come along
|
|
39
|
-
const binaryRules = worker.config.rules.filter(rule => rule.type === 'CompiledWasm' || rule.type === 'Data');
|
|
40
|
-
const bundled = worker.main
|
|
41
|
-
? { main: 'index.js', no_bundle: true, rules: [{ type: 'ESModule', globs: ['**/*.js', '**/*.mjs'] }, ...binaryRules] }
|
|
42
|
-
: { main: undefined };
|
|
43
|
-
|
|
44
|
-
return {
|
|
45
|
-
...config,
|
|
46
|
-
...bundled,
|
|
47
|
-
assets: worker.assets ? { ...worker.config.assets, directory: rebase(worker.assets.directory) } : undefined,
|
|
48
|
-
containers: worker.config.containers?.map((container) => {
|
|
49
|
-
const rebased = { ...container };
|
|
50
|
-
// image is either a Dockerfile path or a registry reference; readConfig makes paths absolute, so only those need rebasing
|
|
51
|
-
if (container.image && path.isAbsolute(container.image)) {
|
|
52
|
-
rebased.image = rebase(container.image);
|
|
53
|
-
}
|
|
54
|
-
if (container.image_build_context) {
|
|
55
|
-
rebased.image_build_context = rebase(container.image_build_context);
|
|
56
|
-
}
|
|
57
|
-
return rebased;
|
|
58
|
-
}),
|
|
59
|
-
upload_source_maps: worker.config.upload_source_maps ?? true,
|
|
60
|
-
};
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
async function runCompiler(compiler: Compiler) {
|
|
64
|
-
try {
|
|
65
|
-
return await new Promise<Stats>((resolve, reject) => {
|
|
66
|
-
compiler.run((error, stats) => {
|
|
67
|
-
if (error || !stats) {
|
|
68
|
-
reject(error ?? new Error('Worker build produced no stats'));
|
|
69
|
-
} else {
|
|
70
|
-
resolve(stats);
|
|
71
|
-
}
|
|
72
|
-
});
|
|
73
|
-
});
|
|
74
|
-
} finally {
|
|
75
|
-
await new Promise<void>((resolve) => {
|
|
76
|
-
compiler.close(() => resolve());
|
|
77
|
-
});
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
/** The local secrets for this environment, written beside the build so `wrangler dev` can preview it like the Vite plugin's `vite preview`. */
|
|
82
|
-
function createDevVars(worker: ResolvedWorker) {
|
|
83
|
-
const vars = unstable_getVarsForDev(worker.configPath, undefined, {}, worker.environment, true, worker.config.secrets);
|
|
84
|
-
const lines = Object.entries(vars).map(([key, binding]) => `${key}=${JSON.stringify(String(binding.value))}`);
|
|
85
|
-
return lines.length > 0 ? `${lines.join('\n')}\n` : undefined;
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
/** Bundles one Worker into its output directory beside the `wrangler.json` that deploys it, returning that config's path. */
|
|
89
|
-
async function buildWorker(compiler: Compiler, worker: ResolvedWorker, pluginOptions: CloudflarePluginOptions) {
|
|
90
|
-
if (worker.main) {
|
|
91
|
-
const { config } = createWorkerConfig({
|
|
92
|
-
compiler,
|
|
93
|
-
worker,
|
|
94
|
-
pluginOptions,
|
|
95
|
-
outputDir: worker.outputDir,
|
|
96
|
-
entry: worker.main,
|
|
97
|
-
mode: compiler.options.mode === 'production' ? 'production' : 'development',
|
|
98
|
-
});
|
|
99
|
-
const workerCompiler = compiler.rspack.rspack(config);
|
|
100
|
-
const stats = await runCompiler(workerCompiler);
|
|
101
|
-
if (stats.hasErrors()) {
|
|
102
|
-
throw new Error(`Worker "${worker.name}" build failed:\n${stats.toString({ preset: 'errors-only', colors: false })}`);
|
|
103
|
-
}
|
|
104
|
-
} else {
|
|
105
|
-
await fs.rm(worker.outputDir, { recursive: true, force: true });
|
|
106
|
-
await fs.mkdir(worker.outputDir, { recursive: true });
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
const outputConfigPath = path.join(worker.outputDir, 'wrangler.json');
|
|
110
|
-
await fs.writeFile(outputConfigPath, JSON.stringify(createOutputConfig(worker), null, '\t'));
|
|
111
|
-
const devVars = createDevVars(worker);
|
|
112
|
-
if (devVars) {
|
|
113
|
-
await fs.writeFile(path.join(worker.outputDir, '.dev.vars'), devVars);
|
|
114
|
-
}
|
|
115
|
-
return outputConfigPath;
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
/** Moves assets the Worker imported into its assets directory, once the client build has emitted (and maybe cleaned) it. */
|
|
119
|
-
export async function copyImportedAssets(workers: ResolvedWorker[]) {
|
|
120
|
-
for (const worker of workers) {
|
|
121
|
-
const source = path.join(worker.outputDir, IMPORTED_ASSETS_DIR);
|
|
122
|
-
if (!worker.assets || !existsSync(source)) {
|
|
123
|
-
continue;
|
|
124
|
-
}
|
|
125
|
-
await fs.cp(source, worker.assets.directory, { recursive: true });
|
|
126
|
-
await fs.rm(source, { recursive: true, force: true });
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
/** Builds every Worker, entry first, and writes the redirect `wrangler deploy` follows to the built configs. */
|
|
131
|
-
export async function buildWorkers(options: { compiler: Compiler; workers: ResolvedWorker[]; pluginOptions: CloudflarePluginOptions; }) {
|
|
132
|
-
const { compiler, workers, pluginOptions } = options;
|
|
133
|
-
const [entry] = workers;
|
|
134
|
-
if (!entry) {
|
|
135
|
-
return;
|
|
136
|
-
}
|
|
137
|
-
const configPaths: string[] = [];
|
|
138
|
-
for (const worker of workers) {
|
|
139
|
-
configPaths.push(await buildWorker(compiler, worker, pluginOptions));
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
// the same redirect @cloudflare/vite-plugin writes, so a plain `wrangler deploy` next to the user config deploys the build
|
|
143
|
-
const deployConfigPath = path.join(entry.rootDir, '.wrangler', 'deploy', 'config.json');
|
|
144
|
-
const relativeToDeploy = (filePath: string) => path.relative(path.dirname(deployConfigPath), filePath).replaceAll('\\', '/');
|
|
145
|
-
const [entryConfigPath, ...auxiliaryConfigPaths] = configPaths;
|
|
146
|
-
await fs.mkdir(path.dirname(deployConfigPath), { recursive: true });
|
|
147
|
-
await fs.writeFile(deployConfigPath, JSON.stringify({
|
|
148
|
-
configPath: entryConfigPath && relativeToDeploy(entryConfigPath),
|
|
149
|
-
auxiliaryWorkers: auxiliaryConfigPaths.map((configPath) => {
|
|
150
|
-
return { configPath: relativeToDeploy(configPath) };
|
|
151
|
-
}),
|
|
152
|
-
}));
|
|
153
|
-
}
|
package/src/config.ts
DELETED
|
@@ -1,138 +0,0 @@
|
|
|
1
|
-
import fs from 'node:fs';
|
|
2
|
-
import path from 'node:path';
|
|
3
|
-
|
|
4
|
-
import { unstable_readConfig } from 'wrangler';
|
|
5
|
-
|
|
6
|
-
import type {
|
|
7
|
-
AuxiliaryWorkerOptions,
|
|
8
|
-
CloudflarePluginOptions,
|
|
9
|
-
WorkerConfig,
|
|
10
|
-
WorkerConfigCustomizer,
|
|
11
|
-
} from './options.js';
|
|
12
|
-
|
|
13
|
-
const CONFIG_FILE_NAMES = ['wrangler.jsonc', 'wrangler.json', 'wrangler.toml'];
|
|
14
|
-
|
|
15
|
-
export interface ResolvedWorker {
|
|
16
|
-
config: WorkerConfig;
|
|
17
|
-
configPath: string;
|
|
18
|
-
environment: string | undefined;
|
|
19
|
-
name: string;
|
|
20
|
-
/** Undefined for assets-only projects, which deploy static files without a Worker. */
|
|
21
|
-
main: string | undefined;
|
|
22
|
-
/** Directory holding the Wrangler config; relative paths in the config resolve against it. */
|
|
23
|
-
rootDir: string;
|
|
24
|
-
assets: {
|
|
25
|
-
directory: string;
|
|
26
|
-
binding: string | undefined;
|
|
27
|
-
} | undefined;
|
|
28
|
-
outputDir: string;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
function findConfigPath(context: string, configPath: string | undefined) {
|
|
32
|
-
if (configPath) {
|
|
33
|
-
return path.resolve(context, configPath);
|
|
34
|
-
}
|
|
35
|
-
// projects often point rspack's context at a source folder, so walk up like wrangler does
|
|
36
|
-
let directory = context;
|
|
37
|
-
while (true) {
|
|
38
|
-
for (const fileName of CONFIG_FILE_NAMES) {
|
|
39
|
-
const candidate = path.join(directory, fileName);
|
|
40
|
-
if (fs.existsSync(candidate)) {
|
|
41
|
-
return candidate;
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
const parent = path.dirname(directory);
|
|
45
|
-
if (parent === directory) {
|
|
46
|
-
throw new Error(`No Wrangler config found in ${context} or its parents. Looked for ${CONFIG_FILE_NAMES.join(', ')}.`);
|
|
47
|
-
}
|
|
48
|
-
directory = parent;
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
function isInside(parent: string, child: string) {
|
|
53
|
-
const relative = path.relative(parent, child);
|
|
54
|
-
return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
|
58
|
-
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
/** Deep-merges plain objects so an override like `{ vars: { A: '1' } }` keeps the other vars; arrays are replaced. */
|
|
62
|
-
function mergeConfig(target: WorkerConfig | Record<string, unknown>, overrides: Partial<WorkerConfig> | Record<string, unknown>) {
|
|
63
|
-
for (const [key, value] of Object.entries(overrides)) {
|
|
64
|
-
const existing: unknown = Reflect.get(target, key);
|
|
65
|
-
if (isPlainObject(existing) && isPlainObject(value)) {
|
|
66
|
-
mergeConfig(existing, value);
|
|
67
|
-
} else {
|
|
68
|
-
Reflect.set(target, key, value);
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
function applyCustomizer(config: WorkerConfig, customizer: WorkerConfigCustomizer | undefined) {
|
|
74
|
-
if (!customizer) {
|
|
75
|
-
return;
|
|
76
|
-
}
|
|
77
|
-
const overrides = typeof customizer === 'function' ? customizer(config) : customizer;
|
|
78
|
-
if (overrides) {
|
|
79
|
-
mergeConfig(config, overrides);
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
export function resolveWorker(context: string, options: CloudflarePluginOptions): ResolvedWorker {
|
|
84
|
-
const configPath = findConfigPath(context, options.configPath);
|
|
85
|
-
const environment = options.environment ?? process.env.CLOUDFLARE_ENV;
|
|
86
|
-
// an explicit path skips wrangler's .wrangler/deploy redirect, which would otherwise point dev at our own build output
|
|
87
|
-
const config = unstable_readConfig({ config: configPath, env: environment }, { preserveOriginalMain: true });
|
|
88
|
-
applyCustomizer(config, options.config);
|
|
89
|
-
const rootDir = path.dirname(configPath);
|
|
90
|
-
|
|
91
|
-
if (!config.main && !config.assets?.directory) {
|
|
92
|
-
throw new Error(`${configPath} needs a \`main\` Worker entry, or an \`assets.directory\` for an assets-only project.`);
|
|
93
|
-
}
|
|
94
|
-
if (!config.name) {
|
|
95
|
-
throw new Error(`${configPath} has no \`name\`.`);
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
const assets = config.assets?.directory
|
|
99
|
-
? { directory: path.resolve(rootDir, config.assets.directory), binding: config.assets.binding }
|
|
100
|
-
: undefined;
|
|
101
|
-
const outputDir = path.resolve(rootDir, options.outputDir ?? path.join('dist', config.name));
|
|
102
|
-
|
|
103
|
-
// anything in the assets directory is publicly served, so the Worker bundle can't live there
|
|
104
|
-
if (assets && isInside(assets.directory, outputDir)) {
|
|
105
|
-
throw new Error(`outputDir (${outputDir}) is inside the assets directory (${assets.directory}); the Worker bundle would be publicly served.`);
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
return {
|
|
109
|
-
config,
|
|
110
|
-
configPath,
|
|
111
|
-
environment,
|
|
112
|
-
name: config.name,
|
|
113
|
-
main: config.main ? path.resolve(rootDir, config.main) : undefined,
|
|
114
|
-
rootDir,
|
|
115
|
-
assets,
|
|
116
|
-
outputDir,
|
|
117
|
-
};
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
/** Resolves an auxiliary Worker, which only the entry Worker's service bindings reach, so it can't serve assets. */
|
|
121
|
-
function resolveAuxiliaryWorker(context: string, options: CloudflarePluginOptions, auxiliary: AuxiliaryWorkerOptions) {
|
|
122
|
-
const worker = resolveWorker(context, { ...auxiliary, environment: options.environment });
|
|
123
|
-
if (!worker.main) {
|
|
124
|
-
throw new Error(`Auxiliary Worker config ${worker.configPath} needs a \`main\` entry.`);
|
|
125
|
-
}
|
|
126
|
-
if (worker.assets) {
|
|
127
|
-
throw new Error(`Auxiliary Worker "${worker.name}" has \`assets\`, which only the entry Worker supports.`);
|
|
128
|
-
}
|
|
129
|
-
return worker;
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
/** A resolver per Worker, entry first, so a config change can re-read just the Worker it belongs to. */
|
|
133
|
-
export function getWorkerResolvers(context: string, options: CloudflarePluginOptions): (() => ResolvedWorker)[] {
|
|
134
|
-
return [
|
|
135
|
-
() => resolveWorker(context, options),
|
|
136
|
-
...(options.auxiliaryWorkers ?? []).map(auxiliary => () => resolveAuxiliaryWorker(context, options, auxiliary)),
|
|
137
|
-
];
|
|
138
|
-
}
|
package/src/containers.ts
DELETED
|
@@ -1,183 +0,0 @@
|
|
|
1
|
-
import { execFileSync, spawn } from 'node:child_process';
|
|
2
|
-
import fs from 'node:fs';
|
|
3
|
-
import path from 'node:path';
|
|
4
|
-
|
|
5
|
-
import type { WorkerConfig } from './options.js';
|
|
6
|
-
|
|
7
|
-
/** One image a Container-backed Durable Object runs, under the tag wrangler's Miniflare options expect. */
|
|
8
|
-
export interface ContainerImage {
|
|
9
|
-
tag: string;
|
|
10
|
-
dockerfile?: string;
|
|
11
|
-
buildContext?: string;
|
|
12
|
-
buildArgs?: Record<string, string>;
|
|
13
|
-
/** A registry image to pull instead of building. */
|
|
14
|
-
uri?: string;
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
// the egress sidecar workerd runs beside each container; we name it explicitly so the image we pull is the one Miniflare uses
|
|
18
|
-
const EGRESS_IMAGE = process.env.MINIFLARE_CONTAINER_EGRESS_IMAGE ?? 'cloudflare/proxy-everything:3cb1195@sha256:0ef6716c52430096900b150d84a3302057d6cd2319dae7987128c85d0733e3c8';
|
|
19
|
-
|
|
20
|
-
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
|
21
|
-
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
/** `WRANGLER_DOCKER_BIN`, like wrangler, so both find the same Docker. */
|
|
25
|
-
export function getDockerPath() {
|
|
26
|
-
return process.env.WRANGLER_DOCKER_BIN ?? 'docker';
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
function getContainerClassName(container: NonNullable<WorkerConfig['containers']>[number], exports: unknown) {
|
|
30
|
-
if (container.class_name) {
|
|
31
|
-
return container.class_name;
|
|
32
|
-
}
|
|
33
|
-
if (!isPlainObject(exports)) {
|
|
34
|
-
return;
|
|
35
|
-
}
|
|
36
|
-
for (const [className, entry] of Object.entries(exports)) {
|
|
37
|
-
if (isPlainObject(entry) && entry.container === container.name) {
|
|
38
|
-
return className;
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
/** The runtime container settings wrangler put on each Durable Object, keyed by class name. */
|
|
44
|
-
function getContainerRuntimeOptions(durableObjects: unknown) {
|
|
45
|
-
const runtimeOptions = new Map<string, Record<string, unknown>>();
|
|
46
|
-
if (!isPlainObject(durableObjects)) {
|
|
47
|
-
return runtimeOptions;
|
|
48
|
-
}
|
|
49
|
-
for (const durableObject of Object.values(durableObjects)) {
|
|
50
|
-
if (isPlainObject(durableObject) && typeof durableObject.className === 'string' && isPlainObject(durableObject.container)) {
|
|
51
|
-
runtimeOptions.set(durableObject.className, durableObject.container);
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
return runtimeOptions;
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
function findNamedImageTag(runtime: Record<string, unknown>, imageName: string) {
|
|
58
|
-
if (!Array.isArray(runtime.images)) {
|
|
59
|
-
return;
|
|
60
|
-
}
|
|
61
|
-
for (const image of runtime.images as unknown[]) {
|
|
62
|
-
if (isPlainObject(image) && image.name === imageName && typeof image.image === 'string') {
|
|
63
|
-
return image.image;
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
/**
|
|
69
|
-
* The images to build or pull before workerd can start these containers. Tags come from the Durable Object options
|
|
70
|
-
* wrangler generated, so they always match what workerd will ask Docker for.
|
|
71
|
-
*/
|
|
72
|
-
export function getContainerImages(config: WorkerConfig, durableObjects: unknown): ContainerImage[] {
|
|
73
|
-
const runtimeOptions = getContainerRuntimeOptions(durableObjects);
|
|
74
|
-
const configDir = path.dirname(config.configPath ?? path.resolve('wrangler.json'));
|
|
75
|
-
const images: ContainerImage[] = [];
|
|
76
|
-
for (const container of config.containers ?? []) {
|
|
77
|
-
const className = getContainerClassName(container, config.exports);
|
|
78
|
-
const runtime = className === undefined ? undefined : runtimeOptions.get(className);
|
|
79
|
-
if (!runtime) {
|
|
80
|
-
continue;
|
|
81
|
-
}
|
|
82
|
-
for (const [imageName, image] of Object.entries(container.images ?? {})) {
|
|
83
|
-
const tag = findNamedImageTag(runtime, imageName);
|
|
84
|
-
if (tag === undefined) {
|
|
85
|
-
continue;
|
|
86
|
-
}
|
|
87
|
-
if (image.dockerfile === undefined) {
|
|
88
|
-
images.push({ tag, uri: image.image });
|
|
89
|
-
} else {
|
|
90
|
-
const dockerfile = path.resolve(configDir, image.dockerfile);
|
|
91
|
-
const buildContext = image.build_context === undefined ? path.dirname(dockerfile) : path.resolve(configDir, image.build_context);
|
|
92
|
-
images.push({ tag, dockerfile, buildContext, buildArgs: image.build_vars });
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
|
-
if (container.image === undefined || typeof runtime.imageName !== 'string') {
|
|
96
|
-
continue;
|
|
97
|
-
}
|
|
98
|
-
// readConfig resolves Dockerfile paths against the config, leaving registry references as they were
|
|
99
|
-
if (path.isAbsolute(container.image) && fs.existsSync(container.image)) {
|
|
100
|
-
const buildContext = container.image_build_context ?? path.dirname(container.image);
|
|
101
|
-
images.push({ tag: runtime.imageName, dockerfile: container.image, buildContext, buildArgs: container.image_vars });
|
|
102
|
-
} else {
|
|
103
|
-
images.push({ tag: runtime.imageName, uri: container.image });
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
return images;
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
function runDocker(dockerPath: string, args: string[]) {
|
|
110
|
-
return new Promise<void>((resolve, reject) => {
|
|
111
|
-
// build and pull progress is worth seeing, since a first build can take minutes
|
|
112
|
-
const child = spawn(dockerPath, args, { stdio: ['ignore', 'inherit', 'inherit'] });
|
|
113
|
-
child.once('error', reject);
|
|
114
|
-
child.once('exit', (code) => {
|
|
115
|
-
if (code === 0) {
|
|
116
|
-
resolve();
|
|
117
|
-
} else {
|
|
118
|
-
reject(new Error(`\`docker ${args[0] ?? ''}\` exited with code ${String(code)}`));
|
|
119
|
-
}
|
|
120
|
-
});
|
|
121
|
-
});
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
/** The Docker socket workerd should talk to, found the same way wrangler finds it. */
|
|
125
|
-
export function resolveDockerHost(dockerPath: string) {
|
|
126
|
-
const fromEnv = process.env.WRANGLER_DOCKER_HOST ?? process.env.DOCKER_HOST;
|
|
127
|
-
if (fromEnv) {
|
|
128
|
-
return fromEnv;
|
|
129
|
-
}
|
|
130
|
-
try {
|
|
131
|
-
const contexts = execFileSync(dockerPath, ['context', 'ls', '--format', 'json'], { encoding: 'utf8' });
|
|
132
|
-
for (const line of contexts.trim().split('\n')) {
|
|
133
|
-
const context: unknown = JSON.parse(line);
|
|
134
|
-
if (isPlainObject(context) && context.Current === true && typeof context.DockerEndpoint === 'string') {
|
|
135
|
-
return context.DockerEndpoint;
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
} catch {
|
|
139
|
-
// an old Docker without JSON context output still answers on the default socket
|
|
140
|
-
}
|
|
141
|
-
return 'unix:///var/run/docker.sock';
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
/** Miniflare's `containerEngine`, naming the egress sidecar image we pulled. */
|
|
145
|
-
export function getContainerEngine(dockerPath: string) {
|
|
146
|
-
return { localDocker: { socketPath: resolveDockerHost(dockerPath), containerEgressInterceptorImage: EGRESS_IMAGE } };
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
/** Builds or pulls each image, then the egress sidecar, so workerd can start containers without waiting on Docker. */
|
|
150
|
-
export async function prepareContainerImages(dockerPath: string, images: ContainerImage[]) {
|
|
151
|
-
if (process.platform === 'win32') {
|
|
152
|
-
throw new Error('Containers in dev are not supported on Windows, matching wrangler. Run dev in WSL, or set `dev.enable_containers` to false in the Wrangler config.');
|
|
153
|
-
}
|
|
154
|
-
try {
|
|
155
|
-
execFileSync(dockerPath, ['info'], { stdio: 'ignore' });
|
|
156
|
-
} catch (error) {
|
|
157
|
-
throw new Error('Containers need a running Docker daemon to build their images. Start Docker, or set `dev.enable_containers` to false in the Wrangler config.', { cause: error });
|
|
158
|
-
}
|
|
159
|
-
for (const image of images) {
|
|
160
|
-
if (image.dockerfile) {
|
|
161
|
-
const buildArgs = Object.entries(image.buildArgs ?? {}).flatMap(([key, value]) => ['--build-arg', `${key}=${value}`]);
|
|
162
|
-
await runDocker(dockerPath, ['build', '--platform', 'linux/amd64', '--tag', image.tag, '--file', image.dockerfile, ...buildArgs, image.buildContext ?? path.dirname(image.dockerfile)]);
|
|
163
|
-
} else if (image.uri) {
|
|
164
|
-
await runDocker(dockerPath, ['pull', '--platform', 'linux/amd64', image.uri]);
|
|
165
|
-
await runDocker(dockerPath, ['tag', image.uri, image.tag]);
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
await runDocker(dockerPath, ['pull', EGRESS_IMAGE]);
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
/** Force-removes containers started from these images; synchronous so it can also run while the process exits. */
|
|
172
|
-
export function removeContainers(dockerPath: string, tags: Iterable<string>) {
|
|
173
|
-
for (const tag of tags) {
|
|
174
|
-
try {
|
|
175
|
-
const ids = execFileSync(dockerPath, ['ps', '--all', '--quiet', '--filter', `ancestor=${tag}`], { encoding: 'utf8' }).split('\n').filter(Boolean);
|
|
176
|
-
if (ids.length > 0) {
|
|
177
|
-
execFileSync(dockerPath, ['rm', '--force', ...ids], { stdio: 'ignore' });
|
|
178
|
-
}
|
|
179
|
-
} catch {
|
|
180
|
-
// best effort, since Docker may already have stopped by the time dev exits
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
}
|
package/src/dev-entry.ts
DELETED
|
@@ -1,50 +0,0 @@
|
|
|
1
|
-
import { fileURLToPath } from 'node:url';
|
|
2
|
-
|
|
3
|
-
import type { ResolvedWorker } from './config.js';
|
|
4
|
-
|
|
5
|
-
const RUNTIME_PATH = fileURLToPath(new URL('../runtime/dev-runtime.js', import.meta.url));
|
|
6
|
-
|
|
7
|
-
// these names are shared with runtime/dev-runtime.js
|
|
8
|
-
export const HMR_RUNNER_CLASS = '__RSPACK_HMR_RUNNER__';
|
|
9
|
-
export const HMR_TOKEN_BINDING = '__RSPACK_HMR_TOKEN__';
|
|
10
|
-
export const HMR_HEADER = 'x-rspack-plugin-cloudflare-hmr';
|
|
11
|
-
|
|
12
|
-
function toSpecifier(filePath: string) {
|
|
13
|
-
return JSON.stringify(filePath.replaceAll('\\', '/'));
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
/** Export names we can know before building: `default` plus the Durable Object and Workflow classes this Worker owns. */
|
|
17
|
-
export function getConfiguredExports(worker: ResolvedWorker) {
|
|
18
|
-
const names = new Set(['default']);
|
|
19
|
-
for (const binding of worker.config.durable_objects.bindings) {
|
|
20
|
-
if (!binding.script_name) {
|
|
21
|
-
names.add(binding.class_name);
|
|
22
|
-
}
|
|
23
|
-
}
|
|
24
|
-
for (const workflow of worker.config.workflows) {
|
|
25
|
-
if (!workflow.script_name) {
|
|
26
|
-
names.add(workflow.class_name);
|
|
27
|
-
}
|
|
28
|
-
}
|
|
29
|
-
return [...names].toSorted((left, right) => left.localeCompare(right));
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
/**
|
|
33
|
-
* Source for the dev-only entry around `main`. It accepts hot updates to `main` so rspack re-evaluates the changed
|
|
34
|
-
* modules in place, and re-exports each of the user's exports through a wrapper that always calls the current code.
|
|
35
|
-
*/
|
|
36
|
-
export function createDevEntrySource(main: string, exportNames: string[]) {
|
|
37
|
-
const mainSpecifier = toSpecifier(main);
|
|
38
|
-
const lines = [
|
|
39
|
-
`import * as worker from ${mainSpecifier};`,
|
|
40
|
-
`import { initialize, wrapExport, RspackHmrRunner } from ${toSpecifier(RUNTIME_PATH)};`,
|
|
41
|
-
'initialize(() => worker);',
|
|
42
|
-
`if (import.meta.webpackHot) import.meta.webpackHot.accept(${mainSpecifier});`,
|
|
43
|
-
`export { RspackHmrRunner as ${HMR_RUNNER_CLASS} };`,
|
|
44
|
-
];
|
|
45
|
-
for (const [index, name] of exportNames.entries()) {
|
|
46
|
-
// string export names cover anything the user exported, even names that aren't valid identifiers
|
|
47
|
-
lines.push(`const export${index} = wrapExport(${JSON.stringify(name)});`, `export { export${index} as ${JSON.stringify(name)} };`);
|
|
48
|
-
}
|
|
49
|
-
return `${lines.join('\n')}\n`;
|
|
50
|
-
}
|