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
package/src/index.ts
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import { buildWorkers, copyImportedAssets } from './build.js';
|
|
2
|
+
import { getWorkerResolvers } from './config.js';
|
|
3
|
+
import { DevSession } from './dev.js';
|
|
4
|
+
import { startTunnel } from './tunnel.js';
|
|
5
|
+
|
|
6
|
+
import type { ResolvedWorker } from './config.js';
|
|
7
|
+
import type { CloudflarePluginOptions } from './options.js';
|
|
8
|
+
import type { Tunnel } from './tunnel.js';
|
|
9
|
+
import type { Compiler, RspackPluginInstance } from '@rspack/core';
|
|
10
|
+
import type { RspackDevServer } from '@rspack/dev-server';
|
|
11
|
+
import type { IncomingMessage, Server, ServerResponse } from 'node:http';
|
|
12
|
+
|
|
13
|
+
export type {
|
|
14
|
+
AuxiliaryWorkerOptions,
|
|
15
|
+
CloudflarePluginOptions,
|
|
16
|
+
TunnelOptions,
|
|
17
|
+
WorkerConfig,
|
|
18
|
+
WorkerConfigCustomizer,
|
|
19
|
+
} from './options.js';
|
|
20
|
+
|
|
21
|
+
const PLUGIN_NAME = 'rspack-plugin-cloudflare';
|
|
22
|
+
|
|
23
|
+
// listen addresses a tunnel can't dial by name, so it reaches the dev server through localhost instead
|
|
24
|
+
const WILDCARD_HOSTS = new Set(['0.0.0.0', '::', 'local-ip', 'local-ipv4', 'local-ipv6']);
|
|
25
|
+
|
|
26
|
+
function getDevServerOrigin(server: RspackDevServer) {
|
|
27
|
+
const address = server.server?.address();
|
|
28
|
+
const port = typeof address === 'object' && address ? address.port : Number(server.options.port);
|
|
29
|
+
const serverOption = server.options.server;
|
|
30
|
+
const serverType = typeof serverOption === 'object' ? serverOption.type : serverOption;
|
|
31
|
+
const protocol = serverType === undefined || serverType === 'http' ? 'http' : 'https';
|
|
32
|
+
const { host } = server.options;
|
|
33
|
+
const hostname = !host || WILDCARD_HOSTS.has(host) ? 'localhost' : host;
|
|
34
|
+
return new URL(`${protocol}://${hostname}:${port}`);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Lets the tunnel's hostnames past the dev server's Host header check. */
|
|
38
|
+
function allowHosts(server: RspackDevServer, urls: string[]) {
|
|
39
|
+
const { allowedHosts } = server.options;
|
|
40
|
+
if (allowedHosts === 'all') {
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
const hostnames = urls.map(url => new URL(url).hostname);
|
|
44
|
+
// a list keeps what 'auto' allowed, since localhost, IPs and the configured host always pass
|
|
45
|
+
if (Array.isArray(allowedHosts)) {
|
|
46
|
+
server.options.allowedHosts = [...allowedHosts, ...hostnames];
|
|
47
|
+
} else if (allowedHosts && allowedHosts !== 'auto') {
|
|
48
|
+
server.options.allowedHosts = [allowedHosts, ...hostnames];
|
|
49
|
+
} else {
|
|
50
|
+
server.options.allowedHosts = hostnames;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function getSocketPath(server: RspackDevServer) {
|
|
55
|
+
const socketOptions = server.options.webSocketServer;
|
|
56
|
+
if (typeof socketOptions === 'object' && socketOptions && typeof socketOptions.options?.path === 'string') {
|
|
57
|
+
return socketOptions.options.path;
|
|
58
|
+
}
|
|
59
|
+
return '/ws';
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export class CloudflarePlugin implements RspackPluginInstance {
|
|
63
|
+
#tunnel: Tunnel | undefined;
|
|
64
|
+
readonly options: CloudflarePluginOptions;
|
|
65
|
+
|
|
66
|
+
constructor(options: CloudflarePluginOptions = {}) {
|
|
67
|
+
this.options = options;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async #openTunnel(server: RspackDevServer, entry: ResolvedWorker | undefined, logger: ReturnType<Compiler['getInfrastructureLogger']>) {
|
|
71
|
+
const { tunnel: tunnelOption } = this.options;
|
|
72
|
+
if (!entry || !tunnelOption) {
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
logger.warn('Starting a Cloudflare Tunnel: anyone with its URL can reach this dev server and its Worker\'s local bindings.');
|
|
76
|
+
this.#tunnel = await startTunnel({
|
|
77
|
+
origin: getDevServerOrigin(server),
|
|
78
|
+
tunnel: tunnelOption === true ? {} : tunnelOption,
|
|
79
|
+
config: entry.config,
|
|
80
|
+
cwd: entry.rootDir,
|
|
81
|
+
});
|
|
82
|
+
allowHosts(server, this.#tunnel.urls);
|
|
83
|
+
for (const url of this.#tunnel.urls) {
|
|
84
|
+
logger.info(`Tunnel: ${url}`);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
apply(compiler: Compiler) {
|
|
89
|
+
type DevServerOptions = NonNullable<RspackDevServer['options']>;
|
|
90
|
+
const logger = compiler.getInfrastructureLogger(PLUGIN_NAME);
|
|
91
|
+
const resolvers = getWorkerResolvers(compiler.context, this.options);
|
|
92
|
+
let session: DevSession | undefined;
|
|
93
|
+
|
|
94
|
+
// `rspack serve` builds the dev server from these options after plugins apply, so wrapping them here hooks us in
|
|
95
|
+
const devServer = compiler.options.devServer as DevServerOptions | undefined;
|
|
96
|
+
if (devServer) {
|
|
97
|
+
type Middlewares = Parameters<NonNullable<DevServerOptions['setupMiddlewares']>>[0];
|
|
98
|
+
const { setupMiddlewares, onListening } = devServer;
|
|
99
|
+
devServer.setupMiddlewares = (middlewares: Middlewares, server: RspackDevServer) => {
|
|
100
|
+
const result = setupMiddlewares ? setupMiddlewares(middlewares, server) : middlewares;
|
|
101
|
+
session = new DevSession({ compiler, resolvers, pluginOptions: this.options, logger });
|
|
102
|
+
session.start({
|
|
103
|
+
waitUntilValid: () => new Promise((resolve) => {
|
|
104
|
+
if (server.middleware) {
|
|
105
|
+
server.middleware.waitUntilValid(() => resolve());
|
|
106
|
+
} else {
|
|
107
|
+
resolve();
|
|
108
|
+
}
|
|
109
|
+
}),
|
|
110
|
+
sendToClients: (type, data) => {
|
|
111
|
+
if (server.webSocketServer) {
|
|
112
|
+
server.sendMessage(server.webSocketServer.clients, type, data);
|
|
113
|
+
}
|
|
114
|
+
},
|
|
115
|
+
});
|
|
116
|
+
const activeSession = session;
|
|
117
|
+
// ahead of dev-middleware so `run_worker_first` decides who answers, not whatever the client build emitted
|
|
118
|
+
const devMiddlewareIndex = result.findIndex(middleware => typeof middleware === 'object' && middleware.name === '@rspack/dev-middleware');
|
|
119
|
+
result.splice(devMiddlewareIndex === -1 ? result.length : devMiddlewareIndex, 0, {
|
|
120
|
+
name: PLUGIN_NAME,
|
|
121
|
+
middleware: (req: IncomingMessage, res: ServerResponse, next: () => void) => {
|
|
122
|
+
activeSession.handle(req, res, next).catch(next);
|
|
123
|
+
},
|
|
124
|
+
});
|
|
125
|
+
return result;
|
|
126
|
+
};
|
|
127
|
+
devServer.onListening = (server: RspackDevServer) => {
|
|
128
|
+
if (session && server.server) {
|
|
129
|
+
session.attachUpgradeHandler(server.server as Server, getSocketPath(server));
|
|
130
|
+
}
|
|
131
|
+
if (this.options.tunnel) {
|
|
132
|
+
this.#openTunnel(server, resolvers[0]?.(), logger).catch((error: unknown) => {
|
|
133
|
+
logger.error(`Tunnel failed to start: ${error instanceof Error ? error.message : String(error)}`);
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
onListening?.(server);
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// the Workers `rspack build` bundled, whose imported assets join the client output once it has emitted
|
|
141
|
+
let builtWorkers: ResolvedWorker[] | undefined;
|
|
142
|
+
compiler.hooks.beforeRun.tapPromise(PLUGIN_NAME, async () => {
|
|
143
|
+
const workers = resolvers.map(resolve => resolve());
|
|
144
|
+
await buildWorkers({ compiler, workers, pluginOptions: this.options });
|
|
145
|
+
for (const worker of workers) {
|
|
146
|
+
logger.info(`Built ${worker.main ? 'Worker' : 'assets-only config'} "${worker.name}" into ${worker.outputDir}`);
|
|
147
|
+
}
|
|
148
|
+
builtWorkers = workers;
|
|
149
|
+
});
|
|
150
|
+
compiler.hooks.afterEmit.tapPromise(PLUGIN_NAME, async () => {
|
|
151
|
+
if (builtWorkers) {
|
|
152
|
+
await copyImportedAssets(builtWorkers);
|
|
153
|
+
}
|
|
154
|
+
});
|
|
155
|
+
compiler.hooks.shutdown.tapPromise(PLUGIN_NAME, async () => {
|
|
156
|
+
this.#tunnel?.close();
|
|
157
|
+
await session?.dispose();
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export function cloudflare(options?: CloudflarePluginOptions) {
|
|
163
|
+
return new CloudflarePlugin(options);
|
|
164
|
+
}
|
package/src/inspector.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import net from 'node:net';
|
|
2
|
+
|
|
3
|
+
export const DEBUG_PATH = '/__debug';
|
|
4
|
+
const DEFAULT_INSPECTOR_PORT = 9229;
|
|
5
|
+
|
|
6
|
+
function isPortFree(port: number) {
|
|
7
|
+
return new Promise<boolean>((resolve) => {
|
|
8
|
+
const server = net.createServer();
|
|
9
|
+
server.once('error', () => resolve(false));
|
|
10
|
+
server.listen(port, '127.0.0.1', () => {
|
|
11
|
+
server.close(() => resolve(true));
|
|
12
|
+
});
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Resolves the inspector port: the configured one, or 9229 falling back to the next free port like the Vite plugin. */
|
|
17
|
+
export async function resolveInspectorPort(option: number | false | undefined) {
|
|
18
|
+
if (option === false) {
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
if (option !== undefined) {
|
|
22
|
+
return option;
|
|
23
|
+
}
|
|
24
|
+
for (let port = DEFAULT_INSPECTOR_PORT; port < 65535; port++) {
|
|
25
|
+
if (await isPortFree(port)) {
|
|
26
|
+
return port;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** A page that sends the browser to Cloudflare's hosted DevTools, connected to each Worker through Miniflare's inspector proxy. */
|
|
32
|
+
export function getDebugPageHtml(workerNames: string[], inspectorPort: number) {
|
|
33
|
+
const urls = workerNames.map((name) => {
|
|
34
|
+
const params = new URLSearchParams({ theme: 'systemPreferred', debugger: 'true', ws: `localhost:${inspectorPort}/${name}`, domain: name });
|
|
35
|
+
return `https://devtools.devprod.cloudflare.dev/js_app?${params.toString()}`;
|
|
36
|
+
});
|
|
37
|
+
return `<!doctype html><script>
|
|
38
|
+
const [first, ...rest] = ${JSON.stringify(urls)};
|
|
39
|
+
for (const url of rest) {
|
|
40
|
+
window.open(url);
|
|
41
|
+
}
|
|
42
|
+
window.location.replace(first);
|
|
43
|
+
</script>`;
|
|
44
|
+
}
|
package/src/miniflare.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
|
|
3
|
+
// wrangler's Miniflare options target its own Miniflare build, so load that copy rather than whichever one is hoisted
|
|
4
|
+
const require = createRequire(import.meta.url);
|
|
5
|
+
const wranglerRequire = createRequire(require.resolve('wrangler/package.json'));
|
|
6
|
+
|
|
7
|
+
export const miniflare = wranglerRequire('miniflare') as typeof import('miniflare');
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
|
|
3
|
+
import type { ResolvedWorker } from './config.js';
|
|
4
|
+
|
|
5
|
+
export type ModuleType = 'CompiledWasm' | 'Data' | 'Text';
|
|
6
|
+
|
|
7
|
+
// wrangler's defaults, which apply after any rules in the config
|
|
8
|
+
const DEFAULT_RULES: { type: ModuleType; globs: string[]; }[] = [
|
|
9
|
+
{ type: 'Text', globs: ['**/*.txt', '**/*.html', '**/*.sql'] },
|
|
10
|
+
{ type: 'Data', globs: ['**/*.bin'] },
|
|
11
|
+
{ type: 'CompiledWasm', globs: ['**/*.wasm', '**/*.wasm?module'] },
|
|
12
|
+
];
|
|
13
|
+
|
|
14
|
+
const MODULE_TYPES: readonly string[] = ['CompiledWasm', 'Data', 'Text'] satisfies ModuleType[];
|
|
15
|
+
|
|
16
|
+
function isModuleType(type: string): type is ModuleType {
|
|
17
|
+
return MODULE_TYPES.includes(type);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Maps file extensions to the non-JS module type wrangler would give them, with config rules taking precedence. */
|
|
21
|
+
export function getModuleTypes(worker: ResolvedWorker) {
|
|
22
|
+
const types = new Map<string, ModuleType>();
|
|
23
|
+
for (const rule of [...worker.config.rules, ...DEFAULT_RULES]) {
|
|
24
|
+
if (!isModuleType(rule.type)) {
|
|
25
|
+
continue;
|
|
26
|
+
}
|
|
27
|
+
for (const glob of rule.globs) {
|
|
28
|
+
// wrangler's module rules use `**/*.ext` style globs, so the extension is all that matters
|
|
29
|
+
const extension = path.extname(glob.replace(/\?.*$/, ''));
|
|
30
|
+
if (extension && !types.has(extension)) {
|
|
31
|
+
types.set(extension, rule.type);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return types;
|
|
36
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { fileURLToPath } from 'node:url';
|
|
2
|
+
|
|
3
|
+
import { getCloudflarePreset } from '@cloudflare/unenv-preset';
|
|
4
|
+
import { defineEnv } from 'unenv';
|
|
5
|
+
|
|
6
|
+
import { miniflare } from './miniflare.js';
|
|
7
|
+
|
|
8
|
+
import type { ResolvedWorker } from './config.js';
|
|
9
|
+
|
|
10
|
+
export interface NodeJsCompat {
|
|
11
|
+
/** Builtin specifiers workerd provides natively, mapped to the specifier to import at runtime. */
|
|
12
|
+
externals: Map<string, string>;
|
|
13
|
+
/** Builtin specifiers workerd lacks, mapped to the unenv polyfill file that replaces them. */
|
|
14
|
+
polyfills: Map<string, string>;
|
|
15
|
+
/** A module that sets up injected globals like `process` and runs polyfills, when the preset needs any. */
|
|
16
|
+
injectSource: string | undefined;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function resolvePolyfill(specifier: string) {
|
|
20
|
+
// polyfills are this package's dependencies, which the user's project can't necessarily resolve
|
|
21
|
+
return fileURLToPath(import.meta.resolve(specifier));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function createInjectSource(inject: Record<string, string | readonly string[]>, polyfills: readonly string[]) {
|
|
25
|
+
const lines: string[] = [];
|
|
26
|
+
for (const [index, [globalName, specifier]] of Object.entries(inject).entries()) {
|
|
27
|
+
const [moduleSpecifier, exportName] = typeof specifier === 'string' ? [specifier, 'default'] : specifier;
|
|
28
|
+
if (!moduleSpecifier || !exportName) {
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
lines.push(
|
|
32
|
+
`import { ${exportName} as inject${index} } from ${JSON.stringify(resolvePolyfill(moduleSpecifier))};`,
|
|
33
|
+
`globalThis.${globalName} = inject${index};`,
|
|
34
|
+
);
|
|
35
|
+
}
|
|
36
|
+
for (const polyfill of polyfills) {
|
|
37
|
+
lines.push(`import ${JSON.stringify(resolvePolyfill(polyfill))};`);
|
|
38
|
+
}
|
|
39
|
+
return lines.length > 0 ? lines.join('\n') : undefined;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Applies Cloudflare's unenv preset, as wrangler and the Vite plugin do: modules workerd has natively stay external,
|
|
44
|
+
* the rest are polyfilled, and globals like `process` are injected for older compatibility dates.
|
|
45
|
+
*/
|
|
46
|
+
export function getNodeJsCompat(worker: ResolvedWorker): NodeJsCompat | undefined {
|
|
47
|
+
const { compatibility_date: compatibilityDate, compatibility_flags: compatibilityFlags } = worker.config;
|
|
48
|
+
if (!miniflare.getNodeCompat(compatibilityDate, compatibilityFlags).isNodejsCompatEnabled) {
|
|
49
|
+
return undefined;
|
|
50
|
+
}
|
|
51
|
+
const { env } = defineEnv({ presets: [getCloudflarePreset({ compatibilityDate, compatibilityFlags })] });
|
|
52
|
+
const nativeModules = new Set(env.external);
|
|
53
|
+
const externals = new Map<string, string>();
|
|
54
|
+
const polyfills = new Map<string, string>();
|
|
55
|
+
for (const [specifier, target] of Object.entries(env.alias)) {
|
|
56
|
+
if (nativeModules.has(target)) {
|
|
57
|
+
externals.set(specifier, target);
|
|
58
|
+
} else {
|
|
59
|
+
polyfills.set(specifier, resolvePolyfill(target));
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return { externals, polyfills, injectSource: createInjectSource(env.inject, env.polyfill) };
|
|
63
|
+
}
|
package/src/options.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { RspackOptions } from '@rspack/core';
|
|
2
|
+
import type { Unstable_Config } from 'wrangler';
|
|
3
|
+
|
|
4
|
+
export type WorkerConfig = Unstable_Config;
|
|
5
|
+
|
|
6
|
+
/** Overrides merged into the Wrangler config after it loads, or a function that edits or returns overrides. */
|
|
7
|
+
export type WorkerConfigCustomizer = Partial<WorkerConfig> | ((config: WorkerConfig) => Partial<WorkerConfig> | void);
|
|
8
|
+
|
|
9
|
+
export interface AuxiliaryWorkerOptions {
|
|
10
|
+
/** Wrangler config for the auxiliary Worker, relative to the rspack `context`. */
|
|
11
|
+
configPath: string;
|
|
12
|
+
/** Changes the auxiliary Worker's config in code, applied after its config file loads. */
|
|
13
|
+
config?: WorkerConfigCustomizer;
|
|
14
|
+
/** Where `rspack build` writes it, relative to its Wrangler config. Defaults to `dist/<worker name>`. */
|
|
15
|
+
outputDir?: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface TunnelOptions {
|
|
19
|
+
/** An existing named tunnel with a route to the dev server. Without one, a Quick Tunnel gets a random trycloudflare.com URL. */
|
|
20
|
+
name?: string;
|
|
21
|
+
/** Email addresses or `*@domain` patterns allowed through a Quick Tunnel, which then asks visitors to sign in. */
|
|
22
|
+
allowedMail?: string[];
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface CloudflarePluginOptions {
|
|
26
|
+
/** Wrangler config file, relative to the rspack `context`. Defaults to the nearest wrangler.jsonc, wrangler.json or wrangler.toml at or above `context`. */
|
|
27
|
+
configPath?: string;
|
|
28
|
+
/** Changes the Worker config in code, applied after the config file loads. */
|
|
29
|
+
config?: WorkerConfigCustomizer;
|
|
30
|
+
/** Wrangler environment to use, like `wrangler --env`, for every Worker. Defaults to `CLOUDFLARE_ENV`. */
|
|
31
|
+
environment?: string;
|
|
32
|
+
/** More Workers the entry Worker reaches through service bindings, run and built alongside it. */
|
|
33
|
+
auxiliaryWorkers?: AuxiliaryWorkerOptions[];
|
|
34
|
+
/** Adjusts the rspack config used to bundle a Worker. Return a new config or mutate the one given. */
|
|
35
|
+
worker?: (config: RspackOptions, context: { name: string; }) => RspackOptions | void;
|
|
36
|
+
/** Where `rspack build` writes the Worker bundle and its generated `wrangler.json`, relative to the Wrangler config. Defaults to `dist/<worker name>`. */
|
|
37
|
+
outputDir?: string;
|
|
38
|
+
/** Where local binding state (KV, Durable Objects, etc.) lives in dev, relative to the Wrangler config. `false` keeps it in memory. Defaults to `.wrangler/state`, shared with `wrangler dev`. */
|
|
39
|
+
persistState?: boolean | { path: string; };
|
|
40
|
+
/** Port for the workerd inspector in dev, or `false` to turn it off. Defaults to 9229, or the next free port. */
|
|
41
|
+
inspectorPort?: number | false;
|
|
42
|
+
/** Connects bindings marked `remote: true` to their real resources on Cloudflare in dev. `false` keeps every binding local. */
|
|
43
|
+
remoteBindings?: boolean;
|
|
44
|
+
/** Shares the dev server publicly through a Cloudflare Tunnel once it's listening. */
|
|
45
|
+
tunnel?: boolean | TunnelOptions;
|
|
46
|
+
}
|
package/src/routing.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
interface StaticRouting {
|
|
2
|
+
/** Paths that always go to the Worker. */
|
|
3
|
+
userWorker: RegExp[];
|
|
4
|
+
/** Paths that always skip the Worker, from `!/` rules. */
|
|
5
|
+
assetWorker: RegExp[];
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
function ruleToRegExp(rule: string) {
|
|
9
|
+
const escaped = rule.split('*').map(part => part.replaceAll(/[$()+.?[\\\]^{|}]/g, String.raw`\$&`));
|
|
10
|
+
return new RegExp(`^${escaped.join('.*')}$`);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Mirrors `assets.run_worker_first`, where `true` sends everything to the Worker and an array holds `/` and `!/` glob rules. */
|
|
14
|
+
export function parseStaticRouting(runWorkerFirst: boolean | string[] | undefined): StaticRouting {
|
|
15
|
+
if (runWorkerFirst === true) {
|
|
16
|
+
return { userWorker: [/^\/.*$/], assetWorker: [] };
|
|
17
|
+
}
|
|
18
|
+
const routing: StaticRouting = { userWorker: [], assetWorker: [] };
|
|
19
|
+
if (!Array.isArray(runWorkerFirst)) {
|
|
20
|
+
return routing;
|
|
21
|
+
}
|
|
22
|
+
for (const rule of runWorkerFirst) {
|
|
23
|
+
if (rule.startsWith('!/')) {
|
|
24
|
+
routing.assetWorker.push(ruleToRegExp(rule.slice(1)));
|
|
25
|
+
} else if (rule.startsWith('/')) {
|
|
26
|
+
routing.userWorker.push(ruleToRegExp(rule));
|
|
27
|
+
} else {
|
|
28
|
+
throw new Error(`Invalid \`run_worker_first\` rule '${rule}': rules must start with '/' or '!/'.`);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return routing;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
type Route = 'worker' | 'asset' | 'asset-then-worker';
|
|
35
|
+
|
|
36
|
+
/** Negative rules win over positive ones, matching Cloudflare's router. */
|
|
37
|
+
export function routeRequest(routing: StaticRouting, pathname: string, hasAssets: boolean): Route {
|
|
38
|
+
if (!hasAssets) {
|
|
39
|
+
return 'worker';
|
|
40
|
+
}
|
|
41
|
+
if (routing.assetWorker.some(rule => rule.test(pathname))) {
|
|
42
|
+
return 'asset';
|
|
43
|
+
}
|
|
44
|
+
if (routing.userWorker.some(rule => rule.test(pathname))) {
|
|
45
|
+
return 'worker';
|
|
46
|
+
}
|
|
47
|
+
return 'asset-then-worker';
|
|
48
|
+
}
|
package/src/tunnel.ts
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { createRequire } from 'node:module';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
|
|
5
|
+
import { unstable_resolveNamedTunnel } from 'wrangler';
|
|
6
|
+
|
|
7
|
+
import type { TunnelOptions, WorkerConfig } from './options.js';
|
|
8
|
+
import type { ChildProcess } from 'node:child_process';
|
|
9
|
+
|
|
10
|
+
const QUICK_TUNNEL_URL_RE = /https:\/\/[\da-z-]+\.trycloudflare\.com/;
|
|
11
|
+
// cloudflared logs this once the edge accepts the tunnel, which is when the public URL starts working
|
|
12
|
+
const CONNECTED_RE = /Registered tunnel connection/;
|
|
13
|
+
const STARTUP_TIMEOUT_MS = 30000;
|
|
14
|
+
|
|
15
|
+
export interface Tunnel {
|
|
16
|
+
urls: string[];
|
|
17
|
+
close: () => void;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function getWranglerBin() {
|
|
21
|
+
const require = createRequire(import.meta.url);
|
|
22
|
+
return path.join(path.dirname(require.resolve('wrangler/package.json')), 'bin', 'wrangler.js');
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function stopProcessTree(child: ChildProcess) {
|
|
26
|
+
if (child.exitCode !== null || child.pid === undefined) {
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
if (process.platform === 'win32') {
|
|
30
|
+
// Windows has no SIGTERM for wrangler to forward, so cloudflared would outlive it without killing the whole tree
|
|
31
|
+
spawn('taskkill', ['/pid', String(child.pid), '/t', '/f'], { stdio: 'ignore' });
|
|
32
|
+
} else {
|
|
33
|
+
child.kill('SIGTERM');
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function waitUntilConnected(child: ChildProcess, isNamed: boolean) {
|
|
38
|
+
return new Promise<string | undefined>((resolve, reject) => {
|
|
39
|
+
let output = '';
|
|
40
|
+
let quickUrl: string | undefined;
|
|
41
|
+
let settled = false;
|
|
42
|
+
function fail(error: Error) {
|
|
43
|
+
if (!settled) {
|
|
44
|
+
settled = true;
|
|
45
|
+
stopProcessTree(child);
|
|
46
|
+
reject(error);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
function onData(data: Buffer) {
|
|
50
|
+
// only kept for the error message, so a long-running tunnel doesn't keep growing it
|
|
51
|
+
if (output.length < 20000) {
|
|
52
|
+
output += String(data);
|
|
53
|
+
}
|
|
54
|
+
quickUrl ??= QUICK_TUNNEL_URL_RE.exec(output)?.[0];
|
|
55
|
+
if (!settled && CONNECTED_RE.test(output) && (isNamed || quickUrl)) {
|
|
56
|
+
settled = true;
|
|
57
|
+
resolve(quickUrl);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
AbortSignal.timeout(STARTUP_TIMEOUT_MS).addEventListener('abort', () => {
|
|
61
|
+
fail(new Error(`The tunnel didn't connect within ${STARTUP_TIMEOUT_MS / 1000}s:\n${output}`));
|
|
62
|
+
});
|
|
63
|
+
child.stdout?.on('data', onData);
|
|
64
|
+
child.stderr?.on('data', onData);
|
|
65
|
+
child.once('error', fail);
|
|
66
|
+
child.once('exit', (code) => {
|
|
67
|
+
fail(new Error(`wrangler tunnel exited with code ${String(code)}:\n${output}`));
|
|
68
|
+
});
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Shares the dev server through a Cloudflare Tunnel: a Quick Tunnel on a random trycloudflare.com URL, or a named
|
|
74
|
+
* tunnel whose routes point at the dev server. wrangler runs it, so it downloads and updates cloudflared as needed.
|
|
75
|
+
*/
|
|
76
|
+
export async function startTunnel(options: { origin: URL; tunnel: TunnelOptions; config: WorkerConfig; cwd: string; }): Promise<Tunnel> {
|
|
77
|
+
const { origin, tunnel, config } = options;
|
|
78
|
+
const args = ['tunnel'];
|
|
79
|
+
const env: NodeJS.ProcessEnv = { ...process.env };
|
|
80
|
+
let urls: string[] = [];
|
|
81
|
+
if (tunnel.name === undefined) {
|
|
82
|
+
args.push('quick-start', origin.href, ...(tunnel.allowedMail ?? []).flatMap(mail => ['--allowed-mail', mail]));
|
|
83
|
+
if (origin.protocol === 'https:') {
|
|
84
|
+
// the dev server's certificate is for the developer's own hostname, never the loopback address cloudflared dials
|
|
85
|
+
env.NO_TLS_VERIFY = 'true';
|
|
86
|
+
}
|
|
87
|
+
} else {
|
|
88
|
+
if (tunnel.allowedMail?.length) {
|
|
89
|
+
throw new Error('`tunnel.allowedMail` only works with Quick Tunnels; protect a named tunnel with Cloudflare Access instead.');
|
|
90
|
+
}
|
|
91
|
+
// also checks the tunnel has a route to this dev server, which is the usual setup mistake
|
|
92
|
+
const { hostnames } = await unstable_resolveNamedTunnel(tunnel.name, origin, {
|
|
93
|
+
accountId: config.account_id,
|
|
94
|
+
complianceRegion: config.compliance_region,
|
|
95
|
+
});
|
|
96
|
+
urls = hostnames.map(hostname => `https://${hostname}`);
|
|
97
|
+
args.push('run', tunnel.name);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const child = spawn(process.execPath, [getWranglerBin(), ...args], { cwd: options.cwd, env, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
101
|
+
const quickUrl = await waitUntilConnected(child, tunnel.name !== undefined);
|
|
102
|
+
if (quickUrl) {
|
|
103
|
+
urls = [quickUrl];
|
|
104
|
+
}
|
|
105
|
+
return { urls, close: () => stopProcessTree(child) };
|
|
106
|
+
}
|