@cloudflare/worker-bundler 0.0.4 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +231 -23
- package/dist/esbuild.wasm +0 -0
- package/dist/file-system-BQyEt1bf.d.ts +139 -0
- package/dist/index.d.ts +61 -3
- package/dist/index.js +234 -304
- package/dist/index.js.map +1 -1
- package/dist/installer-CwkPhXvX.js +268 -0
- package/dist/installer-CwkPhXvX.js.map +1 -0
- package/dist/typescript.d.ts +47 -0
- package/dist/typescript.js +114587 -0
- package/dist/typescript.js.map +1 -0
- package/package.json +10 -4
package/dist/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
+
import { n as hasDependencies, r as installDependencies } from "./installer-CwkPhXvX.js";
|
|
1
2
|
import * as esbuild from "esbuild-wasm/lib/browser.js";
|
|
2
3
|
import esbuildWasm from "./esbuild.wasm";
|
|
3
4
|
import { parse } from "es-module-lexer/js";
|
|
4
5
|
import * as resolveExports from "resolve.exports";
|
|
5
6
|
import { parse as parse$1 } from "smol-toml";
|
|
6
|
-
import * as semver from "semver";
|
|
7
7
|
import { transform } from "sucrase";
|
|
8
8
|
//#region src/resolver.ts
|
|
9
9
|
const DEFAULT_EXTENSIONS = [
|
|
@@ -52,7 +52,8 @@ function resolveRelative(specifier, importer, files, extensions) {
|
|
|
52
52
|
*/
|
|
53
53
|
function resolvePackage(specifier, files, conditions, extensions) {
|
|
54
54
|
const { packageName, subpath } = parsePackageSpecifier(specifier);
|
|
55
|
-
const
|
|
55
|
+
const packageJsonPath = `node_modules/${packageName}/package.json`;
|
|
56
|
+
const packageJson = files.read(packageJsonPath);
|
|
56
57
|
if (!packageJson) return {
|
|
57
58
|
path: specifier,
|
|
58
59
|
external: true
|
|
@@ -70,7 +71,7 @@ function resolvePackage(specifier, files, conditions, extensions) {
|
|
|
70
71
|
const resolvedPath = resolved[0];
|
|
71
72
|
if (resolvedPath) {
|
|
72
73
|
const fullPath = `node_modules/${packageName}/${normalizeRelativePath(resolvedPath)}`;
|
|
73
|
-
if (fullPath
|
|
74
|
+
if (files.read(fullPath) !== null) return {
|
|
74
75
|
path: fullPath,
|
|
75
76
|
external: false
|
|
76
77
|
};
|
|
@@ -80,7 +81,7 @@ function resolvePackage(specifier, files, conditions, extensions) {
|
|
|
80
81
|
const legacyEntry = resolveExports.legacy(pkg, { fields: ["module", "main"] });
|
|
81
82
|
if (legacyEntry && typeof legacyEntry === "string") {
|
|
82
83
|
const fullPath = `node_modules/${packageName}/${normalizeRelativePath(legacyEntry)}`;
|
|
83
|
-
if (fullPath
|
|
84
|
+
if (files.read(fullPath) !== null) return {
|
|
84
85
|
path: fullPath,
|
|
85
86
|
external: false
|
|
86
87
|
};
|
|
@@ -100,14 +101,14 @@ function resolvePackage(specifier, files, conditions, extensions) {
|
|
|
100
101
|
*/
|
|
101
102
|
function resolveWithExtensions(path, files, extensions) {
|
|
102
103
|
const normalized = normalizePath(path);
|
|
103
|
-
if (normalized
|
|
104
|
+
if (files.read(normalized) !== null) return normalized;
|
|
104
105
|
for (const ext of extensions) {
|
|
105
106
|
const withExt = normalized + ext;
|
|
106
|
-
if (withExt
|
|
107
|
+
if (files.read(withExt) !== null) return withExt;
|
|
107
108
|
}
|
|
108
109
|
for (const ext of extensions) {
|
|
109
110
|
const indexPath = `${normalized}/index${ext}`;
|
|
110
|
-
if (indexPath
|
|
111
|
+
if (files.read(indexPath) !== null) return indexPath;
|
|
111
112
|
}
|
|
112
113
|
}
|
|
113
114
|
/**
|
|
@@ -253,7 +254,7 @@ async function bundleWithEsbuild(files, entryPoint, externals, target, minify, s
|
|
|
253
254
|
};
|
|
254
255
|
}
|
|
255
256
|
const normalizedPath = args.path.startsWith("/") ? args.path.slice(1) : args.path;
|
|
256
|
-
if (normalizedPath
|
|
257
|
+
if (files.read(normalizedPath) !== null) return {
|
|
257
258
|
path: normalizedPath,
|
|
258
259
|
namespace: "virtual"
|
|
259
260
|
};
|
|
@@ -266,8 +267,8 @@ async function bundleWithEsbuild(files, entryPoint, externals, target, minify, s
|
|
|
266
267
|
filter: /.*/,
|
|
267
268
|
namespace: "virtual"
|
|
268
269
|
}, (args) => {
|
|
269
|
-
const content = files
|
|
270
|
-
if (content ===
|
|
270
|
+
const content = files.read(args.path);
|
|
271
|
+
if (content === null) return { errors: [{ text: `File not found: ${args.path}` }] };
|
|
271
272
|
const loader = getLoader(args.path);
|
|
272
273
|
const lastSlash = args.path.lastIndexOf("/");
|
|
273
274
|
return {
|
|
@@ -304,7 +305,7 @@ function resolveRelativePath(resolveDir, relativePath, files) {
|
|
|
304
305
|
for (const part of relParts) if (part === "..") parts.pop();
|
|
305
306
|
else if (part !== ".") parts.push(part);
|
|
306
307
|
const resolved = parts.join("/");
|
|
307
|
-
if (resolved
|
|
308
|
+
if (files.read(resolved) !== null) return resolved;
|
|
308
309
|
const extensions = [
|
|
309
310
|
".ts",
|
|
310
311
|
".tsx",
|
|
@@ -313,10 +314,10 @@ function resolveRelativePath(resolveDir, relativePath, files) {
|
|
|
313
314
|
".mts",
|
|
314
315
|
".mjs"
|
|
315
316
|
];
|
|
316
|
-
for (const ext of extensions) if (resolved + ext
|
|
317
|
+
for (const ext of extensions) if (files.read(resolved + ext) !== null) return resolved + ext;
|
|
317
318
|
for (const ext of extensions) {
|
|
318
319
|
const indexPath = `${resolved}/index${ext}`;
|
|
319
|
-
if (indexPath
|
|
320
|
+
if (files.read(indexPath) !== null) return indexPath;
|
|
320
321
|
}
|
|
321
322
|
}
|
|
322
323
|
function getLoader(path) {
|
|
@@ -376,11 +377,11 @@ async function initializeEsbuild() {
|
|
|
376
377
|
* @returns Parsed wrangler config, or undefined if no config file found
|
|
377
378
|
*/
|
|
378
379
|
function parseWranglerConfig(files) {
|
|
379
|
-
const tomlContent = files
|
|
380
|
+
const tomlContent = files.read("wrangler.toml");
|
|
380
381
|
if (tomlContent) return parseWranglerToml(tomlContent);
|
|
381
|
-
const jsonContent = files
|
|
382
|
+
const jsonContent = files.read("wrangler.json");
|
|
382
383
|
if (jsonContent) return parseWranglerJson(jsonContent);
|
|
383
|
-
const jsoncContent = files
|
|
384
|
+
const jsoncContent = files.read("wrangler.jsonc");
|
|
384
385
|
if (jsoncContent) return parseWranglerJsonc(jsoncContent);
|
|
385
386
|
}
|
|
386
387
|
/**
|
|
@@ -476,267 +477,6 @@ function hasNodejsCompat(config) {
|
|
|
476
477
|
return config?.compatibilityFlags?.includes("nodejs_compat") ?? false;
|
|
477
478
|
}
|
|
478
479
|
//#endregion
|
|
479
|
-
//#region src/installer.ts
|
|
480
|
-
/**
|
|
481
|
-
* NPM package installer for virtual file systems.
|
|
482
|
-
*
|
|
483
|
-
* This module fetches packages from the npm registry and populates
|
|
484
|
-
* a virtual node_modules directory structure.
|
|
485
|
-
*/
|
|
486
|
-
const NPM_REGISTRY = "https://registry.npmjs.org";
|
|
487
|
-
const DEFAULT_TIMEOUT_MS = 3e4;
|
|
488
|
-
/**
|
|
489
|
-
* Fetch with a timeout.
|
|
490
|
-
* Throws an error if the request takes longer than the specified timeout.
|
|
491
|
-
*/
|
|
492
|
-
async function fetchWithTimeout(url, options = {}, timeoutMs = DEFAULT_TIMEOUT_MS) {
|
|
493
|
-
const controller = new AbortController();
|
|
494
|
-
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
|
|
495
|
-
try {
|
|
496
|
-
return await fetch(url, {
|
|
497
|
-
...options,
|
|
498
|
-
signal: controller.signal
|
|
499
|
-
});
|
|
500
|
-
} catch (error) {
|
|
501
|
-
if (error instanceof Error && error.name === "AbortError") throw new Error(`Request timed out after ${timeoutMs}ms: ${url}`);
|
|
502
|
-
throw error;
|
|
503
|
-
} finally {
|
|
504
|
-
clearTimeout(timeoutId);
|
|
505
|
-
}
|
|
506
|
-
}
|
|
507
|
-
/**
|
|
508
|
-
* Install npm dependencies into a virtual file system.
|
|
509
|
-
*
|
|
510
|
-
* Reads the package.json from the files, resolves all dependencies,
|
|
511
|
-
* and populates node_modules with the package contents.
|
|
512
|
-
*
|
|
513
|
-
* @param files - Virtual file system containing package.json
|
|
514
|
-
* @param options - Installation options
|
|
515
|
-
* @returns Files with node_modules populated
|
|
516
|
-
*/
|
|
517
|
-
async function installDependencies(files, options = {}) {
|
|
518
|
-
const { dev = false, registry = NPM_REGISTRY } = options;
|
|
519
|
-
const result = {
|
|
520
|
-
files: { ...files },
|
|
521
|
-
installed: [],
|
|
522
|
-
warnings: []
|
|
523
|
-
};
|
|
524
|
-
const packageJsonContent = files["package.json"];
|
|
525
|
-
if (!packageJsonContent) return result;
|
|
526
|
-
let packageJson;
|
|
527
|
-
try {
|
|
528
|
-
packageJson = JSON.parse(packageJsonContent);
|
|
529
|
-
} catch {
|
|
530
|
-
result.warnings.push("Failed to parse package.json");
|
|
531
|
-
return result;
|
|
532
|
-
}
|
|
533
|
-
const depsToInstall = {
|
|
534
|
-
...packageJson.dependencies,
|
|
535
|
-
...dev ? packageJson.devDependencies : {}
|
|
536
|
-
};
|
|
537
|
-
if (Object.keys(depsToInstall).length === 0) return result;
|
|
538
|
-
const installedPackages = /* @__PURE__ */ new Map();
|
|
539
|
-
const inProgress = /* @__PURE__ */ new Map();
|
|
540
|
-
await Promise.all(Object.entries(depsToInstall).map(([name, versionRange]) => installPackage(name, versionRange, result, installedPackages, inProgress, registry)));
|
|
541
|
-
return result;
|
|
542
|
-
}
|
|
543
|
-
/**
|
|
544
|
-
* Install a single package and its dependencies recursively.
|
|
545
|
-
*/
|
|
546
|
-
async function installPackage(name, versionRange, result, installedPackages, inProgress, registry) {
|
|
547
|
-
if (installedPackages.has(name)) return;
|
|
548
|
-
const existing = inProgress.get(name);
|
|
549
|
-
if (existing) return existing;
|
|
550
|
-
const installPromise = (async () => {
|
|
551
|
-
try {
|
|
552
|
-
const metadata = await fetchPackageMetadata(name, registry);
|
|
553
|
-
const version = resolveVersion(versionRange, metadata);
|
|
554
|
-
if (!version) {
|
|
555
|
-
result.warnings.push(`Could not resolve version for ${name}@${versionRange}`);
|
|
556
|
-
return;
|
|
557
|
-
}
|
|
558
|
-
const versionMetadata = metadata.versions[version];
|
|
559
|
-
if (!versionMetadata) {
|
|
560
|
-
result.warnings.push(`Version ${version} not found for ${name}`);
|
|
561
|
-
return;
|
|
562
|
-
}
|
|
563
|
-
installedPackages.set(name, version);
|
|
564
|
-
result.installed.push(`${name}@${version}`);
|
|
565
|
-
const packageFiles = await fetchPackageFiles(name, versionMetadata);
|
|
566
|
-
for (const [filePath, content] of Object.entries(packageFiles)) result.files[`node_modules/${name}/${filePath}`] = content;
|
|
567
|
-
const deps = versionMetadata.dependencies ?? {};
|
|
568
|
-
await Promise.all(Object.entries(deps).map(([depName, depVersion]) => installPackage(depName, depVersion, result, installedPackages, inProgress, registry)));
|
|
569
|
-
} catch (error) {
|
|
570
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
571
|
-
result.warnings.push(`Failed to install ${name}: ${message}`);
|
|
572
|
-
}
|
|
573
|
-
})();
|
|
574
|
-
inProgress.set(name, installPromise);
|
|
575
|
-
try {
|
|
576
|
-
await installPromise;
|
|
577
|
-
} finally {
|
|
578
|
-
inProgress.delete(name);
|
|
579
|
-
}
|
|
580
|
-
}
|
|
581
|
-
/**
|
|
582
|
-
* Fetch package metadata from npm registry.
|
|
583
|
-
*/
|
|
584
|
-
async function fetchPackageMetadata(name, registry) {
|
|
585
|
-
const response = await fetchWithTimeout(`${registry}/${name.startsWith("@") ? `@${encodeURIComponent(name.slice(1))}` : name}`, { headers: { Accept: "application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8" } });
|
|
586
|
-
if (!response.ok) throw new Error(`Failed to fetch package metadata: ${response.status}`);
|
|
587
|
-
return await response.json();
|
|
588
|
-
}
|
|
589
|
-
/**
|
|
590
|
-
* Resolve a semver range to a specific version.
|
|
591
|
-
*/
|
|
592
|
-
function resolveVersion(range, metadata) {
|
|
593
|
-
if (range === "latest" || range === "*") return metadata["dist-tags"]["latest"];
|
|
594
|
-
if (metadata.versions[range]) return range;
|
|
595
|
-
if (metadata["dist-tags"][range]) return metadata["dist-tags"][range];
|
|
596
|
-
const versions = Object.keys(metadata.versions);
|
|
597
|
-
return semver.maxSatisfying(versions, range) ?? void 0;
|
|
598
|
-
}
|
|
599
|
-
/**
|
|
600
|
-
* Fetch and extract package files from npm tarball.
|
|
601
|
-
*/
|
|
602
|
-
async function fetchPackageFiles(name, metadata) {
|
|
603
|
-
const tarballUrl = metadata.dist?.tarball;
|
|
604
|
-
if (!tarballUrl) throw new Error(`No tarball URL for ${name}`);
|
|
605
|
-
const response = await fetchWithTimeout(tarballUrl, {}, DEFAULT_TIMEOUT_MS * 2);
|
|
606
|
-
if (!response.ok) throw new Error(`Failed to fetch tarball: ${response.status}`);
|
|
607
|
-
const buffer = await response.arrayBuffer();
|
|
608
|
-
return extractTarball(new Uint8Array(buffer));
|
|
609
|
-
}
|
|
610
|
-
/**
|
|
611
|
-
* Extract files from a gzipped tarball.
|
|
612
|
-
*
|
|
613
|
-
* npm packages are distributed as .tgz files (gzipped tar).
|
|
614
|
-
* The contents are in a "package/" directory.
|
|
615
|
-
*/
|
|
616
|
-
async function extractTarball(data) {
|
|
617
|
-
return parseTar(await decompress(data));
|
|
618
|
-
}
|
|
619
|
-
/**
|
|
620
|
-
* Decompress gzip data using DecompressionStream.
|
|
621
|
-
*/
|
|
622
|
-
async function decompress(data) {
|
|
623
|
-
const ds = new DecompressionStream("gzip");
|
|
624
|
-
const writer = ds.writable.getWriter();
|
|
625
|
-
const reader = ds.readable.getReader();
|
|
626
|
-
writer.write(data).catch(() => {});
|
|
627
|
-
writer.close().catch(() => {});
|
|
628
|
-
const chunks = [];
|
|
629
|
-
let totalLength = 0;
|
|
630
|
-
while (true) {
|
|
631
|
-
const { done, value } = await reader.read();
|
|
632
|
-
if (done) break;
|
|
633
|
-
chunks.push(value);
|
|
634
|
-
totalLength += value.length;
|
|
635
|
-
}
|
|
636
|
-
const result = new Uint8Array(totalLength);
|
|
637
|
-
let offset = 0;
|
|
638
|
-
for (const chunk of chunks) {
|
|
639
|
-
result.set(chunk, offset);
|
|
640
|
-
offset += chunk.length;
|
|
641
|
-
}
|
|
642
|
-
return result;
|
|
643
|
-
}
|
|
644
|
-
/**
|
|
645
|
-
* Parse a tar archive and extract text files.
|
|
646
|
-
*
|
|
647
|
-
* TAR format:
|
|
648
|
-
* - 512-byte header blocks
|
|
649
|
-
* - File content (padded to 512 bytes)
|
|
650
|
-
* - Two empty blocks at the end
|
|
651
|
-
*/
|
|
652
|
-
function parseTar(data) {
|
|
653
|
-
const files = {};
|
|
654
|
-
const textDecoder = new TextDecoder();
|
|
655
|
-
let offset = 0;
|
|
656
|
-
while (offset < data.length - 512) {
|
|
657
|
-
const header = data.slice(offset, offset + 512);
|
|
658
|
-
if (header.every((b) => b === 0)) break;
|
|
659
|
-
const name = readString(header, 0, 100);
|
|
660
|
-
const sizeStr = readString(header, 124, 12);
|
|
661
|
-
const typeFlag = header[156];
|
|
662
|
-
const size = parseInt(sizeStr.trim(), 8) || 0;
|
|
663
|
-
offset += 512;
|
|
664
|
-
if ((typeFlag === 48 || typeFlag === 0) && size > 0) {
|
|
665
|
-
const content = data.slice(offset, offset + size);
|
|
666
|
-
let filePath = name;
|
|
667
|
-
if (filePath.startsWith("package/")) filePath = filePath.slice(8);
|
|
668
|
-
if (isTextFile(filePath)) try {
|
|
669
|
-
files[filePath] = textDecoder.decode(content);
|
|
670
|
-
} catch {}
|
|
671
|
-
}
|
|
672
|
-
offset += Math.ceil(size / 512) * 512;
|
|
673
|
-
}
|
|
674
|
-
return files;
|
|
675
|
-
}
|
|
676
|
-
/**
|
|
677
|
-
* Read a null-terminated string from a buffer.
|
|
678
|
-
*/
|
|
679
|
-
function readString(buffer, offset, length) {
|
|
680
|
-
const bytes = buffer.slice(offset, offset + length);
|
|
681
|
-
const nullIndex = bytes.indexOf(0);
|
|
682
|
-
const relevantBytes = nullIndex >= 0 ? bytes.slice(0, nullIndex) : bytes;
|
|
683
|
-
return new TextDecoder().decode(relevantBytes);
|
|
684
|
-
}
|
|
685
|
-
/**
|
|
686
|
-
* Check if a file path is likely a text file.
|
|
687
|
-
*/
|
|
688
|
-
function isTextFile(path) {
|
|
689
|
-
const textExtensions = [
|
|
690
|
-
".js",
|
|
691
|
-
".mjs",
|
|
692
|
-
".cjs",
|
|
693
|
-
".ts",
|
|
694
|
-
".mts",
|
|
695
|
-
".cts",
|
|
696
|
-
".tsx",
|
|
697
|
-
".jsx",
|
|
698
|
-
".json",
|
|
699
|
-
".md",
|
|
700
|
-
".txt",
|
|
701
|
-
".css",
|
|
702
|
-
".html",
|
|
703
|
-
".yml",
|
|
704
|
-
".yaml",
|
|
705
|
-
".toml",
|
|
706
|
-
".xml",
|
|
707
|
-
".svg",
|
|
708
|
-
".map",
|
|
709
|
-
".d.ts",
|
|
710
|
-
".d.mts",
|
|
711
|
-
".d.cts"
|
|
712
|
-
];
|
|
713
|
-
const configFiles = [
|
|
714
|
-
"LICENSE",
|
|
715
|
-
"README",
|
|
716
|
-
"CHANGELOG",
|
|
717
|
-
"package.json",
|
|
718
|
-
"tsconfig.json",
|
|
719
|
-
".npmignore",
|
|
720
|
-
".gitignore"
|
|
721
|
-
];
|
|
722
|
-
const fileName = path.split("/").pop() ?? "";
|
|
723
|
-
if (configFiles.some((f) => fileName.toUpperCase().startsWith(f.toUpperCase()))) return true;
|
|
724
|
-
return textExtensions.some((ext) => path.toLowerCase().endsWith(ext));
|
|
725
|
-
}
|
|
726
|
-
/**
|
|
727
|
-
* Check if files contain a package.json with dependencies that need installing.
|
|
728
|
-
*/
|
|
729
|
-
function hasDependencies(files) {
|
|
730
|
-
const packageJson = files["package.json"];
|
|
731
|
-
if (!packageJson) return false;
|
|
732
|
-
try {
|
|
733
|
-
const deps = JSON.parse(packageJson).dependencies ?? {};
|
|
734
|
-
return Object.keys(deps).length > 0;
|
|
735
|
-
} catch {
|
|
736
|
-
return false;
|
|
737
|
-
}
|
|
738
|
-
}
|
|
739
|
-
//#endregion
|
|
740
480
|
//#region src/transformer.ts
|
|
741
481
|
/**
|
|
742
482
|
* Transform TypeScript/JSX code to JavaScript using Sucrase.
|
|
@@ -814,8 +554,8 @@ async function transformAndResolve(files, entryPoint, externals) {
|
|
|
814
554
|
const filePath = toProcess.pop();
|
|
815
555
|
if (!filePath || processed.has(filePath)) continue;
|
|
816
556
|
processed.add(filePath);
|
|
817
|
-
const content = files
|
|
818
|
-
if (content ===
|
|
557
|
+
const content = files.read(filePath);
|
|
558
|
+
if (content === null) {
|
|
819
559
|
warnings.push(`File not found: ${filePath}`);
|
|
820
560
|
continue;
|
|
821
561
|
}
|
|
@@ -845,8 +585,8 @@ async function transformAndResolve(files, entryPoint, externals) {
|
|
|
845
585
|
}
|
|
846
586
|
}
|
|
847
587
|
for (const [sourcePath, outputPath] of pathMap) {
|
|
848
|
-
const content = files
|
|
849
|
-
if (content ===
|
|
588
|
+
const content = files.read(sourcePath);
|
|
589
|
+
if (content === null || !isJavaScriptFile(sourcePath)) continue;
|
|
850
590
|
let transformedCode;
|
|
851
591
|
if (isTypeScriptFile(sourcePath)) try {
|
|
852
592
|
transformedCode = transformCode(content, { filePath: sourcePath }).code;
|
|
@@ -935,7 +675,7 @@ function getDirectory(filePath) {
|
|
|
935
675
|
*/
|
|
936
676
|
function detectEntryPoint(files, wranglerConfig) {
|
|
937
677
|
if (wranglerConfig?.main) return normalizeEntryPath(wranglerConfig.main);
|
|
938
|
-
const packageJsonContent = files
|
|
678
|
+
const packageJsonContent = files.read("package.json");
|
|
939
679
|
if (packageJsonContent) try {
|
|
940
680
|
const pkg = JSON.parse(packageJsonContent);
|
|
941
681
|
if (pkg.exports) {
|
|
@@ -962,7 +702,7 @@ function detectEntryPoint(files, wranglerConfig) {
|
|
|
962
702
|
"index.js",
|
|
963
703
|
"src/worker.ts",
|
|
964
704
|
"src/worker.js"
|
|
965
|
-
]) if (entry
|
|
705
|
+
]) if (files.read(entry) !== null) return entry;
|
|
966
706
|
}
|
|
967
707
|
function normalizeEntryPath(path) {
|
|
968
708
|
if (path.startsWith("./")) return path.slice(2);
|
|
@@ -978,6 +718,194 @@ function showExperimentalWarning(fn) {
|
|
|
978
718
|
}
|
|
979
719
|
}
|
|
980
720
|
//#endregion
|
|
721
|
+
//#region src/file-system.ts
|
|
722
|
+
/**
|
|
723
|
+
* A simple in-memory filesystem backed by a `Map`. Intended for use in tests
|
|
724
|
+
* and build pipelines where persistence is not required.
|
|
725
|
+
*/
|
|
726
|
+
var InMemoryFileSystem = class {
|
|
727
|
+
/**
|
|
728
|
+
* @param files Optional initial file contents. Accepts either a plain object
|
|
729
|
+
* (keys are paths, values are file contents) or a `Map`. Defaults to an
|
|
730
|
+
* empty filesystem.
|
|
731
|
+
*/
|
|
732
|
+
constructor(files = /* @__PURE__ */ new Map()) {
|
|
733
|
+
this.files = /* @__PURE__ */ new Map();
|
|
734
|
+
this.files = files instanceof Map ? files : new Map(Object.entries(files));
|
|
735
|
+
}
|
|
736
|
+
read(path) {
|
|
737
|
+
return this.files.get(path) ?? null;
|
|
738
|
+
}
|
|
739
|
+
write(path, content) {
|
|
740
|
+
this.files.set(path, content);
|
|
741
|
+
}
|
|
742
|
+
delete(path) {
|
|
743
|
+
this.files.delete(path);
|
|
744
|
+
}
|
|
745
|
+
list(prefix) {
|
|
746
|
+
return Array.from(this.files.keys()).filter((path) => prefix === void 0 || path.startsWith(prefix));
|
|
747
|
+
}
|
|
748
|
+
flush() {
|
|
749
|
+
return Promise.resolve();
|
|
750
|
+
}
|
|
751
|
+
};
|
|
752
|
+
/**
|
|
753
|
+
* A generic write-overlay on top of any `FileSystem`. Not re-exported from the
|
|
754
|
+
* package entry point — intended as an implementation detail for higher-level
|
|
755
|
+
* filesystem classes.
|
|
756
|
+
*
|
|
757
|
+
* Writes and deletes are buffered in memory keyed by the raw (untransformed)
|
|
758
|
+
* path. Reads are served from the write buffer first; deleted paths return
|
|
759
|
+
* `null`; remaining reads are delegated to the inner filesystem. `flush()`
|
|
760
|
+
* drains deletes and writes into the inner filesystem, awaits `inner.flush()`,
|
|
761
|
+
* and then clears the buffers.
|
|
762
|
+
*/
|
|
763
|
+
var OverlayFileSystem = class {
|
|
764
|
+
constructor(inner) {
|
|
765
|
+
this.inner = inner;
|
|
766
|
+
this.overlay = null;
|
|
767
|
+
this.deletions = null;
|
|
768
|
+
}
|
|
769
|
+
read(path) {
|
|
770
|
+
if (this.overlay?.has(path)) return this.overlay.get(path) ?? null;
|
|
771
|
+
if (this.deletions?.has(path)) return null;
|
|
772
|
+
return this.inner.read(path);
|
|
773
|
+
}
|
|
774
|
+
write(path, content) {
|
|
775
|
+
if (this.overlay === null) this.overlay = /* @__PURE__ */ new Map();
|
|
776
|
+
this.overlay.set(path, content);
|
|
777
|
+
this.deletions?.delete(path);
|
|
778
|
+
}
|
|
779
|
+
delete(path) {
|
|
780
|
+
this.overlay?.delete(path);
|
|
781
|
+
if (this.deletions === null) this.deletions = /* @__PURE__ */ new Set();
|
|
782
|
+
this.deletions.add(path);
|
|
783
|
+
}
|
|
784
|
+
list(prefix) {
|
|
785
|
+
const innerPaths = this.inner.list(prefix).filter((path) => !this.deletions?.has(path));
|
|
786
|
+
const result = new Set(innerPaths);
|
|
787
|
+
for (const path of this.overlay?.keys() ?? []) if (prefix === void 0 || path.startsWith(prefix)) result.add(path);
|
|
788
|
+
return Array.from(result);
|
|
789
|
+
}
|
|
790
|
+
async flush() {
|
|
791
|
+
if (this.overlay === null && this.deletions === null) return;
|
|
792
|
+
for (const path of this.deletions ?? []) this.inner.delete(path);
|
|
793
|
+
for (const [path, content] of this.overlay ?? []) this.inner.write(path, content);
|
|
794
|
+
await this.inner.flush();
|
|
795
|
+
this.overlay = null;
|
|
796
|
+
this.deletions = null;
|
|
797
|
+
}
|
|
798
|
+
};
|
|
799
|
+
/**
|
|
800
|
+
* A filesystem backed directly by Durable Object KV storage. Every write is
|
|
801
|
+
* committed to KV synchronously with no in-memory buffering, and `flush()` is
|
|
802
|
+
* a no-op.
|
|
803
|
+
*
|
|
804
|
+
* Use this when you want immediate, per-write durability and the overhead of
|
|
805
|
+
* individual KV writes is acceptable — for example, when seeding a small number
|
|
806
|
+
* of files. For bulk write workloads, prefer `DurableObjectKVFileSystem`, which
|
|
807
|
+
* batches all writes into a single flush.
|
|
808
|
+
*/
|
|
809
|
+
var DurableObjectRawFileSystem = class {
|
|
810
|
+
/**
|
|
811
|
+
* @param storage The Durable Object storage instance to persist files to.
|
|
812
|
+
* @param prefix An optional path prefix prepended to every key stored in KV.
|
|
813
|
+
* Defaults to `"bundle/"`, which namespaces bundle files away
|
|
814
|
+
* from any other keys the Durable Object may store.
|
|
815
|
+
*/
|
|
816
|
+
constructor(storage, prefix = "bundle/") {
|
|
817
|
+
this.storage = storage;
|
|
818
|
+
this.prefix = prefix;
|
|
819
|
+
}
|
|
820
|
+
read(path) {
|
|
821
|
+
return this.storage.kv.get(this.formatPath(path)) ?? null;
|
|
822
|
+
}
|
|
823
|
+
write(path, content) {
|
|
824
|
+
this.storage.kv.put(this.formatPath(path), content);
|
|
825
|
+
}
|
|
826
|
+
delete(path) {
|
|
827
|
+
this.storage.kv.delete(this.formatPath(path));
|
|
828
|
+
}
|
|
829
|
+
list(prefix) {
|
|
830
|
+
const formattedPrefix = prefix !== void 0 ? this.formatPath(prefix) : this.prefix;
|
|
831
|
+
const result = [];
|
|
832
|
+
for (const [key] of this.storage.kv.list({ prefix: formattedPrefix })) result.push(key.slice(this.prefix.length));
|
|
833
|
+
return result;
|
|
834
|
+
}
|
|
835
|
+
flush() {
|
|
836
|
+
return Promise.resolve();
|
|
837
|
+
}
|
|
838
|
+
formatPath(path) {
|
|
839
|
+
return `${this.prefix}${path}`;
|
|
840
|
+
}
|
|
841
|
+
};
|
|
842
|
+
/**
|
|
843
|
+
* A filesystem backed by Durable Object KV storage with a write-overlay.
|
|
844
|
+
* Writes are buffered in memory and only persisted to KV when `flush()` is
|
|
845
|
+
* called, avoiding the cost of a KV write on every individual file operation.
|
|
846
|
+
* Reads are served from the overlay when possible, falling back to KV, so
|
|
847
|
+
* callers always observe their own writes immediately.
|
|
848
|
+
*
|
|
849
|
+
* Implemented as an `OverlayFileSystem` wrapping a `DurableObjectRawFileSystem`.
|
|
850
|
+
* Use `DurableObjectRawFileSystem` directly if you want immediate per-write KV
|
|
851
|
+
* durability without buffering.
|
|
852
|
+
*/
|
|
853
|
+
var DurableObjectKVFileSystem = class {
|
|
854
|
+
/**
|
|
855
|
+
* @param storage The Durable Object storage instance to persist files to.
|
|
856
|
+
* @param prefix An optional path prefix prepended to every key stored in KV.
|
|
857
|
+
* Defaults to `"bundle/"`, which namespaces bundle files away
|
|
858
|
+
* from any other keys the Durable Object may store.
|
|
859
|
+
*/
|
|
860
|
+
constructor(storage, prefix = "bundle/") {
|
|
861
|
+
this.fs = new OverlayFileSystem(new DurableObjectRawFileSystem(storage, prefix));
|
|
862
|
+
}
|
|
863
|
+
read(path) {
|
|
864
|
+
return this.fs.read(path);
|
|
865
|
+
}
|
|
866
|
+
write(path, content) {
|
|
867
|
+
this.fs.write(path, content);
|
|
868
|
+
}
|
|
869
|
+
delete(path) {
|
|
870
|
+
this.fs.delete(path);
|
|
871
|
+
}
|
|
872
|
+
list(prefix) {
|
|
873
|
+
return this.fs.list(prefix);
|
|
874
|
+
}
|
|
875
|
+
flush() {
|
|
876
|
+
return this.fs.flush();
|
|
877
|
+
}
|
|
878
|
+
};
|
|
879
|
+
/**
|
|
880
|
+
* Creates an `InMemoryFileSystem` from an async source of file entries.
|
|
881
|
+
*
|
|
882
|
+
* This is the bridge between async storage backends (e.g. a Durable Object
|
|
883
|
+
* `Workspace` backed by SQLite/R2) and the synchronous `FileSystem` interface
|
|
884
|
+
* required by the bundler and TypeScript language service.
|
|
885
|
+
*
|
|
886
|
+
* @example
|
|
887
|
+
* ```ts
|
|
888
|
+
* // Snapshot a Workspace into a bundler-compatible FileSystem
|
|
889
|
+
* async function* workspaceFiles(workspace) {
|
|
890
|
+
* for (const entry of workspace.glob("**\/*.{ts,tsx,json}")) {
|
|
891
|
+
* const content = await workspace.readFile(entry.path);
|
|
892
|
+
* if (content !== null) yield [entry.path, content];
|
|
893
|
+
* }
|
|
894
|
+
* }
|
|
895
|
+
*
|
|
896
|
+
* const fs = await createFileSystemSnapshot(workspaceFiles(workspace));
|
|
897
|
+
* const { languageService } = await createTypescriptLanguageService({ fileSystem: fs });
|
|
898
|
+
* ```
|
|
899
|
+
*/
|
|
900
|
+
async function createFileSystemSnapshot(entries) {
|
|
901
|
+
const fs = new InMemoryFileSystem();
|
|
902
|
+
for await (const [path, content] of entries) fs.write(path, content);
|
|
903
|
+
return fs;
|
|
904
|
+
}
|
|
905
|
+
function isFileSystem(obj) {
|
|
906
|
+
return "read" in obj && typeof obj.read === "function" && "delete" in obj && typeof obj.delete === "function";
|
|
907
|
+
}
|
|
908
|
+
//#endregion
|
|
981
909
|
//#region src/mime.ts
|
|
982
910
|
/**
|
|
983
911
|
* MIME type inference from file extensions.
|
|
@@ -1459,22 +1387,22 @@ async function handleAssetRequest(request, manifest, storage, config) {
|
|
|
1459
1387
|
*/
|
|
1460
1388
|
async function createApp(options) {
|
|
1461
1389
|
showExperimentalWarning("createApp");
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
const
|
|
1390
|
+
const { files, bundle = true, externals: rawExternals = [], target = "es2022", minify = false, sourcemap = false, registry } = options;
|
|
1391
|
+
const fileSystem = isFileSystem(files) ? files : new InMemoryFileSystem(files);
|
|
1392
|
+
const externals = ["cloudflare:", ...rawExternals];
|
|
1393
|
+
const wranglerConfig = parseWranglerConfig(fileSystem);
|
|
1465
1394
|
const nodejsCompat = hasNodejsCompat(wranglerConfig);
|
|
1466
1395
|
const installWarnings = [];
|
|
1467
|
-
if (hasDependencies(
|
|
1468
|
-
const installResult = await installDependencies(
|
|
1469
|
-
files = installResult.files;
|
|
1396
|
+
if (hasDependencies(fileSystem)) {
|
|
1397
|
+
const installResult = await installDependencies(fileSystem, registry ? { registry } : {});
|
|
1470
1398
|
installWarnings.push(...installResult.warnings);
|
|
1471
1399
|
}
|
|
1472
1400
|
const clientEntries = options.client ? Array.isArray(options.client) ? options.client : [options.client] : [];
|
|
1473
1401
|
const clientOutputs = {};
|
|
1474
1402
|
const clientBundles = [];
|
|
1475
1403
|
for (const clientEntry of clientEntries) {
|
|
1476
|
-
if (
|
|
1477
|
-
const bundleModule = (await bundleWithEsbuild(
|
|
1404
|
+
if (fileSystem.read(clientEntry) === null) throw new Error(`Client entry point "${clientEntry}" not found in files.`);
|
|
1405
|
+
const bundleModule = (await bundleWithEsbuild(fileSystem, clientEntry, externals, "es2022", minify, sourcemap, false)).modules["bundle.js"];
|
|
1478
1406
|
if (typeof bundleModule === "string") {
|
|
1479
1407
|
const outputPath = `/${clientEntry.replace(/^src\//, "").replace(/\.(tsx?|jsx?)$/, ".js")}`;
|
|
1480
1408
|
clientOutputs[outputPath] = bundleModule;
|
|
@@ -1488,12 +1416,12 @@ async function createApp(options) {
|
|
|
1488
1416
|
}
|
|
1489
1417
|
for (const [pathname, content] of Object.entries(clientOutputs)) allAssets[pathname] = content;
|
|
1490
1418
|
const assetManifest = await buildAssetManifest(allAssets);
|
|
1491
|
-
const serverEntry = options.server ?? detectEntryPoint(
|
|
1419
|
+
const serverEntry = options.server ?? detectEntryPoint(fileSystem, wranglerConfig);
|
|
1492
1420
|
if (!serverEntry) throw new Error("Could not determine server entry point. Specify the 'server' option.");
|
|
1493
|
-
if (
|
|
1421
|
+
if (fileSystem.read(serverEntry) === null) throw new Error(`Server entry point "${serverEntry}" not found in files.`);
|
|
1494
1422
|
let serverResult;
|
|
1495
|
-
if (bundle) serverResult = await bundleWithEsbuild(
|
|
1496
|
-
else serverResult = await transformAndResolve(
|
|
1423
|
+
if (bundle) serverResult = await bundleWithEsbuild(fileSystem, serverEntry, externals, target, minify, sourcemap, nodejsCompat);
|
|
1424
|
+
else serverResult = await transformAndResolve(fileSystem, serverEntry, externals);
|
|
1497
1425
|
const result = {
|
|
1498
1426
|
mainModule: serverResult.mainModule,
|
|
1499
1427
|
modules: serverResult.modules,
|
|
@@ -1530,31 +1458,33 @@ async function createApp(options) {
|
|
|
1530
1458
|
async function createWorker(options) {
|
|
1531
1459
|
showExperimentalWarning("createWorker");
|
|
1532
1460
|
let { files, bundle = true, externals = [], target = "es2022", minify = false, sourcemap = false, registry } = options;
|
|
1461
|
+
let fileSystem;
|
|
1462
|
+
if (isFileSystem(files)) fileSystem = files;
|
|
1463
|
+
else fileSystem = new InMemoryFileSystem(files);
|
|
1533
1464
|
externals = ["cloudflare:", ...externals];
|
|
1534
|
-
const wranglerConfig = parseWranglerConfig(
|
|
1465
|
+
const wranglerConfig = parseWranglerConfig(fileSystem);
|
|
1535
1466
|
const nodejsCompat = hasNodejsCompat(wranglerConfig);
|
|
1536
1467
|
const installWarnings = [];
|
|
1537
|
-
if (hasDependencies(
|
|
1538
|
-
const installResult = await installDependencies(
|
|
1539
|
-
files = installResult.files;
|
|
1468
|
+
if (hasDependencies(fileSystem)) {
|
|
1469
|
+
const installResult = await installDependencies(fileSystem, registry ? { registry } : {});
|
|
1540
1470
|
installWarnings.push(...installResult.warnings);
|
|
1541
1471
|
}
|
|
1542
|
-
const entryPoint = options.entryPoint ?? detectEntryPoint(
|
|
1472
|
+
const entryPoint = options.entryPoint ?? detectEntryPoint(fileSystem, wranglerConfig);
|
|
1543
1473
|
if (!entryPoint) throw new Error("Could not determine entry point. Please specify entryPoint option.");
|
|
1544
|
-
if (
|
|
1474
|
+
if (fileSystem.read(entryPoint) === null) throw new Error(`Entry point "${entryPoint}" not found in files.`);
|
|
1545
1475
|
if (bundle) {
|
|
1546
|
-
const result = await bundleWithEsbuild(
|
|
1476
|
+
const result = await bundleWithEsbuild(fileSystem, entryPoint, externals, target, minify, sourcemap, nodejsCompat);
|
|
1547
1477
|
if (wranglerConfig !== void 0) result.wranglerConfig = wranglerConfig;
|
|
1548
1478
|
if (installWarnings.length > 0) result.warnings = [...result.warnings ?? [], ...installWarnings];
|
|
1549
1479
|
return result;
|
|
1550
1480
|
} else {
|
|
1551
|
-
const result = await transformAndResolve(
|
|
1481
|
+
const result = await transformAndResolve(fileSystem, entryPoint, externals);
|
|
1552
1482
|
if (wranglerConfig !== void 0) result.wranglerConfig = wranglerConfig;
|
|
1553
1483
|
if (installWarnings.length > 0) result.warnings = [...result.warnings ?? [], ...installWarnings];
|
|
1554
1484
|
return result;
|
|
1555
1485
|
}
|
|
1556
1486
|
}
|
|
1557
1487
|
//#endregion
|
|
1558
|
-
export { buildAssetManifest, buildAssets, createApp, createMemoryStorage, createWorker, handleAssetRequest, inferContentType, isTextContentType };
|
|
1488
|
+
export { DurableObjectKVFileSystem, DurableObjectRawFileSystem, InMemoryFileSystem, buildAssetManifest, buildAssets, createApp, createFileSystemSnapshot, createMemoryStorage, createWorker, handleAssetRequest, hasDependencies, inferContentType, installDependencies, isTextContentType };
|
|
1559
1489
|
|
|
1560
1490
|
//# sourceMappingURL=index.js.map
|