rspack-plugin-cloudflare 0.0.1-stage → 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/dist/index.js ADDED
@@ -0,0 +1,3599 @@
1
+ import { createRequire, isBuiltin } from "node:module";
2
+ import fs, { existsSync, readFileSync } from "node:fs";
3
+ import fs$1 from "node:fs/promises";
4
+ import path, { relative } from "node:path";
5
+ import { maybeStartOrUpdateRemoteProxySession, unstable_convertConfigBindingsToStartWorkerBindings, unstable_getMiniflareWorkerOptions, unstable_getVarsForDev, unstable_printBindings, unstable_readConfig, unstable_resolveNamedTunnel } from "wrangler";
6
+ import { createHash, randomUUID } from "node:crypto";
7
+ import { fileURLToPath } from "node:url";
8
+ import { getCloudflarePreset } from "@cloudflare/unenv-preset";
9
+ import * as miniflare from "miniflare";
10
+ import { defineEnv } from "unenv";
11
+ import { WebSocketServer } from "ws";
12
+ import { cleanupContainers, createContainerDevPlan, generateContainerBuildId, prepareContainerImagesForDev, resolveDockerHost } from "@cloudflare/containers-shared";
13
+ import { Readable } from "node:stream";
14
+ import net from "node:net";
15
+ import { spawn } from "node:child_process";
16
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod, mod.exports), cb = null), mod.exports);
17
+ // src/module-rules.ts
18
+ const DEFAULT_RULES = [
19
+ {
20
+ type: "Text",
21
+ globs: [
22
+ "**/*.txt",
23
+ "**/*.html",
24
+ "**/*.sql"
25
+ ]
26
+ },
27
+ {
28
+ type: "Data",
29
+ globs: ["**/*.bin"]
30
+ },
31
+ {
32
+ type: "CompiledWasm",
33
+ globs: ["**/*.wasm", "**/*.wasm?module"]
34
+ }
35
+ ];
36
+ const MODULE_TYPES = [
37
+ "CompiledWasm",
38
+ "Data",
39
+ "Text"
40
+ ];
41
+ function isModuleType(type) {
42
+ return MODULE_TYPES.includes(type);
43
+ }
44
+ /** Maps file extensions to the non-JS module type wrangler would give them, with config rules taking precedence. */
45
+ function getModuleTypes(worker) {
46
+ const types = /* @__PURE__ */ new Map();
47
+ for (const rule of [...worker.config.rules, ...DEFAULT_RULES]) {
48
+ if (!isModuleType(rule.type)) continue;
49
+ for (const glob of rule.globs) {
50
+ const extension = path.extname(glob.replace(/\?.*$/, ""));
51
+ if (extension && !types.has(extension)) types.set(extension, rule.type);
52
+ }
53
+ }
54
+ return types;
55
+ }
56
+ // src/nodejs-compat.ts
57
+ function resolvePolyfill(specifier) {
58
+ return fileURLToPath(import.meta.resolve(specifier));
59
+ }
60
+ function createInjectSource(inject, polyfills) {
61
+ const lines = [];
62
+ for (const [index, [globalName, specifier]] of Object.entries(inject).entries()) {
63
+ const [moduleSpecifier, exportName] = typeof specifier === "string" ? [specifier, "default"] : specifier;
64
+ if (!moduleSpecifier || !exportName) continue;
65
+ lines.push(`import { ${exportName} as inject${index} } from ${JSON.stringify(resolvePolyfill(moduleSpecifier))};`, `globalThis.${globalName} = inject${index};`);
66
+ }
67
+ for (const polyfill of polyfills) lines.push(`import ${JSON.stringify(resolvePolyfill(polyfill))};`);
68
+ return lines.length > 0 ? lines.join("\n") : void 0;
69
+ }
70
+ /**
71
+ * Applies Cloudflare's unenv preset, as wrangler and the Vite plugin do: modules workerd has natively stay external,
72
+ * the rest are polyfilled, and globals like `process` are injected for older compatibility dates.
73
+ */
74
+ function getNodeJsCompat(worker) {
75
+ const { compatibility_date: compatibilityDate, compatibility_flags: compatibilityFlags } = worker.config;
76
+ if (!miniflare.getNodeCompat(compatibilityDate, compatibilityFlags).isNodejsCompatEnabled) return;
77
+ const { env } = defineEnv({ presets: [getCloudflarePreset({
78
+ compatibilityDate,
79
+ compatibilityFlags
80
+ })] });
81
+ const nativeModules = new Set(env.external);
82
+ const externals = /* @__PURE__ */ new Map();
83
+ const polyfills = /* @__PURE__ */ new Map();
84
+ for (const [specifier, target] of Object.entries(env.alias)) if (nativeModules.has(target)) externals.set(specifier, target);
85
+ else polyfills.set(specifier, resolvePolyfill(target));
86
+ return {
87
+ externals,
88
+ polyfills,
89
+ injectSource: createInjectSource(env.inject, env.polyfill)
90
+ };
91
+ }
92
+ // src/worker-config.ts
93
+ const PLUGIN_NAME$2 = "rspack-plugin-cloudflare";
94
+ const TYPESCRIPT_RE = /\.[cm]?tsx?$/;
95
+ 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;
96
+ const URL_QUERY_RE = /\?(?:[^#]*&)?url(?:[&=#]|$)/;
97
+ /** Output subdirectory for assets Worker code imports, laid out the way the assets directory serves them. */
98
+ const IMPORTED_ASSETS_DIR = "imported-assets";
99
+ /** Copies imported `.wasm`/`.bin` files next to the bundle, where workerd loads them as their own modules. */
100
+ var AdditionalModulesPlugin = class {
101
+ #files = /* @__PURE__ */ new Map();
102
+ /** Every file emitted so far; dev passes these to Miniflare, since rspack's incremental asset list can leave them out. */
103
+ get modules() {
104
+ return [...this.#files].map(([fileName, { type }]) => {
105
+ return {
106
+ fileName,
107
+ type
108
+ };
109
+ });
110
+ }
111
+ /** Records a file to emit and returns the specifier the bundle should import it by. */
112
+ add(sourcePath, type) {
113
+ const fileName = `${createHash("sha1").update(fs.readFileSync(sourcePath)).digest("hex").slice(0, 16)}-${path.basename(sourcePath)}`;
114
+ this.#files.set(fileName, {
115
+ sourcePath,
116
+ type
117
+ });
118
+ return `./${fileName}`;
119
+ }
120
+ apply(compiler) {
121
+ const { Compilation, sources } = compiler.rspack;
122
+ compiler.hooks.thisCompilation.tap(PLUGIN_NAME$2, (compilation) => {
123
+ compilation.hooks.processAssets.tap({
124
+ name: PLUGIN_NAME$2,
125
+ stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL
126
+ }, () => {
127
+ for (const [fileName, { sourcePath }] of this.#files) {
128
+ compilation.emitAsset(fileName, new sources.RawSource(fs.readFileSync(sourcePath)));
129
+ compilation.fileDependencies.add(sourcePath);
130
+ }
131
+ });
132
+ });
133
+ }
134
+ };
135
+ function createExternals(nodeJsCompat, moduleTypes, additionalModules) {
136
+ return ({ request, context }, callback) => {
137
+ if (!request) {
138
+ callback();
139
+ return;
140
+ }
141
+ if (request.startsWith("cloudflare:")) {
142
+ callback(void 0, request);
143
+ return;
144
+ }
145
+ if (nodeJsCompat) {
146
+ const native = nodeJsCompat.externals.get(request);
147
+ if (native) {
148
+ callback(void 0, native);
149
+ return;
150
+ }
151
+ if (isBuiltin(request) && !nodeJsCompat.polyfills.has(request)) {
152
+ callback(void 0, request.startsWith("node:") ? request : `node:${request}`);
153
+ return;
154
+ }
155
+ }
156
+ const filePath = request.replace(/\?.*$/, "");
157
+ const type = moduleTypes.get(path.extname(filePath));
158
+ if ((type === "CompiledWasm" || type === "Data") && !URL_QUERY_RE.test(request) && context && (filePath.startsWith(".") || path.isAbsolute(filePath))) {
159
+ callback(void 0, additionalModules.add(path.resolve(context, filePath), type));
160
+ return;
161
+ }
162
+ callback();
163
+ };
164
+ }
165
+ /** Text modules inline as strings; with an assets directory, static files and `?url` imports become URLs served from it. */
166
+ function getAssetRules(worker, textExtensions) {
167
+ const textRule = {
168
+ test: (file) => textExtensions.has(path.extname(file)),
169
+ type: "asset/source"
170
+ };
171
+ if (!worker.assets) return [textRule];
172
+ const generator = {
173
+ filename: "assets/[name].[contenthash:8][ext]",
174
+ outputPath: IMPORTED_ASSETS_DIR,
175
+ publicPath: "/"
176
+ };
177
+ return [
178
+ {
179
+ resourceQuery: URL_QUERY_RE,
180
+ type: "asset/resource",
181
+ generator
182
+ },
183
+ textRule,
184
+ {
185
+ test: ASSET_RE,
186
+ type: "asset/resource",
187
+ generator
188
+ }
189
+ ];
190
+ }
191
+ /** Builds the rspack config for the Worker bundle: a single ESM file workerd can load as-is. */
192
+ function createWorkerConfig(options) {
193
+ const { compiler, worker, pluginOptions, outputDir, entry, entrySource, mode, hot = false, publicPath = "/" } = options;
194
+ const { rspack } = compiler;
195
+ const moduleTypes = getModuleTypes(worker);
196
+ const textExtensions = new Set([...moduleTypes].filter(([, type]) => type === "Text").map(([extension]) => extension));
197
+ const additionalModules = new AdditionalModulesPlugin();
198
+ const nodeJsCompat = getNodeJsCompat(worker);
199
+ const virtualModules = {};
200
+ const entries = [entry];
201
+ if (entrySource !== void 0) virtualModules[entry] = entrySource;
202
+ if (nodeJsCompat?.injectSource) {
203
+ const injectPath = path.join(worker.rootDir, ".wrangler", "tmp", `rspack-${worker.name}`, "nodejs-compat-inject.js");
204
+ virtualModules[injectPath] = nodeJsCompat.injectSource;
205
+ entries.unshift(injectPath);
206
+ }
207
+ const plugins = [
208
+ new rspack.DefinePlugin(worker.config.define),
209
+ new rspack.optimize.LimitChunkCountPlugin({ maxChunks: 1 }),
210
+ additionalModules
211
+ ];
212
+ const polyfills = nodeJsCompat?.polyfills;
213
+ if (polyfills && polyfills.size > 0) plugins.push(new rspack.NormalModuleReplacementPlugin(/^(?:node:)?[a-z_]/, (resource) => {
214
+ const polyfill = polyfills.get(resource.request);
215
+ if (polyfill) resource.request = polyfill;
216
+ }));
217
+ const virtualModulesPlugin = new rspack.experiments.VirtualModulesPlugin(virtualModules);
218
+ plugins.push(virtualModulesPlugin);
219
+ if (hot) plugins.push(new rspack.HotModuleReplacementPlugin());
220
+ let config = {
221
+ name: `cloudflare:${worker.name}`,
222
+ mode,
223
+ context: worker.rootDir,
224
+ target: ["webworker", "es2024"],
225
+ entry: { index: entries },
226
+ output: {
227
+ path: outputDir,
228
+ filename: "index.js",
229
+ module: true,
230
+ chunkFormat: "module",
231
+ library: { type: "module" },
232
+ clean: true,
233
+ publicPath
234
+ },
235
+ externalsType: "module-import",
236
+ externals: [createExternals(nodeJsCompat, moduleTypes, additionalModules)],
237
+ resolve: {
238
+ extensions: [
239
+ ".ts",
240
+ ".tsx",
241
+ ".mts",
242
+ ".cts",
243
+ ".js",
244
+ ".mjs",
245
+ ".cjs",
246
+ ".json"
247
+ ],
248
+ extensionAlias: {
249
+ ".js": [
250
+ ".ts",
251
+ ".tsx",
252
+ ".js"
253
+ ],
254
+ ".mjs": [".mts", ".mjs"]
255
+ },
256
+ conditionNames: [
257
+ "workerd",
258
+ "worker",
259
+ "browser",
260
+ "module",
261
+ "import",
262
+ "default"
263
+ ],
264
+ alias: worker.config.alias
265
+ },
266
+ module: { rules: [{
267
+ test: TYPESCRIPT_RE,
268
+ loader: "builtin:swc-loader",
269
+ options: { jsc: {
270
+ parser: {
271
+ syntax: "typescript",
272
+ tsx: true,
273
+ decorators: true
274
+ },
275
+ target: "es2024"
276
+ } },
277
+ type: "javascript/auto"
278
+ }, { oneOf: getAssetRules(worker, textExtensions) }] },
279
+ devtool: "source-map",
280
+ optimization: {
281
+ minimize: false,
282
+ emitOnErrors: false
283
+ },
284
+ plugins,
285
+ performance: { hints: false },
286
+ watchOptions: { ignored: /[/\\](?:\.git|node_modules|\.wrangler)[/\\]/ },
287
+ stats: "errors-warnings",
288
+ infrastructureLogging: compiler.options.infrastructureLogging
289
+ };
290
+ if (pluginOptions.worker) config = pluginOptions.worker(config, { name: worker.name }) ?? config;
291
+ return {
292
+ config,
293
+ virtualModules: virtualModulesPlugin,
294
+ additionalModules
295
+ };
296
+ }
297
+ // src/build.ts
298
+ const OMITTED_CONFIG_KEYS = /* @__PURE__ */ new Set([
299
+ "configPath",
300
+ "userConfigPath",
301
+ "topLevelName",
302
+ "definedEnvironments",
303
+ "targetEnvironment",
304
+ "build",
305
+ "define",
306
+ "alias",
307
+ "tsconfig",
308
+ "find_additional_modules",
309
+ "base_dir",
310
+ "preserve_file_names"
311
+ ]);
312
+ /** The Wrangler config `wrangler deploy` reads for the built Worker, with every path rebased onto the output directory. */
313
+ function createOutputConfig(worker) {
314
+ const rebase = (filePath) => path.relative(worker.outputDir, path.resolve(worker.rootDir, filePath)).replaceAll("\\", "/") || ".";
315
+ const config = Object.fromEntries(Object.entries(worker.config).filter(([key]) => !OMITTED_CONFIG_KEYS.has(key)));
316
+ if (worker.config.unsafe && Object.keys(worker.config.unsafe).length === 0) delete config.unsafe;
317
+ const binaryRules = worker.config.rules.filter((rule) => rule.type === "CompiledWasm" || rule.type === "Data");
318
+ const bundled = worker.main ? {
319
+ main: "index.js",
320
+ no_bundle: true,
321
+ rules: [{
322
+ type: "ESModule",
323
+ globs: ["**/*.js", "**/*.mjs"]
324
+ }, ...binaryRules]
325
+ } : { main: void 0 };
326
+ return {
327
+ ...config,
328
+ ...bundled,
329
+ assets: worker.assets ? {
330
+ ...worker.config.assets,
331
+ directory: rebase(worker.assets.directory)
332
+ } : void 0,
333
+ containers: worker.config.containers?.map((container) => {
334
+ const rebased = { ...container };
335
+ if (container.image && path.isAbsolute(container.image)) rebased.image = rebase(container.image);
336
+ if (container.image_build_context) rebased.image_build_context = rebase(container.image_build_context);
337
+ return rebased;
338
+ }),
339
+ upload_source_maps: worker.config.upload_source_maps ?? true
340
+ };
341
+ }
342
+ async function runCompiler(compiler) {
343
+ try {
344
+ return await new Promise((resolve, reject) => {
345
+ compiler.run((error, stats) => {
346
+ if (error || !stats) reject(error ?? /* @__PURE__ */ new Error("Worker build produced no stats"));
347
+ else resolve(stats);
348
+ });
349
+ });
350
+ } finally {
351
+ await new Promise((resolve) => {
352
+ compiler.close(() => resolve());
353
+ });
354
+ }
355
+ }
356
+ /** The local secrets for this environment, written beside the build so `wrangler dev` can preview it like the Vite plugin's `vite preview`. */
357
+ function createDevVars(worker) {
358
+ const vars = unstable_getVarsForDev(worker.configPath, void 0, {}, worker.environment, true, worker.config.secrets);
359
+ const lines = Object.entries(vars).map(([key, binding]) => `${key}=${JSON.stringify(String(binding.value))}`);
360
+ return lines.length > 0 ? `${lines.join("\n")}\n` : void 0;
361
+ }
362
+ /** Bundles one Worker into its output directory beside the `wrangler.json` that deploys it, returning that config's path. */
363
+ async function buildWorker(compiler, worker, pluginOptions) {
364
+ if (worker.main) {
365
+ const { config } = createWorkerConfig({
366
+ compiler,
367
+ worker,
368
+ pluginOptions,
369
+ outputDir: worker.outputDir,
370
+ entry: worker.main,
371
+ mode: compiler.options.mode === "production" ? "production" : "development"
372
+ });
373
+ const stats = await runCompiler(compiler.rspack.rspack(config));
374
+ if (stats.hasErrors()) throw new Error(`Worker "${worker.name}" build failed:\n${stats.toString({
375
+ preset: "errors-only",
376
+ colors: false
377
+ })}`);
378
+ } else {
379
+ await fs$1.rm(worker.outputDir, {
380
+ recursive: true,
381
+ force: true
382
+ });
383
+ await fs$1.mkdir(worker.outputDir, { recursive: true });
384
+ }
385
+ const outputConfigPath = path.join(worker.outputDir, "wrangler.json");
386
+ await fs$1.writeFile(outputConfigPath, JSON.stringify(createOutputConfig(worker), null, " "));
387
+ const devVars = createDevVars(worker);
388
+ if (devVars) await fs$1.writeFile(path.join(worker.outputDir, ".dev.vars"), devVars);
389
+ return outputConfigPath;
390
+ }
391
+ /** Moves assets the Worker imported into its assets directory, once the client build has emitted (and maybe cleaned) it. */
392
+ async function copyImportedAssets(workers) {
393
+ for (const worker of workers) {
394
+ const source = path.join(worker.outputDir, IMPORTED_ASSETS_DIR);
395
+ if (!worker.assets || !existsSync(source)) continue;
396
+ await fs$1.cp(source, worker.assets.directory, { recursive: true });
397
+ await fs$1.rm(source, {
398
+ recursive: true,
399
+ force: true
400
+ });
401
+ }
402
+ }
403
+ /** Builds every Worker, entry first, and writes the redirect `wrangler deploy` follows to the built configs. */
404
+ async function buildWorkers(options) {
405
+ const { compiler, workers, pluginOptions } = options;
406
+ const [entry] = workers;
407
+ if (!entry) return;
408
+ const configPaths = [];
409
+ for (const worker of workers) configPaths.push(await buildWorker(compiler, worker, pluginOptions));
410
+ const deployConfigPath = path.join(entry.rootDir, ".wrangler", "deploy", "config.json");
411
+ const relativeToDeploy = (filePath) => path.relative(path.dirname(deployConfigPath), filePath).replaceAll("\\", "/");
412
+ const [entryConfigPath, ...auxiliaryConfigPaths] = configPaths;
413
+ await fs$1.mkdir(path.dirname(deployConfigPath), { recursive: true });
414
+ await fs$1.writeFile(deployConfigPath, JSON.stringify({
415
+ configPath: entryConfigPath && relativeToDeploy(entryConfigPath),
416
+ auxiliaryWorkers: auxiliaryConfigPaths.map((configPath) => {
417
+ return { configPath: relativeToDeploy(configPath) };
418
+ })
419
+ }));
420
+ }
421
+ // src/config.ts
422
+ const CONFIG_FILE_NAMES = [
423
+ "wrangler.jsonc",
424
+ "wrangler.json",
425
+ "wrangler.toml"
426
+ ];
427
+ function findConfigPath(context, configPath) {
428
+ if (configPath) return path.resolve(context, configPath);
429
+ let directory = context;
430
+ while (true) {
431
+ for (const fileName of CONFIG_FILE_NAMES) {
432
+ const candidate = path.join(directory, fileName);
433
+ if (fs.existsSync(candidate)) return candidate;
434
+ }
435
+ const parent = path.dirname(directory);
436
+ if (parent === directory) throw new Error(`No Wrangler config found in ${context} or its parents. Looked for ${CONFIG_FILE_NAMES.join(", ")}.`);
437
+ directory = parent;
438
+ }
439
+ }
440
+ function isInside(parent, child) {
441
+ const relative = path.relative(parent, child);
442
+ return relative === "" || !relative.startsWith("..") && !path.isAbsolute(relative);
443
+ }
444
+ function isPlainObject$1(value) {
445
+ return typeof value === "object" && value !== null && !Array.isArray(value);
446
+ }
447
+ /** Deep-merges plain objects so an override like `{ vars: { A: '1' } }` keeps the other vars; arrays are replaced. */
448
+ function mergeConfig(target, overrides) {
449
+ for (const [key, value] of Object.entries(overrides)) {
450
+ const existing = Reflect.get(target, key);
451
+ if (isPlainObject$1(existing) && isPlainObject$1(value)) mergeConfig(existing, value);
452
+ else Reflect.set(target, key, value);
453
+ }
454
+ }
455
+ function applyCustomizer(config, customizer) {
456
+ if (!customizer) return;
457
+ const overrides = typeof customizer === "function" ? customizer(config) : customizer;
458
+ if (overrides) mergeConfig(config, overrides);
459
+ }
460
+ function resolveWorker(context, options) {
461
+ const configPath = findConfigPath(context, options.configPath);
462
+ const environment = options.environment ?? process.env.CLOUDFLARE_ENV;
463
+ const config = unstable_readConfig({
464
+ config: configPath,
465
+ env: environment
466
+ }, { preserveOriginalMain: true });
467
+ applyCustomizer(config, options.config);
468
+ const rootDir = path.dirname(configPath);
469
+ if (!config.main && !config.assets?.directory) throw new Error(`${configPath} needs a \`main\` Worker entry, or an \`assets.directory\` for an assets-only project.`);
470
+ if (!config.name) throw new Error(`${configPath} has no \`name\`.`);
471
+ const assets = config.assets?.directory ? {
472
+ directory: path.resolve(rootDir, config.assets.directory),
473
+ binding: config.assets.binding
474
+ } : void 0;
475
+ const outputDir = path.resolve(rootDir, options.outputDir ?? path.join("dist", config.name));
476
+ if (assets && isInside(assets.directory, outputDir)) throw new Error(`outputDir (${outputDir}) is inside the assets directory (${assets.directory}); the Worker bundle would be publicly served.`);
477
+ return {
478
+ config,
479
+ configPath,
480
+ environment,
481
+ name: config.name,
482
+ main: config.main ? path.resolve(rootDir, config.main) : void 0,
483
+ rootDir,
484
+ assets,
485
+ outputDir
486
+ };
487
+ }
488
+ /** Resolves an auxiliary Worker, which only the entry Worker's service bindings reach, so it can't serve assets. */
489
+ function resolveAuxiliaryWorker(context, options, auxiliary) {
490
+ const worker = resolveWorker(context, {
491
+ ...auxiliary,
492
+ environment: options.environment
493
+ });
494
+ if (!worker.main) throw new Error(`Auxiliary Worker config ${worker.configPath} needs a \`main\` entry.`);
495
+ if (worker.assets) throw new Error(`Auxiliary Worker "${worker.name}" has \`assets\`, which only the entry Worker supports.`);
496
+ return worker;
497
+ }
498
+ /** A resolver per Worker, entry first, so a config change can re-read just the Worker it belongs to. */
499
+ function getWorkerResolvers(context, options) {
500
+ return [() => resolveWorker(context, options), ...(options.auxiliaryWorkers ?? []).map((auxiliary) => () => resolveAuxiliaryWorker(context, options, auxiliary))];
501
+ }
502
+ // workers-sdk/packages/workers-shared/utils/configuration/constants.ts
503
+ const PERMITTED_STATUS_CODES = /* @__PURE__ */ new Set([
504
+ 200,
505
+ 301,
506
+ 302,
507
+ 303,
508
+ 307,
509
+ 308
510
+ ]);
511
+ const MAX_LINE_LENGTH = 2e3;
512
+ const MAX_STATIC_REDIRECT_RULES = 2e3;
513
+ const SPLAT_REGEX = /\*/g;
514
+ const PLACEHOLDER_REGEX = /:[A-Za-z]\w*/g;
515
+ // workers-sdk/packages/workers-shared/utils/configuration/constructConfiguration.ts
516
+ function constructRedirects({ redirects, redirectsFile, logger }) {
517
+ if (!redirects) return {};
518
+ const num_valid = redirects.rules.length;
519
+ const num_invalid = redirects.invalid.length;
520
+ const redirectsRelativePath = redirectsFile ? relative(process.cwd(), redirectsFile) : "";
521
+ logger.log(`✨ Parsed ${num_valid} valid redirect rule${num_valid === 1 ? "" : "s"}.`);
522
+ if (num_invalid > 0) {
523
+ let invalidRedirectRulesList = ``;
524
+ for (const { line, lineNumber, message } of redirects.invalid) {
525
+ invalidRedirectRulesList += `▶︎ ${message}\n`;
526
+ if (line) invalidRedirectRulesList += ` at ${redirectsRelativePath}${lineNumber ? `:${lineNumber}` : ""} | ${line}\n\n`;
527
+ }
528
+ logger.warn(`Found ${num_invalid} invalid redirect rule${num_invalid === 1 ? "" : "s"}:\n${invalidRedirectRulesList}`);
529
+ }
530
+ if (num_valid === 0) return {};
531
+ const staticRedirects = {};
532
+ const dynamicRedirects = {};
533
+ let canCreateStaticRule = true;
534
+ for (const rule of redirects.rules) {
535
+ if (!rule.from.match(SPLAT_REGEX) && !rule.from.match(PLACEHOLDER_REGEX)) {
536
+ if (canCreateStaticRule) {
537
+ staticRedirects[rule.from] = {
538
+ status: rule.status,
539
+ to: rule.to,
540
+ lineNumber: rule.lineNumber
541
+ };
542
+ continue;
543
+ } else logger.info(`The redirect rule ${rule.from} → ${rule.status} ${rule.to} could be made more performant by bringing it above any lines with splats or placeholders.`);
544
+ }
545
+ dynamicRedirects[rule.from] = {
546
+ status: rule.status,
547
+ to: rule.to
548
+ };
549
+ canCreateStaticRule = false;
550
+ }
551
+ return { redirects: {
552
+ version: 1,
553
+ staticRules: staticRedirects,
554
+ rules: dynamicRedirects
555
+ } };
556
+ }
557
+ function constructHeaders({ headers, headersFile, logger }) {
558
+ if (!headers) return {};
559
+ const num_valid = headers.rules.length;
560
+ const num_invalid = headers.invalid.length;
561
+ const headersRelativePath = headersFile ? relative(process.cwd(), headersFile) : "";
562
+ logger.log(`✨ Parsed ${num_valid} valid header rule${num_valid === 1 ? "" : "s"}.`);
563
+ if (num_invalid > 0) {
564
+ let invalidHeaderRulesList = ``;
565
+ for (const { line, lineNumber, message } of headers.invalid) {
566
+ invalidHeaderRulesList += `▶︎ ${message}\n`;
567
+ if (line) invalidHeaderRulesList += ` at ${headersRelativePath}${lineNumber ? `:${lineNumber}` : ""} | ${line}\n\n`;
568
+ }
569
+ logger.warn(`Found ${num_invalid} invalid header rule${num_invalid === 1 ? "" : "s"}:\n${invalidHeaderRulesList}`);
570
+ }
571
+ if (num_valid === 0) return {};
572
+ const rules = {};
573
+ for (const rule of headers.rules) {
574
+ const configuredRule = {};
575
+ if (Object.keys(rule.headers).length) configuredRule.set = rule.headers;
576
+ if (rule.unsetHeaders.length) configuredRule.unset = rule.unsetHeaders;
577
+ rules[rule.path] = configuredRule;
578
+ }
579
+ return { headers: {
580
+ version: 2,
581
+ rules
582
+ } };
583
+ }
584
+ // workers-sdk/packages/workers-shared/utils/configuration/validateURL.ts
585
+ const extractPathname = (path = "/", includeSearch, includeHash) => {
586
+ if (!path.startsWith("/")) path = `/${path}`;
587
+ const url = new URL(`//${path}`, "relative://");
588
+ return `${url.pathname}${includeSearch ? url.search : ""}${includeHash ? url.hash : ""}`;
589
+ };
590
+ const URL_REGEX = /^https:\/\/+(?<host>[^/]+)\/?(?<path>.*)/;
591
+ const HOST_WITH_PORT_REGEX = /.*:\d+$/;
592
+ const PATH_REGEX = /^\//;
593
+ const validateUrl = (token, onlyRelative = false, disallowPorts = false, includeSearch = false, includeHash = false) => {
594
+ const host = URL_REGEX.exec(token);
595
+ if (host && host.groups && host.groups.host) {
596
+ if (onlyRelative) return [void 0, `Only relative URLs are allowed. Skipping absolute URL ${token}.`];
597
+ if (disallowPorts && host.groups.host.match(HOST_WITH_PORT_REGEX)) return [void 0, `Specifying ports is not supported. Skipping absolute URL ${token}.`];
598
+ return [`https://${host.groups.host}${extractPathname(host.groups.path, includeSearch, includeHash)}`, void 0];
599
+ } else {
600
+ if (!token.startsWith("/") && onlyRelative) token = `/${token}`;
601
+ if (PATH_REGEX.exec(token)) try {
602
+ return [extractPathname(token, includeSearch, includeHash), void 0];
603
+ } catch {
604
+ return [void 0, `Error parsing URL segment ${token}. Skipping.`];
605
+ }
606
+ }
607
+ return [void 0, onlyRelative ? "URLs should begin with a forward-slash." : "URLs should either be relative (e.g. begin with a forward-slash), or use HTTPS (e.g. begin with \"https://\")."];
608
+ };
609
+ function urlHasHost(token) {
610
+ const host = URL_REGEX.exec(token);
611
+ return Boolean(host && host.groups && host.groups.host);
612
+ }
613
+ // workers-sdk/packages/workers-shared/utils/configuration/parseHeaders.ts
614
+ const LINE_IS_PROBABLY_A_PATH = /* @__PURE__ */ new RegExp(/^([^\s]+:\/\/|^\/)/);
615
+ function parseHeaders(input, { maxRules = 100, maxLineLength = MAX_LINE_LENGTH } = {}) {
616
+ const lines = input.split("\n");
617
+ const rules = [];
618
+ const invalid = [];
619
+ let rule = void 0;
620
+ let skipUntilNextPath = false;
621
+ for (let i = 0; i < lines.length; i++) {
622
+ const line = (lines[i] || "").trim();
623
+ if (line.length === 0 || line.startsWith("#")) continue;
624
+ if (line.length > maxLineLength) {
625
+ invalid.push({ message: `Ignoring line ${i + 1} as it exceeds the maximum allowed length of ${maxLineLength}.` });
626
+ continue;
627
+ }
628
+ if (LINE_IS_PROBABLY_A_PATH.test(line)) {
629
+ skipUntilNextPath = false;
630
+ if (rules.length >= maxRules) {
631
+ invalid.push({ message: `Maximum number of rules supported is ${maxRules}. Skipping remaining ${lines.length - i} lines of file.` });
632
+ break;
633
+ }
634
+ if (rule) {
635
+ if (isValidRule(rule)) rules.push({
636
+ path: rule.path,
637
+ headers: rule.headers,
638
+ unsetHeaders: rule.unsetHeaders
639
+ });
640
+ else invalid.push({
641
+ line: rule.line,
642
+ lineNumber: i + 1,
643
+ message: "No headers specified"
644
+ });
645
+ }
646
+ const [path, pathError] = validateUrl(line, false, true);
647
+ if (pathError) {
648
+ invalid.push({
649
+ line,
650
+ lineNumber: i + 1,
651
+ message: pathError
652
+ });
653
+ rule = void 0;
654
+ skipUntilNextPath = true;
655
+ continue;
656
+ }
657
+ const wildcardError = validateNoMultipleWildcards(path);
658
+ if (wildcardError) {
659
+ invalid.push({
660
+ line,
661
+ lineNumber: i + 1,
662
+ message: wildcardError
663
+ });
664
+ rule = void 0;
665
+ skipUntilNextPath = true;
666
+ continue;
667
+ }
668
+ rule = {
669
+ path,
670
+ line,
671
+ headers: {},
672
+ unsetHeaders: []
673
+ };
674
+ continue;
675
+ }
676
+ if (skipUntilNextPath) continue;
677
+ if (!line.includes(":")) {
678
+ if (!rule) invalid.push({
679
+ line,
680
+ lineNumber: i + 1,
681
+ message: "Expected a path beginning with at least one forward-slash"
682
+ });
683
+ else if (line.trim().startsWith("! ")) rule.unsetHeaders.push(line.trim().replace("! ", ""));
684
+ else invalid.push({
685
+ line,
686
+ lineNumber: i + 1,
687
+ message: "Expected a colon-separated header pair (e.g. name: value)"
688
+ });
689
+ continue;
690
+ }
691
+ const [rawName, ...rawValue] = line.split(":");
692
+ const name = (rawName || "").trim().toLowerCase();
693
+ if (name.includes(" ")) {
694
+ invalid.push({
695
+ line,
696
+ lineNumber: i + 1,
697
+ message: "Header name cannot include spaces"
698
+ });
699
+ continue;
700
+ }
701
+ const value = rawValue.join(":").trim();
702
+ if (name === "") {
703
+ invalid.push({
704
+ line,
705
+ lineNumber: i + 1,
706
+ message: "No header name specified"
707
+ });
708
+ continue;
709
+ }
710
+ if (value === "") {
711
+ invalid.push({
712
+ line,
713
+ lineNumber: i + 1,
714
+ message: "No header value specified"
715
+ });
716
+ continue;
717
+ }
718
+ if (!rule) {
719
+ invalid.push({
720
+ line,
721
+ lineNumber: i + 1,
722
+ message: `Path should come before header (${name}: ${value})`
723
+ });
724
+ continue;
725
+ }
726
+ const existingValues = rule.headers[name];
727
+ rule.headers[name] = existingValues ? `${existingValues}, ${value}` : value;
728
+ }
729
+ if (rule) {
730
+ if (isValidRule(rule)) rules.push({
731
+ path: rule.path,
732
+ headers: rule.headers,
733
+ unsetHeaders: rule.unsetHeaders
734
+ });
735
+ else invalid.push({
736
+ line: rule.line,
737
+ message: "No headers specified"
738
+ });
739
+ }
740
+ return {
741
+ rules,
742
+ invalid
743
+ };
744
+ }
745
+ function isValidRule(rule) {
746
+ return Object.keys(rule.headers).length > 0 || rule.unsetHeaders.length > 0;
747
+ }
748
+ /**
749
+ * At runtime, `*` wildcards are converted to `:splat` placeholders. This means
750
+ * a path with multiple wildcards, or a wildcard combined with an explicit
751
+ * `:splat` placeholder, would result in duplicate `:splat` parameters which is
752
+ * unsupported.
753
+ */
754
+ function validateNoMultipleWildcards(path) {
755
+ const wildcardCount = (path.match(SPLAT_REGEX) ?? []).length;
756
+ const hasSplatPlaceholder = /:splat(?!\w)/.test(path);
757
+ if (wildcardCount > 1) return `Only one wildcard is allowed per rule. Use a named placeholder (e.g. :project) instead. Skipping ${path}.`;
758
+ if (wildcardCount > 0 && hasSplatPlaceholder) return `Cannot combine a wildcard * with a :splat placeholder because wildcards are converted to :splat at runtime. Skipping ${path}.`;
759
+ }
760
+ // workers-sdk/packages/workers-shared/utils/configuration/parseRedirects.ts
761
+ function parseRedirects(input, { htmlHandling = void 0, maxStaticRules = MAX_STATIC_REDIRECT_RULES, maxDynamicRules = 100, maxLineLength = MAX_LINE_LENGTH } = {}) {
762
+ const lines = input.split("\n");
763
+ const rules = [];
764
+ const seen_paths = /* @__PURE__ */ new Set();
765
+ const invalid = [];
766
+ let staticRules = 0;
767
+ let dynamicRules = 0;
768
+ let canCreateStaticRule = true;
769
+ for (let i = 0; i < lines.length; i++) {
770
+ const line = (lines[i] || "").trim();
771
+ if (line.length === 0 || line.startsWith("#")) continue;
772
+ if (line.length > maxLineLength) {
773
+ invalid.push({ message: `Ignoring line ${i + 1} as it exceeds the maximum allowed length of ${maxLineLength}.` });
774
+ continue;
775
+ }
776
+ const tokens = line.replace(/\s+#.*$/, "").split(/\s+/);
777
+ if (tokens.length < 2 || tokens.length > 3) {
778
+ invalid.push({
779
+ line,
780
+ lineNumber: i + 1,
781
+ message: `Expected exactly 2 or 3 whitespace-separated tokens. Got ${tokens.length}.`
782
+ });
783
+ continue;
784
+ }
785
+ const [str_from, str_to, str_status = "302"] = tokens;
786
+ const fromResult = validateUrl(str_from, true, true, false, false);
787
+ if (fromResult[0] === void 0) {
788
+ invalid.push({
789
+ line,
790
+ lineNumber: i + 1,
791
+ message: fromResult[1]
792
+ });
793
+ continue;
794
+ }
795
+ const from = fromResult[0];
796
+ if (canCreateStaticRule && !from.match(SPLAT_REGEX) && !from.match(PLACEHOLDER_REGEX)) {
797
+ staticRules += 1;
798
+ if (staticRules > maxStaticRules) {
799
+ invalid.push({ message: `Maximum number of static rules supported is ${maxStaticRules}. Skipping line.` });
800
+ continue;
801
+ }
802
+ } else {
803
+ dynamicRules += 1;
804
+ canCreateStaticRule = false;
805
+ if (dynamicRules > maxDynamicRules) {
806
+ invalid.push({ message: `Maximum number of dynamic rules supported is ${maxDynamicRules}. Skipping remaining ${lines.length - i} lines of file.` });
807
+ break;
808
+ }
809
+ }
810
+ const toResult = validateUrl(str_to, false, false, true, true);
811
+ if (toResult[0] === void 0) {
812
+ invalid.push({
813
+ line,
814
+ lineNumber: i + 1,
815
+ message: toResult[1]
816
+ });
817
+ continue;
818
+ }
819
+ const to = toResult[0];
820
+ const status = Number(str_status);
821
+ if (isNaN(status) || !PERMITTED_STATUS_CODES.has(status)) {
822
+ invalid.push({
823
+ line,
824
+ lineNumber: i + 1,
825
+ message: `Valid status codes are 200, 301, 302 (default), 303, 307, or 308. Got ${str_status}.`
826
+ });
827
+ continue;
828
+ }
829
+ const hasRelativePath = !urlHasHost(to);
830
+ const hasWildcardToIndex = from.endsWith("/*") && /\/index(.html)?$/.test(to);
831
+ const hasRootToIndex = from.endsWith("/") && /\/index(.html)?$/.test(to);
832
+ if (hasRelativePath && (hasWildcardToIndex || hasRootToIndex && htmlHandling !== "none")) {
833
+ invalid.push({
834
+ line,
835
+ lineNumber: i + 1,
836
+ message: "Infinite loop detected in this rule and has been ignored. This will cause a redirect to strip `.html` or `/index` and end up triggering this rule again. Please fix or remove this rule to silence this warning."
837
+ });
838
+ continue;
839
+ }
840
+ if (seen_paths.has(from)) {
841
+ invalid.push({
842
+ line,
843
+ lineNumber: i + 1,
844
+ message: `Ignoring duplicate rule for path ${from}.`
845
+ });
846
+ continue;
847
+ }
848
+ seen_paths.add(from);
849
+ if (status === 200) {
850
+ if (urlHasHost(to)) {
851
+ invalid.push({
852
+ line,
853
+ lineNumber: i + 1,
854
+ message: `Proxy (200) redirects can only point to relative paths. Got ${to}`
855
+ });
856
+ continue;
857
+ }
858
+ }
859
+ rules.push({
860
+ from,
861
+ to,
862
+ status,
863
+ lineNumber: i + 1
864
+ });
865
+ }
866
+ return {
867
+ rules,
868
+ invalid
869
+ };
870
+ }
871
+ (/* @__PURE__ */ __commonJSMin(((exports, module) => {
872
+ function makeArray(subject) {
873
+ return Array.isArray(subject) ? subject : [subject];
874
+ }
875
+ const EMPTY = "";
876
+ const SPACE = " ";
877
+ const ESCAPE = "\\";
878
+ const REGEX_TEST_BLANK_LINE = /^\s+$/;
879
+ const REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/;
880
+ const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
881
+ const REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/;
882
+ const REGEX_SPLITALL_CRLF = /\r?\n/g;
883
+ const REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/;
884
+ const SLASH = "/";
885
+ let TMP_KEY_IGNORE = "node-ignore";
886
+ /* istanbul ignore else */
887
+ if (typeof Symbol !== "undefined") TMP_KEY_IGNORE = Symbol.for("node-ignore");
888
+ const KEY_IGNORE = TMP_KEY_IGNORE;
889
+ const define = (object, key, value) => Object.defineProperty(object, key, { value });
890
+ const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g;
891
+ const RETURN_FALSE = () => false;
892
+ const sanitizeRange = (range) => range.replace(REGEX_REGEXP_RANGE, (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) ? match : EMPTY);
893
+ const cleanRangeBackSlash = (slashes) => {
894
+ const { length } = slashes;
895
+ return slashes.slice(0, length - length % 2);
896
+ };
897
+ const REPLACERS = [
898
+ [/^\uFEFF/, () => EMPTY],
899
+ [/\\?\s+$/, (match) => match.indexOf("\\") === 0 ? SPACE : EMPTY],
900
+ [/\\\s/g, () => SPACE],
901
+ [/[\\$.|*+(){^]/g, (match) => `\\${match}`],
902
+ [/(?!\\)\?/g, () => "[^/]"],
903
+ [/^\//, () => "^"],
904
+ [/\//g, () => "\\/"],
905
+ [/^\^*\\\*\\\*\\\//, () => "^(?:.*\\/)?"],
906
+ [/^(?=[^^])/, function startingReplacer() {
907
+ return !/\/(?!$)/.test(this) ? "(?:^|\\/)" : "^";
908
+ }],
909
+ [/\\\/\\\*\\\*(?=\\\/|$)/g, (_, index, str) => index + 6 < str.length ? "(?:\\/[^\\/]+)*" : "\\/.+"],
910
+ [/(^|[^\\]+)(\\\*)+(?=.+)/g, (_, p1, p2) => {
911
+ return p1 + p2.replace(/\\\*/g, "[^\\/]*");
912
+ }],
913
+ [/\\\\\\(?=[$.|*+(){^])/g, () => ESCAPE],
914
+ [/\\\\/g, () => ESCAPE],
915
+ [/(\\)?\[([^\]/]*?)(\\*)($|\])/g, (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE ? `\\[${range}${cleanRangeBackSlash(endEscape)}${close}` : close === "]" ? endEscape.length % 2 === 0 ? `[${sanitizeRange(range)}${endEscape}]` : "[]" : "[]"],
916
+ [/(?:[^*])$/, (match) => /\/$/.test(match) ? `${match}$` : `${match}(?=$|\\/$)`],
917
+ [/(\^|\\\/)?\\\*$/, (_, p1) => {
918
+ return `${p1 ? `${p1}[^/]+` : "[^/]*"}(?=$|\\/$)`;
919
+ }]
920
+ ];
921
+ const regexCache = Object.create(null);
922
+ const makeRegex = (pattern, ignoreCase) => {
923
+ let source = regexCache[pattern];
924
+ if (!source) {
925
+ source = REPLACERS.reduce((prev, current) => prev.replace(current[0], current[1].bind(pattern)), pattern);
926
+ regexCache[pattern] = source;
927
+ }
928
+ return ignoreCase ? new RegExp(source, "i") : new RegExp(source);
929
+ };
930
+ const isString = (subject) => typeof subject === "string";
931
+ const checkPattern = (pattern) => pattern && isString(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern) && pattern.indexOf("#") !== 0;
932
+ const splitPattern = (pattern) => pattern.split(REGEX_SPLITALL_CRLF);
933
+ var IgnoreRule = class {
934
+ constructor(origin, pattern, negative, regex) {
935
+ this.origin = origin;
936
+ this.pattern = pattern;
937
+ this.negative = negative;
938
+ this.regex = regex;
939
+ }
940
+ };
941
+ const createRule = (pattern, ignoreCase) => {
942
+ const origin = pattern;
943
+ let negative = false;
944
+ if (pattern.indexOf("!") === 0) {
945
+ negative = true;
946
+ pattern = pattern.substr(1);
947
+ }
948
+ pattern = pattern.replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, "!").replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, "#");
949
+ const regex = makeRegex(pattern, ignoreCase);
950
+ return new IgnoreRule(origin, pattern, negative, regex);
951
+ };
952
+ const throwError = (message, Ctor) => {
953
+ throw new Ctor(message);
954
+ };
955
+ const checkPath = (path, originalPath, doThrow) => {
956
+ if (!isString(path)) return doThrow(`path must be a string, but got \`${originalPath}\``, TypeError);
957
+ if (!path) return doThrow(`path must not be empty`, TypeError);
958
+ if (checkPath.isNotRelative(path)) return doThrow(`path should be a \`path.relative()\`d string, but got "${originalPath}"`, RangeError);
959
+ return true;
960
+ };
961
+ const isNotRelative = (path) => REGEX_TEST_INVALID_PATH.test(path);
962
+ checkPath.isNotRelative = isNotRelative;
963
+ checkPath.convert = (p) => p;
964
+ var Ignore = class {
965
+ constructor({ ignorecase = true, ignoreCase = ignorecase, allowRelativePaths = false } = {}) {
966
+ define(this, KEY_IGNORE, true);
967
+ this._rules = [];
968
+ this._ignoreCase = ignoreCase;
969
+ this._allowRelativePaths = allowRelativePaths;
970
+ this._initCache();
971
+ }
972
+ _initCache() {
973
+ this._ignoreCache = Object.create(null);
974
+ this._testCache = Object.create(null);
975
+ }
976
+ _addPattern(pattern) {
977
+ if (pattern && pattern[KEY_IGNORE]) {
978
+ this._rules = this._rules.concat(pattern._rules);
979
+ this._added = true;
980
+ return;
981
+ }
982
+ if (checkPattern(pattern)) {
983
+ const rule = createRule(pattern, this._ignoreCase);
984
+ this._added = true;
985
+ this._rules.push(rule);
986
+ }
987
+ }
988
+ add(pattern) {
989
+ this._added = false;
990
+ makeArray(isString(pattern) ? splitPattern(pattern) : pattern).forEach(this._addPattern, this);
991
+ if (this._added) this._initCache();
992
+ return this;
993
+ }
994
+ addPattern(pattern) {
995
+ return this.add(pattern);
996
+ }
997
+ _testOne(path, checkUnignored) {
998
+ let ignored = false;
999
+ let unignored = false;
1000
+ this._rules.forEach((rule) => {
1001
+ const { negative } = rule;
1002
+ if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) return;
1003
+ if (rule.regex.test(path)) {
1004
+ ignored = !negative;
1005
+ unignored = negative;
1006
+ }
1007
+ });
1008
+ return {
1009
+ ignored,
1010
+ unignored
1011
+ };
1012
+ }
1013
+ _test(originalPath, cache, checkUnignored, slices) {
1014
+ const path = originalPath && checkPath.convert(originalPath);
1015
+ checkPath(path, originalPath, this._allowRelativePaths ? RETURN_FALSE : throwError);
1016
+ return this._t(path, cache, checkUnignored, slices);
1017
+ }
1018
+ _t(path, cache, checkUnignored, slices) {
1019
+ if (path in cache) return cache[path];
1020
+ if (!slices) slices = path.split(SLASH);
1021
+ slices.pop();
1022
+ if (!slices.length) return cache[path] = this._testOne(path, checkUnignored);
1023
+ const parent = this._t(slices.join(SLASH) + SLASH, cache, checkUnignored, slices);
1024
+ return cache[path] = parent.ignored ? parent : this._testOne(path, checkUnignored);
1025
+ }
1026
+ ignores(path) {
1027
+ return this._test(path, this._ignoreCache, false).ignored;
1028
+ }
1029
+ createFilter() {
1030
+ return (path) => !this.ignores(path);
1031
+ }
1032
+ filter(paths) {
1033
+ return makeArray(paths).filter(this.createFilter());
1034
+ }
1035
+ test(path) {
1036
+ return this._test(path, this._testCache, true);
1037
+ }
1038
+ };
1039
+ const factory = (options) => new Ignore(options);
1040
+ const isPathValid = (path) => checkPath(path && checkPath.convert(path), path, RETURN_FALSE);
1041
+ factory.isPathValid = isPathValid;
1042
+ factory.default = factory;
1043
+ module.exports = factory;
1044
+ /* istanbul ignore if */
1045
+ if (typeof process !== "undefined" && (process.env && process.env.IGNORE_TEST_WIN32 || process.platform === "win32")) {
1046
+ const makePosix = (str) => /^\\\\\?\\/.test(str) || /["<>|\u0000-\u001F]+/u.test(str) ? str : str.replace(/\\/g, "/");
1047
+ checkPath.convert = makePosix;
1048
+ const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
1049
+ checkPath.isNotRelative = (path) => REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path) || isNotRelative(path);
1050
+ }
1051
+ })))();
1052
+ const types$1 = {
1053
+ "application/prs.cww": ["cww"],
1054
+ "application/prs.xsf+xml": ["xsf"],
1055
+ "application/vnd.1000minds.decision-model+xml": ["1km"],
1056
+ "application/vnd.3gpp.pic-bw-large": ["plb"],
1057
+ "application/vnd.3gpp.pic-bw-small": ["psb"],
1058
+ "application/vnd.3gpp.pic-bw-var": ["pvb"],
1059
+ "application/vnd.3gpp2.tcap": ["tcap"],
1060
+ "application/vnd.3m.post-it-notes": ["pwn"],
1061
+ "application/vnd.accpac.simply.aso": ["aso"],
1062
+ "application/vnd.accpac.simply.imp": ["imp"],
1063
+ "application/vnd.acucobol": ["acu"],
1064
+ "application/vnd.acucorp": ["atc", "acutc"],
1065
+ "application/vnd.adobe.air-application-installer-package+zip": ["air"],
1066
+ "application/vnd.adobe.formscentral.fcdt": ["fcdt"],
1067
+ "application/vnd.adobe.fxp": ["fxp", "fxpl"],
1068
+ "application/vnd.adobe.xdp+xml": ["xdp"],
1069
+ "application/vnd.adobe.xfdf": ["*xfdf"],
1070
+ "application/vnd.age": ["age"],
1071
+ "application/vnd.ahead.space": ["ahead"],
1072
+ "application/vnd.airzip.filesecure.azf": ["azf"],
1073
+ "application/vnd.airzip.filesecure.azs": ["azs"],
1074
+ "application/vnd.amazon.ebook": ["azw"],
1075
+ "application/vnd.americandynamics.acc": ["acc"],
1076
+ "application/vnd.amiga.ami": ["ami"],
1077
+ "application/vnd.android.package-archive": ["apk"],
1078
+ "application/vnd.anser-web-certificate-issue-initiation": ["cii"],
1079
+ "application/vnd.anser-web-funds-transfer-initiation": ["fti"],
1080
+ "application/vnd.antix.game-component": ["atx"],
1081
+ "application/vnd.apple.installer+xml": ["mpkg"],
1082
+ "application/vnd.apple.keynote": ["key"],
1083
+ "application/vnd.apple.mpegurl": ["m3u8"],
1084
+ "application/vnd.apple.numbers": ["numbers"],
1085
+ "application/vnd.apple.pages": ["pages"],
1086
+ "application/vnd.apple.pkpass": ["pkpass"],
1087
+ "application/vnd.aristanetworks.swi": ["swi"],
1088
+ "application/vnd.astraea-software.iota": ["iota"],
1089
+ "application/vnd.audiograph": ["aep"],
1090
+ "application/vnd.autodesk.fbx": ["fbx"],
1091
+ "application/vnd.balsamiq.bmml+xml": ["bmml"],
1092
+ "application/vnd.blueice.multipass": ["mpm"],
1093
+ "application/vnd.bmi": ["bmi"],
1094
+ "application/vnd.businessobjects": ["rep"],
1095
+ "application/vnd.chemdraw+xml": ["cdxml"],
1096
+ "application/vnd.chipnuts.karaoke-mmd": ["mmd"],
1097
+ "application/vnd.cinderella": ["cdy"],
1098
+ "application/vnd.citationstyles.style+xml": ["csl"],
1099
+ "application/vnd.claymore": ["cla"],
1100
+ "application/vnd.cloanto.rp9": ["rp9"],
1101
+ "application/vnd.clonk.c4group": [
1102
+ "c4g",
1103
+ "c4d",
1104
+ "c4f",
1105
+ "c4p",
1106
+ "c4u"
1107
+ ],
1108
+ "application/vnd.cluetrust.cartomobile-config": ["c11amc"],
1109
+ "application/vnd.cluetrust.cartomobile-config-pkg": ["c11amz"],
1110
+ "application/vnd.commonspace": ["csp"],
1111
+ "application/vnd.contact.cmsg": ["cdbcmsg"],
1112
+ "application/vnd.cosmocaller": ["cmc"],
1113
+ "application/vnd.crick.clicker": ["clkx"],
1114
+ "application/vnd.crick.clicker.keyboard": ["clkk"],
1115
+ "application/vnd.crick.clicker.palette": ["clkp"],
1116
+ "application/vnd.crick.clicker.template": ["clkt"],
1117
+ "application/vnd.crick.clicker.wordbank": ["clkw"],
1118
+ "application/vnd.criticaltools.wbs+xml": ["wbs"],
1119
+ "application/vnd.ctc-posml": ["pml"],
1120
+ "application/vnd.cups-ppd": ["ppd"],
1121
+ "application/vnd.curl.car": ["car"],
1122
+ "application/vnd.curl.pcurl": ["pcurl"],
1123
+ "application/vnd.dart": ["dart"],
1124
+ "application/vnd.data-vision.rdz": ["rdz"],
1125
+ "application/vnd.dbf": ["dbf"],
1126
+ "application/vnd.dcmp+xml": ["dcmp"],
1127
+ "application/vnd.dece.data": [
1128
+ "uvf",
1129
+ "uvvf",
1130
+ "uvd",
1131
+ "uvvd"
1132
+ ],
1133
+ "application/vnd.dece.ttml+xml": ["uvt", "uvvt"],
1134
+ "application/vnd.dece.unspecified": ["uvx", "uvvx"],
1135
+ "application/vnd.dece.zip": ["uvz", "uvvz"],
1136
+ "application/vnd.denovo.fcselayout-link": ["fe_launch"],
1137
+ "application/vnd.dna": ["dna"],
1138
+ "application/vnd.dolby.mlp": ["mlp"],
1139
+ "application/vnd.dpgraph": ["dpg"],
1140
+ "application/vnd.dreamfactory": ["dfac"],
1141
+ "application/vnd.ds-keypoint": ["kpxx"],
1142
+ "application/vnd.dvb.ait": ["ait"],
1143
+ "application/vnd.dvb.service": ["svc"],
1144
+ "application/vnd.dynageo": ["geo"],
1145
+ "application/vnd.ecowin.chart": ["mag"],
1146
+ "application/vnd.enliven": ["nml"],
1147
+ "application/vnd.epson.esf": ["esf"],
1148
+ "application/vnd.epson.msf": ["msf"],
1149
+ "application/vnd.epson.quickanime": ["qam"],
1150
+ "application/vnd.epson.salt": ["slt"],
1151
+ "application/vnd.epson.ssf": ["ssf"],
1152
+ "application/vnd.eszigno3+xml": ["es3", "et3"],
1153
+ "application/vnd.ezpix-album": ["ez2"],
1154
+ "application/vnd.ezpix-package": ["ez3"],
1155
+ "application/vnd.fdf": ["*fdf"],
1156
+ "application/vnd.fdsn.mseed": ["mseed"],
1157
+ "application/vnd.fdsn.seed": ["seed", "dataless"],
1158
+ "application/vnd.flographit": ["gph"],
1159
+ "application/vnd.fluxtime.clip": ["ftc"],
1160
+ "application/vnd.framemaker": [
1161
+ "fm",
1162
+ "frame",
1163
+ "maker",
1164
+ "book"
1165
+ ],
1166
+ "application/vnd.frogans.fnc": ["fnc"],
1167
+ "application/vnd.frogans.ltf": ["ltf"],
1168
+ "application/vnd.fsc.weblaunch": ["fsc"],
1169
+ "application/vnd.fujitsu.oasys": ["oas"],
1170
+ "application/vnd.fujitsu.oasys2": ["oa2"],
1171
+ "application/vnd.fujitsu.oasys3": ["oa3"],
1172
+ "application/vnd.fujitsu.oasysgp": ["fg5"],
1173
+ "application/vnd.fujitsu.oasysprs": ["bh2"],
1174
+ "application/vnd.fujixerox.ddd": ["ddd"],
1175
+ "application/vnd.fujixerox.docuworks": ["xdw"],
1176
+ "application/vnd.fujixerox.docuworks.binder": ["xbd"],
1177
+ "application/vnd.fuzzysheet": ["fzs"],
1178
+ "application/vnd.genomatix.tuxedo": ["txd"],
1179
+ "application/vnd.geogebra.file": ["ggb"],
1180
+ "application/vnd.geogebra.slides": ["ggs"],
1181
+ "application/vnd.geogebra.tool": ["ggt"],
1182
+ "application/vnd.geometry-explorer": ["gex", "gre"],
1183
+ "application/vnd.geonext": ["gxt"],
1184
+ "application/vnd.geoplan": ["g2w"],
1185
+ "application/vnd.geospace": ["g3w"],
1186
+ "application/vnd.gmx": ["gmx"],
1187
+ "application/vnd.google-apps.document": ["gdoc"],
1188
+ "application/vnd.google-apps.drawing": ["gdraw"],
1189
+ "application/vnd.google-apps.form": ["gform"],
1190
+ "application/vnd.google-apps.jam": ["gjam"],
1191
+ "application/vnd.google-apps.map": ["gmap"],
1192
+ "application/vnd.google-apps.presentation": ["gslides"],
1193
+ "application/vnd.google-apps.script": ["gscript"],
1194
+ "application/vnd.google-apps.site": ["gsite"],
1195
+ "application/vnd.google-apps.spreadsheet": ["gsheet"],
1196
+ "application/vnd.google-earth.kml+xml": ["kml"],
1197
+ "application/vnd.google-earth.kmz": ["kmz"],
1198
+ "application/vnd.gov.sk.xmldatacontainer+xml": ["xdcf"],
1199
+ "application/vnd.grafeq": ["gqf", "gqs"],
1200
+ "application/vnd.groove-account": ["gac"],
1201
+ "application/vnd.groove-help": ["ghf"],
1202
+ "application/vnd.groove-identity-message": ["gim"],
1203
+ "application/vnd.groove-injector": ["grv"],
1204
+ "application/vnd.groove-tool-message": ["gtm"],
1205
+ "application/vnd.groove-tool-template": ["tpl"],
1206
+ "application/vnd.groove-vcard": ["vcg"],
1207
+ "application/vnd.hal+xml": ["hal"],
1208
+ "application/vnd.handheld-entertainment+xml": ["zmm"],
1209
+ "application/vnd.hbci": ["hbci"],
1210
+ "application/vnd.hhe.lesson-player": ["les"],
1211
+ "application/vnd.hp-hpgl": ["hpgl"],
1212
+ "application/vnd.hp-hpid": ["hpid"],
1213
+ "application/vnd.hp-hps": ["hps"],
1214
+ "application/vnd.hp-jlyt": ["jlt"],
1215
+ "application/vnd.hp-pcl": ["pcl"],
1216
+ "application/vnd.hp-pclxl": ["pclxl"],
1217
+ "application/vnd.hydrostatix.sof-data": ["sfd-hdstx"],
1218
+ "application/vnd.ibm.minipay": ["mpy"],
1219
+ "application/vnd.ibm.modcap": [
1220
+ "afp",
1221
+ "listafp",
1222
+ "list3820"
1223
+ ],
1224
+ "application/vnd.ibm.rights-management": ["irm"],
1225
+ "application/vnd.ibm.secure-container": ["sc"],
1226
+ "application/vnd.iccprofile": ["icc", "icm"],
1227
+ "application/vnd.igloader": ["igl"],
1228
+ "application/vnd.immervision-ivp": ["ivp"],
1229
+ "application/vnd.immervision-ivu": ["ivu"],
1230
+ "application/vnd.insors.igm": ["igm"],
1231
+ "application/vnd.intercon.formnet": ["xpw", "xpx"],
1232
+ "application/vnd.intergeo": ["i2g"],
1233
+ "application/vnd.intu.qbo": ["qbo"],
1234
+ "application/vnd.intu.qfx": ["qfx"],
1235
+ "application/vnd.ipunplugged.rcprofile": ["rcprofile"],
1236
+ "application/vnd.irepository.package+xml": ["irp"],
1237
+ "application/vnd.is-xpr": ["xpr"],
1238
+ "application/vnd.isac.fcs": ["fcs"],
1239
+ "application/vnd.jam": ["jam"],
1240
+ "application/vnd.jcp.javame.midlet-rms": ["rms"],
1241
+ "application/vnd.jisp": ["jisp"],
1242
+ "application/vnd.joost.joda-archive": ["joda"],
1243
+ "application/vnd.kahootz": ["ktz", "ktr"],
1244
+ "application/vnd.kde.karbon": ["karbon"],
1245
+ "application/vnd.kde.kchart": ["chrt"],
1246
+ "application/vnd.kde.kformula": ["kfo"],
1247
+ "application/vnd.kde.kivio": ["flw"],
1248
+ "application/vnd.kde.kontour": ["kon"],
1249
+ "application/vnd.kde.kpresenter": ["kpr", "kpt"],
1250
+ "application/vnd.kde.kspread": ["ksp"],
1251
+ "application/vnd.kde.kword": ["kwd", "kwt"],
1252
+ "application/vnd.kenameaapp": ["htke"],
1253
+ "application/vnd.kidspiration": ["kia"],
1254
+ "application/vnd.kinar": ["kne", "knp"],
1255
+ "application/vnd.koan": [
1256
+ "skp",
1257
+ "skd",
1258
+ "skt",
1259
+ "skm"
1260
+ ],
1261
+ "application/vnd.kodak-descriptor": ["sse"],
1262
+ "application/vnd.las.las+xml": ["lasxml"],
1263
+ "application/vnd.llamagraphics.life-balance.desktop": ["lbd"],
1264
+ "application/vnd.llamagraphics.life-balance.exchange+xml": ["lbe"],
1265
+ "application/vnd.lotus-1-2-3": ["123"],
1266
+ "application/vnd.lotus-approach": ["apr"],
1267
+ "application/vnd.lotus-freelance": ["pre"],
1268
+ "application/vnd.lotus-notes": ["nsf"],
1269
+ "application/vnd.lotus-organizer": ["org"],
1270
+ "application/vnd.lotus-screencam": ["scm"],
1271
+ "application/vnd.lotus-wordpro": ["lwp"],
1272
+ "application/vnd.macports.portpkg": ["portpkg"],
1273
+ "application/vnd.mapbox-vector-tile": ["mvt"],
1274
+ "application/vnd.mcd": ["mcd"],
1275
+ "application/vnd.medcalcdata": ["mc1"],
1276
+ "application/vnd.mediastation.cdkey": ["cdkey"],
1277
+ "application/vnd.mfer": ["mwf"],
1278
+ "application/vnd.mfmp": ["mfm"],
1279
+ "application/vnd.micrografx.flo": ["flo"],
1280
+ "application/vnd.micrografx.igx": ["igx"],
1281
+ "application/vnd.mif": ["mif"],
1282
+ "application/vnd.mobius.daf": ["daf"],
1283
+ "application/vnd.mobius.dis": ["dis"],
1284
+ "application/vnd.mobius.mbk": ["mbk"],
1285
+ "application/vnd.mobius.mqy": ["mqy"],
1286
+ "application/vnd.mobius.msl": ["msl"],
1287
+ "application/vnd.mobius.plc": ["plc"],
1288
+ "application/vnd.mobius.txf": ["txf"],
1289
+ "application/vnd.mophun.application": ["mpn"],
1290
+ "application/vnd.mophun.certificate": ["mpc"],
1291
+ "application/vnd.mozilla.xul+xml": ["xul"],
1292
+ "application/vnd.ms-artgalry": ["cil"],
1293
+ "application/vnd.ms-cab-compressed": ["cab"],
1294
+ "application/vnd.ms-excel": [
1295
+ "xls",
1296
+ "xlm",
1297
+ "xla",
1298
+ "xlc",
1299
+ "xlt",
1300
+ "xlw"
1301
+ ],
1302
+ "application/vnd.ms-excel.addin.macroenabled.12": ["xlam"],
1303
+ "application/vnd.ms-excel.sheet.binary.macroenabled.12": ["xlsb"],
1304
+ "application/vnd.ms-excel.sheet.macroenabled.12": ["xlsm"],
1305
+ "application/vnd.ms-excel.template.macroenabled.12": ["xltm"],
1306
+ "application/vnd.ms-fontobject": ["eot"],
1307
+ "application/vnd.ms-htmlhelp": ["chm"],
1308
+ "application/vnd.ms-ims": ["ims"],
1309
+ "application/vnd.ms-lrm": ["lrm"],
1310
+ "application/vnd.ms-officetheme": ["thmx"],
1311
+ "application/vnd.ms-outlook": ["msg"],
1312
+ "application/vnd.ms-pki.seccat": ["cat"],
1313
+ "application/vnd.ms-pki.stl": ["*stl"],
1314
+ "application/vnd.ms-powerpoint": [
1315
+ "ppt",
1316
+ "pps",
1317
+ "pot"
1318
+ ],
1319
+ "application/vnd.ms-powerpoint.addin.macroenabled.12": ["ppam"],
1320
+ "application/vnd.ms-powerpoint.presentation.macroenabled.12": ["pptm"],
1321
+ "application/vnd.ms-powerpoint.slide.macroenabled.12": ["sldm"],
1322
+ "application/vnd.ms-powerpoint.slideshow.macroenabled.12": ["ppsm"],
1323
+ "application/vnd.ms-powerpoint.template.macroenabled.12": ["potm"],
1324
+ "application/vnd.ms-project": ["*mpp", "mpt"],
1325
+ "application/vnd.ms-visio.viewer": ["vdx"],
1326
+ "application/vnd.ms-word.document.macroenabled.12": ["docm"],
1327
+ "application/vnd.ms-word.template.macroenabled.12": ["dotm"],
1328
+ "application/vnd.ms-works": [
1329
+ "wps",
1330
+ "wks",
1331
+ "wcm",
1332
+ "wdb"
1333
+ ],
1334
+ "application/vnd.ms-wpl": ["wpl"],
1335
+ "application/vnd.ms-xpsdocument": ["xps"],
1336
+ "application/vnd.mseq": ["mseq"],
1337
+ "application/vnd.musician": ["mus"],
1338
+ "application/vnd.muvee.style": ["msty"],
1339
+ "application/vnd.mynfc": ["taglet"],
1340
+ "application/vnd.nato.bindingdataobject+xml": ["bdo"],
1341
+ "application/vnd.neurolanguage.nlu": ["nlu"],
1342
+ "application/vnd.nitf": ["ntf", "nitf"],
1343
+ "application/vnd.noblenet-directory": ["nnd"],
1344
+ "application/vnd.noblenet-sealer": ["nns"],
1345
+ "application/vnd.noblenet-web": ["nnw"],
1346
+ "application/vnd.nokia.n-gage.ac+xml": ["*ac"],
1347
+ "application/vnd.nokia.n-gage.data": ["ngdat"],
1348
+ "application/vnd.nokia.n-gage.symbian.install": ["n-gage"],
1349
+ "application/vnd.nokia.radio-preset": ["rpst"],
1350
+ "application/vnd.nokia.radio-presets": ["rpss"],
1351
+ "application/vnd.novadigm.edm": ["edm"],
1352
+ "application/vnd.novadigm.edx": ["edx"],
1353
+ "application/vnd.novadigm.ext": ["ext"],
1354
+ "application/vnd.oasis.opendocument.chart": ["odc"],
1355
+ "application/vnd.oasis.opendocument.chart-template": ["otc"],
1356
+ "application/vnd.oasis.opendocument.database": ["odb"],
1357
+ "application/vnd.oasis.opendocument.formula": ["odf"],
1358
+ "application/vnd.oasis.opendocument.formula-template": ["odft"],
1359
+ "application/vnd.oasis.opendocument.graphics": ["odg"],
1360
+ "application/vnd.oasis.opendocument.graphics-template": ["otg"],
1361
+ "application/vnd.oasis.opendocument.image": ["odi"],
1362
+ "application/vnd.oasis.opendocument.image-template": ["oti"],
1363
+ "application/vnd.oasis.opendocument.presentation": ["odp"],
1364
+ "application/vnd.oasis.opendocument.presentation-template": ["otp"],
1365
+ "application/vnd.oasis.opendocument.spreadsheet": ["ods"],
1366
+ "application/vnd.oasis.opendocument.spreadsheet-template": ["ots"],
1367
+ "application/vnd.oasis.opendocument.text": ["odt"],
1368
+ "application/vnd.oasis.opendocument.text-master": ["odm"],
1369
+ "application/vnd.oasis.opendocument.text-template": ["ott"],
1370
+ "application/vnd.oasis.opendocument.text-web": ["oth"],
1371
+ "application/vnd.olpc-sugar": ["xo"],
1372
+ "application/vnd.oma.dd2+xml": ["dd2"],
1373
+ "application/vnd.openblox.game+xml": ["obgx"],
1374
+ "application/vnd.openofficeorg.extension": ["oxt"],
1375
+ "application/vnd.openstreetmap.data+xml": ["osm"],
1376
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation": ["pptx"],
1377
+ "application/vnd.openxmlformats-officedocument.presentationml.slide": ["sldx"],
1378
+ "application/vnd.openxmlformats-officedocument.presentationml.slideshow": ["ppsx"],
1379
+ "application/vnd.openxmlformats-officedocument.presentationml.template": ["potx"],
1380
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ["xlsx"],
1381
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.template": ["xltx"],
1382
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": ["docx"],
1383
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.template": ["dotx"],
1384
+ "application/vnd.osgeo.mapguide.package": ["mgp"],
1385
+ "application/vnd.osgi.dp": ["dp"],
1386
+ "application/vnd.osgi.subsystem": ["esa"],
1387
+ "application/vnd.palm": [
1388
+ "pdb",
1389
+ "pqa",
1390
+ "oprc"
1391
+ ],
1392
+ "application/vnd.pawaafile": ["paw"],
1393
+ "application/vnd.pg.format": ["str"],
1394
+ "application/vnd.pg.osasli": ["ei6"],
1395
+ "application/vnd.picsel": ["efif"],
1396
+ "application/vnd.pmi.widget": ["wg"],
1397
+ "application/vnd.pocketlearn": ["plf"],
1398
+ "application/vnd.powerbuilder6": ["pbd"],
1399
+ "application/vnd.previewsystems.box": ["box"],
1400
+ "application/vnd.procrate.brushset": ["brushset"],
1401
+ "application/vnd.procreate.brush": ["brush"],
1402
+ "application/vnd.procreate.dream": ["drm"],
1403
+ "application/vnd.proteus.magazine": ["mgz"],
1404
+ "application/vnd.publishare-delta-tree": ["qps"],
1405
+ "application/vnd.pvi.ptid1": ["ptid"],
1406
+ "application/vnd.pwg-xhtml-print+xml": ["xhtm"],
1407
+ "application/vnd.quark.quarkxpress": [
1408
+ "qxd",
1409
+ "qxt",
1410
+ "qwd",
1411
+ "qwt",
1412
+ "qxl",
1413
+ "qxb"
1414
+ ],
1415
+ "application/vnd.rar": ["rar"],
1416
+ "application/vnd.realvnc.bed": ["bed"],
1417
+ "application/vnd.recordare.musicxml": ["mxl"],
1418
+ "application/vnd.recordare.musicxml+xml": ["musicxml"],
1419
+ "application/vnd.rig.cryptonote": ["cryptonote"],
1420
+ "application/vnd.rim.cod": ["cod"],
1421
+ "application/vnd.rn-realmedia": ["rm"],
1422
+ "application/vnd.rn-realmedia-vbr": ["rmvb"],
1423
+ "application/vnd.route66.link66+xml": ["link66"],
1424
+ "application/vnd.sailingtracker.track": ["st"],
1425
+ "application/vnd.seemail": ["see"],
1426
+ "application/vnd.sema": ["sema"],
1427
+ "application/vnd.semd": ["semd"],
1428
+ "application/vnd.semf": ["semf"],
1429
+ "application/vnd.shana.informed.formdata": ["ifm"],
1430
+ "application/vnd.shana.informed.formtemplate": ["itp"],
1431
+ "application/vnd.shana.informed.interchange": ["iif"],
1432
+ "application/vnd.shana.informed.package": ["ipk"],
1433
+ "application/vnd.simtech-mindmapper": ["twd", "twds"],
1434
+ "application/vnd.smaf": ["mmf"],
1435
+ "application/vnd.smart.teacher": ["teacher"],
1436
+ "application/vnd.software602.filler.form+xml": ["fo"],
1437
+ "application/vnd.solent.sdkm+xml": ["sdkm", "sdkd"],
1438
+ "application/vnd.spotfire.dxp": ["dxp"],
1439
+ "application/vnd.spotfire.sfs": ["sfs"],
1440
+ "application/vnd.stardivision.calc": ["sdc"],
1441
+ "application/vnd.stardivision.draw": ["sda"],
1442
+ "application/vnd.stardivision.impress": ["sdd"],
1443
+ "application/vnd.stardivision.math": ["smf"],
1444
+ "application/vnd.stardivision.writer": ["sdw", "vor"],
1445
+ "application/vnd.stardivision.writer-global": ["sgl"],
1446
+ "application/vnd.stepmania.package": ["smzip"],
1447
+ "application/vnd.stepmania.stepchart": ["sm"],
1448
+ "application/vnd.sun.wadl+xml": ["wadl"],
1449
+ "application/vnd.sun.xml.calc": ["sxc"],
1450
+ "application/vnd.sun.xml.calc.template": ["stc"],
1451
+ "application/vnd.sun.xml.draw": ["sxd"],
1452
+ "application/vnd.sun.xml.draw.template": ["std"],
1453
+ "application/vnd.sun.xml.impress": ["sxi"],
1454
+ "application/vnd.sun.xml.impress.template": ["sti"],
1455
+ "application/vnd.sun.xml.math": ["sxm"],
1456
+ "application/vnd.sun.xml.writer": ["sxw"],
1457
+ "application/vnd.sun.xml.writer.global": ["sxg"],
1458
+ "application/vnd.sun.xml.writer.template": ["stw"],
1459
+ "application/vnd.sus-calendar": ["sus", "susp"],
1460
+ "application/vnd.svd": ["svd"],
1461
+ "application/vnd.symbian.install": ["sis", "sisx"],
1462
+ "application/vnd.syncml+xml": ["xsm"],
1463
+ "application/vnd.syncml.dm+wbxml": ["bdm"],
1464
+ "application/vnd.syncml.dm+xml": ["xdm"],
1465
+ "application/vnd.syncml.dmddf+xml": ["ddf"],
1466
+ "application/vnd.tao.intent-module-archive": ["tao"],
1467
+ "application/vnd.tcpdump.pcap": [
1468
+ "pcap",
1469
+ "cap",
1470
+ "dmp"
1471
+ ],
1472
+ "application/vnd.tmobile-livetv": ["tmo"],
1473
+ "application/vnd.trid.tpt": ["tpt"],
1474
+ "application/vnd.triscape.mxs": ["mxs"],
1475
+ "application/vnd.trueapp": ["tra"],
1476
+ "application/vnd.ufdl": ["ufd", "ufdl"],
1477
+ "application/vnd.uiq.theme": ["utz"],
1478
+ "application/vnd.umajin": ["umj"],
1479
+ "application/vnd.unity": ["unityweb"],
1480
+ "application/vnd.uoml+xml": ["uoml", "uo"],
1481
+ "application/vnd.vcx": ["vcx"],
1482
+ "application/vnd.visio": [
1483
+ "vsd",
1484
+ "vst",
1485
+ "vss",
1486
+ "vsw",
1487
+ "vsdx",
1488
+ "vtx"
1489
+ ],
1490
+ "application/vnd.visionary": ["vis"],
1491
+ "application/vnd.vsf": ["vsf"],
1492
+ "application/vnd.wap.wbxml": ["wbxml"],
1493
+ "application/vnd.wap.wmlc": ["wmlc"],
1494
+ "application/vnd.wap.wmlscriptc": ["wmlsc"],
1495
+ "application/vnd.webturbo": ["wtb"],
1496
+ "application/vnd.wolfram.player": ["nbp"],
1497
+ "application/vnd.wordperfect": ["wpd"],
1498
+ "application/vnd.wqd": ["wqd"],
1499
+ "application/vnd.wt.stf": ["stf"],
1500
+ "application/vnd.xara": ["xar"],
1501
+ "application/vnd.xfdl": ["xfdl"],
1502
+ "application/vnd.yamaha.hv-dic": ["hvd"],
1503
+ "application/vnd.yamaha.hv-script": ["hvs"],
1504
+ "application/vnd.yamaha.hv-voice": ["hvp"],
1505
+ "application/vnd.yamaha.openscoreformat": ["osf"],
1506
+ "application/vnd.yamaha.openscoreformat.osfpvg+xml": ["osfpvg"],
1507
+ "application/vnd.yamaha.smaf-audio": ["saf"],
1508
+ "application/vnd.yamaha.smaf-phrase": ["spf"],
1509
+ "application/vnd.yellowriver-custom-menu": ["cmp"],
1510
+ "application/vnd.zul": ["zir", "zirz"],
1511
+ "application/vnd.zzazz.deck+xml": ["zaz"],
1512
+ "application/x-7z-compressed": ["7z"],
1513
+ "application/x-abiword": ["abw"],
1514
+ "application/x-ace-compressed": ["ace"],
1515
+ "application/x-apple-diskimage": ["*dmg"],
1516
+ "application/x-arj": ["arj"],
1517
+ "application/x-authorware-bin": [
1518
+ "aab",
1519
+ "x32",
1520
+ "u32",
1521
+ "vox"
1522
+ ],
1523
+ "application/x-authorware-map": ["aam"],
1524
+ "application/x-authorware-seg": ["aas"],
1525
+ "application/x-bcpio": ["bcpio"],
1526
+ "application/x-bdoc": ["*bdoc"],
1527
+ "application/x-bittorrent": ["torrent"],
1528
+ "application/x-blender": ["blend"],
1529
+ "application/x-blorb": ["blb", "blorb"],
1530
+ "application/x-bzip": ["bz"],
1531
+ "application/x-bzip2": ["bz2", "boz"],
1532
+ "application/x-cbr": [
1533
+ "cbr",
1534
+ "cba",
1535
+ "cbt",
1536
+ "cbz",
1537
+ "cb7"
1538
+ ],
1539
+ "application/x-cdlink": ["vcd"],
1540
+ "application/x-cfs-compressed": ["cfs"],
1541
+ "application/x-chat": ["chat"],
1542
+ "application/x-chess-pgn": ["pgn"],
1543
+ "application/x-chrome-extension": ["crx"],
1544
+ "application/x-cocoa": ["cco"],
1545
+ "application/x-compressed": ["*rar"],
1546
+ "application/x-conference": ["nsc"],
1547
+ "application/x-cpio": ["cpio"],
1548
+ "application/x-csh": ["csh"],
1549
+ "application/x-debian-package": ["*deb", "udeb"],
1550
+ "application/x-dgc-compressed": ["dgc"],
1551
+ "application/x-director": [
1552
+ "dir",
1553
+ "dcr",
1554
+ "dxr",
1555
+ "cst",
1556
+ "cct",
1557
+ "cxt",
1558
+ "w3d",
1559
+ "fgd",
1560
+ "swa"
1561
+ ],
1562
+ "application/x-doom": ["wad"],
1563
+ "application/x-dtbncx+xml": ["ncx"],
1564
+ "application/x-dtbook+xml": ["dtb"],
1565
+ "application/x-dtbresource+xml": ["res"],
1566
+ "application/x-dvi": ["dvi"],
1567
+ "application/x-envoy": ["evy"],
1568
+ "application/x-eva": ["eva"],
1569
+ "application/x-font-bdf": ["bdf"],
1570
+ "application/x-font-ghostscript": ["gsf"],
1571
+ "application/x-font-linux-psf": ["psf"],
1572
+ "application/x-font-pcf": ["pcf"],
1573
+ "application/x-font-snf": ["snf"],
1574
+ "application/x-font-type1": [
1575
+ "pfa",
1576
+ "pfb",
1577
+ "pfm",
1578
+ "afm"
1579
+ ],
1580
+ "application/x-freearc": ["arc"],
1581
+ "application/x-futuresplash": ["spl"],
1582
+ "application/x-gca-compressed": ["gca"],
1583
+ "application/x-glulx": ["ulx"],
1584
+ "application/x-gnumeric": ["gnumeric"],
1585
+ "application/x-gramps-xml": ["gramps"],
1586
+ "application/x-gtar": ["gtar"],
1587
+ "application/x-hdf": ["hdf"],
1588
+ "application/x-httpd-php": ["php"],
1589
+ "application/x-install-instructions": ["install"],
1590
+ "application/x-ipynb+json": ["ipynb"],
1591
+ "application/x-iso9660-image": ["*iso"],
1592
+ "application/x-iwork-keynote-sffkey": ["*key"],
1593
+ "application/x-iwork-numbers-sffnumbers": ["*numbers"],
1594
+ "application/x-iwork-pages-sffpages": ["*pages"],
1595
+ "application/x-java-archive-diff": ["jardiff"],
1596
+ "application/x-java-jnlp-file": ["jnlp"],
1597
+ "application/x-keepass2": ["kdbx"],
1598
+ "application/x-latex": ["latex"],
1599
+ "application/x-lua-bytecode": ["luac"],
1600
+ "application/x-lzh-compressed": ["lzh", "lha"],
1601
+ "application/x-makeself": ["run"],
1602
+ "application/x-mie": ["mie"],
1603
+ "application/x-mobipocket-ebook": ["*prc", "mobi"],
1604
+ "application/x-ms-application": ["application"],
1605
+ "application/x-ms-shortcut": ["lnk"],
1606
+ "application/x-ms-wmd": ["wmd"],
1607
+ "application/x-ms-wmz": ["wmz"],
1608
+ "application/x-ms-xbap": ["xbap"],
1609
+ "application/x-msaccess": ["mdb"],
1610
+ "application/x-msbinder": ["obd"],
1611
+ "application/x-mscardfile": ["crd"],
1612
+ "application/x-msclip": ["clp"],
1613
+ "application/x-msdos-program": ["*exe"],
1614
+ "application/x-msdownload": [
1615
+ "*exe",
1616
+ "*dll",
1617
+ "com",
1618
+ "bat",
1619
+ "*msi"
1620
+ ],
1621
+ "application/x-msmediaview": [
1622
+ "mvb",
1623
+ "m13",
1624
+ "m14"
1625
+ ],
1626
+ "application/x-msmetafile": [
1627
+ "*wmf",
1628
+ "*wmz",
1629
+ "*emf",
1630
+ "emz"
1631
+ ],
1632
+ "application/x-msmoney": ["mny"],
1633
+ "application/x-mspublisher": ["pub"],
1634
+ "application/x-msschedule": ["scd"],
1635
+ "application/x-msterminal": ["trm"],
1636
+ "application/x-mswrite": ["wri"],
1637
+ "application/x-netcdf": ["nc", "cdf"],
1638
+ "application/x-ns-proxy-autoconfig": ["pac"],
1639
+ "application/x-nzb": ["nzb"],
1640
+ "application/x-perl": ["pl", "pm"],
1641
+ "application/x-pilot": ["*prc", "*pdb"],
1642
+ "application/x-pkcs12": ["p12", "pfx"],
1643
+ "application/x-pkcs7-certificates": ["p7b", "spc"],
1644
+ "application/x-pkcs7-certreqresp": ["p7r"],
1645
+ "application/x-rar-compressed": ["*rar"],
1646
+ "application/x-redhat-package-manager": ["rpm"],
1647
+ "application/x-research-info-systems": ["ris"],
1648
+ "application/x-sea": ["sea"],
1649
+ "application/x-sh": ["sh"],
1650
+ "application/x-shar": ["shar"],
1651
+ "application/x-shockwave-flash": ["swf"],
1652
+ "application/x-silverlight-app": ["xap"],
1653
+ "application/x-sql": ["*sql"],
1654
+ "application/x-stuffit": ["sit"],
1655
+ "application/x-stuffitx": ["sitx"],
1656
+ "application/x-subrip": ["srt"],
1657
+ "application/x-sv4cpio": ["sv4cpio"],
1658
+ "application/x-sv4crc": ["sv4crc"],
1659
+ "application/x-t3vm-image": ["t3"],
1660
+ "application/x-tads": ["gam"],
1661
+ "application/x-tar": ["tar"],
1662
+ "application/x-tcl": ["tcl", "tk"],
1663
+ "application/x-tex": ["tex"],
1664
+ "application/x-tex-tfm": ["tfm"],
1665
+ "application/x-texinfo": ["texinfo", "texi"],
1666
+ "application/x-tgif": ["*obj"],
1667
+ "application/x-ustar": ["ustar"],
1668
+ "application/x-virtualbox-hdd": ["hdd"],
1669
+ "application/x-virtualbox-ova": ["ova"],
1670
+ "application/x-virtualbox-ovf": ["ovf"],
1671
+ "application/x-virtualbox-vbox": ["vbox"],
1672
+ "application/x-virtualbox-vbox-extpack": ["vbox-extpack"],
1673
+ "application/x-virtualbox-vdi": ["vdi"],
1674
+ "application/x-virtualbox-vhd": ["vhd"],
1675
+ "application/x-virtualbox-vmdk": ["vmdk"],
1676
+ "application/x-wais-source": ["src"],
1677
+ "application/x-web-app-manifest+json": ["webapp"],
1678
+ "application/x-x509-ca-cert": [
1679
+ "der",
1680
+ "crt",
1681
+ "pem"
1682
+ ],
1683
+ "application/x-xfig": ["fig"],
1684
+ "application/x-xliff+xml": ["*xlf"],
1685
+ "application/x-xpinstall": ["xpi"],
1686
+ "application/x-xz": ["xz"],
1687
+ "application/x-zip-compressed": ["*zip"],
1688
+ "application/x-zmachine": [
1689
+ "z1",
1690
+ "z2",
1691
+ "z3",
1692
+ "z4",
1693
+ "z5",
1694
+ "z6",
1695
+ "z7",
1696
+ "z8"
1697
+ ],
1698
+ "audio/vnd.dece.audio": ["uva", "uvva"],
1699
+ "audio/vnd.digital-winds": ["eol"],
1700
+ "audio/vnd.dra": ["dra"],
1701
+ "audio/vnd.dts": ["dts"],
1702
+ "audio/vnd.dts.hd": ["dtshd"],
1703
+ "audio/vnd.lucent.voice": ["lvp"],
1704
+ "audio/vnd.ms-playready.media.pya": ["pya"],
1705
+ "audio/vnd.nuera.ecelp4800": ["ecelp4800"],
1706
+ "audio/vnd.nuera.ecelp7470": ["ecelp7470"],
1707
+ "audio/vnd.nuera.ecelp9600": ["ecelp9600"],
1708
+ "audio/vnd.rip": ["rip"],
1709
+ "audio/x-aac": ["*aac"],
1710
+ "audio/x-aiff": [
1711
+ "aif",
1712
+ "aiff",
1713
+ "aifc"
1714
+ ],
1715
+ "audio/x-caf": ["caf"],
1716
+ "audio/x-flac": ["flac"],
1717
+ "audio/x-m4a": ["*m4a"],
1718
+ "audio/x-matroska": ["mka"],
1719
+ "audio/x-mpegurl": ["m3u"],
1720
+ "audio/x-ms-wax": ["wax"],
1721
+ "audio/x-ms-wma": ["wma"],
1722
+ "audio/x-pn-realaudio": ["ram", "ra"],
1723
+ "audio/x-pn-realaudio-plugin": ["rmp"],
1724
+ "audio/x-realaudio": ["*ra"],
1725
+ "audio/x-wav": ["*wav"],
1726
+ "chemical/x-cdx": ["cdx"],
1727
+ "chemical/x-cif": ["cif"],
1728
+ "chemical/x-cmdf": ["cmdf"],
1729
+ "chemical/x-cml": ["cml"],
1730
+ "chemical/x-csml": ["csml"],
1731
+ "chemical/x-xyz": ["xyz"],
1732
+ "image/prs.btif": ["btif", "btf"],
1733
+ "image/prs.pti": ["pti"],
1734
+ "image/vnd.adobe.photoshop": ["psd"],
1735
+ "image/vnd.airzip.accelerator.azv": ["azv"],
1736
+ "image/vnd.dece.graphic": [
1737
+ "uvi",
1738
+ "uvvi",
1739
+ "uvg",
1740
+ "uvvg"
1741
+ ],
1742
+ "image/vnd.djvu": ["djvu", "djv"],
1743
+ "image/vnd.dvb.subtitle": ["*sub"],
1744
+ "image/vnd.dwg": ["dwg"],
1745
+ "image/vnd.dxf": ["dxf"],
1746
+ "image/vnd.fastbidsheet": ["fbs"],
1747
+ "image/vnd.fpx": ["fpx"],
1748
+ "image/vnd.fst": ["fst"],
1749
+ "image/vnd.fujixerox.edmics-mmr": ["mmr"],
1750
+ "image/vnd.fujixerox.edmics-rlc": ["rlc"],
1751
+ "image/vnd.microsoft.icon": ["ico"],
1752
+ "image/vnd.ms-dds": ["dds"],
1753
+ "image/vnd.ms-modi": ["mdi"],
1754
+ "image/vnd.ms-photo": ["wdp"],
1755
+ "image/vnd.net-fpx": ["npx"],
1756
+ "image/vnd.pco.b16": ["b16"],
1757
+ "image/vnd.tencent.tap": ["tap"],
1758
+ "image/vnd.valve.source.texture": ["vtf"],
1759
+ "image/vnd.wap.wbmp": ["wbmp"],
1760
+ "image/vnd.xiff": ["xif"],
1761
+ "image/vnd.zbrush.pcx": ["pcx"],
1762
+ "image/x-3ds": ["3ds"],
1763
+ "image/x-adobe-dng": ["dng"],
1764
+ "image/x-cmu-raster": ["ras"],
1765
+ "image/x-cmx": ["cmx"],
1766
+ "image/x-freehand": [
1767
+ "fh",
1768
+ "fhc",
1769
+ "fh4",
1770
+ "fh5",
1771
+ "fh7"
1772
+ ],
1773
+ "image/x-icon": ["*ico"],
1774
+ "image/x-jng": ["jng"],
1775
+ "image/x-mrsid-image": ["sid"],
1776
+ "image/x-ms-bmp": ["*bmp"],
1777
+ "image/x-pcx": ["*pcx"],
1778
+ "image/x-pict": ["pic", "pct"],
1779
+ "image/x-portable-anymap": ["pnm"],
1780
+ "image/x-portable-bitmap": ["pbm"],
1781
+ "image/x-portable-graymap": ["pgm"],
1782
+ "image/x-portable-pixmap": ["ppm"],
1783
+ "image/x-rgb": ["rgb"],
1784
+ "image/x-tga": ["tga"],
1785
+ "image/x-xbitmap": ["xbm"],
1786
+ "image/x-xpixmap": ["xpm"],
1787
+ "image/x-xwindowdump": ["xwd"],
1788
+ "message/vnd.wfa.wsc": ["wsc"],
1789
+ "model/vnd.bary": ["bary"],
1790
+ "model/vnd.cld": ["cld"],
1791
+ "model/vnd.collada+xml": ["dae"],
1792
+ "model/vnd.dwf": ["dwf"],
1793
+ "model/vnd.gdl": ["gdl"],
1794
+ "model/vnd.gtw": ["gtw"],
1795
+ "model/vnd.mts": ["*mts"],
1796
+ "model/vnd.opengex": ["ogex"],
1797
+ "model/vnd.parasolid.transmit.binary": ["x_b"],
1798
+ "model/vnd.parasolid.transmit.text": ["x_t"],
1799
+ "model/vnd.pytha.pyox": ["pyo", "pyox"],
1800
+ "model/vnd.sap.vds": ["vds"],
1801
+ "model/vnd.usda": ["usda"],
1802
+ "model/vnd.usdz+zip": ["usdz"],
1803
+ "model/vnd.valve.source.compiled-map": ["bsp"],
1804
+ "model/vnd.vtu": ["vtu"],
1805
+ "text/prs.lines.tag": ["dsc"],
1806
+ "text/vnd.curl": ["curl"],
1807
+ "text/vnd.curl.dcurl": ["dcurl"],
1808
+ "text/vnd.curl.mcurl": ["mcurl"],
1809
+ "text/vnd.curl.scurl": ["scurl"],
1810
+ "text/vnd.dvb.subtitle": ["sub"],
1811
+ "text/vnd.familysearch.gedcom": ["ged"],
1812
+ "text/vnd.fly": ["fly"],
1813
+ "text/vnd.fmi.flexstor": ["flx"],
1814
+ "text/vnd.graphviz": ["gv"],
1815
+ "text/vnd.in3d.3dml": ["3dml"],
1816
+ "text/vnd.in3d.spot": ["spot"],
1817
+ "text/vnd.sun.j2me.app-descriptor": ["jad"],
1818
+ "text/vnd.wap.wml": ["wml"],
1819
+ "text/vnd.wap.wmlscript": ["wmls"],
1820
+ "text/x-asm": ["s", "asm"],
1821
+ "text/x-c": [
1822
+ "c",
1823
+ "cc",
1824
+ "cxx",
1825
+ "cpp",
1826
+ "h",
1827
+ "hh",
1828
+ "dic"
1829
+ ],
1830
+ "text/x-component": ["htc"],
1831
+ "text/x-fortran": [
1832
+ "f",
1833
+ "for",
1834
+ "f77",
1835
+ "f90"
1836
+ ],
1837
+ "text/x-handlebars-template": ["hbs"],
1838
+ "text/x-java-source": ["java"],
1839
+ "text/x-lua": ["lua"],
1840
+ "text/x-markdown": ["mkd"],
1841
+ "text/x-nfo": ["nfo"],
1842
+ "text/x-opml": ["opml"],
1843
+ "text/x-org": ["*org"],
1844
+ "text/x-pascal": ["p", "pas"],
1845
+ "text/x-processing": ["pde"],
1846
+ "text/x-sass": ["sass"],
1847
+ "text/x-scss": ["scss"],
1848
+ "text/x-setext": ["etx"],
1849
+ "text/x-sfv": ["sfv"],
1850
+ "text/x-suse-ymp": ["ymp"],
1851
+ "text/x-uuencode": ["uu"],
1852
+ "text/x-vcalendar": ["vcs"],
1853
+ "text/x-vcard": ["vcf"],
1854
+ "video/vnd.dece.hd": ["uvh", "uvvh"],
1855
+ "video/vnd.dece.mobile": ["uvm", "uvvm"],
1856
+ "video/vnd.dece.pd": ["uvp", "uvvp"],
1857
+ "video/vnd.dece.sd": ["uvs", "uvvs"],
1858
+ "video/vnd.dece.video": ["uvv", "uvvv"],
1859
+ "video/vnd.dvb.file": ["dvb"],
1860
+ "video/vnd.fvt": ["fvt"],
1861
+ "video/vnd.mpegurl": ["mxu", "m4u"],
1862
+ "video/vnd.ms-playready.media.pyv": ["pyv"],
1863
+ "video/vnd.uvvu.mp4": ["uvu", "uvvu"],
1864
+ "video/vnd.vivo": ["viv"],
1865
+ "video/x-f4v": ["f4v"],
1866
+ "video/x-fli": ["fli"],
1867
+ "video/x-flv": ["flv"],
1868
+ "video/x-m4v": ["m4v"],
1869
+ "video/x-matroska": [
1870
+ "mkv",
1871
+ "mk3d",
1872
+ "mks"
1873
+ ],
1874
+ "video/x-mng": ["mng"],
1875
+ "video/x-ms-asf": ["asf", "asx"],
1876
+ "video/x-ms-vob": ["vob"],
1877
+ "video/x-ms-wm": ["wm"],
1878
+ "video/x-ms-wmv": ["wmv"],
1879
+ "video/x-ms-wmx": ["wmx"],
1880
+ "video/x-ms-wvx": ["wvx"],
1881
+ "video/x-msvideo": ["avi"],
1882
+ "video/x-sgi-movie": ["movie"],
1883
+ "video/x-smv": ["smv"],
1884
+ "x-conference/x-cooltalk": ["ice"]
1885
+ };
1886
+ Object.freeze(types$1);
1887
+ // node_modules/mime/dist/types/standard.js
1888
+ const types = {
1889
+ "application/andrew-inset": ["ez"],
1890
+ "application/appinstaller": ["appinstaller"],
1891
+ "application/applixware": ["aw"],
1892
+ "application/appx": ["appx"],
1893
+ "application/appxbundle": ["appxbundle"],
1894
+ "application/atom+xml": ["atom"],
1895
+ "application/atomcat+xml": ["atomcat"],
1896
+ "application/atomdeleted+xml": ["atomdeleted"],
1897
+ "application/atomsvc+xml": ["atomsvc"],
1898
+ "application/atsc-dwd+xml": ["dwd"],
1899
+ "application/atsc-held+xml": ["held"],
1900
+ "application/atsc-rsat+xml": ["rsat"],
1901
+ "application/automationml-aml+xml": ["aml"],
1902
+ "application/automationml-amlx+zip": ["amlx"],
1903
+ "application/bdoc": ["bdoc"],
1904
+ "application/calendar+xml": ["xcs"],
1905
+ "application/ccxml+xml": ["ccxml"],
1906
+ "application/cdfx+xml": ["cdfx"],
1907
+ "application/cdmi-capability": ["cdmia"],
1908
+ "application/cdmi-container": ["cdmic"],
1909
+ "application/cdmi-domain": ["cdmid"],
1910
+ "application/cdmi-object": ["cdmio"],
1911
+ "application/cdmi-queue": ["cdmiq"],
1912
+ "application/cpl+xml": ["cpl"],
1913
+ "application/cu-seeme": ["cu"],
1914
+ "application/cwl": ["cwl"],
1915
+ "application/dash+xml": ["mpd"],
1916
+ "application/dash-patch+xml": ["mpp"],
1917
+ "application/davmount+xml": ["davmount"],
1918
+ "application/dicom": ["dcm"],
1919
+ "application/docbook+xml": ["dbk"],
1920
+ "application/dssc+der": ["dssc"],
1921
+ "application/dssc+xml": ["xdssc"],
1922
+ "application/ecmascript": ["ecma"],
1923
+ "application/emma+xml": ["emma"],
1924
+ "application/emotionml+xml": ["emotionml"],
1925
+ "application/epub+zip": ["epub"],
1926
+ "application/exi": ["exi"],
1927
+ "application/express": ["exp"],
1928
+ "application/fdf": ["fdf"],
1929
+ "application/fdt+xml": ["fdt"],
1930
+ "application/font-tdpfr": ["pfr"],
1931
+ "application/geo+json": ["geojson"],
1932
+ "application/gml+xml": ["gml"],
1933
+ "application/gpx+xml": ["gpx"],
1934
+ "application/gxf": ["gxf"],
1935
+ "application/gzip": ["gz"],
1936
+ "application/hjson": ["hjson"],
1937
+ "application/hyperstudio": ["stk"],
1938
+ "application/inkml+xml": ["ink", "inkml"],
1939
+ "application/ipfix": ["ipfix"],
1940
+ "application/its+xml": ["its"],
1941
+ "application/java-archive": [
1942
+ "jar",
1943
+ "war",
1944
+ "ear"
1945
+ ],
1946
+ "application/java-serialized-object": ["ser"],
1947
+ "application/java-vm": ["class"],
1948
+ "application/javascript": ["*js"],
1949
+ "application/json": ["json", "map"],
1950
+ "application/json5": ["json5"],
1951
+ "application/jsonml+json": ["jsonml"],
1952
+ "application/ld+json": ["jsonld"],
1953
+ "application/lgr+xml": ["lgr"],
1954
+ "application/lost+xml": ["lostxml"],
1955
+ "application/mac-binhex40": ["hqx"],
1956
+ "application/mac-compactpro": ["cpt"],
1957
+ "application/mads+xml": ["mads"],
1958
+ "application/manifest+json": ["webmanifest"],
1959
+ "application/marc": ["mrc"],
1960
+ "application/marcxml+xml": ["mrcx"],
1961
+ "application/mathematica": [
1962
+ "ma",
1963
+ "nb",
1964
+ "mb"
1965
+ ],
1966
+ "application/mathml+xml": ["mathml"],
1967
+ "application/mbox": ["mbox"],
1968
+ "application/media-policy-dataset+xml": ["mpf"],
1969
+ "application/mediaservercontrol+xml": ["mscml"],
1970
+ "application/metalink+xml": ["metalink"],
1971
+ "application/metalink4+xml": ["meta4"],
1972
+ "application/mets+xml": ["mets"],
1973
+ "application/mmt-aei+xml": ["maei"],
1974
+ "application/mmt-usd+xml": ["musd"],
1975
+ "application/mods+xml": ["mods"],
1976
+ "application/mp21": ["m21", "mp21"],
1977
+ "application/mp4": [
1978
+ "*mp4",
1979
+ "*mpg4",
1980
+ "mp4s",
1981
+ "m4p"
1982
+ ],
1983
+ "application/msix": ["msix"],
1984
+ "application/msixbundle": ["msixbundle"],
1985
+ "application/msword": ["doc", "dot"],
1986
+ "application/mxf": ["mxf"],
1987
+ "application/n-quads": ["nq"],
1988
+ "application/n-triples": ["nt"],
1989
+ "application/node": ["cjs"],
1990
+ "application/octet-stream": [
1991
+ "bin",
1992
+ "dms",
1993
+ "lrf",
1994
+ "mar",
1995
+ "so",
1996
+ "dist",
1997
+ "distz",
1998
+ "pkg",
1999
+ "bpk",
2000
+ "dump",
2001
+ "elc",
2002
+ "deploy",
2003
+ "exe",
2004
+ "dll",
2005
+ "deb",
2006
+ "dmg",
2007
+ "iso",
2008
+ "img",
2009
+ "msi",
2010
+ "msp",
2011
+ "msm",
2012
+ "buffer"
2013
+ ],
2014
+ "application/oda": ["oda"],
2015
+ "application/oebps-package+xml": ["opf"],
2016
+ "application/ogg": ["ogx"],
2017
+ "application/omdoc+xml": ["omdoc"],
2018
+ "application/onenote": [
2019
+ "onetoc",
2020
+ "onetoc2",
2021
+ "onetmp",
2022
+ "onepkg",
2023
+ "one",
2024
+ "onea"
2025
+ ],
2026
+ "application/oxps": ["oxps"],
2027
+ "application/p2p-overlay+xml": ["relo"],
2028
+ "application/patch-ops-error+xml": ["xer"],
2029
+ "application/pdf": ["pdf"],
2030
+ "application/pgp-encrypted": ["pgp"],
2031
+ "application/pgp-keys": ["asc"],
2032
+ "application/pgp-signature": ["sig", "*asc"],
2033
+ "application/pics-rules": ["prf"],
2034
+ "application/pkcs10": ["p10"],
2035
+ "application/pkcs7-mime": ["p7m", "p7c"],
2036
+ "application/pkcs7-signature": ["p7s"],
2037
+ "application/pkcs8": ["p8"],
2038
+ "application/pkix-attr-cert": ["ac"],
2039
+ "application/pkix-cert": ["cer"],
2040
+ "application/pkix-crl": ["crl"],
2041
+ "application/pkix-pkipath": ["pkipath"],
2042
+ "application/pkixcmp": ["pki"],
2043
+ "application/pls+xml": ["pls"],
2044
+ "application/postscript": [
2045
+ "ai",
2046
+ "eps",
2047
+ "ps"
2048
+ ],
2049
+ "application/provenance+xml": ["provx"],
2050
+ "application/pskc+xml": ["pskcxml"],
2051
+ "application/raml+yaml": ["raml"],
2052
+ "application/rdf+xml": ["rdf", "owl"],
2053
+ "application/reginfo+xml": ["rif"],
2054
+ "application/relax-ng-compact-syntax": ["rnc"],
2055
+ "application/resource-lists+xml": ["rl"],
2056
+ "application/resource-lists-diff+xml": ["rld"],
2057
+ "application/rls-services+xml": ["rs"],
2058
+ "application/route-apd+xml": ["rapd"],
2059
+ "application/route-s-tsid+xml": ["sls"],
2060
+ "application/route-usd+xml": ["rusd"],
2061
+ "application/rpki-ghostbusters": ["gbr"],
2062
+ "application/rpki-manifest": ["mft"],
2063
+ "application/rpki-roa": ["roa"],
2064
+ "application/rsd+xml": ["rsd"],
2065
+ "application/rss+xml": ["rss"],
2066
+ "application/rtf": ["rtf"],
2067
+ "application/sbml+xml": ["sbml"],
2068
+ "application/scvp-cv-request": ["scq"],
2069
+ "application/scvp-cv-response": ["scs"],
2070
+ "application/scvp-vp-request": ["spq"],
2071
+ "application/scvp-vp-response": ["spp"],
2072
+ "application/sdp": ["sdp"],
2073
+ "application/senml+xml": ["senmlx"],
2074
+ "application/sensml+xml": ["sensmlx"],
2075
+ "application/set-payment-initiation": ["setpay"],
2076
+ "application/set-registration-initiation": ["setreg"],
2077
+ "application/shf+xml": ["shf"],
2078
+ "application/sieve": ["siv", "sieve"],
2079
+ "application/smil+xml": ["smi", "smil"],
2080
+ "application/sparql-query": ["rq"],
2081
+ "application/sparql-results+xml": ["srx"],
2082
+ "application/sql": ["sql"],
2083
+ "application/srgs": ["gram"],
2084
+ "application/srgs+xml": ["grxml"],
2085
+ "application/sru+xml": ["sru"],
2086
+ "application/ssdl+xml": ["ssdl"],
2087
+ "application/ssml+xml": ["ssml"],
2088
+ "application/swid+xml": ["swidtag"],
2089
+ "application/tei+xml": ["tei", "teicorpus"],
2090
+ "application/thraud+xml": ["tfi"],
2091
+ "application/timestamped-data": ["tsd"],
2092
+ "application/toml": ["toml"],
2093
+ "application/trig": ["trig"],
2094
+ "application/ttml+xml": ["ttml"],
2095
+ "application/ubjson": ["ubj"],
2096
+ "application/urc-ressheet+xml": ["rsheet"],
2097
+ "application/urc-targetdesc+xml": ["td"],
2098
+ "application/voicexml+xml": ["vxml"],
2099
+ "application/wasm": ["wasm"],
2100
+ "application/watcherinfo+xml": ["wif"],
2101
+ "application/widget": ["wgt"],
2102
+ "application/winhlp": ["hlp"],
2103
+ "application/wsdl+xml": ["wsdl"],
2104
+ "application/wspolicy+xml": ["wspolicy"],
2105
+ "application/xaml+xml": ["xaml"],
2106
+ "application/xcap-att+xml": ["xav"],
2107
+ "application/xcap-caps+xml": ["xca"],
2108
+ "application/xcap-diff+xml": ["xdf"],
2109
+ "application/xcap-el+xml": ["xel"],
2110
+ "application/xcap-ns+xml": ["xns"],
2111
+ "application/xenc+xml": ["xenc"],
2112
+ "application/xfdf": ["xfdf"],
2113
+ "application/xhtml+xml": ["xhtml", "xht"],
2114
+ "application/xliff+xml": ["xlf"],
2115
+ "application/xml": [
2116
+ "xml",
2117
+ "xsl",
2118
+ "xsd",
2119
+ "rng"
2120
+ ],
2121
+ "application/xml-dtd": ["dtd"],
2122
+ "application/xop+xml": ["xop"],
2123
+ "application/xproc+xml": ["xpl"],
2124
+ "application/xslt+xml": ["*xsl", "xslt"],
2125
+ "application/xspf+xml": ["xspf"],
2126
+ "application/xv+xml": [
2127
+ "mxml",
2128
+ "xhvml",
2129
+ "xvml",
2130
+ "xvm"
2131
+ ],
2132
+ "application/yang": ["yang"],
2133
+ "application/yin+xml": ["yin"],
2134
+ "application/zip": ["zip"],
2135
+ "application/zip+dotlottie": ["lottie"],
2136
+ "audio/3gpp": ["*3gpp"],
2137
+ "audio/aac": ["adts", "aac"],
2138
+ "audio/adpcm": ["adp"],
2139
+ "audio/amr": ["amr"],
2140
+ "audio/basic": ["au", "snd"],
2141
+ "audio/midi": [
2142
+ "mid",
2143
+ "midi",
2144
+ "kar",
2145
+ "rmi"
2146
+ ],
2147
+ "audio/mobile-xmf": ["mxmf"],
2148
+ "audio/mp3": ["*mp3"],
2149
+ "audio/mp4": [
2150
+ "m4a",
2151
+ "mp4a",
2152
+ "m4b"
2153
+ ],
2154
+ "audio/mpeg": [
2155
+ "mpga",
2156
+ "mp2",
2157
+ "mp2a",
2158
+ "mp3",
2159
+ "m2a",
2160
+ "m3a"
2161
+ ],
2162
+ "audio/ogg": [
2163
+ "oga",
2164
+ "ogg",
2165
+ "spx",
2166
+ "opus"
2167
+ ],
2168
+ "audio/s3m": ["s3m"],
2169
+ "audio/silk": ["sil"],
2170
+ "audio/wav": ["wav"],
2171
+ "audio/wave": ["*wav"],
2172
+ "audio/webm": ["weba"],
2173
+ "audio/xm": ["xm"],
2174
+ "font/collection": ["ttc"],
2175
+ "font/otf": ["otf"],
2176
+ "font/ttf": ["ttf"],
2177
+ "font/woff": ["woff"],
2178
+ "font/woff2": ["woff2"],
2179
+ "image/aces": ["exr"],
2180
+ "image/apng": ["apng"],
2181
+ "image/avci": ["avci"],
2182
+ "image/avcs": ["avcs"],
2183
+ "image/avif": ["avif"],
2184
+ "image/bmp": ["bmp", "dib"],
2185
+ "image/cgm": ["cgm"],
2186
+ "image/dicom-rle": ["drle"],
2187
+ "image/dpx": ["dpx"],
2188
+ "image/emf": ["emf"],
2189
+ "image/fits": ["fits"],
2190
+ "image/g3fax": ["g3"],
2191
+ "image/gif": ["gif"],
2192
+ "image/heic": ["heic"],
2193
+ "image/heic-sequence": ["heics"],
2194
+ "image/heif": ["heif"],
2195
+ "image/heif-sequence": ["heifs"],
2196
+ "image/hej2k": ["hej2"],
2197
+ "image/ief": ["ief"],
2198
+ "image/jaii": ["jaii"],
2199
+ "image/jais": ["jais"],
2200
+ "image/jls": ["jls"],
2201
+ "image/jp2": ["jp2", "jpg2"],
2202
+ "image/jpeg": [
2203
+ "jpg",
2204
+ "jpeg",
2205
+ "jpe"
2206
+ ],
2207
+ "image/jph": ["jph"],
2208
+ "image/jphc": ["jhc"],
2209
+ "image/jpm": ["jpm", "jpgm"],
2210
+ "image/jpx": ["jpx", "jpf"],
2211
+ "image/jxl": ["jxl"],
2212
+ "image/jxr": ["jxr"],
2213
+ "image/jxra": ["jxra"],
2214
+ "image/jxrs": ["jxrs"],
2215
+ "image/jxs": ["jxs"],
2216
+ "image/jxsc": ["jxsc"],
2217
+ "image/jxsi": ["jxsi"],
2218
+ "image/jxss": ["jxss"],
2219
+ "image/ktx": ["ktx"],
2220
+ "image/ktx2": ["ktx2"],
2221
+ "image/pjpeg": ["jfif"],
2222
+ "image/png": ["png"],
2223
+ "image/sgi": ["sgi"],
2224
+ "image/svg+xml": ["svg", "svgz"],
2225
+ "image/t38": ["t38"],
2226
+ "image/tiff": ["tif", "tiff"],
2227
+ "image/tiff-fx": ["tfx"],
2228
+ "image/webp": ["webp"],
2229
+ "image/wmf": ["wmf"],
2230
+ "message/disposition-notification": ["disposition-notification"],
2231
+ "message/global": ["u8msg"],
2232
+ "message/global-delivery-status": ["u8dsn"],
2233
+ "message/global-disposition-notification": ["u8mdn"],
2234
+ "message/global-headers": ["u8hdr"],
2235
+ "message/rfc822": [
2236
+ "eml",
2237
+ "mime",
2238
+ "mht",
2239
+ "mhtml"
2240
+ ],
2241
+ "model/3mf": ["3mf"],
2242
+ "model/gltf+json": ["gltf"],
2243
+ "model/gltf-binary": ["glb"],
2244
+ "model/iges": ["igs", "iges"],
2245
+ "model/jt": ["jt"],
2246
+ "model/mesh": [
2247
+ "msh",
2248
+ "mesh",
2249
+ "silo"
2250
+ ],
2251
+ "model/mtl": ["mtl"],
2252
+ "model/obj": ["obj"],
2253
+ "model/prc": ["prc"],
2254
+ "model/step": [
2255
+ "step",
2256
+ "stp",
2257
+ "stpnc",
2258
+ "p21",
2259
+ "210"
2260
+ ],
2261
+ "model/step+xml": ["stpx"],
2262
+ "model/step+zip": ["stpz"],
2263
+ "model/step-xml+zip": ["stpxz"],
2264
+ "model/stl": ["stl"],
2265
+ "model/u3d": ["u3d"],
2266
+ "model/vrml": ["wrl", "vrml"],
2267
+ "model/x3d+binary": ["*x3db", "x3dbz"],
2268
+ "model/x3d+fastinfoset": ["x3db"],
2269
+ "model/x3d+vrml": ["*x3dv", "x3dvz"],
2270
+ "model/x3d+xml": ["x3d", "x3dz"],
2271
+ "model/x3d-vrml": ["x3dv"],
2272
+ "text/cache-manifest": ["appcache", "manifest"],
2273
+ "text/calendar": ["ics", "ifb"],
2274
+ "text/coffeescript": ["coffee", "litcoffee"],
2275
+ "text/css": ["css"],
2276
+ "text/csv": ["csv"],
2277
+ "text/html": [
2278
+ "html",
2279
+ "htm",
2280
+ "shtml"
2281
+ ],
2282
+ "text/jade": ["jade"],
2283
+ "text/javascript": ["js", "mjs"],
2284
+ "text/jsx": ["jsx"],
2285
+ "text/less": ["less"],
2286
+ "text/markdown": ["md", "markdown"],
2287
+ "text/mathml": ["mml"],
2288
+ "text/mdx": ["mdx"],
2289
+ "text/n3": ["n3"],
2290
+ "text/plain": [
2291
+ "txt",
2292
+ "text",
2293
+ "conf",
2294
+ "def",
2295
+ "list",
2296
+ "log",
2297
+ "in",
2298
+ "ini"
2299
+ ],
2300
+ "text/richtext": ["rtx"],
2301
+ "text/rtf": ["*rtf"],
2302
+ "text/sgml": ["sgml", "sgm"],
2303
+ "text/shex": ["shex"],
2304
+ "text/slim": ["slim", "slm"],
2305
+ "text/spdx": ["spdx"],
2306
+ "text/stylus": ["stylus", "styl"],
2307
+ "text/tab-separated-values": ["tsv"],
2308
+ "text/troff": [
2309
+ "t",
2310
+ "tr",
2311
+ "roff",
2312
+ "man",
2313
+ "me",
2314
+ "ms"
2315
+ ],
2316
+ "text/turtle": ["ttl"],
2317
+ "text/uri-list": [
2318
+ "uri",
2319
+ "uris",
2320
+ "urls"
2321
+ ],
2322
+ "text/vcard": ["vcard"],
2323
+ "text/vtt": ["vtt"],
2324
+ "text/wgsl": ["wgsl"],
2325
+ "text/xml": ["*xml"],
2326
+ "text/yaml": ["yaml", "yml"],
2327
+ "video/3gpp": ["3gp", "3gpp"],
2328
+ "video/3gpp2": ["3g2"],
2329
+ "video/h261": ["h261"],
2330
+ "video/h263": ["h263"],
2331
+ "video/h264": ["h264"],
2332
+ "video/iso.segment": ["m4s"],
2333
+ "video/jpeg": ["jpgv"],
2334
+ "video/jpm": ["*jpm", "*jpgm"],
2335
+ "video/mj2": ["mj2", "mjp2"],
2336
+ "video/mp2t": [
2337
+ "ts",
2338
+ "m2t",
2339
+ "m2ts",
2340
+ "mts"
2341
+ ],
2342
+ "video/mp4": [
2343
+ "mp4",
2344
+ "mp4v",
2345
+ "mpg4"
2346
+ ],
2347
+ "video/mpeg": [
2348
+ "mpeg",
2349
+ "mpg",
2350
+ "mpe",
2351
+ "m1v",
2352
+ "m2v"
2353
+ ],
2354
+ "video/ogg": ["ogv"],
2355
+ "video/quicktime": ["qt", "mov"],
2356
+ "video/webm": ["webm"]
2357
+ };
2358
+ Object.freeze(types);
2359
+ // node_modules/mime/dist/src/Mime.js
2360
+ var __classPrivateFieldGet = function(receiver, state, kind, f) {
2361
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
2362
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
2363
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
2364
+ };
2365
+ var _Mime_extensionToType;
2366
+ var _Mime_typeToExtension;
2367
+ var _Mime_typeToExtensions;
2368
+ var Mime = class {
2369
+ constructor(...args) {
2370
+ _Mime_extensionToType.set(this, /* @__PURE__ */ new Map());
2371
+ _Mime_typeToExtension.set(this, /* @__PURE__ */ new Map());
2372
+ _Mime_typeToExtensions.set(this, /* @__PURE__ */ new Map());
2373
+ for (const arg of args) this.define(arg);
2374
+ }
2375
+ define(typeMap, force = false) {
2376
+ for (let [type, extensions] of Object.entries(typeMap)) {
2377
+ type = type.toLowerCase();
2378
+ extensions = extensions.map((ext) => ext.toLowerCase());
2379
+ if (!__classPrivateFieldGet(this, _Mime_typeToExtensions, "f").has(type)) __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").set(type, /* @__PURE__ */ new Set());
2380
+ const allExtensions = __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").get(type);
2381
+ let first = true;
2382
+ for (let extension of extensions) {
2383
+ const starred = extension.startsWith("*");
2384
+ extension = starred ? extension.slice(1) : extension;
2385
+ allExtensions?.add(extension);
2386
+ if (first) __classPrivateFieldGet(this, _Mime_typeToExtension, "f").set(type, extension);
2387
+ first = false;
2388
+ if (starred) continue;
2389
+ const currentType = __classPrivateFieldGet(this, _Mime_extensionToType, "f").get(extension);
2390
+ if (currentType && currentType != type && !force) throw new Error(`"${type} -> ${extension}" conflicts with "${currentType} -> ${extension}". Pass \`force=true\` to override this definition.`);
2391
+ __classPrivateFieldGet(this, _Mime_extensionToType, "f").set(extension, type);
2392
+ }
2393
+ }
2394
+ return this;
2395
+ }
2396
+ getType(path) {
2397
+ if (typeof path !== "string") return null;
2398
+ const last = path.replace(/^.*[/\\]/s, "").toLowerCase();
2399
+ const ext = last.replace(/^.*\./s, "").toLowerCase();
2400
+ const hasPath = last.length < path.length;
2401
+ if (!(ext.length < last.length - 1) && hasPath) return null;
2402
+ return __classPrivateFieldGet(this, _Mime_extensionToType, "f").get(ext) ?? null;
2403
+ }
2404
+ getExtension(type) {
2405
+ if (typeof type !== "string") return null;
2406
+ type = type?.split?.(";")[0];
2407
+ return (type && __classPrivateFieldGet(this, _Mime_typeToExtension, "f").get(type.trim().toLowerCase())) ?? null;
2408
+ }
2409
+ getAllExtensions(type) {
2410
+ if (typeof type !== "string") return null;
2411
+ return __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").get(type.toLowerCase()) ?? null;
2412
+ }
2413
+ _freeze() {
2414
+ this.define = () => {
2415
+ throw new Error("define() not allowed for built-in Mime objects. See https://github.com/broofa/mime/blob/main/README.md#custom-mime-instances");
2416
+ };
2417
+ Object.freeze(this);
2418
+ for (const extensions of __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").values()) Object.freeze(extensions);
2419
+ return this;
2420
+ }
2421
+ _getTestState() {
2422
+ return {
2423
+ types: __classPrivateFieldGet(this, _Mime_extensionToType, "f"),
2424
+ extensions: __classPrivateFieldGet(this, _Mime_typeToExtension, "f")
2425
+ };
2426
+ }
2427
+ };
2428
+ _Mime_extensionToType = /* @__PURE__ */ new WeakMap(), _Mime_typeToExtension = /* @__PURE__ */ new WeakMap(), _Mime_typeToExtensions = /* @__PURE__ */ new WeakMap();
2429
+ // node_modules/mime/dist/src/index.js
2430
+ var src_default = new Mime(types, types$1)._freeze();
2431
+ // workers-sdk/packages/workers-shared/utils/helpers.ts
2432
+ const getContentType = (absFilePath) => {
2433
+ let contentType = src_default.getType(absFilePath);
2434
+ if (contentType && contentType.startsWith("text/") && !contentType.includes("charset")) contentType = `${contentType}; charset=utf-8`;
2435
+ return contentType;
2436
+ };
2437
+ // src/assets.ts
2438
+ const ROUTER_WORKER_NAME = "__rspack-plugin-cloudflare-router__";
2439
+ const ASSET_WORKER_NAME = "__rspack-plugin-cloudflare-assets__";
2440
+ const INTERNAL_WORKERS_COMPATIBILITY_DATE = "2024-10-04";
2441
+ const RESERVED_FILES = /* @__PURE__ */ new Set([
2442
+ "/_headers",
2443
+ "/_redirects",
2444
+ "/.assetsignore"
2445
+ ]);
2446
+ function toJsonBinding(config) {
2447
+ return Object.fromEntries(Object.entries(config).filter(([, value]) => value !== void 0));
2448
+ }
2449
+ function getInternalWorkerPath(name) {
2450
+ return fileURLToPath(new URL(`workers/${name}/index.js`, import.meta.url));
2451
+ }
2452
+ function statFile(fileSystem, filePath) {
2453
+ return new Promise((resolve) => {
2454
+ fileSystem.stat(filePath, (error, stats) => {
2455
+ resolve(!error && Boolean(stats?.isFile()));
2456
+ });
2457
+ });
2458
+ }
2459
+ function readFile(fileSystem, filePath) {
2460
+ return new Promise((resolve, reject) => {
2461
+ fileSystem.readFile(filePath, (error, data) => {
2462
+ if (error || data === void 0) {
2463
+ reject(error ?? /* @__PURE__ */ new Error(`Could not read ${filePath}`));
2464
+ return;
2465
+ }
2466
+ resolve(Buffer.from(data));
2467
+ });
2468
+ });
2469
+ }
2470
+ /**
2471
+ * Finds asset files for the asset Worker, reading the compiler's output filesystem first so files only emitted in
2472
+ * memory by the dev server are visible, then the assets directory on disk.
2473
+ */
2474
+ var DevAssets = class {
2475
+ #roots;
2476
+ #getOutputFileSystem;
2477
+ #waitUntilValid;
2478
+ constructor(options) {
2479
+ this.#roots = [options.directory, ...options.extraDirectories];
2480
+ this.#getOutputFileSystem = options.getOutputFileSystem;
2481
+ this.#waitUntilValid = options.waitUntilValid;
2482
+ }
2483
+ async #find(pathname) {
2484
+ const outputFileSystem = this.#getOutputFileSystem();
2485
+ for (const root of this.#roots) {
2486
+ const filePath = path.join(root, pathname);
2487
+ if (!filePath.startsWith(root + path.sep)) continue;
2488
+ if (outputFileSystem && await statFile(outputFileSystem, filePath)) return {
2489
+ fileSystem: outputFileSystem,
2490
+ filePath
2491
+ };
2492
+ if (await statFile(fs, filePath)) return {
2493
+ fileSystem: fs,
2494
+ filePath
2495
+ };
2496
+ }
2497
+ }
2498
+ async #readText(pathname) {
2499
+ const file = await this.#find(pathname);
2500
+ return file && String(await readFile(file.fileSystem, file.filePath));
2501
+ }
2502
+ async readRules() {
2503
+ await this.#waitUntilValid();
2504
+ return {
2505
+ headers: await this.#readText("/_headers"),
2506
+ redirects: await this.#readText("/_redirects")
2507
+ };
2508
+ }
2509
+ /** Answers the asset Worker's lookups, using the pathname itself as the ETag. */
2510
+ async handle(request) {
2511
+ const url = new URL(request.url);
2512
+ const pathname = url.searchParams.get(url.pathname === "/exists" ? "pathname" : "eTag") ?? "";
2513
+ await this.#waitUntilValid();
2514
+ const file = RESERVED_FILES.has(pathname) ? void 0 : await this.#find(pathname);
2515
+ if (url.pathname === "/exists") return miniflare.Response.json(file ? pathname : null);
2516
+ if (!file) return new miniflare.Response(null, { status: 404 });
2517
+ const body = await readFile(file.fileSystem, file.filePath);
2518
+ return new miniflare.Response(body, { headers: { "Content-Type": getContentType(file.filePath) ?? "application/octet-stream" } });
2519
+ }
2520
+ };
2521
+ /** Adds the build's `_headers` and `_redirects` to wrangler's asset config, the way Miniflare does for wrangler dev. */
2522
+ function getAssetConfig(options, rules, logger) {
2523
+ const { assetConfig, routerConfig } = options;
2524
+ const parserLogger = {
2525
+ debug: () => {},
2526
+ log: () => {},
2527
+ info: (message) => logger.info(message),
2528
+ warn: (message) => logger.warn(message),
2529
+ error: (error) => logger.error(error.message)
2530
+ };
2531
+ const config = {
2532
+ ...assetConfig,
2533
+ debug: true,
2534
+ has_static_routing: Boolean(routerConfig.static_routing)
2535
+ };
2536
+ if (rules.redirects !== void 0) {
2537
+ const redirects = parseRedirects(rules.redirects, { htmlHandling: assetConfig.html_handling });
2538
+ Object.assign(config, constructRedirects({
2539
+ redirects,
2540
+ redirectsFile: "_redirects",
2541
+ logger: parserLogger
2542
+ }));
2543
+ }
2544
+ if (rules.headers !== void 0) Object.assign(config, constructHeaders({
2545
+ headers: parseHeaders(rules.headers),
2546
+ headersFile: "_headers",
2547
+ logger: parserLogger
2548
+ }));
2549
+ return config;
2550
+ }
2551
+ /** Miniflare options for Cloudflare's router and asset Workers, with assets coming from `assets` instead of a manifest. */
2552
+ function getAssetWorkers(options) {
2553
+ const routerPath = getInternalWorkerPath("router-worker");
2554
+ const assetPath = getInternalWorkerPath("asset-worker");
2555
+ return [{
2556
+ name: ROUTER_WORKER_NAME,
2557
+ compatibilityDate: INTERNAL_WORKERS_COMPATIBILITY_DATE,
2558
+ compatibilityFlags: ["enable_ctx_exports"],
2559
+ modulesRoot: path.dirname(routerPath),
2560
+ modules: [{
2561
+ type: "ESModule",
2562
+ path: routerPath
2563
+ }],
2564
+ bindings: { CONFIG: toJsonBinding(options.routerConfig) },
2565
+ serviceBindings: {
2566
+ ASSET_WORKER: ASSET_WORKER_NAME,
2567
+ ...options.userWorkerName !== void 0 && { USER_WORKER: options.userWorkerName }
2568
+ },
2569
+ unsafeRegisterWorker: false
2570
+ }, {
2571
+ name: ASSET_WORKER_NAME,
2572
+ compatibilityDate: INTERNAL_WORKERS_COMPATIBILITY_DATE,
2573
+ modulesRoot: path.dirname(assetPath),
2574
+ modules: [{
2575
+ type: "ESModule",
2576
+ path: assetPath
2577
+ }],
2578
+ bindings: { CONFIG: toJsonBinding(options.assetConfig) },
2579
+ serviceBindings: { __RSPACK_ASSETS__: (request) => options.assets.handle(request) },
2580
+ unsafeRegisterWorker: false
2581
+ }];
2582
+ }
2583
+ // src/containers.ts
2584
+ /** `WRANGLER_DOCKER_BIN`, like wrangler, so both find the same Docker. */
2585
+ function getDockerPath() {
2586
+ return process.env.WRANGLER_DOCKER_BIN || "docker";
2587
+ }
2588
+ /** The images a Worker's Containers need, tagged to match the Durable Object options wrangler generates with the same build id. */
2589
+ function getContainerOptions(config, containerBuildId) {
2590
+ return createContainerDevPlan({
2591
+ containers: config.containers,
2592
+ exports: config.exports,
2593
+ configPath: config.configPath,
2594
+ containerBuildId
2595
+ })?.containerOptions ?? [];
2596
+ }
2597
+ /** The Docker endpoint workerd starts containers through; Miniflare picks the egress sidecar image itself. */
2598
+ function getContainerEngine(config, dockerPath) {
2599
+ return config.dev.container_engine ?? resolveDockerHost(dockerPath);
2600
+ }
2601
+ /** Builds or pulls each image and the egress sidecar the way wrangler dev does, including its Windows and Docker checks. */
2602
+ async function prepareContainerImages(options) {
2603
+ const { config } = options;
2604
+ await prepareContainerImagesForDev({
2605
+ dockerPath: options.dockerPath,
2606
+ containerOptions: options.containerOptions,
2607
+ onContainerImagePreparationStart: () => {},
2608
+ onContainerImagePreparationEnd: () => {},
2609
+ logger: options.logger,
2610
+ complianceConfig: config,
2611
+ configFileName: path.basename(config.configPath ?? "wrangler.json"),
2612
+ registryConfigureCommand: "wrangler containers registries configure"
2613
+ });
2614
+ }
2615
+ /** Force-removes containers started from these images; synchronous so it can also run while the process exits. */
2616
+ function removeContainers(dockerPath, tags) {
2617
+ if (tags.size > 0) cleanupContainers(dockerPath, tags);
2618
+ }
2619
+ // src/dev-entry.ts
2620
+ const RUNTIME_PATH = fileURLToPath(new URL("../runtime/dev-runtime.js", import.meta.url));
2621
+ const HMR_RUNNER_CLASS = "__RSPACK_HMR_RUNNER__";
2622
+ const HMR_TOKEN_BINDING = "__RSPACK_HMR_TOKEN__";
2623
+ const HMR_HEADER = "x-rspack-plugin-cloudflare-hmr";
2624
+ function toSpecifier(filePath) {
2625
+ return JSON.stringify(filePath.replaceAll("\\", "/"));
2626
+ }
2627
+ /** Export names we can know before building: `default` plus the Durable Object and Workflow classes this Worker owns. */
2628
+ function getConfiguredExports(worker) {
2629
+ const names = /* @__PURE__ */ new Set(["default"]);
2630
+ for (const binding of worker.config.durable_objects.bindings) if (!binding.script_name) names.add(binding.class_name);
2631
+ for (const workflow of worker.config.workflows) if (!workflow.script_name) names.add(workflow.class_name);
2632
+ return [...names].toSorted((left, right) => left.localeCompare(right));
2633
+ }
2634
+ /**
2635
+ * Source for the dev-only entry around `main`. It accepts hot updates to `main` so rspack re-evaluates the changed
2636
+ * modules in place, and re-exports each of the user's exports through a wrapper that always calls the current code.
2637
+ */
2638
+ function createDevEntrySource(main, exportNames) {
2639
+ const mainSpecifier = toSpecifier(main);
2640
+ const lines = [
2641
+ `import * as worker from ${mainSpecifier};`,
2642
+ `import { initialize, wrapExport, RspackHmrRunner } from ${toSpecifier(RUNTIME_PATH)};`,
2643
+ "initialize(() => worker);",
2644
+ `if (import.meta.webpackHot) import.meta.webpackHot.accept(${mainSpecifier});`,
2645
+ `export { RspackHmrRunner as ${HMR_RUNNER_CLASS} };`
2646
+ ];
2647
+ for (const [index, name] of exportNames.entries()) lines.push(`const export${index} = wrapExport(${JSON.stringify(name)});`, `export { export${index} as ${JSON.stringify(name)} };`);
2648
+ return `${lines.join("\n")}\n`;
2649
+ }
2650
+ // src/dev-worker.ts
2651
+ const HOT_UPDATE_RE = /\.hot-update\.(?:json\.)?mjs$/;
2652
+ function isPlainObject(value) {
2653
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2654
+ }
2655
+ /** The export names rspack found on `main`, or undefined when it couldn't tell, like for CommonJS. */
2656
+ function getProvidedExports(stats, main) {
2657
+ const { modules = [] } = stats.toJson({
2658
+ all: false,
2659
+ modules: true,
2660
+ providedExports: true
2661
+ });
2662
+ const provided = modules.find((module) => module.nameForCondition && path.resolve(module.nameForCondition) === path.resolve(main))?.providedExports;
2663
+ return Array.isArray(provided) ? provided.map(String).toSorted((left, right) => left.localeCompare(right)) : void 0;
2664
+ }
2665
+ /** One Worker in a dev session: its rspack watcher, its hot updates, and its slice of the Miniflare config. */
2666
+ var DevWorker = class {
2667
+ #compiler;
2668
+ #options;
2669
+ #logger;
2670
+ #events;
2671
+ #resolve;
2672
+ #hmrToken = randomUUID();
2673
+ #resolved;
2674
+ #watching;
2675
+ #virtualModules;
2676
+ #additionalModules;
2677
+ #exportNames = [];
2678
+ #loadedModules = "";
2679
+ #builtModules = [];
2680
+ #restartReason = "it is starting";
2681
+ #remoteProxy = null;
2682
+ #containerBuildId = "";
2683
+ buildError;
2684
+ building = true;
2685
+ constructor(options) {
2686
+ this.#compiler = options.compiler;
2687
+ this.#options = options.pluginOptions;
2688
+ this.#logger = options.logger;
2689
+ this.#events = options.events;
2690
+ this.#resolve = options.resolve;
2691
+ this.#resolved = options.resolve();
2692
+ }
2693
+ get #outputDir() {
2694
+ return path.join(this.#resolved.rootDir, ".wrangler", "rspack", this.#resolved.name);
2695
+ }
2696
+ get #entryPath() {
2697
+ return path.join(this.#resolved.rootDir, ".wrangler", "tmp", `rspack-${this.#resolved.name}`, "dev-entry.js");
2698
+ }
2699
+ /** Records a finished build, returning false when it triggered another build that should be waited for instead. */
2700
+ #handleBuild(main, error, stats) {
2701
+ if (error || !stats || stats.hasErrors() || !("compilation" in stats)) {
2702
+ this.buildError = error?.message ?? stats?.toString({
2703
+ preset: "errors-only",
2704
+ colors: false
2705
+ }) ?? "Unknown error";
2706
+ return true;
2707
+ }
2708
+ const exportNames = getProvidedExports(stats, main);
2709
+ if (exportNames && exportNames.join(",") !== this.#exportNames.join(",")) {
2710
+ this.#exportNames = exportNames;
2711
+ this.#restartReason ??= "its exports changed";
2712
+ this.#virtualModules?.writeModule(this.#entryPath, createDevEntrySource(main, exportNames));
2713
+ this.#rebuildEntry();
2714
+ return false;
2715
+ }
2716
+ const entryExports = getProvidedExports(stats, this.#entryPath)?.filter((name) => name !== HMR_RUNNER_CLASS);
2717
+ if (entryExports && entryExports.join(",") !== this.#exportNames.join(",")) {
2718
+ this.#rebuildEntry();
2719
+ return false;
2720
+ }
2721
+ this.buildError = void 0;
2722
+ return true;
2723
+ }
2724
+ #rebuildEntry() {
2725
+ this.#watching?.invalidateWithChangesAndRemovals(/* @__PURE__ */ new Set([this.#entryPath]));
2726
+ }
2727
+ #getModules() {
2728
+ const modules = [{
2729
+ type: "ESModule",
2730
+ path: path.join(this.#outputDir, "index.js")
2731
+ }];
2732
+ for (const { fileName, type } of this.#additionalModules?.modules ?? []) modules.push({
2733
+ type,
2734
+ path: path.join(this.#outputDir, fileName)
2735
+ });
2736
+ return modules;
2737
+ }
2738
+ #readBuiltModules() {
2739
+ return this.#getModules().map((module) => {
2740
+ return {
2741
+ ...module,
2742
+ contents: readFileSync(module.path)
2743
+ };
2744
+ });
2745
+ }
2746
+ /** Starts or refreshes the proxy for bindings marked `remote: true`, which wrangler only opens when some exist. */
2747
+ async #getRemoteProxyConnectionString() {
2748
+ if (this.#options.remoteBindings === false) return;
2749
+ const { config } = this.#resolved;
2750
+ this.#remoteProxy = await maybeStartOrUpdateRemoteProxySession({
2751
+ name: config.name,
2752
+ bindings: unstable_convertConfigBindingsToStartWorkerBindings(config) ?? {},
2753
+ account_id: config.account_id,
2754
+ complianceRegion: config.compliance_region
2755
+ }, this.#remoteProxy);
2756
+ return this.#remoteProxy?.session.remoteProxyConnectionString;
2757
+ }
2758
+ async #closeWatcher() {
2759
+ const watching = this.#watching;
2760
+ this.#watching = void 0;
2761
+ await new Promise((resolve) => {
2762
+ if (watching) watching.close(() => resolve());
2763
+ else resolve();
2764
+ });
2765
+ }
2766
+ get resolved() {
2767
+ return this.#resolved;
2768
+ }
2769
+ get name() {
2770
+ return this.#resolved.name;
2771
+ }
2772
+ /** Why the next build needs a restart instead of a hot update, if it does. */
2773
+ get restartReason() {
2774
+ if (this.#restartReason) return this.#restartReason;
2775
+ if (JSON.stringify(this.#getModules()) !== this.#loadedModules) return "its .wasm or .bin modules changed";
2776
+ }
2777
+ start() {
2778
+ const { main } = this.#resolved;
2779
+ this.#containerBuildId = generateContainerBuildId();
2780
+ if (!main) {
2781
+ this.building = false;
2782
+ return;
2783
+ }
2784
+ this.building = true;
2785
+ this.#exportNames = getConfiguredExports(this.#resolved);
2786
+ const { config, virtualModules, additionalModules } = createWorkerConfig({
2787
+ compiler: this.#compiler,
2788
+ worker: this.#resolved,
2789
+ pluginOptions: this.#options,
2790
+ outputDir: this.#outputDir,
2791
+ entry: this.#entryPath,
2792
+ entrySource: createDevEntrySource(main, this.#exportNames),
2793
+ mode: "development",
2794
+ hot: true,
2795
+ publicPath: `/${this.name}/`
2796
+ });
2797
+ this.#virtualModules = virtualModules;
2798
+ this.#additionalModules = additionalModules;
2799
+ const workerCompiler = this.#compiler.rspack.rspack(config);
2800
+ workerCompiler.hooks.invalid.tap("rspack-plugin-cloudflare", () => {
2801
+ this.building = true;
2802
+ this.#events.onBuildStart(this);
2803
+ });
2804
+ this.#watching = workerCompiler.watch({}, (error, stats) => {
2805
+ if (this.#handleBuild(main, error, stats)) {
2806
+ if (!this.buildError) this.#builtModules = this.#readBuiltModules();
2807
+ this.building = false;
2808
+ this.#events.onBuildDone(this).catch((loadError) => {
2809
+ this.#logger.error(`Worker "${this.name}" failed to load: ${String(loadError)}`);
2810
+ });
2811
+ }
2812
+ });
2813
+ }
2814
+ /** Re-reads the Wrangler config and rebuilds from scratch, since anything from `main` to bindings may have changed. */
2815
+ async reload() {
2816
+ await this.#closeWatcher();
2817
+ this.#resolved = this.#resolve();
2818
+ this.#restartReason = "its Wrangler config changed";
2819
+ this.start();
2820
+ }
2821
+ /** Records that Miniflare is now running this Worker's latest build. */
2822
+ markLoaded() {
2823
+ this.#restartReason = void 0;
2824
+ this.#loadedModules = JSON.stringify(this.#getModules());
2825
+ }
2826
+ /** Asks the running Worker to apply its pending hot update, through a fetch its dev entry recognizes by token. */
2827
+ async applyHotUpdate(mf) {
2828
+ const response = await mf.dispatchFetch("http://localhost/", { headers: {
2829
+ [HMR_HEADER]: this.#hmrToken,
2830
+ [miniflare.CoreHeaders.ROUTE_OVERRIDE]: this.name
2831
+ } });
2832
+ const result = await response.json().catch(() => {});
2833
+ if (isPlainObject(result) && result.reload === false) return { reload: false };
2834
+ return {
2835
+ reload: true,
2836
+ reason: isPlainObject(result) && typeof result.reason === "string" ? result.reason : `the update request failed (${response.status})`
2837
+ };
2838
+ }
2839
+ /** Reads one of this Worker's hot-update modules, given its path below the Worker's public path. */
2840
+ async readHotUpdate(relativePath) {
2841
+ const filePath = path.join(this.#outputDir, relativePath);
2842
+ if (!HOT_UPDATE_RE.test(filePath) || !filePath.startsWith(this.#outputDir + path.sep)) return;
2843
+ return fs$1.readFile(filePath, "utf8");
2844
+ }
2845
+ /** Where assets imported by the Worker's code are emitted, laid out the way they're served. */
2846
+ get importedAssetsDir() {
2847
+ return path.join(this.#outputDir, IMPORTED_ASSETS_DIR);
2848
+ }
2849
+ /**
2850
+ * This Worker's Miniflare options, any external Workers wrangler adds for its bindings, the container images it needs,
2851
+ * and its asset options, which configure the router and asset Workers the session runs.
2852
+ */
2853
+ async getMiniflareOptions(extraServiceBindings, inspectorEnabled) {
2854
+ const { config, environment } = this.#resolved;
2855
+ const remoteProxyConnectionString = await this.#getRemoteProxyConnectionString();
2856
+ const { workerOptions, externalWorkers } = unstable_getMiniflareWorkerOptions(config, environment, {
2857
+ remoteProxyConnectionString,
2858
+ containerBuildId: this.#containerBuildId
2859
+ });
2860
+ const { modulesRules: _modulesRules, assets, ...options } = workerOptions;
2861
+ const containersEnabled = Boolean(config.containers?.length) && config.dev.enable_containers;
2862
+ let assetWorkerOptions;
2863
+ if (assets) {
2864
+ const { routerConfig, assetConfig } = assets;
2865
+ assetWorkerOptions = {
2866
+ routerConfig,
2867
+ assetConfig
2868
+ };
2869
+ }
2870
+ return {
2871
+ assetWorkerOptions,
2872
+ externalWorkers,
2873
+ containerOptions: containersEnabled ? getContainerOptions(config, this.#containerBuildId) : [],
2874
+ worker: {
2875
+ ...options,
2876
+ name: this.name,
2877
+ durableObjects: {
2878
+ ...options.durableObjects,
2879
+ [HMR_RUNNER_CLASS]: {
2880
+ className: HMR_RUNNER_CLASS,
2881
+ unsafeUniqueKey: miniflare.kUnsafeEphemeralUniqueKey,
2882
+ unsafePreventEviction: true
2883
+ }
2884
+ },
2885
+ unsafeUseModuleFallbackService: true,
2886
+ bindings: {
2887
+ ...options.bindings,
2888
+ [HMR_TOKEN_BINDING]: this.#hmrToken
2889
+ },
2890
+ serviceBindings: {
2891
+ ...options.serviceBindings,
2892
+ ...extraServiceBindings
2893
+ },
2894
+ modulesRoot: this.#outputDir,
2895
+ modules: this.#builtModules,
2896
+ unsafeInspectorProxy: inspectorEnabled
2897
+ }
2898
+ };
2899
+ }
2900
+ async dispose() {
2901
+ await this.#closeWatcher();
2902
+ await this.#remoteProxy?.session.dispose();
2903
+ this.#remoteProxy = null;
2904
+ }
2905
+ };
2906
+ // src/http.ts
2907
+ function getRequestUrl(req) {
2908
+ const forwardedProto = req.headers["x-forwarded-proto"];
2909
+ let protocol = "http:";
2910
+ if (typeof forwardedProto === "string") protocol = `${forwardedProto.split(",", 1)[0]?.trim()}:`;
2911
+ else if (req.socket.encrypted) protocol = "https:";
2912
+ const host = req.headers[":authority"] ?? req.headers.host ?? "localhost";
2913
+ return new URL(req.url ?? "/", `${protocol}//${String(host)}`);
2914
+ }
2915
+ function getRequestHeaders(req) {
2916
+ const headers = new Headers();
2917
+ for (const [name, value] of Object.entries(req.headers)) {
2918
+ if (value === void 0 || name.startsWith(":")) continue;
2919
+ if (Array.isArray(value)) for (const item of value) headers.append(name, item);
2920
+ else headers.set(name, value);
2921
+ }
2922
+ return headers;
2923
+ }
2924
+ function createRequestInit(req, res) {
2925
+ const controller = new AbortController();
2926
+ res.on("close", () => controller.abort());
2927
+ const headers = getRequestHeaders(req);
2928
+ headers.set("accept-encoding", "identity");
2929
+ const method = req.method ?? "GET";
2930
+ const hasBody = method !== "GET" && method !== "HEAD";
2931
+ return {
2932
+ method,
2933
+ headers: [...headers],
2934
+ body: hasBody ? Readable.toWeb(req) : void 0,
2935
+ duplex: "half",
2936
+ redirect: "manual",
2937
+ signal: controller.signal
2938
+ };
2939
+ }
2940
+ function escapeHtml(text) {
2941
+ return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
2942
+ }
2943
+ /** Responds with the error's (source-mapped) stack, as a page for browsers and plain text for everything else. */
2944
+ function sendErrorPage(res, error) {
2945
+ if (res.headersSent) {
2946
+ res.destroy();
2947
+ return;
2948
+ }
2949
+ const message = error instanceof Error ? error.stack ?? error.message : String(error);
2950
+ if (res.req.headers.accept?.includes("text/html")) {
2951
+ res.writeHead(500, { "Content-Type": "text/html; charset=utf-8" });
2952
+ res.end(`<!doctype html><title>Worker error</title><body style="font-family:system-ui;margin:2rem"><h1>Worker error</h1><pre style="white-space:pre-wrap">${escapeHtml(message)}</pre></body>`);
2953
+ return;
2954
+ }
2955
+ res.writeHead(500, { "Content-Type": "text/plain; charset=utf-8" });
2956
+ res.end(message);
2957
+ }
2958
+ function sendResponse(res, response) {
2959
+ const headers = {};
2960
+ for (const [name, value] of response.headers) {
2961
+ if (name === "set-cookie") continue;
2962
+ headers[name] = value;
2963
+ }
2964
+ const cookies = response.headers.getSetCookie();
2965
+ if (cookies.length > 0) headers["set-cookie"] = cookies;
2966
+ res.writeHead(response.status, headers);
2967
+ if (!response.body || res.req.method === "HEAD") {
2968
+ res.end();
2969
+ return;
2970
+ }
2971
+ const body = Readable.fromWeb(response.body);
2972
+ res.on("close", () => body.destroy());
2973
+ body.pipe(res);
2974
+ }
2975
+ // src/inspector.ts
2976
+ const DEBUG_PATH = "/__debug";
2977
+ const DEFAULT_INSPECTOR_PORT = 9229;
2978
+ function isPortFree(port) {
2979
+ return new Promise((resolve) => {
2980
+ const server = net.createServer();
2981
+ server.once("error", () => resolve(false));
2982
+ server.listen(port, "127.0.0.1", () => {
2983
+ server.close(() => resolve(true));
2984
+ });
2985
+ });
2986
+ }
2987
+ /** Resolves the inspector port: the configured one, or 9229 falling back to the next free port like the Vite plugin. */
2988
+ async function resolveInspectorPort(option) {
2989
+ if (option === false) return;
2990
+ if (option !== void 0) return option;
2991
+ for (let port = DEFAULT_INSPECTOR_PORT; port < 65535; port++) if (await isPortFree(port)) return port;
2992
+ }
2993
+ /** A page that sends the browser to Cloudflare's hosted DevTools, connected to each Worker through Miniflare's inspector proxy. */
2994
+ function getDebugPageHtml(workerNames, inspectorPort) {
2995
+ const urls = workerNames.map((name) => {
2996
+ return `https://devtools.devprod.cloudflare.dev/js_app?${new URLSearchParams({
2997
+ theme: "systemPreferred",
2998
+ debugger: "true",
2999
+ ws: `localhost:${inspectorPort}/${name}`,
3000
+ domain: name
3001
+ }).toString()}`;
3002
+ });
3003
+ return `<!doctype html><script>
3004
+ const [first, ...rest] = ${JSON.stringify(urls)};
3005
+ for (const url of rest) {
3006
+ window.open(url);
3007
+ }
3008
+ window.location.replace(first);
3009
+ <\/script>`;
3010
+ }
3011
+ // src/dev.ts
3012
+ const PLUGIN_NAME$1 = "rspack-plugin-cloudflare";
3013
+ const DEV_SERVER_PATH_RE = /^\/(?:webpack-dev-server|__webpack_dev_server__|__open-in-editor|lazy-compilation-using-)/;
3014
+ const MINIFLARE_PATH_RE = /^\/(?:cdn-cgi\/local|__cf_local)\//;
3015
+ const LEGACY_PATH_REWRITES = [
3016
+ ["/cdn-cgi/handler", "/cdn-cgi/local"],
3017
+ ["/cdn-cgi/mf/scheduled", "/cdn-cgi/local/scheduled"],
3018
+ ["/cdn-cgi/mf/stream", "/__cf_local/stream"],
3019
+ ["/cdn-cgi/mf/imagedelivery", "/__cf_local/imagedelivery"],
3020
+ ["/cdn-cgi/explorer", "/cdn-cgi/local/explorer"]
3021
+ ];
3022
+ const SECRETS_FILE_RE = /^\.(?:dev\.vars|env)(?:\..+)?$/;
3023
+ function rewriteLegacyMiniflarePath(pathname) {
3024
+ for (const [oldPrefix, newPrefix] of LEGACY_PATH_REWRITES) if (pathname === oldPrefix || pathname.startsWith(`${oldPrefix}/`)) return newPrefix + pathname.slice(oldPrefix.length);
3025
+ return pathname;
3026
+ }
3027
+ /** Runs the entry Worker and any auxiliary Workers in one Miniflare, routing dev server requests like Cloudflare does. */
3028
+ var DevSession = class {
3029
+ #compiler;
3030
+ #options;
3031
+ #logger;
3032
+ #workers;
3033
+ #entry;
3034
+ #hooks;
3035
+ #assets;
3036
+ #miniflare;
3037
+ #inspectorPort;
3038
+ #configWatchers = [];
3039
+ #containerTags = /* @__PURE__ */ new Set();
3040
+ #removeContainersOnExit = () => removeContainers(getDockerPath(), this.#containerTags);
3041
+ #updated = /* @__PURE__ */ new Set();
3042
+ #failing = /* @__PURE__ */ new Set();
3043
+ #loading = Promise.resolve();
3044
+ #gate;
3045
+ #assetRules;
3046
+ constructor(options) {
3047
+ this.#compiler = options.compiler;
3048
+ this.#options = options.pluginOptions;
3049
+ this.#logger = options.logger;
3050
+ this.#workers = options.resolvers.map((resolve) => new DevWorker({
3051
+ compiler: options.compiler,
3052
+ resolve,
3053
+ pluginOptions: options.pluginOptions,
3054
+ logger: options.logger,
3055
+ events: {
3056
+ onBuildStart: () => this.#openGate(),
3057
+ onBuildDone: (worker) => {
3058
+ this.#loading = this.#loading.then(() => this.#onBuildDone(worker));
3059
+ return this.#loading;
3060
+ }
3061
+ }
3062
+ }));
3063
+ const [entry] = this.#workers;
3064
+ if (!entry) throw new Error("A dev session needs at least one Worker.");
3065
+ this.#entry = entry;
3066
+ this.#openGate();
3067
+ }
3068
+ #openGate() {
3069
+ if (this.#gate) return;
3070
+ const { promise, resolve } = Promise.withResolvers();
3071
+ this.#gate = {
3072
+ promise,
3073
+ release: resolve
3074
+ };
3075
+ }
3076
+ #releaseGateIfIdle() {
3077
+ if (this.#gate && this.#workers.every((worker) => !worker.building)) {
3078
+ this.#gate.release();
3079
+ this.#gate = void 0;
3080
+ }
3081
+ }
3082
+ async #ready() {
3083
+ while (this.#gate) await this.#gate.promise;
3084
+ return this.#miniflare;
3085
+ }
3086
+ async #onBuildDone(worker) {
3087
+ if (worker.buildError) {
3088
+ this.#failing.add(worker);
3089
+ this.#logger.error(`Worker "${worker.name}" build failed${this.#miniflare ? "; still serving the previous build" : ""}:\n${worker.buildError}`);
3090
+ this.#hooks?.sendToClients("errors", [{
3091
+ moduleName: `Worker "${worker.name}"`,
3092
+ message: worker.buildError
3093
+ }]);
3094
+ } else {
3095
+ this.#updated.add(worker);
3096
+ if (this.#failing.delete(worker) && this.#failing.size === 0) this.#hooks?.sendToClients("still-ok");
3097
+ }
3098
+ if (this.#workers.some((other) => other.building)) return;
3099
+ try {
3100
+ await this.#load();
3101
+ } catch (error) {
3102
+ this.#logger.error(`Workers failed to start:\n${String(error)}`);
3103
+ }
3104
+ this.#releaseGateIfIdle();
3105
+ }
3106
+ /** Gets new builds running: hot updates when possible, otherwise a restart of every Worker. */
3107
+ async #load() {
3108
+ if (!this.#miniflare) {
3109
+ if (this.#failing.size > 0) return;
3110
+ this.#miniflare = new miniflare.Miniflare(await this.#getMiniflareOptions());
3111
+ await this.#miniflare.ready;
3112
+ this.#printReady();
3113
+ this.#markLoaded();
3114
+ return;
3115
+ }
3116
+ const restart = this.#workers.find((worker) => worker.restartReason);
3117
+ if (restart) {
3118
+ await this.#restart(`Worker "${restart.name}" restarted: ${restart.restartReason ?? ""}`);
3119
+ return;
3120
+ }
3121
+ for (const worker of this.#updated) {
3122
+ const result = await worker.applyHotUpdate(this.#miniflare);
3123
+ if (result.reload) {
3124
+ await this.#restart(`Worker "${worker.name}" restarted: ${result.reason ?? "the update could not be applied in place"}`);
3125
+ return;
3126
+ }
3127
+ this.#logger.info(`Worker "${worker.name}" hot updated`);
3128
+ }
3129
+ this.#updated.clear();
3130
+ }
3131
+ async #restart(message) {
3132
+ await this.#miniflare?.setOptions(await this.#getMiniflareOptions());
3133
+ this.#logger.info(message);
3134
+ this.#markLoaded();
3135
+ }
3136
+ #markLoaded() {
3137
+ for (const worker of this.#workers) worker.markLoaded();
3138
+ this.#updated.clear();
3139
+ }
3140
+ #printReady() {
3141
+ for (const worker of this.#workers) {
3142
+ const { config, name } = worker.resolved;
3143
+ unstable_printBindings(unstable_convertConfigBindingsToStartWorkerBindings(config), {
3144
+ name,
3145
+ local: true,
3146
+ warnIfNoBindings: false,
3147
+ isMultiWorker: this.#workers.length > 1,
3148
+ containers: config.containers,
3149
+ tailConsumers: config.tail_consumers,
3150
+ streamingTailConsumers: config.streaming_tail_consumers,
3151
+ log: (message) => this.#logger.info(message)
3152
+ });
3153
+ }
3154
+ const names = this.#workers.map((worker) => `"${worker.name}"`).join(", ");
3155
+ const debug = this.#inspectorPort === void 0 ? "" : `; debug at ${DEBUG_PATH} (inspector on port ${this.#inspectorPort})`;
3156
+ this.#logger.info(`${this.#workers.length > 1 ? "Workers" : "Worker"} ${names} ready${debug}`);
3157
+ }
3158
+ /** Serves rspack's hot-update modules, which workerd imports through Miniflare's module fallback as `/<worker>/<file>`. */
3159
+ async #serveHotUpdate(request) {
3160
+ const [, workerName = "", ...rest] = ((await miniflare.parseModuleFallbackRequest(request))?.specifier ?? "").split("/");
3161
+ const source = await this.#workers.find((candidate) => candidate.name === workerName)?.readHotUpdate(rest.join("/"));
3162
+ if (source === void 0) return new miniflare.Response(null, { status: 404 });
3163
+ return miniflare.Response.json({ esModule: source });
3164
+ }
3165
+ #assetsServiceBinding() {
3166
+ const binding = this.#entry.resolved.assets?.binding;
3167
+ if (!binding || !this.#assets) return {};
3168
+ return { [binding]: ASSET_WORKER_NAME };
3169
+ }
3170
+ /** Builds images not seen yet this session, returning the engine Miniflare should start containers with. */
3171
+ async #prepareContainers(workers) {
3172
+ const withContainers = workers.filter((worker) => worker.containerOptions.length > 0);
3173
+ const [first] = withContainers;
3174
+ if (!first) return;
3175
+ const dockerPath = getDockerPath();
3176
+ const pending = withContainers.map(({ config, containerOptions }) => {
3177
+ return {
3178
+ config,
3179
+ containerOptions: containerOptions.filter((options) => !this.#containerTags.has(options.image_tag))
3180
+ };
3181
+ });
3182
+ if (pending.some((worker) => worker.containerOptions.length > 0)) {
3183
+ this.#logger.info("Building container images for local development...");
3184
+ for (const { config, containerOptions } of pending) {
3185
+ await prepareContainerImages({
3186
+ config,
3187
+ dockerPath,
3188
+ containerOptions,
3189
+ logger: this.#logger
3190
+ });
3191
+ for (const options of containerOptions) this.#containerTags.add(options.image_tag);
3192
+ }
3193
+ process.off("exit", this.#removeContainersOnExit);
3194
+ process.on("exit", this.#removeContainersOnExit);
3195
+ this.#logger.info("Container images built; restart dev to rebuild them after changing a Dockerfile.");
3196
+ }
3197
+ return getContainerEngine(first.config, dockerPath);
3198
+ }
3199
+ async #getAssetWorkers(assetWorkerOptions) {
3200
+ const assets = this.#assets;
3201
+ if (!assetWorkerOptions || !assets) return [];
3202
+ this.#assetRules = await assets.readRules();
3203
+ return getAssetWorkers({
3204
+ routerConfig: assetWorkerOptions.routerConfig,
3205
+ assetConfig: getAssetConfig(assetWorkerOptions, this.#assetRules, this.#logger),
3206
+ userWorkerName: this.#entry.resolved.main ? this.#entry.name : void 0,
3207
+ assets
3208
+ });
3209
+ }
3210
+ /** Restarts the Workers when the build's `_headers` or `_redirects` change, since the asset Worker reads them at startup. */
3211
+ async #checkAssetRules() {
3212
+ const previous = this.#assetRules;
3213
+ if (!this.#miniflare || !this.#assets || !previous) return;
3214
+ const current = await this.#assets.readRules();
3215
+ if (current.headers !== previous.headers || current.redirects !== previous.redirects) await this.#restart("Workers restarted: _headers or _redirects changed");
3216
+ }
3217
+ async #getMiniflareOptions() {
3218
+ const workers = [];
3219
+ const externalWorkers = [];
3220
+ const containers = [];
3221
+ let assetWorkerOptions;
3222
+ for (const worker of this.#workers) {
3223
+ const extraBindings = worker === this.#entry ? this.#assetsServiceBinding() : {};
3224
+ const options = await worker.getMiniflareOptions(extraBindings, this.#inspectorPort !== void 0);
3225
+ if (worker === this.#entry) assetWorkerOptions = options.assetWorkerOptions;
3226
+ if (!worker.resolved.main) continue;
3227
+ workers.push(options.worker);
3228
+ externalWorkers.push(...options.externalWorkers);
3229
+ containers.push({
3230
+ config: worker.resolved.config,
3231
+ containerOptions: options.containerOptions
3232
+ });
3233
+ }
3234
+ const containerEngine = await this.#prepareContainers(containers);
3235
+ const assetWorkers = await this.#getAssetWorkers(assetWorkerOptions);
3236
+ const { rootDir } = this.#entry.resolved;
3237
+ const { persistState = true } = this.#options;
3238
+ let resourcePersistencePath;
3239
+ if (persistState !== false) {
3240
+ const statePath = typeof persistState === "object" ? persistState.path : path.join(".wrangler", "state");
3241
+ resourcePersistencePath = path.resolve(rootDir, statePath, "v3");
3242
+ }
3243
+ return miniflare.convertV4MiniflareOptions({
3244
+ log: new miniflare.Log(miniflare.LogLevel.INFO),
3245
+ inspectorPort: this.#inspectorPort,
3246
+ resourcePersistencePath,
3247
+ resourceTmpPath: path.join(rootDir, ".wrangler", "tmp"),
3248
+ containerEngine,
3249
+ unsafeDevRegistryPath: miniflare.getDefaultDevRegistryPath(),
3250
+ unsafeTriggerHandlers: true,
3251
+ unsafeModuleFallbackService: (request) => this.#serveHotUpdate(request),
3252
+ workers: [
3253
+ ...workers,
3254
+ ...assetWorkers,
3255
+ ...externalWorkers
3256
+ ]
3257
+ });
3258
+ }
3259
+ #createDevAssets() {
3260
+ const { assets } = this.#entry.resolved;
3261
+ const hooks = this.#hooks;
3262
+ if (!assets || !hooks) return;
3263
+ return new DevAssets({
3264
+ directory: assets.directory,
3265
+ extraDirectories: [this.#entry.importedAssetsDir],
3266
+ getOutputFileSystem: () => this.#compiler.outputFileSystem ?? void 0,
3267
+ waitUntilValid: hooks.waitUntilValid
3268
+ });
3269
+ }
3270
+ /** Rebuilds a Worker when its Wrangler config or local secrets change, like the Vite plugin restarting its server. */
3271
+ #watchConfigs() {
3272
+ const pending = /* @__PURE__ */ new Map();
3273
+ const reload = (worker) => {
3274
+ clearTimeout(pending.get(worker));
3275
+ pending.set(worker, setTimeout(() => {
3276
+ pending.delete(worker);
3277
+ this.#reloadWorker(worker).catch((error) => {
3278
+ this.#logger.error(`Worker "${worker.name}" failed to reload its config:\n${String(error)}`);
3279
+ });
3280
+ }, 100));
3281
+ };
3282
+ const directories = new Set(this.#workers.map((worker) => worker.resolved.rootDir));
3283
+ for (const directory of directories) this.#configWatchers.push(fs.watch(directory, (_event, fileName) => {
3284
+ if (!fileName) return;
3285
+ for (const worker of this.#workers) {
3286
+ const { configPath, rootDir } = worker.resolved;
3287
+ if (rootDir === directory && (fileName === path.basename(configPath) || SECRETS_FILE_RE.test(fileName))) reload(worker);
3288
+ }
3289
+ }));
3290
+ }
3291
+ async #reloadWorker(worker) {
3292
+ this.#logger.info(`Worker "${worker.name}" config changed; rebuilding`);
3293
+ this.#openGate();
3294
+ await worker.reload();
3295
+ if (worker === this.#entry) this.#assets = this.#createDevAssets();
3296
+ }
3297
+ async #upgrade(webSocketServer, url, req, socket, head) {
3298
+ const mf = await this.#ready();
3299
+ if (!mf) {
3300
+ socket.destroy();
3301
+ return;
3302
+ }
3303
+ const workerSocket = (await mf.dispatchFetch(url, {
3304
+ method: req.method,
3305
+ headers: [...getRequestHeaders(req)]
3306
+ })).webSocket;
3307
+ if (!workerSocket || socket.destroyed) {
3308
+ socket.destroy();
3309
+ return;
3310
+ }
3311
+ webSocketServer.handleUpgrade(req, socket, head, (clientSocket) => {
3312
+ miniflare.coupleWebSocket(clientSocket, workerSocket).catch((error) => {
3313
+ this.#logger.error(`WebSocket to the Worker failed: ${String(error)}`);
3314
+ clientSocket.terminate();
3315
+ });
3316
+ });
3317
+ }
3318
+ #sendError(res, error) {
3319
+ this.#logger.error(error instanceof Error ? error.stack ?? error.message : String(error));
3320
+ sendErrorPage(res, error);
3321
+ }
3322
+ async #start() {
3323
+ this.#inspectorPort = await resolveInspectorPort(this.#options.inspectorPort);
3324
+ for (const worker of this.#workers) worker.start();
3325
+ this.#watchConfigs();
3326
+ if (this.#workers.every((worker) => !worker.building)) {
3327
+ this.#loading = this.#loading.then(() => this.#load());
3328
+ await this.#loading;
3329
+ }
3330
+ this.#releaseGateIfIdle();
3331
+ }
3332
+ start(hooks) {
3333
+ this.#hooks = hooks;
3334
+ this.#assets = this.#createDevAssets();
3335
+ this.#compiler.hooks.done.tap(PLUGIN_NAME$1, () => {
3336
+ this.#loading = this.#loading.then(() => this.#checkAssetRules()).catch((error) => {
3337
+ this.#logger.error(`Workers failed to pick up _headers or _redirects:\n${String(error)}`);
3338
+ });
3339
+ });
3340
+ this.#start().catch((error) => {
3341
+ this.#logger.error(`Workers failed to start:\n${String(error)}`);
3342
+ this.#gate?.release();
3343
+ });
3344
+ }
3345
+ /** Connect middleware that sends each request through Cloudflare's router Worker, or straight to the Worker without assets. */
3346
+ async handle(req, res, next) {
3347
+ const url = getRequestUrl(req);
3348
+ if (DEV_SERVER_PATH_RE.test(url.pathname)) {
3349
+ next();
3350
+ return;
3351
+ }
3352
+ if (url.pathname === "/__debug" && this.#inspectorPort !== void 0) {
3353
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
3354
+ res.end(getDebugPageHtml(this.#workers.map((worker) => worker.name), this.#inspectorPort));
3355
+ return;
3356
+ }
3357
+ try {
3358
+ url.pathname = rewriteLegacyMiniflarePath(url.pathname);
3359
+ const mf = await this.#ready();
3360
+ if (!mf) {
3361
+ sendErrorPage(res, `Workers failed to start:\n${[...this.#failing].map((worker) => `Worker "${worker.name}":\n${worker.buildError ?? ""}`).join("\n\n")}`);
3362
+ return;
3363
+ }
3364
+ const init = createRequestInit(req, res);
3365
+ if (this.#assets && !MINIFLARE_PATH_RE.test(url.pathname)) init.headers.push([miniflare.CoreHeaders.ROUTE_OVERRIDE, ROUTER_WORKER_NAME]);
3366
+ sendResponse(res, await mf.dispatchFetch(url, init));
3367
+ } catch (error) {
3368
+ this.#sendError(res, error);
3369
+ }
3370
+ }
3371
+ /** Forwards WebSocket upgrades to the Worker, leaving the dev server's own HMR socket alone. */
3372
+ attachUpgradeHandler(server, devServerSocketPath) {
3373
+ if (!this.#entry.resolved.main) return;
3374
+ const webSocketServer = new WebSocketServer({ noServer: true });
3375
+ server.on("upgrade", (req, socket, head) => {
3376
+ const url = getRequestUrl(req);
3377
+ if (url.pathname === devServerSocketPath) return;
3378
+ socket.on("error", () => socket.destroy());
3379
+ this.#upgrade(webSocketServer, url, req, socket, head).catch((error) => {
3380
+ this.#logger.error(`WebSocket upgrade to the Worker failed: ${String(error)}`);
3381
+ socket.destroy();
3382
+ });
3383
+ });
3384
+ }
3385
+ async dispose() {
3386
+ for (const watcher of this.#configWatchers) watcher.close();
3387
+ await Promise.all(this.#workers.map((worker) => worker.dispose()));
3388
+ await this.#miniflare?.dispose();
3389
+ this.#miniflare = void 0;
3390
+ this.#removeContainersOnExit();
3391
+ process.off("exit", this.#removeContainersOnExit);
3392
+ }
3393
+ };
3394
+ // src/tunnel.ts
3395
+ const QUICK_TUNNEL_URL_RE = /https:\/\/[\da-z-]+\.trycloudflare\.com/;
3396
+ const CONNECTED_RE = /Registered tunnel connection/;
3397
+ const STARTUP_TIMEOUT_MS = 3e4;
3398
+ function getWranglerBin() {
3399
+ const require = createRequire(import.meta.url);
3400
+ return path.join(path.dirname(require.resolve("wrangler/package.json")), "bin", "wrangler.js");
3401
+ }
3402
+ function stopProcessTree(child) {
3403
+ if (child.exitCode !== null || child.pid === void 0) return;
3404
+ if (process.platform === "win32") spawn("taskkill", [
3405
+ "/pid",
3406
+ String(child.pid),
3407
+ "/t",
3408
+ "/f"
3409
+ ], { stdio: "ignore" });
3410
+ else child.kill("SIGTERM");
3411
+ }
3412
+ function waitUntilConnected(child, isNamed) {
3413
+ return new Promise((resolve, reject) => {
3414
+ let output = "";
3415
+ let quickUrl;
3416
+ let settled = false;
3417
+ function fail(error) {
3418
+ if (!settled) {
3419
+ settled = true;
3420
+ stopProcessTree(child);
3421
+ reject(error);
3422
+ }
3423
+ }
3424
+ function onData(data) {
3425
+ if (output.length < 2e4) output += String(data);
3426
+ quickUrl ??= QUICK_TUNNEL_URL_RE.exec(output)?.[0];
3427
+ if (!settled && CONNECTED_RE.test(output) && (isNamed || quickUrl)) {
3428
+ settled = true;
3429
+ resolve(quickUrl);
3430
+ }
3431
+ }
3432
+ AbortSignal.timeout(STARTUP_TIMEOUT_MS).addEventListener("abort", () => {
3433
+ fail(/* @__PURE__ */ new Error(`The tunnel didn't connect within ${STARTUP_TIMEOUT_MS / 1e3}s:\n${output}`));
3434
+ });
3435
+ child.stdout?.on("data", onData);
3436
+ child.stderr?.on("data", onData);
3437
+ child.once("error", fail);
3438
+ child.once("exit", (code) => {
3439
+ fail(/* @__PURE__ */ new Error(`wrangler tunnel exited with code ${String(code)}:\n${output}`));
3440
+ });
3441
+ });
3442
+ }
3443
+ /**
3444
+ * Shares the dev server through a Cloudflare Tunnel: a Quick Tunnel on a random trycloudflare.com URL, or a named
3445
+ * tunnel whose routes point at the dev server. wrangler runs it, so it downloads and updates cloudflared as needed.
3446
+ */
3447
+ async function startTunnel(options) {
3448
+ const { origin, tunnel, config } = options;
3449
+ const args = ["tunnel"];
3450
+ const env = { ...process.env };
3451
+ let urls = [];
3452
+ if (tunnel.name === void 0) {
3453
+ args.push("quick-start", origin.href, ...(tunnel.allowedMail ?? []).flatMap((mail) => ["--allowed-mail", mail]));
3454
+ if (origin.protocol === "https:") env.NO_TLS_VERIFY = "true";
3455
+ } else {
3456
+ if (tunnel.allowedMail?.length) throw new Error("`tunnel.allowedMail` only works with Quick Tunnels; protect a named tunnel with Cloudflare Access instead.");
3457
+ const { hostnames } = await unstable_resolveNamedTunnel(tunnel.name, origin, {
3458
+ accountId: config.account_id,
3459
+ complianceRegion: config.compliance_region
3460
+ });
3461
+ urls = hostnames.map((hostname) => `https://${hostname}`);
3462
+ args.push("run", tunnel.name);
3463
+ }
3464
+ const child = spawn(process.execPath, [getWranglerBin(), ...args], {
3465
+ cwd: options.cwd,
3466
+ env,
3467
+ stdio: [
3468
+ "ignore",
3469
+ "pipe",
3470
+ "pipe"
3471
+ ]
3472
+ });
3473
+ const quickUrl = await waitUntilConnected(child, tunnel.name !== void 0);
3474
+ if (quickUrl) urls = [quickUrl];
3475
+ return {
3476
+ urls,
3477
+ close: () => stopProcessTree(child)
3478
+ };
3479
+ }
3480
+ // src/index.ts
3481
+ const PLUGIN_NAME = "rspack-plugin-cloudflare";
3482
+ const WILDCARD_HOSTS = /* @__PURE__ */ new Set([
3483
+ "0.0.0.0",
3484
+ "::",
3485
+ "local-ip",
3486
+ "local-ipv4",
3487
+ "local-ipv6"
3488
+ ]);
3489
+ function getDevServerOrigin(server) {
3490
+ const address = server.server?.address();
3491
+ const port = typeof address === "object" && address ? address.port : Number(server.options.port);
3492
+ const serverOption = server.options.server;
3493
+ const serverType = typeof serverOption === "object" ? serverOption.type : serverOption;
3494
+ const protocol = serverType === void 0 || serverType === "http" ? "http" : "https";
3495
+ const { host } = server.options;
3496
+ const hostname = !host || WILDCARD_HOSTS.has(host) ? "localhost" : host;
3497
+ return new URL(`${protocol}://${hostname}:${port}`);
3498
+ }
3499
+ /** Lets the tunnel's hostnames past the dev server's Host header check. */
3500
+ function allowHosts(server, urls) {
3501
+ const { allowedHosts } = server.options;
3502
+ if (allowedHosts === "all") return;
3503
+ const hostnames = urls.map((url) => new URL(url).hostname);
3504
+ if (Array.isArray(allowedHosts)) server.options.allowedHosts = [...allowedHosts, ...hostnames];
3505
+ else if (allowedHosts && allowedHosts !== "auto") server.options.allowedHosts = [allowedHosts, ...hostnames];
3506
+ else server.options.allowedHosts = hostnames;
3507
+ }
3508
+ function getSocketPath(server) {
3509
+ const socketOptions = server.options.webSocketServer;
3510
+ if (typeof socketOptions === "object" && socketOptions && typeof socketOptions.options?.path === "string") return socketOptions.options.path;
3511
+ return "/ws";
3512
+ }
3513
+ var CloudflarePlugin = class {
3514
+ #tunnel;
3515
+ options;
3516
+ constructor(options = {}) {
3517
+ this.options = options;
3518
+ }
3519
+ async #openTunnel(server, entry, logger) {
3520
+ const { tunnel: tunnelOption } = this.options;
3521
+ if (!entry || !tunnelOption) return;
3522
+ logger.warn("Starting a Cloudflare Tunnel: anyone with its URL can reach this dev server and its Worker's local bindings.");
3523
+ this.#tunnel = await startTunnel({
3524
+ origin: getDevServerOrigin(server),
3525
+ tunnel: tunnelOption === true ? {} : tunnelOption,
3526
+ config: entry.config,
3527
+ cwd: entry.rootDir
3528
+ });
3529
+ allowHosts(server, this.#tunnel.urls);
3530
+ for (const url of this.#tunnel.urls) logger.info(`Tunnel: ${url}`);
3531
+ }
3532
+ apply(compiler) {
3533
+ const logger = compiler.getInfrastructureLogger(PLUGIN_NAME);
3534
+ const resolvers = getWorkerResolvers(compiler.context, this.options);
3535
+ let session;
3536
+ const devServer = compiler.options.devServer;
3537
+ if (devServer) {
3538
+ const { setupMiddlewares, onListening } = devServer;
3539
+ devServer.setupMiddlewares = (middlewares, server) => {
3540
+ const result = setupMiddlewares ? setupMiddlewares(middlewares, server) : middlewares;
3541
+ session = new DevSession({
3542
+ compiler,
3543
+ resolvers,
3544
+ pluginOptions: this.options,
3545
+ logger
3546
+ });
3547
+ session.start({
3548
+ waitUntilValid: () => new Promise((resolve) => {
3549
+ if (server.middleware) server.middleware.waitUntilValid(() => resolve());
3550
+ else resolve();
3551
+ }),
3552
+ sendToClients: (type, data) => {
3553
+ if (server.webSocketServer) server.sendMessage(server.webSocketServer.clients, type, data);
3554
+ }
3555
+ });
3556
+ const activeSession = session;
3557
+ const devMiddlewareIndex = result.findIndex((middleware) => typeof middleware === "object" && middleware.name === "@rspack/dev-middleware");
3558
+ result.splice(devMiddlewareIndex === -1 ? result.length : devMiddlewareIndex, 0, {
3559
+ name: PLUGIN_NAME,
3560
+ middleware: (req, res, next) => {
3561
+ activeSession.handle(req, res, next).catch(next);
3562
+ }
3563
+ });
3564
+ return result;
3565
+ };
3566
+ devServer.onListening = (server) => {
3567
+ if (session && server.server) session.attachUpgradeHandler(server.server, getSocketPath(server));
3568
+ if (this.options.tunnel) this.#openTunnel(server, resolvers[0]?.(), logger).catch((error) => {
3569
+ logger.error(`Tunnel failed to start: ${error instanceof Error ? error.message : String(error)}`);
3570
+ });
3571
+ onListening?.(server);
3572
+ };
3573
+ }
3574
+ let builtWorkers;
3575
+ compiler.hooks.beforeRun.tapPromise(PLUGIN_NAME, async () => {
3576
+ const workers = resolvers.map((resolve) => resolve());
3577
+ await buildWorkers({
3578
+ compiler,
3579
+ workers,
3580
+ pluginOptions: this.options
3581
+ });
3582
+ for (const worker of workers) logger.info(`Built ${worker.main ? "Worker" : "assets-only config"} "${worker.name}" into ${worker.outputDir}`);
3583
+ builtWorkers = workers;
3584
+ });
3585
+ compiler.hooks.afterEmit.tapPromise(PLUGIN_NAME, async () => {
3586
+ if (builtWorkers) await copyImportedAssets(builtWorkers);
3587
+ });
3588
+ compiler.hooks.shutdown.tapPromise(PLUGIN_NAME, async () => {
3589
+ this.#tunnel?.close();
3590
+ await session?.dispose();
3591
+ });
3592
+ }
3593
+ };
3594
+ function cloudflare(options) {
3595
+ return new CloudflarePlugin(options);
3596
+ }
3597
+ export { CloudflarePlugin, cloudflare };
3598
+
3599
+ //# sourceMappingURL=index.js.map