@vite-hub/kv 0.1.0 → 0.4.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 +94 -21
- package/dist/batch--v0ri69O.js +40 -0
- package/dist/cli-DpPhz_Ek.d.ts +163 -0
- package/dist/cli.d.ts +4 -2
- package/dist/cli.js +99 -77
- package/dist/cloudflare-env-lOtHHsgP.js +46 -0
- package/dist/cloudflare-env-lookup-Bs0VDpU5.js +42 -0
- package/dist/cloudflare-kv-C3NO4C21.js +201 -0
- package/dist/cloudflare-kv-local-C2sbIrFy.js +71 -0
- package/dist/config-LfpUj9hs.js +252 -0
- package/dist/{create-storage-29gMzf41.js → create-storage-BORQm2a8.js} +206 -50
- package/dist/{cursor-history-dqYDlsaD.js → cursor-history-DRHh5bO5.js} +31 -14
- package/dist/database-oJdy0ZVX.js +250 -0
- package/dist/{deno-kv-CSYGvRx4.js → deno-kv-D_VtffFv.js} +12 -4
- package/dist/dev-peer-CHafxbtj.js +238 -0
- package/dist/driver-R4Z5Z5fl.d.ts +15 -0
- package/dist/durability.d.ts +17 -0
- package/dist/durability.js +53 -0
- package/dist/error-diagnostics-C54QQEhN.js +155 -0
- package/dist/errors-DzD6YNEH.js +88 -0
- package/dist/errors.d.ts +17 -1
- package/dist/errors.js +2 -2
- package/dist/fs-lite-BAgpmNAF.js +2 -0
- package/dist/fs-lite-BaklCLuV.js +386 -0
- package/dist/index.d.ts +7 -2
- package/dist/index.js +326 -84
- package/dist/inspect-BIKQsqX4.js +118 -0
- package/dist/invariant-DolT9EEx.js +22 -0
- package/dist/object-Da1zyPCR.js +11 -0
- package/dist/{operations-tNUdj3G4.d.ts → operation-definition-nmRu_O3V.d.ts} +42 -15
- package/dist/{operations-pn8_eGob.js → operations-CtrWLmPK.js} +69 -66
- package/dist/operations-D2iI9oN4.js +1363 -0
- package/dist/operations.d.ts +15 -8
- package/dist/operations.js +56 -192
- package/dist/redis-shared-5ogRd3-Y.js +94 -0
- package/dist/runtime/cloudflare-kv.d.ts +1 -1
- package/dist/runtime/cloudflare-kv.js +1 -99
- package/dist/runtime/cloudflare-request-env.d.ts +7 -0
- package/dist/runtime/cloudflare-request-env.js +11 -0
- package/dist/runtime/nitro-plugin.d.ts +12 -0
- package/dist/runtime/nitro-plugin.js +25 -0
- package/dist/runtime/redis-driver.d.ts +11 -0
- package/dist/runtime/redis-driver.js +113 -0
- package/dist/runtime/unstorage-driver.d.ts +14 -0
- package/dist/runtime/unstorage-driver.js +37 -0
- package/dist/runtime/upstash-driver.d.ts +2 -2
- package/dist/runtime/upstash-driver.js +58 -98
- package/dist/{driver-D9fI27jl.d.ts → types-Bj3EQoRg.d.ts} +16 -41
- package/dist/types-Dv-OSXZC.d.ts +325 -0
- package/dist/upstash-B-vaUYqO.js +40 -0
- package/dist/{utils2-Dsb9P4_2.js → utils2-FozcTsmb.js} +5 -2
- package/dist/virtual-module.d.ts +3 -0
- package/dist/vite.d.ts +167 -14
- package/dist/vite.js +1195 -2876
- package/package.json +30 -21
- package/dist/cli-Cniq99iX.d.ts +0 -85
- package/dist/cloudflare-env-C5rM7kUY.js +0 -74
- package/dist/config-DR6_5ZwI.js +0 -124
- package/dist/continuations-DPyH_vr1.js +0 -63
- package/dist/error-diagnostics-D_cQeZTi.js +0 -82
- package/dist/errors-Dc2oiW-Y.js +0 -38
- package/dist/fs-lite-CbLKxLut.js +0 -90
- package/dist/object-B1NW521B.js +0 -7
- package/dist/operations-ByuDE12r.js +0 -1442
- package/dist/types-CMDvN0Wr.d.ts +0 -81
package/dist/vite.js
CHANGED
|
@@ -1,117 +1,49 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { n as
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
1
|
+
import { a as resolve$1, i as relative$1, n as relativeDefinitionFile, r as dirname$1 } from "./inspect-BIKQsqX4.js";
|
|
2
|
+
import { D as readViteHubDevServerFile, M as internalErrorDiagnostics, S as shouldSkipViteProviderBuild, _ as VITEHUB_PROJECT_ROOT, b as isServerEnvironment, j as writeViteHubDevServerFile, k as removeViteHubDevServerFile, p as operationRpcPath, r as collectOperationContributions, v as createNoExternalAddition, x as resolveViteHubProjectRoot, y as hasNitroConfigContext } from "./operations-D2iI9oN4.js";
|
|
3
|
+
import { n as isRecordOrFunction, t as isRecord } from "./object-Da1zyPCR.js";
|
|
4
|
+
import { n as invariantError, t as invariant } from "./invariant-DolT9EEx.js";
|
|
5
|
+
import { n as kvErrorDiagnostics } from "./error-diagnostics-C54QQEhN.js";
|
|
6
|
+
import { a as upstashUrlEnvNames, i as upstashTokenEnvNames, n as kvRedisEnvHint, o as resolveHostPreset, r as normalizeKVOptions } from "./config-LfpUj9hs.js";
|
|
7
|
+
import { n as resolveUpstashRuntimeValues } from "./upstash-B-vaUYqO.js";
|
|
8
|
+
import { t as addViteHubDevPeerDevHandler } from "./dev-peer-CHafxbtj.js";
|
|
9
|
+
import { createRequire, isBuiltin } from "node:module";
|
|
10
|
+
import { copyFile, cp, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
|
|
11
|
+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
12
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
13
|
+
import { formatDiagnostic } from "nostics";
|
|
9
14
|
import { tmpdir } from "node:os";
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
//#region
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
const
|
|
18
|
-
function
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
const
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
}
|
|
39
|
-
resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
|
|
40
|
-
if (resolvedAbsolute && !isAbsolute$1(resolvedPath)) return `/${resolvedPath}`;
|
|
41
|
-
return resolvedPath.length > 0 ? resolvedPath : ".";
|
|
42
|
-
};
|
|
43
|
-
function normalizeString(path, allowAboveRoot) {
|
|
44
|
-
let res = "";
|
|
45
|
-
let lastSegmentLength = 0;
|
|
46
|
-
let lastSlash = -1;
|
|
47
|
-
let dots = 0;
|
|
48
|
-
let char = null;
|
|
49
|
-
for (let index = 0; index <= path.length; ++index) {
|
|
50
|
-
if (index < path.length) char = path[index];
|
|
51
|
-
else if (char === "/") break;
|
|
52
|
-
else char = "/";
|
|
53
|
-
if (char === "/") {
|
|
54
|
-
if (lastSlash === index - 1 || dots === 1);
|
|
55
|
-
else if (dots === 2) {
|
|
56
|
-
if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
|
|
57
|
-
if (res.length > 2) {
|
|
58
|
-
const lastSlashIndex = res.lastIndexOf("/");
|
|
59
|
-
if (lastSlashIndex === -1) {
|
|
60
|
-
res = "";
|
|
61
|
-
lastSegmentLength = 0;
|
|
62
|
-
} else {
|
|
63
|
-
res = res.slice(0, lastSlashIndex);
|
|
64
|
-
lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
|
|
65
|
-
}
|
|
66
|
-
lastSlash = index;
|
|
67
|
-
dots = 0;
|
|
68
|
-
continue;
|
|
69
|
-
} else if (res.length > 0) {
|
|
70
|
-
res = "";
|
|
71
|
-
lastSegmentLength = 0;
|
|
72
|
-
lastSlash = index;
|
|
73
|
-
dots = 0;
|
|
74
|
-
continue;
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
if (allowAboveRoot) {
|
|
78
|
-
res += res.length > 0 ? "/.." : "..";
|
|
79
|
-
lastSegmentLength = 2;
|
|
80
|
-
}
|
|
81
|
-
} else {
|
|
82
|
-
if (res.length > 0) res += `/${path.slice(lastSlash + 1, index)}`;
|
|
83
|
-
else res = path.slice(lastSlash + 1, index);
|
|
84
|
-
lastSegmentLength = index - lastSlash - 1;
|
|
85
|
-
}
|
|
86
|
-
lastSlash = index;
|
|
87
|
-
dots = 0;
|
|
88
|
-
} else if (char === "." && dots !== -1) ++dots;
|
|
89
|
-
else dots = -1;
|
|
90
|
-
}
|
|
91
|
-
return res;
|
|
15
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
16
|
+
import { createHash } from "node:crypto";
|
|
17
|
+
//#region ../internal/src/build/paths.ts
|
|
18
|
+
function resolveRuntimeModule(packageDir, modulePath) {
|
|
19
|
+
const distFile = resolve$1(packageDir, "dist", `${modulePath}.js`);
|
|
20
|
+
return existsSync(distFile) ? distFile : resolve$1(packageDir, "src", `${modulePath}.ts`);
|
|
21
|
+
}
|
|
22
|
+
const packageDirs = /* @__PURE__ */ new Map();
|
|
23
|
+
function findPackageDir(file) {
|
|
24
|
+
const start = dirname$1(file);
|
|
25
|
+
const cached = packageDirs.get(start);
|
|
26
|
+
if (cached) return cached;
|
|
27
|
+
let dir = start;
|
|
28
|
+
while (!existsSync(resolve$1(dir, "package.json"))) {
|
|
29
|
+
const parent = dirname$1(dir);
|
|
30
|
+
invariant(parent !== dir, `a file that a package resolver found has a package.json above it (${file})`);
|
|
31
|
+
dir = parent;
|
|
32
|
+
}
|
|
33
|
+
packageDirs.set(start, dir);
|
|
34
|
+
return dir;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* The absolute path of a module that the calling package builds, such as `ownModule(import.meta.url, "runtime/state")`.
|
|
38
|
+
* Owner plugins write this path into generated code, so the module needs no package export, and an app resolves it
|
|
39
|
+
* only when the owner's feature is on. It is the `dist` file, or the `src` file before the package is built.
|
|
40
|
+
*/
|
|
41
|
+
function ownModule(importMetaUrl, modulePath) {
|
|
42
|
+
return resolveRuntimeModule(findPackageDir(fileURLToPath(importMetaUrl)), modulePath);
|
|
92
43
|
}
|
|
93
|
-
const isAbsolute$1 = function(p) {
|
|
94
|
-
return _IS_ABSOLUTE_RE.test(p);
|
|
95
|
-
};
|
|
96
|
-
const relative$1 = function(from, to) {
|
|
97
|
-
const _from = resolve$1(from).replace(_ROOT_FOLDER_RE, "$1").split("/");
|
|
98
|
-
const _to = resolve$1(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
|
|
99
|
-
if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) return _to.join("/");
|
|
100
|
-
const _fromCopy = [..._from];
|
|
101
|
-
for (const segment of _fromCopy) {
|
|
102
|
-
if (_to[0] !== segment) break;
|
|
103
|
-
_from.shift();
|
|
104
|
-
_to.shift();
|
|
105
|
-
}
|
|
106
|
-
return [..._from.map(() => ".."), ..._to].join("/");
|
|
107
|
-
};
|
|
108
|
-
const dirname$1 = function(p) {
|
|
109
|
-
const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
|
|
110
|
-
if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) segments[0] += "/";
|
|
111
|
-
return segments.join("/") || (isAbsolute$1(p) ? "/" : ".");
|
|
112
|
-
};
|
|
113
44
|
//#endregion
|
|
114
45
|
//#region ../internal/src/definition-catalog.ts
|
|
46
|
+
/** `writeFileIfChangedSync` for async callers. */
|
|
115
47
|
async function writeFileIfChanged(file, contents) {
|
|
116
48
|
if (await readFile(file, "utf8").catch(() => void 0) === contents) return;
|
|
117
49
|
await mkdir(resolve$1(file, ".."), { recursive: true });
|
|
@@ -122,15 +54,12 @@ async function writeFileIfChanged(file, contents) {
|
|
|
122
54
|
function cloneArray(value) {
|
|
123
55
|
return Array.isArray(value) ? [...value] : [];
|
|
124
56
|
}
|
|
125
|
-
function isRecord(value) {
|
|
126
|
-
return Object(value) === value && !Array.isArray(value);
|
|
127
|
-
}
|
|
128
57
|
function sameHandler(left, right) {
|
|
129
58
|
return left.handler === right.handler && left.route === right.route && left.method === right.method && left.middleware === right.middleware;
|
|
130
59
|
}
|
|
131
60
|
/** Create a Nitro 3 configuration builder for generated ViteHub output. */
|
|
132
61
|
function createNitroServerKit(value = {}) {
|
|
133
|
-
const config =
|
|
62
|
+
const config = isRecordOrFunction(value) ? { ...value } : {};
|
|
134
63
|
const handlers = cloneArray(config.handlers);
|
|
135
64
|
const plugins = cloneArray(config.plugins);
|
|
136
65
|
config.handlers = handlers;
|
|
@@ -138,7 +67,7 @@ function createNitroServerKit(value = {}) {
|
|
|
138
67
|
return {
|
|
139
68
|
config,
|
|
140
69
|
addHandler(handler, position = "end") {
|
|
141
|
-
if (handlers.some((candidate) =>
|
|
70
|
+
if (handlers.some((candidate) => isRecordOrFunction(candidate) && sameHandler(candidate, handler))) return;
|
|
142
71
|
if (position === "start") handlers.unshift({ ...handler });
|
|
143
72
|
else handlers.push({ ...handler });
|
|
144
73
|
},
|
|
@@ -159,7 +88,7 @@ async function flattenPlugins(value, plugins, seen) {
|
|
|
159
88
|
for (const item of value) await flattenPlugins(item, plugins, seen);
|
|
160
89
|
return;
|
|
161
90
|
}
|
|
162
|
-
if (!
|
|
91
|
+
if (!isRecord(value) || seen.has(value)) return;
|
|
163
92
|
seen.add(value);
|
|
164
93
|
if (isThenable(value)) {
|
|
165
94
|
await flattenPlugins(await value, plugins, seen);
|
|
@@ -179,17 +108,19 @@ async function flattenPluginOptions(plugins) {
|
|
|
179
108
|
}
|
|
180
109
|
//#endregion
|
|
181
110
|
//#region ../internal/src/operations-vite.ts
|
|
182
|
-
const owners = /* @__PURE__ */ new Set([
|
|
183
|
-
"@vite-hub/kv/
|
|
184
|
-
"@vite-hub/blob/
|
|
185
|
-
"@vite-hub/email/
|
|
186
|
-
"@vite-hub/rate-limit/
|
|
111
|
+
const owners$1 = /* @__PURE__ */ new Set([
|
|
112
|
+
"@vite-hub/kv/vite",
|
|
113
|
+
"@vite-hub/blob/vite",
|
|
114
|
+
"@vite-hub/email/vite",
|
|
115
|
+
"@vite-hub/rate-limit/vite",
|
|
116
|
+
"@vite-hub/forms/vite",
|
|
117
|
+
"@vite-hub/sync/vite"
|
|
187
118
|
]);
|
|
188
119
|
const discoveryInstalled = Symbol.for("vitehub.operations.dev.discovery");
|
|
189
120
|
/** Publish only the elected standalone transport; other Console policies retain their own discovery hook. */
|
|
190
121
|
function publishStandaloneOperationServer(server) {
|
|
191
122
|
const http = server.httpServer;
|
|
192
|
-
if (!http || Reflect.get(server, discoveryInstalled)) return;
|
|
123
|
+
if (!http || server.config.server.middlewareMode || Reflect.get(server, discoveryInstalled)) return;
|
|
193
124
|
const root = resolve(server.config.root);
|
|
194
125
|
const handlers = Reflect.get(Object(Reflect.get(server.config, "nitro")), "handlers");
|
|
195
126
|
if (!Array.isArray(handlers) || !handlers.some((handler) => handler?.handler === resolve(root, ".vitehub/nitro/operations/rpc.mjs"))) return;
|
|
@@ -222,11 +153,12 @@ async function installStandaloneOperationRpc(config, command, module) {
|
|
|
222
153
|
const plugins = await flattenPluginOptions(config.plugins);
|
|
223
154
|
if (plugins.some((plugin) => Reflect.get(plugin, "name") === "vite-hub/dependencies" || Reflect.get(plugin, "name") === "vite-hub/console")) return;
|
|
224
155
|
const contributions = (await collectOperationContributions(plugins)).filter((source) => source.runtime !== false);
|
|
225
|
-
|
|
156
|
+
const owner = contributions.find((source) => owners$1.has(source.plugin));
|
|
157
|
+
if (!owner || !contributions.some((source) => source.module === module && owners$1.has(source.plugin))) return;
|
|
226
158
|
const root = resolve(config.root ?? process.cwd());
|
|
227
159
|
const handler = resolve(root, ".vitehub/nitro/operations/rpc.mjs");
|
|
228
160
|
await writeFileIfChanged(handler, [
|
|
229
|
-
`import { createStandaloneOperationHandler } from ${JSON.stringify(module)}`,
|
|
161
|
+
`import { createStandaloneOperationHandler } from ${JSON.stringify(owner.module)}`,
|
|
230
162
|
...contributions.map((entry, index) => `import * as source${index} from ${JSON.stringify(entry.module)}`),
|
|
231
163
|
`export default createStandaloneOperationHandler([${contributions.map((entry, index) => `{ operations: source${index}[${JSON.stringify(entry.export)}], plugin: ${JSON.stringify(entry.plugin)} }`).join(", ")}], ${JSON.stringify(root)})`,
|
|
232
164
|
""
|
|
@@ -236,9 +168,19 @@ async function installStandaloneOperationRpc(config, command, module) {
|
|
|
236
168
|
handler,
|
|
237
169
|
route: operationRpcPath
|
|
238
170
|
});
|
|
171
|
+
const devHandlers = kit.config.devHandlers;
|
|
172
|
+
const signed = Array.isArray(devHandlers) ? [...devHandlers] : [];
|
|
173
|
+
addViteHubDevPeerDevHandler(signed);
|
|
174
|
+
kit.config.devHandlers = signed;
|
|
239
175
|
Reflect.set(config, "nitro", kit.config);
|
|
240
176
|
}
|
|
241
177
|
//#endregion
|
|
178
|
+
//#region ../internal/src/durability.ts
|
|
179
|
+
/** The `durability` module next to the Vite plugin module at `importMetaUrl`, in source and in `dist`. */
|
|
180
|
+
function durabilityModuleFile(importMetaUrl) {
|
|
181
|
+
return fileURLToPath(new URL(importMetaUrl.endsWith(".ts") ? "./durability.ts" : "./durability.js", importMetaUrl));
|
|
182
|
+
}
|
|
183
|
+
//#endregion
|
|
242
184
|
//#region src/vite-config.ts
|
|
243
185
|
const KV_VITE_PLUGIN_NAME = "@vite-hub/kv/vite";
|
|
244
186
|
const KV_VIRTUAL_CONFIG_ID = "#vitehub/kv/config";
|
|
@@ -251,6 +193,7 @@ function resolveKVViteConfig(kv, input = {}) {
|
|
|
251
193
|
return {
|
|
252
194
|
hosting,
|
|
253
195
|
kv: normalizeKVOptions(kv, {
|
|
196
|
+
...input,
|
|
254
197
|
env,
|
|
255
198
|
hosting
|
|
256
199
|
}) ?? false
|
|
@@ -457,2375 +400,94 @@ async function writeCloudflareWranglerConfig(options) {
|
|
|
457
400
|
});
|
|
458
401
|
}
|
|
459
402
|
//#endregion
|
|
460
|
-
//#region ../internal/src/build/
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
let visit = (value) => {
|
|
501
|
-
if (value === null) bb.write8(0);
|
|
502
|
-
else if (typeof value === "boolean") {
|
|
503
|
-
bb.write8(1);
|
|
504
|
-
bb.write8(+value);
|
|
505
|
-
} else if (typeof value === "number") {
|
|
506
|
-
bb.write8(2);
|
|
507
|
-
bb.write32(value | 0);
|
|
508
|
-
} else if (typeof value === "string") {
|
|
509
|
-
bb.write8(3);
|
|
510
|
-
bb.write(encodeUTF8(value));
|
|
511
|
-
} else if (value instanceof Uint8Array) {
|
|
512
|
-
bb.write8(4);
|
|
513
|
-
bb.write(value);
|
|
514
|
-
} else if (value instanceof Array) {
|
|
515
|
-
bb.write8(5);
|
|
516
|
-
bb.write32(value.length);
|
|
517
|
-
for (let item of value) visit(item);
|
|
518
|
-
} else {
|
|
519
|
-
let keys = Object.keys(value);
|
|
520
|
-
bb.write8(6);
|
|
521
|
-
bb.write32(keys.length);
|
|
522
|
-
for (let key of keys) {
|
|
523
|
-
bb.write(encodeUTF8(key));
|
|
524
|
-
visit(value[key]);
|
|
525
|
-
}
|
|
526
|
-
}
|
|
527
|
-
};
|
|
528
|
-
let bb = new ByteBuffer();
|
|
529
|
-
bb.write32(0);
|
|
530
|
-
bb.write32(packet.id << 1 | +!packet.isRequest);
|
|
531
|
-
visit(packet.value);
|
|
532
|
-
writeUInt32LE(bb.buf, bb.len - 4, 0);
|
|
533
|
-
return bb.buf.subarray(0, bb.len);
|
|
534
|
-
}
|
|
535
|
-
function decodePacket(bytes) {
|
|
536
|
-
let visit = () => {
|
|
537
|
-
switch (bb.read8()) {
|
|
538
|
-
case 0: return null;
|
|
539
|
-
case 1: return !!bb.read8();
|
|
540
|
-
case 2: return bb.read32();
|
|
541
|
-
case 3: return decodeUTF8(bb.read());
|
|
542
|
-
case 4: return bb.read();
|
|
543
|
-
case 5: {
|
|
544
|
-
let count = bb.read32();
|
|
545
|
-
let value2 = [];
|
|
546
|
-
for (let i = 0; i < count; i++) value2.push(visit());
|
|
547
|
-
return value2;
|
|
548
|
-
}
|
|
549
|
-
case 6: {
|
|
550
|
-
let count = bb.read32();
|
|
551
|
-
let value2 = {};
|
|
552
|
-
for (let i = 0; i < count; i++) value2[decodeUTF8(bb.read())] = visit();
|
|
553
|
-
return value2;
|
|
554
|
-
}
|
|
555
|
-
default: throw new Error("Invalid packet");
|
|
556
|
-
}
|
|
557
|
-
};
|
|
558
|
-
let bb = new ByteBuffer(bytes);
|
|
559
|
-
let id = bb.read32();
|
|
560
|
-
let isRequest = (id & 1) === 0;
|
|
561
|
-
id >>>= 1;
|
|
562
|
-
let value = visit();
|
|
563
|
-
if (bb.ptr !== bytes.length) throw new Error("Invalid packet");
|
|
564
|
-
return {
|
|
565
|
-
id,
|
|
566
|
-
isRequest,
|
|
567
|
-
value
|
|
568
|
-
};
|
|
569
|
-
}
|
|
570
|
-
var ByteBuffer = class {
|
|
571
|
-
constructor(buf = /* @__PURE__ */ new Uint8Array(1024)) {
|
|
572
|
-
this.buf = buf;
|
|
573
|
-
this.len = 0;
|
|
574
|
-
this.ptr = 0;
|
|
575
|
-
}
|
|
576
|
-
_write(delta) {
|
|
577
|
-
if (this.len + delta > this.buf.length) {
|
|
578
|
-
let clone = new Uint8Array((this.len + delta) * 2);
|
|
579
|
-
clone.set(this.buf);
|
|
580
|
-
this.buf = clone;
|
|
581
|
-
}
|
|
582
|
-
this.len += delta;
|
|
583
|
-
return this.len - delta;
|
|
584
|
-
}
|
|
585
|
-
write8(value) {
|
|
586
|
-
let offset = this._write(1);
|
|
587
|
-
this.buf[offset] = value;
|
|
588
|
-
}
|
|
589
|
-
write32(value) {
|
|
590
|
-
let offset = this._write(4);
|
|
591
|
-
writeUInt32LE(this.buf, value, offset);
|
|
592
|
-
}
|
|
593
|
-
write(bytes) {
|
|
594
|
-
let offset = this._write(4 + bytes.length);
|
|
595
|
-
writeUInt32LE(this.buf, bytes.length, offset);
|
|
596
|
-
this.buf.set(bytes, offset + 4);
|
|
597
|
-
}
|
|
598
|
-
_read(delta) {
|
|
599
|
-
if (this.ptr + delta > this.buf.length) throw new Error("Invalid packet");
|
|
600
|
-
this.ptr += delta;
|
|
601
|
-
return this.ptr - delta;
|
|
602
|
-
}
|
|
603
|
-
read8() {
|
|
604
|
-
return this.buf[this._read(1)];
|
|
605
|
-
}
|
|
606
|
-
read32() {
|
|
607
|
-
return readUInt32LE(this.buf, this._read(4));
|
|
608
|
-
}
|
|
609
|
-
read() {
|
|
610
|
-
let length = this.read32();
|
|
611
|
-
let bytes = new Uint8Array(length);
|
|
612
|
-
let ptr = this._read(bytes.length);
|
|
613
|
-
bytes.set(this.buf.subarray(ptr, ptr + length));
|
|
614
|
-
return bytes;
|
|
615
|
-
}
|
|
616
|
-
};
|
|
617
|
-
var encodeUTF8;
|
|
618
|
-
var decodeUTF8;
|
|
619
|
-
var encodeInvariant;
|
|
620
|
-
if (typeof TextEncoder !== "undefined" && typeof TextDecoder !== "undefined") {
|
|
621
|
-
let encoder = new TextEncoder();
|
|
622
|
-
let decoder = new TextDecoder();
|
|
623
|
-
encodeUTF8 = (text) => encoder.encode(text);
|
|
624
|
-
decodeUTF8 = (bytes) => decoder.decode(bytes);
|
|
625
|
-
encodeInvariant = "new TextEncoder().encode(\"\")";
|
|
626
|
-
} else if (typeof Buffer !== "undefined") {
|
|
627
|
-
encodeUTF8 = (text) => Buffer.from(text);
|
|
628
|
-
decodeUTF8 = (bytes) => {
|
|
629
|
-
let { buffer, byteOffset, byteLength } = bytes;
|
|
630
|
-
return Buffer.from(buffer, byteOffset, byteLength).toString();
|
|
631
|
-
};
|
|
632
|
-
encodeInvariant = "Buffer.from(\"\")";
|
|
633
|
-
} else throw new Error("No UTF-8 codec found");
|
|
634
|
-
if (!(encodeUTF8("") instanceof Uint8Array)) throw new Error(`Invariant violation: "${encodeInvariant} instanceof Uint8Array" is incorrectly false
|
|
635
|
-
|
|
636
|
-
This indicates that your JavaScript environment is broken. You cannot use
|
|
637
|
-
esbuild in this environment because esbuild relies on this invariant. This
|
|
638
|
-
is not a problem with esbuild. You need to fix your environment instead.
|
|
639
|
-
`);
|
|
640
|
-
function readUInt32LE(buffer, offset) {
|
|
641
|
-
return (buffer[offset++] | buffer[offset++] << 8 | buffer[offset++] << 16 | buffer[offset++] << 24) >>> 0;
|
|
642
|
-
}
|
|
643
|
-
function writeUInt32LE(buffer, value, offset) {
|
|
644
|
-
buffer[offset++] = value;
|
|
645
|
-
buffer[offset++] = value >> 8;
|
|
646
|
-
buffer[offset++] = value >> 16;
|
|
647
|
-
buffer[offset++] = value >> 24;
|
|
648
|
-
}
|
|
649
|
-
var fromCharCode = String.fromCharCode;
|
|
650
|
-
function throwSyntaxError(bytes, index, message) {
|
|
651
|
-
const c = bytes[index];
|
|
652
|
-
let line = 1;
|
|
653
|
-
let column = 0;
|
|
654
|
-
for (let i = 0; i < index; i++) if (bytes[i] === 10) {
|
|
655
|
-
line++;
|
|
656
|
-
column = 0;
|
|
657
|
-
} else column++;
|
|
658
|
-
throw new SyntaxError(message ? message : index === bytes.length ? "Unexpected end of input while parsing JSON" : c >= 32 && c <= 126 ? `Unexpected character ${fromCharCode(c)} in JSON at position ${index} (line ${line}, column ${column})` : `Unexpected byte 0x${c.toString(16)} in JSON at position ${index} (line ${line}, column ${column})`);
|
|
659
|
-
}
|
|
660
|
-
function JSON_parse(bytes) {
|
|
661
|
-
if (!(bytes instanceof Uint8Array)) throw new Error(`JSON input must be a Uint8Array`);
|
|
662
|
-
const propertyStack = [];
|
|
663
|
-
const objectStack = [];
|
|
664
|
-
const stateStack = [];
|
|
665
|
-
const length = bytes.length;
|
|
666
|
-
let property = null;
|
|
667
|
-
let state = 0;
|
|
668
|
-
let object;
|
|
669
|
-
let i = 0;
|
|
670
|
-
while (i < length) {
|
|
671
|
-
let c = bytes[i++];
|
|
672
|
-
if (c <= 32) continue;
|
|
673
|
-
let value;
|
|
674
|
-
if (state === 2 && property === null && c !== 34 && c !== 125) throwSyntaxError(bytes, --i);
|
|
675
|
-
switch (c) {
|
|
676
|
-
case 116:
|
|
677
|
-
if (bytes[i++] !== 114 || bytes[i++] !== 117 || bytes[i++] !== 101) throwSyntaxError(bytes, --i);
|
|
678
|
-
value = true;
|
|
679
|
-
break;
|
|
680
|
-
case 102:
|
|
681
|
-
if (bytes[i++] !== 97 || bytes[i++] !== 108 || bytes[i++] !== 115 || bytes[i++] !== 101) throwSyntaxError(bytes, --i);
|
|
682
|
-
value = false;
|
|
683
|
-
break;
|
|
684
|
-
case 110:
|
|
685
|
-
if (bytes[i++] !== 117 || bytes[i++] !== 108 || bytes[i++] !== 108) throwSyntaxError(bytes, --i);
|
|
686
|
-
value = null;
|
|
687
|
-
break;
|
|
688
|
-
case 45:
|
|
689
|
-
case 46:
|
|
690
|
-
case 48:
|
|
691
|
-
case 49:
|
|
692
|
-
case 50:
|
|
693
|
-
case 51:
|
|
694
|
-
case 52:
|
|
695
|
-
case 53:
|
|
696
|
-
case 54:
|
|
697
|
-
case 55:
|
|
698
|
-
case 56:
|
|
699
|
-
case 57: {
|
|
700
|
-
let index = i;
|
|
701
|
-
value = fromCharCode(c);
|
|
702
|
-
c = bytes[i];
|
|
703
|
-
while (true) {
|
|
704
|
-
switch (c) {
|
|
705
|
-
case 43:
|
|
706
|
-
case 45:
|
|
707
|
-
case 46:
|
|
708
|
-
case 48:
|
|
709
|
-
case 49:
|
|
710
|
-
case 50:
|
|
711
|
-
case 51:
|
|
712
|
-
case 52:
|
|
713
|
-
case 53:
|
|
714
|
-
case 54:
|
|
715
|
-
case 55:
|
|
716
|
-
case 56:
|
|
717
|
-
case 57:
|
|
718
|
-
case 101:
|
|
719
|
-
case 69:
|
|
720
|
-
value += fromCharCode(c);
|
|
721
|
-
c = bytes[++i];
|
|
722
|
-
continue;
|
|
723
|
-
}
|
|
724
|
-
break;
|
|
725
|
-
}
|
|
726
|
-
value = +value;
|
|
727
|
-
if (isNaN(value)) throwSyntaxError(bytes, --index, "Invalid number");
|
|
728
|
-
break;
|
|
729
|
-
}
|
|
730
|
-
case 34:
|
|
731
|
-
value = "";
|
|
732
|
-
while (true) {
|
|
733
|
-
if (i >= length) throwSyntaxError(bytes, length);
|
|
734
|
-
c = bytes[i++];
|
|
735
|
-
if (c === 34) break;
|
|
736
|
-
else if (c === 92) switch (bytes[i++]) {
|
|
737
|
-
case 34:
|
|
738
|
-
value += "\"";
|
|
739
|
-
break;
|
|
740
|
-
case 47:
|
|
741
|
-
value += "/";
|
|
742
|
-
break;
|
|
743
|
-
case 92:
|
|
744
|
-
value += "\\";
|
|
745
|
-
break;
|
|
746
|
-
case 98:
|
|
747
|
-
value += "\b";
|
|
748
|
-
break;
|
|
749
|
-
case 102:
|
|
750
|
-
value += "\f";
|
|
751
|
-
break;
|
|
752
|
-
case 110:
|
|
753
|
-
value += "\n";
|
|
754
|
-
break;
|
|
755
|
-
case 114:
|
|
756
|
-
value += "\r";
|
|
757
|
-
break;
|
|
758
|
-
case 116:
|
|
759
|
-
value += " ";
|
|
760
|
-
break;
|
|
761
|
-
case 117: {
|
|
762
|
-
let code = 0;
|
|
763
|
-
for (let j = 0; j < 4; j++) {
|
|
764
|
-
c = bytes[i++];
|
|
765
|
-
code <<= 4;
|
|
766
|
-
if (c >= 48 && c <= 57) code |= c - 48;
|
|
767
|
-
else if (c >= 97 && c <= 102) code |= c + -87;
|
|
768
|
-
else if (c >= 65 && c <= 70) code |= c + -55;
|
|
769
|
-
else throwSyntaxError(bytes, --i);
|
|
770
|
-
}
|
|
771
|
-
value += fromCharCode(code);
|
|
772
|
-
break;
|
|
773
|
-
}
|
|
774
|
-
default: throwSyntaxError(bytes, --i);
|
|
775
|
-
}
|
|
776
|
-
else if (c <= 127) value += fromCharCode(c);
|
|
777
|
-
else if ((c & 224) === 192) value += fromCharCode((c & 31) << 6 | bytes[i++] & 63);
|
|
778
|
-
else if ((c & 240) === 224) value += fromCharCode((c & 15) << 12 | (bytes[i++] & 63) << 6 | bytes[i++] & 63);
|
|
779
|
-
else if ((c & 248) == 240) {
|
|
780
|
-
let codePoint = (c & 7) << 18 | (bytes[i++] & 63) << 12 | (bytes[i++] & 63) << 6 | bytes[i++] & 63;
|
|
781
|
-
if (codePoint > 65535) {
|
|
782
|
-
codePoint -= 65536;
|
|
783
|
-
value += fromCharCode(codePoint >> 10 & 1023 | 55296);
|
|
784
|
-
codePoint = 56320 | codePoint & 1023;
|
|
785
|
-
}
|
|
786
|
-
value += fromCharCode(codePoint);
|
|
787
|
-
}
|
|
788
|
-
}
|
|
789
|
-
value[0];
|
|
790
|
-
break;
|
|
791
|
-
case 91:
|
|
792
|
-
value = [];
|
|
793
|
-
propertyStack.push(property);
|
|
794
|
-
objectStack.push(object);
|
|
795
|
-
stateStack.push(state);
|
|
796
|
-
property = null;
|
|
797
|
-
object = value;
|
|
798
|
-
state = 1;
|
|
799
|
-
continue;
|
|
800
|
-
case 123:
|
|
801
|
-
value = {};
|
|
802
|
-
propertyStack.push(property);
|
|
803
|
-
objectStack.push(object);
|
|
804
|
-
stateStack.push(state);
|
|
805
|
-
property = null;
|
|
806
|
-
object = value;
|
|
807
|
-
state = 2;
|
|
808
|
-
continue;
|
|
809
|
-
case 93:
|
|
810
|
-
if (state !== 1) throwSyntaxError(bytes, --i);
|
|
811
|
-
value = object;
|
|
812
|
-
property = propertyStack.pop();
|
|
813
|
-
object = objectStack.pop();
|
|
814
|
-
state = stateStack.pop();
|
|
815
|
-
break;
|
|
816
|
-
case 125:
|
|
817
|
-
if (state !== 2) throwSyntaxError(bytes, --i);
|
|
818
|
-
value = object;
|
|
819
|
-
property = propertyStack.pop();
|
|
820
|
-
object = objectStack.pop();
|
|
821
|
-
state = stateStack.pop();
|
|
822
|
-
break;
|
|
823
|
-
default: throwSyntaxError(bytes, --i);
|
|
824
|
-
}
|
|
825
|
-
c = bytes[i];
|
|
826
|
-
while (c <= 32) c = bytes[++i];
|
|
827
|
-
switch (state) {
|
|
828
|
-
case 0:
|
|
829
|
-
if (i === length) return value;
|
|
830
|
-
break;
|
|
831
|
-
case 1:
|
|
832
|
-
object.push(value);
|
|
833
|
-
if (c === 44) {
|
|
834
|
-
i++;
|
|
835
|
-
continue;
|
|
836
|
-
}
|
|
837
|
-
if (c === 93) continue;
|
|
838
|
-
break;
|
|
839
|
-
case 2: if (property === null) {
|
|
840
|
-
property = value;
|
|
841
|
-
if (c === 58) {
|
|
842
|
-
i++;
|
|
843
|
-
continue;
|
|
844
|
-
}
|
|
845
|
-
} else {
|
|
846
|
-
object[property] = value;
|
|
847
|
-
property = null;
|
|
848
|
-
if (c === 44) {
|
|
849
|
-
i++;
|
|
850
|
-
continue;
|
|
851
|
-
}
|
|
852
|
-
if (c === 125) continue;
|
|
853
|
-
}
|
|
854
|
-
}
|
|
855
|
-
break;
|
|
856
|
-
}
|
|
857
|
-
throwSyntaxError(bytes, i);
|
|
858
|
-
}
|
|
859
|
-
var quote = JSON.stringify;
|
|
860
|
-
var buildLogLevelDefault = "warning";
|
|
861
|
-
var transformLogLevelDefault = "silent";
|
|
862
|
-
function validateAndJoinStringArray(values, what) {
|
|
863
|
-
const toJoin = [];
|
|
864
|
-
for (const value of values) {
|
|
865
|
-
validateStringValue(value, what);
|
|
866
|
-
if (value.indexOf(",") >= 0) throw new Error(`Invalid ${what}: ${value}`);
|
|
867
|
-
toJoin.push(value);
|
|
868
|
-
}
|
|
869
|
-
return toJoin.join(",");
|
|
870
|
-
}
|
|
871
|
-
var canBeAnything = () => null;
|
|
872
|
-
var mustBeBoolean = (value) => typeof value === "boolean" ? null : "a boolean";
|
|
873
|
-
var mustBeString = (value) => typeof value === "string" ? null : "a string";
|
|
874
|
-
var mustBeRegExp = (value) => value instanceof RegExp ? null : "a RegExp object";
|
|
875
|
-
var mustBeInteger = (value) => typeof value === "number" && value === (value | 0) ? null : "an integer";
|
|
876
|
-
var mustBeValidPortNumber = (value) => typeof value === "number" && value === (value | 0) && value >= 0 && value <= 65535 ? null : "a valid port number";
|
|
877
|
-
var mustBeFunction = (value) => typeof value === "function" ? null : "a function";
|
|
878
|
-
var mustBeArray = (value) => Array.isArray(value) ? null : "an array";
|
|
879
|
-
var mustBeArrayOfStrings = (value) => Array.isArray(value) && value.every((x) => typeof x === "string") ? null : "an array of strings";
|
|
880
|
-
var mustBeObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? null : "an object";
|
|
881
|
-
var mustBeEntryPoints = (value) => typeof value === "object" && value !== null ? null : "an array or an object";
|
|
882
|
-
var mustBeWebAssemblyModule = (value) => value instanceof WebAssembly.Module ? null : "a WebAssembly.Module";
|
|
883
|
-
var mustBeObjectOrNull = (value) => typeof value === "object" && !Array.isArray(value) ? null : "an object or null";
|
|
884
|
-
var mustBeStringOrBoolean = (value) => typeof value === "string" || typeof value === "boolean" ? null : "a string or a boolean";
|
|
885
|
-
var mustBeStringOrObject = (value) => typeof value === "string" || typeof value === "object" && value !== null && !Array.isArray(value) ? null : "a string or an object";
|
|
886
|
-
var mustBeStringOrArrayOfStrings = (value) => typeof value === "string" || Array.isArray(value) && value.every((x) => typeof x === "string") ? null : "a string or an array of strings";
|
|
887
|
-
var mustBeStringOrUint8Array = (value) => typeof value === "string" || value instanceof Uint8Array ? null : "a string or a Uint8Array";
|
|
888
|
-
var mustBeStringOrURL = (value) => typeof value === "string" || value instanceof URL ? null : "a string or a URL";
|
|
889
|
-
function getFlag(object, keys, key, mustBeFn) {
|
|
890
|
-
let value = object[key];
|
|
891
|
-
keys[key + ""] = true;
|
|
892
|
-
if (value === void 0) return void 0;
|
|
893
|
-
let mustBe = mustBeFn(value);
|
|
894
|
-
if (mustBe !== null) throw new Error(`${quote(key)} must be ${mustBe}`);
|
|
895
|
-
return value;
|
|
896
|
-
}
|
|
897
|
-
function checkForInvalidFlags(object, keys, where) {
|
|
898
|
-
for (let key in object) if (!(key in keys)) throw new Error(`Invalid option ${where}: ${quote(key)}`);
|
|
899
|
-
}
|
|
900
|
-
function validateInitializeOptions(options) {
|
|
901
|
-
let keys = /* @__PURE__ */ Object.create(null);
|
|
902
|
-
let wasmURL = getFlag(options, keys, "wasmURL", mustBeStringOrURL);
|
|
903
|
-
let wasmModule = getFlag(options, keys, "wasmModule", mustBeWebAssemblyModule);
|
|
904
|
-
let worker = getFlag(options, keys, "worker", mustBeBoolean);
|
|
905
|
-
checkForInvalidFlags(options, keys, "in initialize() call");
|
|
906
|
-
return {
|
|
907
|
-
wasmURL,
|
|
908
|
-
wasmModule,
|
|
909
|
-
worker
|
|
910
|
-
};
|
|
911
|
-
}
|
|
912
|
-
function validateMangleCache(mangleCache) {
|
|
913
|
-
let validated;
|
|
914
|
-
if (mangleCache !== void 0) {
|
|
915
|
-
validated = /* @__PURE__ */ Object.create(null);
|
|
916
|
-
for (let key in mangleCache) {
|
|
917
|
-
let value = mangleCache[key];
|
|
918
|
-
if (typeof value === "string" || value === false) validated[key] = value;
|
|
919
|
-
else throw new Error(`Expected ${quote(key)} in mangle cache to map to either a string or false`);
|
|
920
|
-
}
|
|
921
|
-
}
|
|
922
|
-
return validated;
|
|
923
|
-
}
|
|
924
|
-
function pushLogFlags(flags, options, keys, isTTY2, logLevelDefault) {
|
|
925
|
-
let color = getFlag(options, keys, "color", mustBeBoolean);
|
|
926
|
-
let logLevel = getFlag(options, keys, "logLevel", mustBeString);
|
|
927
|
-
let logLimit = getFlag(options, keys, "logLimit", mustBeInteger);
|
|
928
|
-
if (color !== void 0) flags.push(`--color=${color}`);
|
|
929
|
-
else if (isTTY2) flags.push(`--color=true`);
|
|
930
|
-
flags.push(`--log-level=${logLevel || logLevelDefault}`);
|
|
931
|
-
flags.push(`--log-limit=${logLimit || 0}`);
|
|
932
|
-
}
|
|
933
|
-
function validateStringValue(value, what, key) {
|
|
934
|
-
if (typeof value !== "string") throw new Error(`Expected value for ${what}${key !== void 0 ? " " + quote(key) : ""} to be a string, got ${typeof value} instead`);
|
|
935
|
-
return value;
|
|
936
|
-
}
|
|
937
|
-
function pushCommonFlags(flags, options, keys) {
|
|
938
|
-
let legalComments = getFlag(options, keys, "legalComments", mustBeString);
|
|
939
|
-
let sourceRoot = getFlag(options, keys, "sourceRoot", mustBeString);
|
|
940
|
-
let sourcesContent = getFlag(options, keys, "sourcesContent", mustBeBoolean);
|
|
941
|
-
let target = getFlag(options, keys, "target", mustBeStringOrArrayOfStrings);
|
|
942
|
-
let format = getFlag(options, keys, "format", mustBeString);
|
|
943
|
-
let globalName = getFlag(options, keys, "globalName", mustBeString);
|
|
944
|
-
let mangleProps = getFlag(options, keys, "mangleProps", mustBeRegExp);
|
|
945
|
-
let reserveProps = getFlag(options, keys, "reserveProps", mustBeRegExp);
|
|
946
|
-
let mangleQuoted = getFlag(options, keys, "mangleQuoted", mustBeBoolean);
|
|
947
|
-
let minify = getFlag(options, keys, "minify", mustBeBoolean);
|
|
948
|
-
let minifySyntax = getFlag(options, keys, "minifySyntax", mustBeBoolean);
|
|
949
|
-
let minifyWhitespace = getFlag(options, keys, "minifyWhitespace", mustBeBoolean);
|
|
950
|
-
let minifyIdentifiers = getFlag(options, keys, "minifyIdentifiers", mustBeBoolean);
|
|
951
|
-
let lineLimit = getFlag(options, keys, "lineLimit", mustBeInteger);
|
|
952
|
-
let drop = getFlag(options, keys, "drop", mustBeArrayOfStrings);
|
|
953
|
-
let dropLabels = getFlag(options, keys, "dropLabels", mustBeArrayOfStrings);
|
|
954
|
-
let charset = getFlag(options, keys, "charset", mustBeString);
|
|
955
|
-
let treeShaking = getFlag(options, keys, "treeShaking", mustBeBoolean);
|
|
956
|
-
let ignoreAnnotations = getFlag(options, keys, "ignoreAnnotations", mustBeBoolean);
|
|
957
|
-
let jsx = getFlag(options, keys, "jsx", mustBeString);
|
|
958
|
-
let jsxFactory = getFlag(options, keys, "jsxFactory", mustBeString);
|
|
959
|
-
let jsxFragment = getFlag(options, keys, "jsxFragment", mustBeString);
|
|
960
|
-
let jsxImportSource = getFlag(options, keys, "jsxImportSource", mustBeString);
|
|
961
|
-
let jsxDev = getFlag(options, keys, "jsxDev", mustBeBoolean);
|
|
962
|
-
let jsxSideEffects = getFlag(options, keys, "jsxSideEffects", mustBeBoolean);
|
|
963
|
-
let define = getFlag(options, keys, "define", mustBeObject);
|
|
964
|
-
let logOverride = getFlag(options, keys, "logOverride", mustBeObject);
|
|
965
|
-
let supported = getFlag(options, keys, "supported", mustBeObject);
|
|
966
|
-
let pure = getFlag(options, keys, "pure", mustBeArrayOfStrings);
|
|
967
|
-
let keepNames = getFlag(options, keys, "keepNames", mustBeBoolean);
|
|
968
|
-
let platform = getFlag(options, keys, "platform", mustBeString);
|
|
969
|
-
let tsconfigRaw = getFlag(options, keys, "tsconfigRaw", mustBeStringOrObject);
|
|
970
|
-
let absPaths = getFlag(options, keys, "absPaths", mustBeArrayOfStrings);
|
|
971
|
-
if (legalComments) flags.push(`--legal-comments=${legalComments}`);
|
|
972
|
-
if (sourceRoot !== void 0) flags.push(`--source-root=${sourceRoot}`);
|
|
973
|
-
if (sourcesContent !== void 0) flags.push(`--sources-content=${sourcesContent}`);
|
|
974
|
-
if (target) flags.push(`--target=${validateAndJoinStringArray(Array.isArray(target) ? target : [target], "target")}`);
|
|
975
|
-
if (format) flags.push(`--format=${format}`);
|
|
976
|
-
if (globalName) flags.push(`--global-name=${globalName}`);
|
|
977
|
-
if (platform) flags.push(`--platform=${platform}`);
|
|
978
|
-
if (tsconfigRaw) flags.push(`--tsconfig-raw=${typeof tsconfigRaw === "string" ? tsconfigRaw : JSON.stringify(tsconfigRaw)}`);
|
|
979
|
-
if (minify) flags.push("--minify");
|
|
980
|
-
if (minifySyntax) flags.push("--minify-syntax");
|
|
981
|
-
if (minifyWhitespace) flags.push("--minify-whitespace");
|
|
982
|
-
if (minifyIdentifiers) flags.push("--minify-identifiers");
|
|
983
|
-
if (lineLimit) flags.push(`--line-limit=${lineLimit}`);
|
|
984
|
-
if (charset) flags.push(`--charset=${charset}`);
|
|
985
|
-
if (treeShaking !== void 0) flags.push(`--tree-shaking=${treeShaking}`);
|
|
986
|
-
if (ignoreAnnotations) flags.push(`--ignore-annotations`);
|
|
987
|
-
if (drop) for (let what of drop) flags.push(`--drop:${validateStringValue(what, "drop")}`);
|
|
988
|
-
if (dropLabels) flags.push(`--drop-labels=${validateAndJoinStringArray(dropLabels, "drop label")}`);
|
|
989
|
-
if (absPaths) flags.push(`--abs-paths=${validateAndJoinStringArray(absPaths, "abs paths")}`);
|
|
990
|
-
if (mangleProps) flags.push(`--mangle-props=${jsRegExpToGoRegExp(mangleProps)}`);
|
|
991
|
-
if (reserveProps) flags.push(`--reserve-props=${jsRegExpToGoRegExp(reserveProps)}`);
|
|
992
|
-
if (mangleQuoted !== void 0) flags.push(`--mangle-quoted=${mangleQuoted}`);
|
|
993
|
-
if (jsx) flags.push(`--jsx=${jsx}`);
|
|
994
|
-
if (jsxFactory) flags.push(`--jsx-factory=${jsxFactory}`);
|
|
995
|
-
if (jsxFragment) flags.push(`--jsx-fragment=${jsxFragment}`);
|
|
996
|
-
if (jsxImportSource) flags.push(`--jsx-import-source=${jsxImportSource}`);
|
|
997
|
-
if (jsxDev) flags.push(`--jsx-dev`);
|
|
998
|
-
if (jsxSideEffects) flags.push(`--jsx-side-effects`);
|
|
999
|
-
if (define) for (let key in define) {
|
|
1000
|
-
if (key.indexOf("=") >= 0) throw new Error(`Invalid define: ${key}`);
|
|
1001
|
-
flags.push(`--define:${key}=${validateStringValue(define[key], "define", key)}`);
|
|
1002
|
-
}
|
|
1003
|
-
if (logOverride) for (let key in logOverride) {
|
|
1004
|
-
if (key.indexOf("=") >= 0) throw new Error(`Invalid log override: ${key}`);
|
|
1005
|
-
flags.push(`--log-override:${key}=${validateStringValue(logOverride[key], "log override", key)}`);
|
|
1006
|
-
}
|
|
1007
|
-
if (supported) for (let key in supported) {
|
|
1008
|
-
if (key.indexOf("=") >= 0) throw new Error(`Invalid supported: ${key}`);
|
|
1009
|
-
const value = supported[key];
|
|
1010
|
-
if (typeof value !== "boolean") throw new Error(`Expected value for supported ${quote(key)} to be a boolean, got ${typeof value} instead`);
|
|
1011
|
-
flags.push(`--supported:${key}=${value}`);
|
|
1012
|
-
}
|
|
1013
|
-
if (pure) for (let fn of pure) flags.push(`--pure:${validateStringValue(fn, "pure")}`);
|
|
1014
|
-
if (keepNames) flags.push(`--keep-names`);
|
|
1015
|
-
}
|
|
1016
|
-
function flagsForBuildOptions(callName, options, isTTY2, logLevelDefault, writeDefault) {
|
|
1017
|
-
var _a2;
|
|
1018
|
-
let flags = [];
|
|
1019
|
-
let entries = [];
|
|
1020
|
-
let keys = /* @__PURE__ */ Object.create(null);
|
|
1021
|
-
let stdinContents = null;
|
|
1022
|
-
let stdinResolveDir = null;
|
|
1023
|
-
pushLogFlags(flags, options, keys, isTTY2, logLevelDefault);
|
|
1024
|
-
pushCommonFlags(flags, options, keys);
|
|
1025
|
-
let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
|
|
1026
|
-
let bundle = getFlag(options, keys, "bundle", mustBeBoolean);
|
|
1027
|
-
let splitting = getFlag(options, keys, "splitting", mustBeBoolean);
|
|
1028
|
-
let preserveSymlinks = getFlag(options, keys, "preserveSymlinks", mustBeBoolean);
|
|
1029
|
-
let metafile = getFlag(options, keys, "metafile", mustBeBoolean);
|
|
1030
|
-
let outfile = getFlag(options, keys, "outfile", mustBeString);
|
|
1031
|
-
let outdir = getFlag(options, keys, "outdir", mustBeString);
|
|
1032
|
-
let outbase = getFlag(options, keys, "outbase", mustBeString);
|
|
1033
|
-
let tsconfig = getFlag(options, keys, "tsconfig", mustBeString);
|
|
1034
|
-
let resolveExtensions = getFlag(options, keys, "resolveExtensions", mustBeArrayOfStrings);
|
|
1035
|
-
let nodePathsInput = getFlag(options, keys, "nodePaths", mustBeArrayOfStrings);
|
|
1036
|
-
let mainFields = getFlag(options, keys, "mainFields", mustBeArrayOfStrings);
|
|
1037
|
-
let conditions = getFlag(options, keys, "conditions", mustBeArrayOfStrings);
|
|
1038
|
-
let external = getFlag(options, keys, "external", mustBeArrayOfStrings);
|
|
1039
|
-
let packages = getFlag(options, keys, "packages", mustBeString);
|
|
1040
|
-
let alias = getFlag(options, keys, "alias", mustBeObject);
|
|
1041
|
-
let loader = getFlag(options, keys, "loader", mustBeObject);
|
|
1042
|
-
let outExtension = getFlag(options, keys, "outExtension", mustBeObject);
|
|
1043
|
-
let publicPath = getFlag(options, keys, "publicPath", mustBeString);
|
|
1044
|
-
let entryNames = getFlag(options, keys, "entryNames", mustBeString);
|
|
1045
|
-
let chunkNames = getFlag(options, keys, "chunkNames", mustBeString);
|
|
1046
|
-
let assetNames = getFlag(options, keys, "assetNames", mustBeString);
|
|
1047
|
-
let inject = getFlag(options, keys, "inject", mustBeArrayOfStrings);
|
|
1048
|
-
let banner = getFlag(options, keys, "banner", mustBeObject);
|
|
1049
|
-
let footer = getFlag(options, keys, "footer", mustBeObject);
|
|
1050
|
-
let entryPoints = getFlag(options, keys, "entryPoints", mustBeEntryPoints);
|
|
1051
|
-
let absWorkingDir = getFlag(options, keys, "absWorkingDir", mustBeString);
|
|
1052
|
-
let stdin = getFlag(options, keys, "stdin", mustBeObject);
|
|
1053
|
-
let write = (_a2 = getFlag(options, keys, "write", mustBeBoolean)) != null ? _a2 : writeDefault;
|
|
1054
|
-
let allowOverwrite = getFlag(options, keys, "allowOverwrite", mustBeBoolean);
|
|
1055
|
-
let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
|
|
1056
|
-
keys.plugins = true;
|
|
1057
|
-
checkForInvalidFlags(options, keys, `in ${callName}() call`);
|
|
1058
|
-
if (sourcemap) flags.push(`--sourcemap${sourcemap === true ? "" : `=${sourcemap}`}`);
|
|
1059
|
-
if (bundle) flags.push("--bundle");
|
|
1060
|
-
if (allowOverwrite) flags.push("--allow-overwrite");
|
|
1061
|
-
if (splitting) flags.push("--splitting");
|
|
1062
|
-
if (preserveSymlinks) flags.push("--preserve-symlinks");
|
|
1063
|
-
if (metafile) flags.push(`--metafile`);
|
|
1064
|
-
if (outfile) flags.push(`--outfile=${outfile}`);
|
|
1065
|
-
if (outdir) flags.push(`--outdir=${outdir}`);
|
|
1066
|
-
if (outbase) flags.push(`--outbase=${outbase}`);
|
|
1067
|
-
if (tsconfig) flags.push(`--tsconfig=${tsconfig}`);
|
|
1068
|
-
if (packages) flags.push(`--packages=${packages}`);
|
|
1069
|
-
if (resolveExtensions) flags.push(`--resolve-extensions=${validateAndJoinStringArray(resolveExtensions, "resolve extension")}`);
|
|
1070
|
-
if (publicPath) flags.push(`--public-path=${publicPath}`);
|
|
1071
|
-
if (entryNames) flags.push(`--entry-names=${entryNames}`);
|
|
1072
|
-
if (chunkNames) flags.push(`--chunk-names=${chunkNames}`);
|
|
1073
|
-
if (assetNames) flags.push(`--asset-names=${assetNames}`);
|
|
1074
|
-
if (mainFields) flags.push(`--main-fields=${validateAndJoinStringArray(mainFields, "main field")}`);
|
|
1075
|
-
if (conditions) flags.push(`--conditions=${validateAndJoinStringArray(conditions, "condition")}`);
|
|
1076
|
-
if (external) for (let name of external) flags.push(`--external:${validateStringValue(name, "external")}`);
|
|
1077
|
-
if (alias) for (let old in alias) {
|
|
1078
|
-
if (old.indexOf("=") >= 0) throw new Error(`Invalid package name in alias: ${old}`);
|
|
1079
|
-
flags.push(`--alias:${old}=${validateStringValue(alias[old], "alias", old)}`);
|
|
1080
|
-
}
|
|
1081
|
-
if (banner) for (let type in banner) {
|
|
1082
|
-
if (type.indexOf("=") >= 0) throw new Error(`Invalid banner file type: ${type}`);
|
|
1083
|
-
flags.push(`--banner:${type}=${validateStringValue(banner[type], "banner", type)}`);
|
|
1084
|
-
}
|
|
1085
|
-
if (footer) for (let type in footer) {
|
|
1086
|
-
if (type.indexOf("=") >= 0) throw new Error(`Invalid footer file type: ${type}`);
|
|
1087
|
-
flags.push(`--footer:${type}=${validateStringValue(footer[type], "footer", type)}`);
|
|
1088
|
-
}
|
|
1089
|
-
if (inject) for (let path3 of inject) flags.push(`--inject:${validateStringValue(path3, "inject")}`);
|
|
1090
|
-
if (loader) for (let ext in loader) {
|
|
1091
|
-
if (ext.indexOf("=") >= 0) throw new Error(`Invalid loader extension: ${ext}`);
|
|
1092
|
-
flags.push(`--loader:${ext}=${validateStringValue(loader[ext], "loader", ext)}`);
|
|
1093
|
-
}
|
|
1094
|
-
if (outExtension) for (let ext in outExtension) {
|
|
1095
|
-
if (ext.indexOf("=") >= 0) throw new Error(`Invalid out extension: ${ext}`);
|
|
1096
|
-
flags.push(`--out-extension:${ext}=${validateStringValue(outExtension[ext], "out extension", ext)}`);
|
|
1097
|
-
}
|
|
1098
|
-
if (entryPoints) {
|
|
1099
|
-
if (Array.isArray(entryPoints)) for (let i = 0, n = entryPoints.length; i < n; i++) {
|
|
1100
|
-
let entryPoint = entryPoints[i];
|
|
1101
|
-
if (typeof entryPoint === "object" && entryPoint !== null) {
|
|
1102
|
-
let entryPointKeys = /* @__PURE__ */ Object.create(null);
|
|
1103
|
-
let input = getFlag(entryPoint, entryPointKeys, "in", mustBeString);
|
|
1104
|
-
let output = getFlag(entryPoint, entryPointKeys, "out", mustBeString);
|
|
1105
|
-
checkForInvalidFlags(entryPoint, entryPointKeys, "in entry point at index " + i);
|
|
1106
|
-
if (input === void 0) throw new Error("Missing property \"in\" for entry point at index " + i);
|
|
1107
|
-
if (output === void 0) throw new Error("Missing property \"out\" for entry point at index " + i);
|
|
1108
|
-
entries.push([output, input]);
|
|
1109
|
-
} else entries.push(["", validateStringValue(entryPoint, "entry point at index " + i)]);
|
|
1110
|
-
}
|
|
1111
|
-
else for (let key in entryPoints) entries.push([key, validateStringValue(entryPoints[key], "entry point", key)]);
|
|
1112
|
-
}
|
|
1113
|
-
if (stdin) {
|
|
1114
|
-
let stdinKeys = /* @__PURE__ */ Object.create(null);
|
|
1115
|
-
let contents = getFlag(stdin, stdinKeys, "contents", mustBeStringOrUint8Array);
|
|
1116
|
-
let resolveDir = getFlag(stdin, stdinKeys, "resolveDir", mustBeString);
|
|
1117
|
-
let sourcefile = getFlag(stdin, stdinKeys, "sourcefile", mustBeString);
|
|
1118
|
-
let loader2 = getFlag(stdin, stdinKeys, "loader", mustBeString);
|
|
1119
|
-
checkForInvalidFlags(stdin, stdinKeys, "in \"stdin\" object");
|
|
1120
|
-
if (sourcefile) flags.push(`--sourcefile=${sourcefile}`);
|
|
1121
|
-
if (loader2) flags.push(`--loader=${loader2}`);
|
|
1122
|
-
if (resolveDir) stdinResolveDir = resolveDir;
|
|
1123
|
-
if (typeof contents === "string") stdinContents = encodeUTF8(contents);
|
|
1124
|
-
else if (contents instanceof Uint8Array) stdinContents = contents;
|
|
1125
|
-
}
|
|
1126
|
-
let nodePaths = [];
|
|
1127
|
-
if (nodePathsInput) for (let value of nodePathsInput) {
|
|
1128
|
-
value += "";
|
|
1129
|
-
nodePaths.push(value);
|
|
1130
|
-
}
|
|
1131
|
-
return {
|
|
1132
|
-
entries,
|
|
1133
|
-
flags,
|
|
1134
|
-
write,
|
|
1135
|
-
stdinContents,
|
|
1136
|
-
stdinResolveDir,
|
|
1137
|
-
absWorkingDir,
|
|
1138
|
-
nodePaths,
|
|
1139
|
-
mangleCache: validateMangleCache(mangleCache)
|
|
1140
|
-
};
|
|
1141
|
-
}
|
|
1142
|
-
function flagsForTransformOptions(callName, options, isTTY2, logLevelDefault) {
|
|
1143
|
-
let flags = [];
|
|
1144
|
-
let keys = /* @__PURE__ */ Object.create(null);
|
|
1145
|
-
pushLogFlags(flags, options, keys, isTTY2, logLevelDefault);
|
|
1146
|
-
pushCommonFlags(flags, options, keys);
|
|
1147
|
-
let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
|
|
1148
|
-
let sourcefile = getFlag(options, keys, "sourcefile", mustBeString);
|
|
1149
|
-
let loader = getFlag(options, keys, "loader", mustBeString);
|
|
1150
|
-
let banner = getFlag(options, keys, "banner", mustBeString);
|
|
1151
|
-
let footer = getFlag(options, keys, "footer", mustBeString);
|
|
1152
|
-
let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
|
|
1153
|
-
checkForInvalidFlags(options, keys, `in ${callName}() call`);
|
|
1154
|
-
if (sourcemap) flags.push(`--sourcemap=${sourcemap === true ? "external" : sourcemap}`);
|
|
1155
|
-
if (sourcefile) flags.push(`--sourcefile=${sourcefile}`);
|
|
1156
|
-
if (loader) flags.push(`--loader=${loader}`);
|
|
1157
|
-
if (banner) flags.push(`--banner=${banner}`);
|
|
1158
|
-
if (footer) flags.push(`--footer=${footer}`);
|
|
1159
|
-
return {
|
|
1160
|
-
flags,
|
|
1161
|
-
mangleCache: validateMangleCache(mangleCache)
|
|
1162
|
-
};
|
|
1163
|
-
}
|
|
1164
|
-
function createChannel(streamIn) {
|
|
1165
|
-
const requestCallbacksByKey = {};
|
|
1166
|
-
const closeData = {
|
|
1167
|
-
didClose: false,
|
|
1168
|
-
reason: ""
|
|
1169
|
-
};
|
|
1170
|
-
let responseCallbacks = {};
|
|
1171
|
-
let nextRequestID = 0;
|
|
1172
|
-
let nextBuildKey = 0;
|
|
1173
|
-
let stdout = /* @__PURE__ */ new Uint8Array(16384);
|
|
1174
|
-
let stdoutUsed = 0;
|
|
1175
|
-
let readFromStdout = (chunk) => {
|
|
1176
|
-
let limit = stdoutUsed + chunk.length;
|
|
1177
|
-
if (limit > stdout.length) {
|
|
1178
|
-
let swap = new Uint8Array(limit * 2);
|
|
1179
|
-
swap.set(stdout);
|
|
1180
|
-
stdout = swap;
|
|
1181
|
-
}
|
|
1182
|
-
stdout.set(chunk, stdoutUsed);
|
|
1183
|
-
stdoutUsed += chunk.length;
|
|
1184
|
-
let offset = 0;
|
|
1185
|
-
while (offset + 4 <= stdoutUsed) {
|
|
1186
|
-
let length = readUInt32LE(stdout, offset);
|
|
1187
|
-
if (offset + 4 + length > stdoutUsed) break;
|
|
1188
|
-
offset += 4;
|
|
1189
|
-
handleIncomingPacket(stdout.subarray(offset, offset + length));
|
|
1190
|
-
offset += length;
|
|
1191
|
-
}
|
|
1192
|
-
if (offset > 0) {
|
|
1193
|
-
stdout.copyWithin(0, offset, stdoutUsed);
|
|
1194
|
-
stdoutUsed -= offset;
|
|
1195
|
-
}
|
|
1196
|
-
};
|
|
1197
|
-
let afterClose = (error) => {
|
|
1198
|
-
closeData.didClose = true;
|
|
1199
|
-
if (error) closeData.reason = ": " + (error.message || error);
|
|
1200
|
-
const text = "The service was stopped" + closeData.reason;
|
|
1201
|
-
for (let id in responseCallbacks) responseCallbacks[id](text, null);
|
|
1202
|
-
responseCallbacks = {};
|
|
1203
|
-
};
|
|
1204
|
-
let sendRequest = (refs, value, callback) => {
|
|
1205
|
-
if (closeData.didClose) return callback("The service is no longer running" + closeData.reason, null);
|
|
1206
|
-
let id = nextRequestID++;
|
|
1207
|
-
responseCallbacks[id] = (error, response) => {
|
|
1208
|
-
try {
|
|
1209
|
-
callback(error, response);
|
|
1210
|
-
} finally {
|
|
1211
|
-
if (refs) refs.unref();
|
|
1212
|
-
}
|
|
1213
|
-
};
|
|
1214
|
-
if (refs) refs.ref();
|
|
1215
|
-
streamIn.writeToStdin(encodePacket({
|
|
1216
|
-
id,
|
|
1217
|
-
isRequest: true,
|
|
1218
|
-
value
|
|
1219
|
-
}));
|
|
1220
|
-
};
|
|
1221
|
-
let sendResponse = (id, value) => {
|
|
1222
|
-
if (closeData.didClose) throw new Error("The service is no longer running" + closeData.reason);
|
|
1223
|
-
streamIn.writeToStdin(encodePacket({
|
|
1224
|
-
id,
|
|
1225
|
-
isRequest: false,
|
|
1226
|
-
value
|
|
1227
|
-
}));
|
|
1228
|
-
};
|
|
1229
|
-
let handleRequest = async (id, request) => {
|
|
1230
|
-
try {
|
|
1231
|
-
if (request.command === "ping") {
|
|
1232
|
-
sendResponse(id, {});
|
|
1233
|
-
return;
|
|
1234
|
-
}
|
|
1235
|
-
if (typeof request.key === "number") {
|
|
1236
|
-
const requestCallbacks = requestCallbacksByKey[request.key];
|
|
1237
|
-
if (!requestCallbacks) return;
|
|
1238
|
-
const callback = requestCallbacks[request.command];
|
|
1239
|
-
if (callback) {
|
|
1240
|
-
await callback(id, request);
|
|
1241
|
-
return;
|
|
1242
|
-
}
|
|
1243
|
-
}
|
|
1244
|
-
throw new Error(`Invalid command: ` + request.command);
|
|
1245
|
-
} catch (e) {
|
|
1246
|
-
const errors = [extractErrorMessageV8(e, streamIn, null, void 0, "")];
|
|
1247
|
-
try {
|
|
1248
|
-
sendResponse(id, { errors });
|
|
1249
|
-
} catch {}
|
|
1250
|
-
}
|
|
1251
|
-
};
|
|
1252
|
-
let isFirstPacket = true;
|
|
1253
|
-
let handleIncomingPacket = (bytes) => {
|
|
1254
|
-
if (isFirstPacket) {
|
|
1255
|
-
isFirstPacket = false;
|
|
1256
|
-
let binaryVersion = String.fromCharCode(...bytes);
|
|
1257
|
-
if (binaryVersion !== "0.27.7") throw new Error(`Cannot start service: Host version "0.27.7" does not match binary version ${quote(binaryVersion)}`);
|
|
1258
|
-
return;
|
|
1259
|
-
}
|
|
1260
|
-
let packet = decodePacket(bytes);
|
|
1261
|
-
if (packet.isRequest) handleRequest(packet.id, packet.value);
|
|
1262
|
-
else {
|
|
1263
|
-
let callback = responseCallbacks[packet.id];
|
|
1264
|
-
delete responseCallbacks[packet.id];
|
|
1265
|
-
if (packet.value.error) callback(packet.value.error, {});
|
|
1266
|
-
else callback(null, packet.value);
|
|
1267
|
-
}
|
|
1268
|
-
};
|
|
1269
|
-
let buildOrContext = ({ callName, refs, options, isTTY: isTTY2, defaultWD: defaultWD2, callback }) => {
|
|
1270
|
-
let refCount = 0;
|
|
1271
|
-
const buildKey = nextBuildKey++;
|
|
1272
|
-
const requestCallbacks = {};
|
|
1273
|
-
const buildRefs = {
|
|
1274
|
-
ref() {
|
|
1275
|
-
if (++refCount === 1) {
|
|
1276
|
-
if (refs) refs.ref();
|
|
1277
|
-
}
|
|
1278
|
-
},
|
|
1279
|
-
unref() {
|
|
1280
|
-
if (--refCount === 0) {
|
|
1281
|
-
delete requestCallbacksByKey[buildKey];
|
|
1282
|
-
if (refs) refs.unref();
|
|
1283
|
-
}
|
|
1284
|
-
}
|
|
1285
|
-
};
|
|
1286
|
-
requestCallbacksByKey[buildKey] = requestCallbacks;
|
|
1287
|
-
buildRefs.ref();
|
|
1288
|
-
buildOrContextImpl(callName, buildKey, sendRequest, sendResponse, buildRefs, streamIn, requestCallbacks, options, isTTY2, defaultWD2, (err, res) => {
|
|
1289
|
-
try {
|
|
1290
|
-
callback(err, res);
|
|
1291
|
-
} finally {
|
|
1292
|
-
buildRefs.unref();
|
|
1293
|
-
}
|
|
1294
|
-
});
|
|
1295
|
-
};
|
|
1296
|
-
let transform2 = ({ callName, refs, input, options, isTTY: isTTY2, fs: fs3, callback }) => {
|
|
1297
|
-
const details = createObjectStash();
|
|
1298
|
-
let start = (inputPath) => {
|
|
1299
|
-
try {
|
|
1300
|
-
if (typeof input !== "string" && !(input instanceof Uint8Array)) throw new Error("The input to \"transform\" must be a string or a Uint8Array");
|
|
1301
|
-
let { flags, mangleCache } = flagsForTransformOptions(callName, options, isTTY2, transformLogLevelDefault);
|
|
1302
|
-
let request = {
|
|
1303
|
-
command: "transform",
|
|
1304
|
-
flags,
|
|
1305
|
-
inputFS: inputPath !== null,
|
|
1306
|
-
input: inputPath !== null ? encodeUTF8(inputPath) : typeof input === "string" ? encodeUTF8(input) : input
|
|
1307
|
-
};
|
|
1308
|
-
if (mangleCache) request.mangleCache = mangleCache;
|
|
1309
|
-
sendRequest(refs, request, (error, response) => {
|
|
1310
|
-
if (error) return callback(new Error(error), null);
|
|
1311
|
-
let errors = replaceDetailsInMessages(response.errors, details);
|
|
1312
|
-
let warnings = replaceDetailsInMessages(response.warnings, details);
|
|
1313
|
-
let outstanding = 1;
|
|
1314
|
-
let next = () => {
|
|
1315
|
-
if (--outstanding === 0) {
|
|
1316
|
-
let result = {
|
|
1317
|
-
warnings,
|
|
1318
|
-
code: response.code,
|
|
1319
|
-
map: response.map,
|
|
1320
|
-
mangleCache: void 0,
|
|
1321
|
-
legalComments: void 0
|
|
1322
|
-
};
|
|
1323
|
-
if ("legalComments" in response) result.legalComments = response == null ? void 0 : response.legalComments;
|
|
1324
|
-
if (response.mangleCache) result.mangleCache = response == null ? void 0 : response.mangleCache;
|
|
1325
|
-
callback(null, result);
|
|
1326
|
-
}
|
|
1327
|
-
};
|
|
1328
|
-
if (errors.length > 0) return callback(failureErrorWithLog("Transform failed", errors, warnings), null);
|
|
1329
|
-
if (response.codeFS) {
|
|
1330
|
-
outstanding++;
|
|
1331
|
-
fs3.readFile(response.code, (err, contents) => {
|
|
1332
|
-
if (err !== null) callback(err, null);
|
|
1333
|
-
else {
|
|
1334
|
-
response.code = contents;
|
|
1335
|
-
next();
|
|
1336
|
-
}
|
|
1337
|
-
});
|
|
1338
|
-
}
|
|
1339
|
-
if (response.mapFS) {
|
|
1340
|
-
outstanding++;
|
|
1341
|
-
fs3.readFile(response.map, (err, contents) => {
|
|
1342
|
-
if (err !== null) callback(err, null);
|
|
1343
|
-
else {
|
|
1344
|
-
response.map = contents;
|
|
1345
|
-
next();
|
|
1346
|
-
}
|
|
1347
|
-
});
|
|
1348
|
-
}
|
|
1349
|
-
next();
|
|
1350
|
-
});
|
|
1351
|
-
} catch (e) {
|
|
1352
|
-
let flags = [];
|
|
1353
|
-
try {
|
|
1354
|
-
pushLogFlags(flags, options, {}, isTTY2, transformLogLevelDefault);
|
|
1355
|
-
} catch {}
|
|
1356
|
-
const error = extractErrorMessageV8(e, streamIn, details, void 0, "");
|
|
1357
|
-
sendRequest(refs, {
|
|
1358
|
-
command: "error",
|
|
1359
|
-
flags,
|
|
1360
|
-
error
|
|
1361
|
-
}, () => {
|
|
1362
|
-
error.detail = details.load(error.detail);
|
|
1363
|
-
callback(failureErrorWithLog("Transform failed", [error], []), null);
|
|
1364
|
-
});
|
|
1365
|
-
}
|
|
1366
|
-
};
|
|
1367
|
-
if ((typeof input === "string" || input instanceof Uint8Array) && input.length > 1048576) {
|
|
1368
|
-
let next = start;
|
|
1369
|
-
start = () => fs3.writeFile(input, next);
|
|
1370
|
-
}
|
|
1371
|
-
start(null);
|
|
1372
|
-
};
|
|
1373
|
-
let formatMessages2 = ({ callName, refs, messages, options, callback }) => {
|
|
1374
|
-
if (!options) throw new Error(`Missing second argument in ${callName}() call`);
|
|
1375
|
-
let keys = {};
|
|
1376
|
-
let kind = getFlag(options, keys, "kind", mustBeString);
|
|
1377
|
-
let color = getFlag(options, keys, "color", mustBeBoolean);
|
|
1378
|
-
let terminalWidth = getFlag(options, keys, "terminalWidth", mustBeInteger);
|
|
1379
|
-
checkForInvalidFlags(options, keys, `in ${callName}() call`);
|
|
1380
|
-
if (kind === void 0) throw new Error(`Missing "kind" in ${callName}() call`);
|
|
1381
|
-
if (kind !== "error" && kind !== "warning") throw new Error(`Expected "kind" to be "error" or "warning" in ${callName}() call`);
|
|
1382
|
-
let request = {
|
|
1383
|
-
command: "format-msgs",
|
|
1384
|
-
messages: sanitizeMessages(messages, "messages", null, "", terminalWidth),
|
|
1385
|
-
isWarning: kind === "warning"
|
|
1386
|
-
};
|
|
1387
|
-
if (color !== void 0) request.color = color;
|
|
1388
|
-
if (terminalWidth !== void 0) request.terminalWidth = terminalWidth;
|
|
1389
|
-
sendRequest(refs, request, (error, response) => {
|
|
1390
|
-
if (error) return callback(new Error(error), null);
|
|
1391
|
-
callback(null, response.messages);
|
|
1392
|
-
});
|
|
1393
|
-
};
|
|
1394
|
-
let analyzeMetafile2 = ({ callName, refs, metafile, options, callback }) => {
|
|
1395
|
-
if (options === void 0) options = {};
|
|
1396
|
-
let keys = {};
|
|
1397
|
-
let color = getFlag(options, keys, "color", mustBeBoolean);
|
|
1398
|
-
let verbose = getFlag(options, keys, "verbose", mustBeBoolean);
|
|
1399
|
-
checkForInvalidFlags(options, keys, `in ${callName}() call`);
|
|
1400
|
-
let request = {
|
|
1401
|
-
command: "analyze-metafile",
|
|
1402
|
-
metafile
|
|
1403
|
-
};
|
|
1404
|
-
if (color !== void 0) request.color = color;
|
|
1405
|
-
if (verbose !== void 0) request.verbose = verbose;
|
|
1406
|
-
sendRequest(refs, request, (error, response) => {
|
|
1407
|
-
if (error) return callback(new Error(error), null);
|
|
1408
|
-
callback(null, response.result);
|
|
1409
|
-
});
|
|
1410
|
-
};
|
|
1411
|
-
return {
|
|
1412
|
-
readFromStdout,
|
|
1413
|
-
afterClose,
|
|
1414
|
-
service: {
|
|
1415
|
-
buildOrContext,
|
|
1416
|
-
transform: transform2,
|
|
1417
|
-
formatMessages: formatMessages2,
|
|
1418
|
-
analyzeMetafile: analyzeMetafile2
|
|
1419
|
-
}
|
|
1420
|
-
};
|
|
1421
|
-
}
|
|
1422
|
-
function buildOrContextImpl(callName, buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options, isTTY2, defaultWD2, callback) {
|
|
1423
|
-
const details = createObjectStash();
|
|
1424
|
-
const isContext = callName === "context";
|
|
1425
|
-
const handleError = (e, pluginName) => {
|
|
1426
|
-
const flags = [];
|
|
1427
|
-
try {
|
|
1428
|
-
pushLogFlags(flags, options, {}, isTTY2, buildLogLevelDefault);
|
|
1429
|
-
} catch {}
|
|
1430
|
-
const message = extractErrorMessageV8(e, streamIn, details, void 0, pluginName);
|
|
1431
|
-
sendRequest(refs, {
|
|
1432
|
-
command: "error",
|
|
1433
|
-
flags,
|
|
1434
|
-
error: message
|
|
1435
|
-
}, () => {
|
|
1436
|
-
message.detail = details.load(message.detail);
|
|
1437
|
-
callback(failureErrorWithLog(isContext ? "Context failed" : "Build failed", [message], []), null);
|
|
1438
|
-
});
|
|
1439
|
-
};
|
|
1440
|
-
let plugins;
|
|
1441
|
-
if (typeof options === "object") {
|
|
1442
|
-
const value = options.plugins;
|
|
1443
|
-
if (value !== void 0) {
|
|
1444
|
-
if (!Array.isArray(value)) return handleError(/* @__PURE__ */ new Error(`"plugins" must be an array`), "");
|
|
1445
|
-
plugins = value;
|
|
1446
|
-
}
|
|
1447
|
-
}
|
|
1448
|
-
if (plugins && plugins.length > 0) {
|
|
1449
|
-
if (streamIn.isSync) return handleError(/* @__PURE__ */ new Error("Cannot use plugins in synchronous API calls"), "");
|
|
1450
|
-
handlePlugins(buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options, plugins, details).then((result) => {
|
|
1451
|
-
if (!result.ok) return handleError(result.error, result.pluginName);
|
|
1452
|
-
try {
|
|
1453
|
-
buildOrContextContinue(result.requestPlugins, result.runOnEndCallbacks, result.scheduleOnDisposeCallbacks);
|
|
1454
|
-
} catch (e) {
|
|
1455
|
-
handleError(e, "");
|
|
1456
|
-
}
|
|
1457
|
-
}, (e) => handleError(e, ""));
|
|
1458
|
-
return;
|
|
1459
|
-
}
|
|
1460
|
-
try {
|
|
1461
|
-
buildOrContextContinue(null, (result, done) => done([], []), () => {});
|
|
1462
|
-
} catch (e) {
|
|
1463
|
-
handleError(e, "");
|
|
1464
|
-
}
|
|
1465
|
-
function buildOrContextContinue(requestPlugins, runOnEndCallbacks, scheduleOnDisposeCallbacks) {
|
|
1466
|
-
const writeDefault = streamIn.hasFS;
|
|
1467
|
-
const { entries, flags, write, stdinContents, stdinResolveDir, absWorkingDir, nodePaths, mangleCache } = flagsForBuildOptions(callName, options, isTTY2, buildLogLevelDefault, writeDefault);
|
|
1468
|
-
if (write && !streamIn.hasFS) throw new Error(`The "write" option is unavailable in this environment`);
|
|
1469
|
-
const request = {
|
|
1470
|
-
command: "build",
|
|
1471
|
-
key: buildKey,
|
|
1472
|
-
entries,
|
|
1473
|
-
flags,
|
|
1474
|
-
write,
|
|
1475
|
-
stdinContents,
|
|
1476
|
-
stdinResolveDir,
|
|
1477
|
-
absWorkingDir: absWorkingDir || defaultWD2,
|
|
1478
|
-
nodePaths,
|
|
1479
|
-
context: isContext
|
|
1480
|
-
};
|
|
1481
|
-
if (requestPlugins) request.plugins = requestPlugins;
|
|
1482
|
-
if (mangleCache) request.mangleCache = mangleCache;
|
|
1483
|
-
const buildResponseToResult = (response, callback2) => {
|
|
1484
|
-
const result = {
|
|
1485
|
-
errors: replaceDetailsInMessages(response.errors, details),
|
|
1486
|
-
warnings: replaceDetailsInMessages(response.warnings, details),
|
|
1487
|
-
outputFiles: void 0,
|
|
1488
|
-
metafile: void 0,
|
|
1489
|
-
mangleCache: void 0
|
|
1490
|
-
};
|
|
1491
|
-
const originalErrors = result.errors.slice();
|
|
1492
|
-
const originalWarnings = result.warnings.slice();
|
|
1493
|
-
if (response.outputFiles) result.outputFiles = response.outputFiles.map(convertOutputFiles);
|
|
1494
|
-
if (response.metafile && response.metafile.length) result.metafile = parseJSON(response.metafile);
|
|
1495
|
-
if (response.mangleCache) result.mangleCache = response.mangleCache;
|
|
1496
|
-
if (response.writeToStdout !== void 0) console.log(decodeUTF8(response.writeToStdout).replace(/\n$/, ""));
|
|
1497
|
-
runOnEndCallbacks(result, (onEndErrors, onEndWarnings) => {
|
|
1498
|
-
if (originalErrors.length > 0 || onEndErrors.length > 0) return callback2(failureErrorWithLog("Build failed", originalErrors.concat(onEndErrors), originalWarnings.concat(onEndWarnings)), null, onEndErrors, onEndWarnings);
|
|
1499
|
-
callback2(null, result, onEndErrors, onEndWarnings);
|
|
1500
|
-
});
|
|
1501
|
-
};
|
|
1502
|
-
let latestResultPromise;
|
|
1503
|
-
let provideLatestResult;
|
|
1504
|
-
if (isContext) requestCallbacks["on-end"] = (id, request2) => new Promise((resolve) => {
|
|
1505
|
-
buildResponseToResult(request2, (err, result, onEndErrors, onEndWarnings) => {
|
|
1506
|
-
const response = {
|
|
1507
|
-
errors: onEndErrors,
|
|
1508
|
-
warnings: onEndWarnings
|
|
1509
|
-
};
|
|
1510
|
-
if (provideLatestResult) provideLatestResult(err, result);
|
|
1511
|
-
latestResultPromise = void 0;
|
|
1512
|
-
provideLatestResult = void 0;
|
|
1513
|
-
sendResponse(id, response);
|
|
1514
|
-
resolve();
|
|
1515
|
-
});
|
|
1516
|
-
});
|
|
1517
|
-
sendRequest(refs, request, (error, response) => {
|
|
1518
|
-
if (error) return callback(new Error(error), null);
|
|
1519
|
-
if (!isContext) return buildResponseToResult(response, (err, res) => {
|
|
1520
|
-
scheduleOnDisposeCallbacks();
|
|
1521
|
-
return callback(err, res);
|
|
1522
|
-
});
|
|
1523
|
-
if (response.errors.length > 0) return callback(failureErrorWithLog("Context failed", response.errors, response.warnings), null);
|
|
1524
|
-
let didDispose = false;
|
|
1525
|
-
const result = {
|
|
1526
|
-
rebuild: () => {
|
|
1527
|
-
if (!latestResultPromise) latestResultPromise = new Promise((resolve, reject) => {
|
|
1528
|
-
let settlePromise;
|
|
1529
|
-
provideLatestResult = (err, result2) => {
|
|
1530
|
-
if (!settlePromise) settlePromise = () => err ? reject(err) : resolve(result2);
|
|
1531
|
-
};
|
|
1532
|
-
const triggerAnotherBuild = () => {
|
|
1533
|
-
sendRequest(refs, {
|
|
1534
|
-
command: "rebuild",
|
|
1535
|
-
key: buildKey
|
|
1536
|
-
}, (error2, response2) => {
|
|
1537
|
-
if (error2) reject(new Error(error2));
|
|
1538
|
-
else if (settlePromise) settlePromise();
|
|
1539
|
-
else triggerAnotherBuild();
|
|
1540
|
-
});
|
|
1541
|
-
};
|
|
1542
|
-
triggerAnotherBuild();
|
|
1543
|
-
});
|
|
1544
|
-
return latestResultPromise;
|
|
1545
|
-
},
|
|
1546
|
-
watch: (options2 = {}) => new Promise((resolve, reject) => {
|
|
1547
|
-
if (!streamIn.hasFS) throw new Error(`Cannot use the "watch" API in this environment`);
|
|
1548
|
-
const keys = {};
|
|
1549
|
-
const delay = getFlag(options2, keys, "delay", mustBeInteger);
|
|
1550
|
-
checkForInvalidFlags(options2, keys, `in watch() call`);
|
|
1551
|
-
const request2 = {
|
|
1552
|
-
command: "watch",
|
|
1553
|
-
key: buildKey
|
|
1554
|
-
};
|
|
1555
|
-
if (delay) request2.delay = delay;
|
|
1556
|
-
sendRequest(refs, request2, (error2) => {
|
|
1557
|
-
if (error2) reject(new Error(error2));
|
|
1558
|
-
else resolve(void 0);
|
|
1559
|
-
});
|
|
1560
|
-
}),
|
|
1561
|
-
serve: (options2 = {}) => new Promise((resolve, reject) => {
|
|
1562
|
-
if (!streamIn.hasFS) throw new Error(`Cannot use the "serve" API in this environment`);
|
|
1563
|
-
const keys = {};
|
|
1564
|
-
const port = getFlag(options2, keys, "port", mustBeValidPortNumber);
|
|
1565
|
-
const host = getFlag(options2, keys, "host", mustBeString);
|
|
1566
|
-
const servedir = getFlag(options2, keys, "servedir", mustBeString);
|
|
1567
|
-
const keyfile = getFlag(options2, keys, "keyfile", mustBeString);
|
|
1568
|
-
const certfile = getFlag(options2, keys, "certfile", mustBeString);
|
|
1569
|
-
const fallback = getFlag(options2, keys, "fallback", mustBeString);
|
|
1570
|
-
const cors = getFlag(options2, keys, "cors", mustBeObject);
|
|
1571
|
-
const onRequest = getFlag(options2, keys, "onRequest", mustBeFunction);
|
|
1572
|
-
checkForInvalidFlags(options2, keys, `in serve() call`);
|
|
1573
|
-
const request2 = {
|
|
1574
|
-
command: "serve",
|
|
1575
|
-
key: buildKey,
|
|
1576
|
-
onRequest: !!onRequest
|
|
1577
|
-
};
|
|
1578
|
-
if (port !== void 0) request2.port = port;
|
|
1579
|
-
if (host !== void 0) request2.host = host;
|
|
1580
|
-
if (servedir !== void 0) request2.servedir = servedir;
|
|
1581
|
-
if (keyfile !== void 0) request2.keyfile = keyfile;
|
|
1582
|
-
if (certfile !== void 0) request2.certfile = certfile;
|
|
1583
|
-
if (fallback !== void 0) request2.fallback = fallback;
|
|
1584
|
-
if (cors) {
|
|
1585
|
-
const corsKeys = {};
|
|
1586
|
-
const origin = getFlag(cors, corsKeys, "origin", mustBeStringOrArrayOfStrings);
|
|
1587
|
-
checkForInvalidFlags(cors, corsKeys, `on "cors" object`);
|
|
1588
|
-
if (Array.isArray(origin)) request2.corsOrigin = origin;
|
|
1589
|
-
else if (origin !== void 0) request2.corsOrigin = [origin];
|
|
1590
|
-
}
|
|
1591
|
-
sendRequest(refs, request2, (error2, response2) => {
|
|
1592
|
-
if (error2) return reject(new Error(error2));
|
|
1593
|
-
if (onRequest) requestCallbacks["serve-request"] = (id, request3) => {
|
|
1594
|
-
onRequest(request3.args);
|
|
1595
|
-
sendResponse(id, {});
|
|
1596
|
-
};
|
|
1597
|
-
resolve(response2);
|
|
1598
|
-
});
|
|
1599
|
-
}),
|
|
1600
|
-
cancel: () => new Promise((resolve) => {
|
|
1601
|
-
if (didDispose) return resolve();
|
|
1602
|
-
sendRequest(refs, {
|
|
1603
|
-
command: "cancel",
|
|
1604
|
-
key: buildKey
|
|
1605
|
-
}, () => {
|
|
1606
|
-
resolve();
|
|
1607
|
-
});
|
|
1608
|
-
}),
|
|
1609
|
-
dispose: () => new Promise((resolve) => {
|
|
1610
|
-
if (didDispose) return resolve();
|
|
1611
|
-
didDispose = true;
|
|
1612
|
-
sendRequest(refs, {
|
|
1613
|
-
command: "dispose",
|
|
1614
|
-
key: buildKey
|
|
1615
|
-
}, () => {
|
|
1616
|
-
resolve();
|
|
1617
|
-
scheduleOnDisposeCallbacks();
|
|
1618
|
-
refs.unref();
|
|
1619
|
-
});
|
|
1620
|
-
})
|
|
1621
|
-
};
|
|
1622
|
-
refs.ref();
|
|
1623
|
-
callback(null, result);
|
|
1624
|
-
});
|
|
1625
|
-
}
|
|
1626
|
-
}
|
|
1627
|
-
var handlePlugins = async (buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, initialOptions, plugins, details) => {
|
|
1628
|
-
let onStartCallbacks = [];
|
|
1629
|
-
let onEndCallbacks = [];
|
|
1630
|
-
let onResolveCallbacks = {};
|
|
1631
|
-
let onLoadCallbacks = {};
|
|
1632
|
-
let onDisposeCallbacks = [];
|
|
1633
|
-
let nextCallbackID = 0;
|
|
1634
|
-
let i = 0;
|
|
1635
|
-
let requestPlugins = [];
|
|
1636
|
-
let isSetupDone = false;
|
|
1637
|
-
plugins = [...plugins];
|
|
1638
|
-
for (let item of plugins) {
|
|
1639
|
-
let keys = {};
|
|
1640
|
-
if (typeof item !== "object") throw new Error(`Plugin at index ${i} must be an object`);
|
|
1641
|
-
const name = getFlag(item, keys, "name", mustBeString);
|
|
1642
|
-
if (typeof name !== "string" || name === "") throw new Error(`Plugin at index ${i} is missing a name`);
|
|
1643
|
-
try {
|
|
1644
|
-
let setup = getFlag(item, keys, "setup", mustBeFunction);
|
|
1645
|
-
if (typeof setup !== "function") throw new Error(`Plugin is missing a setup function`);
|
|
1646
|
-
checkForInvalidFlags(item, keys, `on plugin ${quote(name)}`);
|
|
1647
|
-
let plugin = {
|
|
1648
|
-
name,
|
|
1649
|
-
onStart: false,
|
|
1650
|
-
onEnd: false,
|
|
1651
|
-
onResolve: [],
|
|
1652
|
-
onLoad: []
|
|
1653
|
-
};
|
|
1654
|
-
i++;
|
|
1655
|
-
let resolve = (path3, options = {}) => {
|
|
1656
|
-
if (!isSetupDone) throw new Error("Cannot call \"resolve\" before plugin setup has completed");
|
|
1657
|
-
if (typeof path3 !== "string") throw new Error(`The path to resolve must be a string`);
|
|
1658
|
-
let keys2 = /* @__PURE__ */ Object.create(null);
|
|
1659
|
-
let pluginName = getFlag(options, keys2, "pluginName", mustBeString);
|
|
1660
|
-
let importer = getFlag(options, keys2, "importer", mustBeString);
|
|
1661
|
-
let namespace = getFlag(options, keys2, "namespace", mustBeString);
|
|
1662
|
-
let resolveDir = getFlag(options, keys2, "resolveDir", mustBeString);
|
|
1663
|
-
let kind = getFlag(options, keys2, "kind", mustBeString);
|
|
1664
|
-
let pluginData = getFlag(options, keys2, "pluginData", canBeAnything);
|
|
1665
|
-
let importAttributes = getFlag(options, keys2, "with", mustBeObject);
|
|
1666
|
-
checkForInvalidFlags(options, keys2, "in resolve() call");
|
|
1667
|
-
return new Promise((resolve2, reject) => {
|
|
1668
|
-
const request = {
|
|
1669
|
-
command: "resolve",
|
|
1670
|
-
path: path3,
|
|
1671
|
-
key: buildKey,
|
|
1672
|
-
pluginName: name
|
|
1673
|
-
};
|
|
1674
|
-
if (pluginName != null) request.pluginName = pluginName;
|
|
1675
|
-
if (importer != null) request.importer = importer;
|
|
1676
|
-
if (namespace != null) request.namespace = namespace;
|
|
1677
|
-
if (resolveDir != null) request.resolveDir = resolveDir;
|
|
1678
|
-
if (kind != null) request.kind = kind;
|
|
1679
|
-
else throw new Error(`Must specify "kind" when calling "resolve"`);
|
|
1680
|
-
if (pluginData != null) request.pluginData = details.store(pluginData);
|
|
1681
|
-
if (importAttributes != null) request.with = sanitizeStringMap(importAttributes, "with");
|
|
1682
|
-
sendRequest(refs, request, (error, response) => {
|
|
1683
|
-
if (error !== null) reject(new Error(error));
|
|
1684
|
-
else resolve2({
|
|
1685
|
-
errors: replaceDetailsInMessages(response.errors, details),
|
|
1686
|
-
warnings: replaceDetailsInMessages(response.warnings, details),
|
|
1687
|
-
path: response.path,
|
|
1688
|
-
external: response.external,
|
|
1689
|
-
sideEffects: response.sideEffects,
|
|
1690
|
-
namespace: response.namespace,
|
|
1691
|
-
suffix: response.suffix,
|
|
1692
|
-
pluginData: details.load(response.pluginData)
|
|
1693
|
-
});
|
|
1694
|
-
});
|
|
1695
|
-
});
|
|
1696
|
-
};
|
|
1697
|
-
let promise = setup({
|
|
1698
|
-
initialOptions,
|
|
1699
|
-
resolve,
|
|
1700
|
-
onStart(callback) {
|
|
1701
|
-
let registeredNote = extractCallerV8(/* @__PURE__ */ new Error(`This error came from the "onStart" callback registered here:`), streamIn, "onStart");
|
|
1702
|
-
onStartCallbacks.push({
|
|
1703
|
-
name,
|
|
1704
|
-
callback,
|
|
1705
|
-
note: registeredNote
|
|
1706
|
-
});
|
|
1707
|
-
plugin.onStart = true;
|
|
1708
|
-
},
|
|
1709
|
-
onEnd(callback) {
|
|
1710
|
-
let registeredNote = extractCallerV8(/* @__PURE__ */ new Error(`This error came from the "onEnd" callback registered here:`), streamIn, "onEnd");
|
|
1711
|
-
onEndCallbacks.push({
|
|
1712
|
-
name,
|
|
1713
|
-
callback,
|
|
1714
|
-
note: registeredNote
|
|
1715
|
-
});
|
|
1716
|
-
plugin.onEnd = true;
|
|
1717
|
-
},
|
|
1718
|
-
onResolve(options, callback) {
|
|
1719
|
-
let registeredNote = extractCallerV8(/* @__PURE__ */ new Error(`This error came from the "onResolve" callback registered here:`), streamIn, "onResolve");
|
|
1720
|
-
let keys2 = {};
|
|
1721
|
-
let filter = getFlag(options, keys2, "filter", mustBeRegExp);
|
|
1722
|
-
let namespace = getFlag(options, keys2, "namespace", mustBeString);
|
|
1723
|
-
checkForInvalidFlags(options, keys2, `in onResolve() call for plugin ${quote(name)}`);
|
|
1724
|
-
if (filter == null) throw new Error(`onResolve() call is missing a filter`);
|
|
1725
|
-
let id = nextCallbackID++;
|
|
1726
|
-
onResolveCallbacks[id] = {
|
|
1727
|
-
name,
|
|
1728
|
-
callback,
|
|
1729
|
-
note: registeredNote
|
|
1730
|
-
};
|
|
1731
|
-
plugin.onResolve.push({
|
|
1732
|
-
id,
|
|
1733
|
-
filter: jsRegExpToGoRegExp(filter),
|
|
1734
|
-
namespace: namespace || ""
|
|
1735
|
-
});
|
|
1736
|
-
},
|
|
1737
|
-
onLoad(options, callback) {
|
|
1738
|
-
let registeredNote = extractCallerV8(/* @__PURE__ */ new Error(`This error came from the "onLoad" callback registered here:`), streamIn, "onLoad");
|
|
1739
|
-
let keys2 = {};
|
|
1740
|
-
let filter = getFlag(options, keys2, "filter", mustBeRegExp);
|
|
1741
|
-
let namespace = getFlag(options, keys2, "namespace", mustBeString);
|
|
1742
|
-
checkForInvalidFlags(options, keys2, `in onLoad() call for plugin ${quote(name)}`);
|
|
1743
|
-
if (filter == null) throw new Error(`onLoad() call is missing a filter`);
|
|
1744
|
-
let id = nextCallbackID++;
|
|
1745
|
-
onLoadCallbacks[id] = {
|
|
1746
|
-
name,
|
|
1747
|
-
callback,
|
|
1748
|
-
note: registeredNote
|
|
1749
|
-
};
|
|
1750
|
-
plugin.onLoad.push({
|
|
1751
|
-
id,
|
|
1752
|
-
filter: jsRegExpToGoRegExp(filter),
|
|
1753
|
-
namespace: namespace || ""
|
|
1754
|
-
});
|
|
1755
|
-
},
|
|
1756
|
-
onDispose(callback) {
|
|
1757
|
-
onDisposeCallbacks.push(callback);
|
|
1758
|
-
},
|
|
1759
|
-
esbuild: streamIn.esbuild
|
|
1760
|
-
});
|
|
1761
|
-
if (promise) await promise;
|
|
1762
|
-
requestPlugins.push(plugin);
|
|
1763
|
-
} catch (e) {
|
|
1764
|
-
return {
|
|
1765
|
-
ok: false,
|
|
1766
|
-
error: e,
|
|
1767
|
-
pluginName: name
|
|
1768
|
-
};
|
|
1769
|
-
}
|
|
1770
|
-
}
|
|
1771
|
-
requestCallbacks["on-start"] = async (id, request) => {
|
|
1772
|
-
details.clear();
|
|
1773
|
-
let response = {
|
|
1774
|
-
errors: [],
|
|
1775
|
-
warnings: []
|
|
1776
|
-
};
|
|
1777
|
-
await Promise.all(onStartCallbacks.map(async ({ name, callback, note }) => {
|
|
1778
|
-
try {
|
|
1779
|
-
let result = await callback();
|
|
1780
|
-
if (result != null) {
|
|
1781
|
-
if (typeof result !== "object") throw new Error(`Expected onStart() callback in plugin ${quote(name)} to return an object`);
|
|
1782
|
-
let keys = {};
|
|
1783
|
-
let errors = getFlag(result, keys, "errors", mustBeArray);
|
|
1784
|
-
let warnings = getFlag(result, keys, "warnings", mustBeArray);
|
|
1785
|
-
checkForInvalidFlags(result, keys, `from onStart() callback in plugin ${quote(name)}`);
|
|
1786
|
-
if (errors != null) response.errors.push(...sanitizeMessages(errors, "errors", details, name, void 0));
|
|
1787
|
-
if (warnings != null) response.warnings.push(...sanitizeMessages(warnings, "warnings", details, name, void 0));
|
|
1788
|
-
}
|
|
1789
|
-
} catch (e) {
|
|
1790
|
-
response.errors.push(extractErrorMessageV8(e, streamIn, details, note && note(), name));
|
|
1791
|
-
}
|
|
1792
|
-
}));
|
|
1793
|
-
sendResponse(id, response);
|
|
1794
|
-
};
|
|
1795
|
-
requestCallbacks["on-resolve"] = async (id, request) => {
|
|
1796
|
-
let response = {}, name = "", callback, note;
|
|
1797
|
-
for (let id2 of request.ids) try {
|
|
1798
|
-
({name, callback, note} = onResolveCallbacks[id2]);
|
|
1799
|
-
let result = await callback({
|
|
1800
|
-
path: request.path,
|
|
1801
|
-
importer: request.importer,
|
|
1802
|
-
namespace: request.namespace,
|
|
1803
|
-
resolveDir: request.resolveDir,
|
|
1804
|
-
kind: request.kind,
|
|
1805
|
-
pluginData: details.load(request.pluginData),
|
|
1806
|
-
with: request.with
|
|
1807
|
-
});
|
|
1808
|
-
if (result != null) {
|
|
1809
|
-
if (typeof result !== "object") throw new Error(`Expected onResolve() callback in plugin ${quote(name)} to return an object`);
|
|
1810
|
-
let keys = {};
|
|
1811
|
-
let pluginName = getFlag(result, keys, "pluginName", mustBeString);
|
|
1812
|
-
let path3 = getFlag(result, keys, "path", mustBeString);
|
|
1813
|
-
let namespace = getFlag(result, keys, "namespace", mustBeString);
|
|
1814
|
-
let suffix = getFlag(result, keys, "suffix", mustBeString);
|
|
1815
|
-
let external = getFlag(result, keys, "external", mustBeBoolean);
|
|
1816
|
-
let sideEffects = getFlag(result, keys, "sideEffects", mustBeBoolean);
|
|
1817
|
-
let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
|
|
1818
|
-
let errors = getFlag(result, keys, "errors", mustBeArray);
|
|
1819
|
-
let warnings = getFlag(result, keys, "warnings", mustBeArray);
|
|
1820
|
-
let watchFiles = getFlag(result, keys, "watchFiles", mustBeArrayOfStrings);
|
|
1821
|
-
let watchDirs = getFlag(result, keys, "watchDirs", mustBeArrayOfStrings);
|
|
1822
|
-
checkForInvalidFlags(result, keys, `from onResolve() callback in plugin ${quote(name)}`);
|
|
1823
|
-
response.id = id2;
|
|
1824
|
-
if (pluginName != null) response.pluginName = pluginName;
|
|
1825
|
-
if (path3 != null) response.path = path3;
|
|
1826
|
-
if (namespace != null) response.namespace = namespace;
|
|
1827
|
-
if (suffix != null) response.suffix = suffix;
|
|
1828
|
-
if (external != null) response.external = external;
|
|
1829
|
-
if (sideEffects != null) response.sideEffects = sideEffects;
|
|
1830
|
-
if (pluginData != null) response.pluginData = details.store(pluginData);
|
|
1831
|
-
if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name, void 0);
|
|
1832
|
-
if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
|
|
1833
|
-
if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
|
|
1834
|
-
if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
|
|
1835
|
-
break;
|
|
1836
|
-
}
|
|
1837
|
-
} catch (e) {
|
|
1838
|
-
response = {
|
|
1839
|
-
id: id2,
|
|
1840
|
-
errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)]
|
|
1841
|
-
};
|
|
1842
|
-
break;
|
|
1843
|
-
}
|
|
1844
|
-
sendResponse(id, response);
|
|
1845
|
-
};
|
|
1846
|
-
requestCallbacks["on-load"] = async (id, request) => {
|
|
1847
|
-
let response = {}, name = "", callback, note;
|
|
1848
|
-
for (let id2 of request.ids) try {
|
|
1849
|
-
({name, callback, note} = onLoadCallbacks[id2]);
|
|
1850
|
-
let result = await callback({
|
|
1851
|
-
path: request.path,
|
|
1852
|
-
namespace: request.namespace,
|
|
1853
|
-
suffix: request.suffix,
|
|
1854
|
-
pluginData: details.load(request.pluginData),
|
|
1855
|
-
with: request.with
|
|
1856
|
-
});
|
|
1857
|
-
if (result != null) {
|
|
1858
|
-
if (typeof result !== "object") throw new Error(`Expected onLoad() callback in plugin ${quote(name)} to return an object`);
|
|
1859
|
-
let keys = {};
|
|
1860
|
-
let pluginName = getFlag(result, keys, "pluginName", mustBeString);
|
|
1861
|
-
let contents = getFlag(result, keys, "contents", mustBeStringOrUint8Array);
|
|
1862
|
-
let resolveDir = getFlag(result, keys, "resolveDir", mustBeString);
|
|
1863
|
-
let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
|
|
1864
|
-
let loader = getFlag(result, keys, "loader", mustBeString);
|
|
1865
|
-
let errors = getFlag(result, keys, "errors", mustBeArray);
|
|
1866
|
-
let warnings = getFlag(result, keys, "warnings", mustBeArray);
|
|
1867
|
-
let watchFiles = getFlag(result, keys, "watchFiles", mustBeArrayOfStrings);
|
|
1868
|
-
let watchDirs = getFlag(result, keys, "watchDirs", mustBeArrayOfStrings);
|
|
1869
|
-
checkForInvalidFlags(result, keys, `from onLoad() callback in plugin ${quote(name)}`);
|
|
1870
|
-
response.id = id2;
|
|
1871
|
-
if (pluginName != null) response.pluginName = pluginName;
|
|
1872
|
-
if (contents instanceof Uint8Array) response.contents = contents;
|
|
1873
|
-
else if (contents != null) response.contents = encodeUTF8(contents);
|
|
1874
|
-
if (resolveDir != null) response.resolveDir = resolveDir;
|
|
1875
|
-
if (pluginData != null) response.pluginData = details.store(pluginData);
|
|
1876
|
-
if (loader != null) response.loader = loader;
|
|
1877
|
-
if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name, void 0);
|
|
1878
|
-
if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
|
|
1879
|
-
if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
|
|
1880
|
-
if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
|
|
1881
|
-
break;
|
|
1882
|
-
}
|
|
1883
|
-
} catch (e) {
|
|
1884
|
-
response = {
|
|
1885
|
-
id: id2,
|
|
1886
|
-
errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)]
|
|
1887
|
-
};
|
|
1888
|
-
break;
|
|
1889
|
-
}
|
|
1890
|
-
sendResponse(id, response);
|
|
1891
|
-
};
|
|
1892
|
-
let runOnEndCallbacks = (result, done) => done([], []);
|
|
1893
|
-
if (onEndCallbacks.length > 0) runOnEndCallbacks = (result, done) => {
|
|
1894
|
-
(async () => {
|
|
1895
|
-
const onEndErrors = [];
|
|
1896
|
-
const onEndWarnings = [];
|
|
1897
|
-
for (const { name, callback, note } of onEndCallbacks) {
|
|
1898
|
-
let newErrors;
|
|
1899
|
-
let newWarnings;
|
|
1900
|
-
try {
|
|
1901
|
-
const value = await callback(result);
|
|
1902
|
-
if (value != null) {
|
|
1903
|
-
if (typeof value !== "object") throw new Error(`Expected onEnd() callback in plugin ${quote(name)} to return an object`);
|
|
1904
|
-
let keys = {};
|
|
1905
|
-
let errors = getFlag(value, keys, "errors", mustBeArray);
|
|
1906
|
-
let warnings = getFlag(value, keys, "warnings", mustBeArray);
|
|
1907
|
-
checkForInvalidFlags(value, keys, `from onEnd() callback in plugin ${quote(name)}`);
|
|
1908
|
-
if (errors != null) newErrors = sanitizeMessages(errors, "errors", details, name, void 0);
|
|
1909
|
-
if (warnings != null) newWarnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
|
|
1910
|
-
}
|
|
1911
|
-
} catch (e) {
|
|
1912
|
-
newErrors = [extractErrorMessageV8(e, streamIn, details, note && note(), name)];
|
|
1913
|
-
}
|
|
1914
|
-
if (newErrors) {
|
|
1915
|
-
onEndErrors.push(...newErrors);
|
|
1916
|
-
try {
|
|
1917
|
-
result.errors.push(...newErrors);
|
|
1918
|
-
} catch {}
|
|
1919
|
-
}
|
|
1920
|
-
if (newWarnings) {
|
|
1921
|
-
onEndWarnings.push(...newWarnings);
|
|
1922
|
-
try {
|
|
1923
|
-
result.warnings.push(...newWarnings);
|
|
1924
|
-
} catch {}
|
|
1925
|
-
}
|
|
1926
|
-
}
|
|
1927
|
-
done(onEndErrors, onEndWarnings);
|
|
1928
|
-
})();
|
|
1929
|
-
};
|
|
1930
|
-
let scheduleOnDisposeCallbacks = () => {
|
|
1931
|
-
for (const cb of onDisposeCallbacks) setTimeout(() => cb(), 0);
|
|
1932
|
-
};
|
|
1933
|
-
isSetupDone = true;
|
|
1934
|
-
return {
|
|
1935
|
-
ok: true,
|
|
1936
|
-
requestPlugins,
|
|
1937
|
-
runOnEndCallbacks,
|
|
1938
|
-
scheduleOnDisposeCallbacks
|
|
1939
|
-
};
|
|
1940
|
-
};
|
|
1941
|
-
function createObjectStash() {
|
|
1942
|
-
const map = /* @__PURE__ */ new Map();
|
|
1943
|
-
let nextID = 0;
|
|
1944
|
-
return {
|
|
1945
|
-
clear() {
|
|
1946
|
-
map.clear();
|
|
1947
|
-
},
|
|
1948
|
-
load(id) {
|
|
1949
|
-
return map.get(id);
|
|
1950
|
-
},
|
|
1951
|
-
store(value) {
|
|
1952
|
-
if (value === void 0) return -1;
|
|
1953
|
-
const id = nextID++;
|
|
1954
|
-
map.set(id, value);
|
|
1955
|
-
return id;
|
|
1956
|
-
}
|
|
1957
|
-
};
|
|
1958
|
-
}
|
|
1959
|
-
function extractCallerV8(e, streamIn, ident) {
|
|
1960
|
-
let note;
|
|
1961
|
-
let tried = false;
|
|
1962
|
-
return () => {
|
|
1963
|
-
if (tried) return note;
|
|
1964
|
-
tried = true;
|
|
1965
|
-
try {
|
|
1966
|
-
let lines = (e.stack + "").split("\n");
|
|
1967
|
-
lines.splice(1, 1);
|
|
1968
|
-
let location = parseStackLinesV8(streamIn, lines, ident);
|
|
1969
|
-
if (location) {
|
|
1970
|
-
note = {
|
|
1971
|
-
text: e.message,
|
|
1972
|
-
location
|
|
1973
|
-
};
|
|
1974
|
-
return note;
|
|
1975
|
-
}
|
|
1976
|
-
} catch {}
|
|
1977
|
-
};
|
|
1978
|
-
}
|
|
1979
|
-
function extractErrorMessageV8(e, streamIn, stash, note, pluginName) {
|
|
1980
|
-
let text = "Internal error";
|
|
1981
|
-
let location = null;
|
|
1982
|
-
try {
|
|
1983
|
-
text = (e && e.message || e) + "";
|
|
1984
|
-
} catch {}
|
|
1985
|
-
try {
|
|
1986
|
-
location = parseStackLinesV8(streamIn, (e.stack + "").split("\n"), "");
|
|
1987
|
-
} catch {}
|
|
1988
|
-
return {
|
|
1989
|
-
id: "",
|
|
1990
|
-
pluginName,
|
|
1991
|
-
text,
|
|
1992
|
-
location,
|
|
1993
|
-
notes: note ? [note] : [],
|
|
1994
|
-
detail: stash ? stash.store(e) : -1
|
|
1995
|
-
};
|
|
1996
|
-
}
|
|
1997
|
-
function parseStackLinesV8(streamIn, lines, ident) {
|
|
1998
|
-
let at = " at ";
|
|
1999
|
-
if (streamIn.readFileSync && !lines[0].startsWith(at) && lines[1].startsWith(at)) for (let i = 1; i < lines.length; i++) {
|
|
2000
|
-
let line = lines[i];
|
|
2001
|
-
if (!line.startsWith(at)) continue;
|
|
2002
|
-
line = line.slice(7);
|
|
2003
|
-
while (true) {
|
|
2004
|
-
let match = /^(?:new |async )?\S+ \((.*)\)$/.exec(line);
|
|
2005
|
-
if (match) {
|
|
2006
|
-
line = match[1];
|
|
2007
|
-
continue;
|
|
2008
|
-
}
|
|
2009
|
-
match = /^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec(line);
|
|
2010
|
-
if (match) {
|
|
2011
|
-
line = match[1];
|
|
2012
|
-
continue;
|
|
2013
|
-
}
|
|
2014
|
-
match = /^(\S+):(\d+):(\d+)$/.exec(line);
|
|
2015
|
-
if (match) {
|
|
2016
|
-
let contents;
|
|
2017
|
-
try {
|
|
2018
|
-
contents = streamIn.readFileSync(match[1], "utf8");
|
|
2019
|
-
} catch {
|
|
2020
|
-
break;
|
|
2021
|
-
}
|
|
2022
|
-
let lineText = contents.split(/\r\n|\r|\n|\u2028|\u2029/)[+match[2] - 1] || "";
|
|
2023
|
-
let column = +match[3] - 1;
|
|
2024
|
-
let length = lineText.slice(column, column + ident.length) === ident ? ident.length : 0;
|
|
2025
|
-
return {
|
|
2026
|
-
file: match[1],
|
|
2027
|
-
namespace: "file",
|
|
2028
|
-
line: +match[2],
|
|
2029
|
-
column: encodeUTF8(lineText.slice(0, column)).length,
|
|
2030
|
-
length: encodeUTF8(lineText.slice(column, column + length)).length,
|
|
2031
|
-
lineText: lineText + "\n" + lines.slice(1).join("\n"),
|
|
2032
|
-
suggestion: ""
|
|
2033
|
-
};
|
|
2034
|
-
}
|
|
2035
|
-
break;
|
|
2036
|
-
}
|
|
2037
|
-
}
|
|
2038
|
-
return null;
|
|
2039
|
-
}
|
|
2040
|
-
function failureErrorWithLog(text, errors, warnings) {
|
|
2041
|
-
let limit = 5;
|
|
2042
|
-
text += errors.length < 1 ? "" : ` with ${errors.length} error${errors.length < 2 ? "" : "s"}:` + errors.slice(0, 6).map((e, i) => {
|
|
2043
|
-
if (i === limit) return "\n...";
|
|
2044
|
-
if (!e.location) return `
|
|
2045
|
-
error: ${e.text}`;
|
|
2046
|
-
let { file, line, column } = e.location;
|
|
2047
|
-
return `
|
|
2048
|
-
${file}:${line}:${column}: ERROR: ${e.pluginName ? `[plugin: ${e.pluginName}] ` : ""}${e.text}`;
|
|
2049
|
-
}).join("");
|
|
2050
|
-
let error = new Error(text);
|
|
2051
|
-
for (const [key, value] of [["errors", errors], ["warnings", warnings]]) Object.defineProperty(error, key, {
|
|
2052
|
-
configurable: true,
|
|
2053
|
-
enumerable: true,
|
|
2054
|
-
get: () => value,
|
|
2055
|
-
set: (value2) => Object.defineProperty(error, key, {
|
|
2056
|
-
configurable: true,
|
|
2057
|
-
enumerable: true,
|
|
2058
|
-
value: value2
|
|
2059
|
-
})
|
|
2060
|
-
});
|
|
2061
|
-
return error;
|
|
2062
|
-
}
|
|
2063
|
-
function replaceDetailsInMessages(messages, stash) {
|
|
2064
|
-
for (const message of messages) message.detail = stash.load(message.detail);
|
|
2065
|
-
return messages;
|
|
2066
|
-
}
|
|
2067
|
-
function sanitizeLocation(location, where, terminalWidth) {
|
|
2068
|
-
if (location == null) return null;
|
|
2069
|
-
let keys = {};
|
|
2070
|
-
let file = getFlag(location, keys, "file", mustBeString);
|
|
2071
|
-
let namespace = getFlag(location, keys, "namespace", mustBeString);
|
|
2072
|
-
let line = getFlag(location, keys, "line", mustBeInteger);
|
|
2073
|
-
let column = getFlag(location, keys, "column", mustBeInteger);
|
|
2074
|
-
let length = getFlag(location, keys, "length", mustBeInteger);
|
|
2075
|
-
let lineText = getFlag(location, keys, "lineText", mustBeString);
|
|
2076
|
-
let suggestion = getFlag(location, keys, "suggestion", mustBeString);
|
|
2077
|
-
checkForInvalidFlags(location, keys, where);
|
|
2078
|
-
if (lineText) {
|
|
2079
|
-
const relevantASCII = lineText.slice(0, (column && column > 0 ? column : 0) + (length && length > 0 ? length : 0) + (terminalWidth && terminalWidth > 0 ? terminalWidth : 80));
|
|
2080
|
-
if (!/[\x7F-\uFFFF]/.test(relevantASCII) && !/\n/.test(lineText)) lineText = relevantASCII;
|
|
2081
|
-
}
|
|
2082
|
-
return {
|
|
2083
|
-
file: file || "",
|
|
2084
|
-
namespace: namespace || "",
|
|
2085
|
-
line: line || 0,
|
|
2086
|
-
column: column || 0,
|
|
2087
|
-
length: length || 0,
|
|
2088
|
-
lineText: lineText || "",
|
|
2089
|
-
suggestion: suggestion || ""
|
|
2090
|
-
};
|
|
2091
|
-
}
|
|
2092
|
-
function sanitizeMessages(messages, property, stash, fallbackPluginName, terminalWidth) {
|
|
2093
|
-
let messagesClone = [];
|
|
2094
|
-
let index = 0;
|
|
2095
|
-
for (const message of messages) {
|
|
2096
|
-
let keys = {};
|
|
2097
|
-
let id = getFlag(message, keys, "id", mustBeString);
|
|
2098
|
-
let pluginName = getFlag(message, keys, "pluginName", mustBeString);
|
|
2099
|
-
let text = getFlag(message, keys, "text", mustBeString);
|
|
2100
|
-
let location = getFlag(message, keys, "location", mustBeObjectOrNull);
|
|
2101
|
-
let notes = getFlag(message, keys, "notes", mustBeArray);
|
|
2102
|
-
let detail = getFlag(message, keys, "detail", canBeAnything);
|
|
2103
|
-
let where = `in element ${index} of "${property}"`;
|
|
2104
|
-
checkForInvalidFlags(message, keys, where);
|
|
2105
|
-
let notesClone = [];
|
|
2106
|
-
if (notes) for (const note of notes) {
|
|
2107
|
-
let noteKeys = {};
|
|
2108
|
-
let noteText = getFlag(note, noteKeys, "text", mustBeString);
|
|
2109
|
-
let noteLocation = getFlag(note, noteKeys, "location", mustBeObjectOrNull);
|
|
2110
|
-
checkForInvalidFlags(note, noteKeys, where);
|
|
2111
|
-
notesClone.push({
|
|
2112
|
-
text: noteText || "",
|
|
2113
|
-
location: sanitizeLocation(noteLocation, where, terminalWidth)
|
|
2114
|
-
});
|
|
2115
|
-
}
|
|
2116
|
-
messagesClone.push({
|
|
2117
|
-
id: id || "",
|
|
2118
|
-
pluginName: pluginName || fallbackPluginName,
|
|
2119
|
-
text: text || "",
|
|
2120
|
-
location: sanitizeLocation(location, where, terminalWidth),
|
|
2121
|
-
notes: notesClone,
|
|
2122
|
-
detail: stash ? stash.store(detail) : -1
|
|
2123
|
-
});
|
|
2124
|
-
index++;
|
|
2125
|
-
}
|
|
2126
|
-
return messagesClone;
|
|
2127
|
-
}
|
|
2128
|
-
function sanitizeStringArray(values, property) {
|
|
2129
|
-
const result = [];
|
|
2130
|
-
for (const value of values) {
|
|
2131
|
-
if (typeof value !== "string") throw new Error(`${quote(property)} must be an array of strings`);
|
|
2132
|
-
result.push(value);
|
|
2133
|
-
}
|
|
2134
|
-
return result;
|
|
2135
|
-
}
|
|
2136
|
-
function sanitizeStringMap(map, property) {
|
|
2137
|
-
const result = /* @__PURE__ */ Object.create(null);
|
|
2138
|
-
for (const key in map) {
|
|
2139
|
-
const value = map[key];
|
|
2140
|
-
if (typeof value !== "string") throw new Error(`key ${quote(key)} in object ${quote(property)} must be a string`);
|
|
2141
|
-
result[key] = value;
|
|
2142
|
-
}
|
|
2143
|
-
return result;
|
|
2144
|
-
}
|
|
2145
|
-
function convertOutputFiles({ path: path3, contents, hash }) {
|
|
2146
|
-
let text = null;
|
|
2147
|
-
return {
|
|
2148
|
-
path: path3,
|
|
2149
|
-
contents,
|
|
2150
|
-
hash,
|
|
2151
|
-
get text() {
|
|
2152
|
-
const binary = this.contents;
|
|
2153
|
-
if (text === null || binary !== contents) {
|
|
2154
|
-
contents = binary;
|
|
2155
|
-
text = decodeUTF8(binary);
|
|
2156
|
-
}
|
|
2157
|
-
return text;
|
|
2158
|
-
}
|
|
2159
|
-
};
|
|
2160
|
-
}
|
|
2161
|
-
function jsRegExpToGoRegExp(regexp) {
|
|
2162
|
-
let result = regexp.source;
|
|
2163
|
-
if (regexp.flags) result = `(?${regexp.flags})${result}`;
|
|
2164
|
-
return result;
|
|
2165
|
-
}
|
|
2166
|
-
function parseJSON(bytes) {
|
|
2167
|
-
let text;
|
|
2168
|
-
try {
|
|
2169
|
-
text = decodeUTF8(bytes);
|
|
2170
|
-
} catch {
|
|
2171
|
-
return JSON_parse(bytes);
|
|
2172
|
-
}
|
|
2173
|
-
return JSON.parse(text);
|
|
2174
|
-
}
|
|
2175
|
-
var fs = __require("fs");
|
|
2176
|
-
var os = __require("os");
|
|
2177
|
-
var path = __require("path");
|
|
2178
|
-
var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH;
|
|
2179
|
-
var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild";
|
|
2180
|
-
var packageDarwin_arm64 = "@esbuild/darwin-arm64";
|
|
2181
|
-
var packageDarwin_x64 = "@esbuild/darwin-x64";
|
|
2182
|
-
var knownWindowsPackages = {
|
|
2183
|
-
"win32 arm64 LE": "@esbuild/win32-arm64",
|
|
2184
|
-
"win32 ia32 LE": "@esbuild/win32-ia32",
|
|
2185
|
-
"win32 x64 LE": "@esbuild/win32-x64"
|
|
2186
|
-
};
|
|
2187
|
-
var knownUnixlikePackages = {
|
|
2188
|
-
"aix ppc64 BE": "@esbuild/aix-ppc64",
|
|
2189
|
-
"android arm64 LE": "@esbuild/android-arm64",
|
|
2190
|
-
"darwin arm64 LE": "@esbuild/darwin-arm64",
|
|
2191
|
-
"darwin x64 LE": "@esbuild/darwin-x64",
|
|
2192
|
-
"freebsd arm64 LE": "@esbuild/freebsd-arm64",
|
|
2193
|
-
"freebsd x64 LE": "@esbuild/freebsd-x64",
|
|
2194
|
-
"linux arm LE": "@esbuild/linux-arm",
|
|
2195
|
-
"linux arm64 LE": "@esbuild/linux-arm64",
|
|
2196
|
-
"linux ia32 LE": "@esbuild/linux-ia32",
|
|
2197
|
-
"linux mips64el LE": "@esbuild/linux-mips64el",
|
|
2198
|
-
"linux ppc64 LE": "@esbuild/linux-ppc64",
|
|
2199
|
-
"linux riscv64 LE": "@esbuild/linux-riscv64",
|
|
2200
|
-
"linux s390x BE": "@esbuild/linux-s390x",
|
|
2201
|
-
"linux x64 LE": "@esbuild/linux-x64",
|
|
2202
|
-
"linux loong64 LE": "@esbuild/linux-loong64",
|
|
2203
|
-
"netbsd arm64 LE": "@esbuild/netbsd-arm64",
|
|
2204
|
-
"netbsd x64 LE": "@esbuild/netbsd-x64",
|
|
2205
|
-
"openbsd arm64 LE": "@esbuild/openbsd-arm64",
|
|
2206
|
-
"openbsd x64 LE": "@esbuild/openbsd-x64",
|
|
2207
|
-
"sunos x64 LE": "@esbuild/sunos-x64"
|
|
2208
|
-
};
|
|
2209
|
-
var knownWebAssemblyFallbackPackages = {
|
|
2210
|
-
"android arm LE": "@esbuild/android-arm",
|
|
2211
|
-
"android x64 LE": "@esbuild/android-x64",
|
|
2212
|
-
"openharmony arm64 LE": "@esbuild/openharmony-arm64"
|
|
2213
|
-
};
|
|
2214
|
-
function pkgAndSubpathForCurrentPlatform() {
|
|
2215
|
-
let pkg;
|
|
2216
|
-
let subpath;
|
|
2217
|
-
let isWASM = false;
|
|
2218
|
-
let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`;
|
|
2219
|
-
if (platformKey in knownWindowsPackages) {
|
|
2220
|
-
pkg = knownWindowsPackages[platformKey];
|
|
2221
|
-
subpath = "esbuild.exe";
|
|
2222
|
-
} else if (platformKey in knownUnixlikePackages) {
|
|
2223
|
-
pkg = knownUnixlikePackages[platformKey];
|
|
2224
|
-
subpath = "bin/esbuild";
|
|
2225
|
-
} else if (platformKey in knownWebAssemblyFallbackPackages) {
|
|
2226
|
-
pkg = knownWebAssemblyFallbackPackages[platformKey];
|
|
2227
|
-
subpath = "bin/esbuild";
|
|
2228
|
-
isWASM = true;
|
|
2229
|
-
} else throw new Error(`Unsupported platform: ${platformKey}`);
|
|
2230
|
-
return {
|
|
2231
|
-
pkg,
|
|
2232
|
-
subpath,
|
|
2233
|
-
isWASM
|
|
2234
|
-
};
|
|
2235
|
-
}
|
|
2236
|
-
function pkgForSomeOtherPlatform() {
|
|
2237
|
-
const libMainJS = __require.resolve("esbuild");
|
|
2238
|
-
const nodeModulesDirectory = path.dirname(path.dirname(path.dirname(libMainJS)));
|
|
2239
|
-
if (path.basename(nodeModulesDirectory) === "node_modules") {
|
|
2240
|
-
for (const unixKey in knownUnixlikePackages) try {
|
|
2241
|
-
const pkg = knownUnixlikePackages[unixKey];
|
|
2242
|
-
if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) return pkg;
|
|
2243
|
-
} catch {}
|
|
2244
|
-
for (const windowsKey in knownWindowsPackages) try {
|
|
2245
|
-
const pkg = knownWindowsPackages[windowsKey];
|
|
2246
|
-
if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) return pkg;
|
|
2247
|
-
} catch {}
|
|
2248
|
-
}
|
|
2249
|
-
return null;
|
|
2250
|
-
}
|
|
2251
|
-
function downloadedBinPath(pkg, subpath) {
|
|
2252
|
-
const esbuildLibDir = path.dirname(__require.resolve("esbuild"));
|
|
2253
|
-
return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`);
|
|
2254
|
-
}
|
|
2255
|
-
function generateBinPath() {
|
|
2256
|
-
if (isValidBinaryPath(ESBUILD_BINARY_PATH)) {
|
|
2257
|
-
if (!fs.existsSync(ESBUILD_BINARY_PATH)) console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`);
|
|
2258
|
-
else return {
|
|
2259
|
-
binPath: ESBUILD_BINARY_PATH,
|
|
2260
|
-
isWASM: false
|
|
2261
|
-
};
|
|
2262
|
-
}
|
|
2263
|
-
const { pkg, subpath, isWASM } = pkgAndSubpathForCurrentPlatform();
|
|
2264
|
-
let binPath;
|
|
2265
|
-
try {
|
|
2266
|
-
binPath = __require.resolve(`${pkg}/${subpath}`);
|
|
2267
|
-
} catch (e) {
|
|
2268
|
-
binPath = downloadedBinPath(pkg, subpath);
|
|
2269
|
-
if (!fs.existsSync(binPath)) {
|
|
2270
|
-
try {
|
|
2271
|
-
__require.resolve(pkg);
|
|
2272
|
-
} catch {
|
|
2273
|
-
const otherPkg = pkgForSomeOtherPlatform();
|
|
2274
|
-
if (otherPkg) {
|
|
2275
|
-
let suggestions = `
|
|
2276
|
-
Specifically the "${otherPkg}" package is present but this platform
|
|
2277
|
-
needs the "${pkg}" package instead. People often get into this
|
|
2278
|
-
situation by installing esbuild on Windows or macOS and copying "node_modules"
|
|
2279
|
-
into a Docker image that runs Linux, or by copying "node_modules" between
|
|
2280
|
-
Windows and WSL environments.
|
|
2281
|
-
|
|
2282
|
-
If you are installing with npm, you can try not copying the "node_modules"
|
|
2283
|
-
directory when you copy the files over, and running "npm ci" or "npm install"
|
|
2284
|
-
on the destination platform after the copy. Or you could consider using yarn
|
|
2285
|
-
instead of npm which has built-in support for installing a package on multiple
|
|
2286
|
-
platforms simultaneously.
|
|
2287
|
-
|
|
2288
|
-
If you are installing with yarn, you can try listing both this platform and the
|
|
2289
|
-
other platform in your ".yarnrc.yml" file using the "supportedArchitectures"
|
|
2290
|
-
feature: https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
|
|
2291
|
-
Keep in mind that this means multiple copies of esbuild will be present.
|
|
2292
|
-
`;
|
|
2293
|
-
if (pkg === packageDarwin_x64 && otherPkg === packageDarwin_arm64 || pkg === packageDarwin_arm64 && otherPkg === packageDarwin_x64) suggestions = `
|
|
2294
|
-
Specifically the "${otherPkg}" package is present but this platform
|
|
2295
|
-
needs the "${pkg}" package instead. People often get into this
|
|
2296
|
-
situation by installing esbuild with npm running inside of Rosetta 2 and then
|
|
2297
|
-
trying to use it with node running outside of Rosetta 2, or vice versa (Rosetta
|
|
2298
|
-
2 is Apple's on-the-fly x86_64-to-arm64 translation service).
|
|
2299
|
-
|
|
2300
|
-
If you are installing with npm, you can try ensuring that both npm and node are
|
|
2301
|
-
not running under Rosetta 2 and then reinstalling esbuild. This likely involves
|
|
2302
|
-
changing how you installed npm and/or node. For example, installing node with
|
|
2303
|
-
the universal installer here should work: https://nodejs.org/en/download/. Or
|
|
2304
|
-
you could consider using yarn instead of npm which has built-in support for
|
|
2305
|
-
installing a package on multiple platforms simultaneously.
|
|
2306
|
-
|
|
2307
|
-
If you are installing with yarn, you can try listing both "arm64" and "x64"
|
|
2308
|
-
in your ".yarnrc.yml" file using the "supportedArchitectures" feature:
|
|
2309
|
-
https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
|
|
2310
|
-
Keep in mind that this means multiple copies of esbuild will be present.
|
|
2311
|
-
`;
|
|
2312
|
-
throw new Error(`
|
|
2313
|
-
You installed esbuild for another platform than the one you're currently using.
|
|
2314
|
-
This won't work because esbuild is written with native code and needs to
|
|
2315
|
-
install a platform-specific binary executable.
|
|
2316
|
-
${suggestions}
|
|
2317
|
-
Another alternative is to use the "esbuild-wasm" package instead, which works
|
|
2318
|
-
the same way on all platforms. But it comes with a heavy performance cost and
|
|
2319
|
-
can sometimes be 10x slower than the "esbuild" package, so you may also not
|
|
2320
|
-
want to do that.
|
|
2321
|
-
`);
|
|
2322
|
-
}
|
|
2323
|
-
throw new Error(`The package "${pkg}" could not be found, and is needed by esbuild.
|
|
2324
|
-
|
|
2325
|
-
If you are installing esbuild with npm, make sure that you don't specify the
|
|
2326
|
-
"--no-optional" or "--omit=optional" flags. The "optionalDependencies" feature
|
|
2327
|
-
of "package.json" is used by esbuild to install the correct binary executable
|
|
2328
|
-
for your current platform.`);
|
|
2329
|
-
}
|
|
2330
|
-
throw e;
|
|
2331
|
-
}
|
|
2332
|
-
}
|
|
2333
|
-
if (/\.zip\//.test(binPath)) {
|
|
2334
|
-
let pnpapi;
|
|
2335
|
-
try {
|
|
2336
|
-
pnpapi = __require("pnpapi");
|
|
2337
|
-
} catch (e) {}
|
|
2338
|
-
if (pnpapi) {
|
|
2339
|
-
const root = pnpapi.getPackageInformation(pnpapi.topLevel).packageLocation;
|
|
2340
|
-
const binTargetPath = path.join(root, "node_modules", ".cache", "esbuild", `pnpapi-${pkg.replace("/", "-")}-0.27.7-${path.basename(subpath)}`);
|
|
2341
|
-
if (!fs.existsSync(binTargetPath)) {
|
|
2342
|
-
fs.mkdirSync(path.dirname(binTargetPath), { recursive: true });
|
|
2343
|
-
fs.copyFileSync(binPath, binTargetPath);
|
|
2344
|
-
fs.chmodSync(binTargetPath, 493);
|
|
2345
|
-
}
|
|
2346
|
-
return {
|
|
2347
|
-
binPath: binTargetPath,
|
|
2348
|
-
isWASM
|
|
2349
|
-
};
|
|
2350
|
-
}
|
|
2351
|
-
}
|
|
2352
|
-
return {
|
|
2353
|
-
binPath,
|
|
2354
|
-
isWASM
|
|
2355
|
-
};
|
|
2356
|
-
}
|
|
2357
|
-
var child_process = __require("child_process");
|
|
2358
|
-
var crypto = __require("crypto");
|
|
2359
|
-
var path2 = __require("path");
|
|
2360
|
-
var fs2 = __require("fs");
|
|
2361
|
-
var os2 = __require("os");
|
|
2362
|
-
var tty = __require("tty");
|
|
2363
|
-
var worker_threads;
|
|
2364
|
-
if (process.env.ESBUILD_WORKER_THREADS !== "0") {
|
|
2365
|
-
try {
|
|
2366
|
-
worker_threads = __require("worker_threads");
|
|
2367
|
-
} catch {}
|
|
2368
|
-
let [major, minor] = process.versions.node.split(".");
|
|
2369
|
-
if (+major < 12 || +major === 12 && +minor < 17 || +major === 13 && +minor < 13) worker_threads = void 0;
|
|
2370
|
-
}
|
|
2371
|
-
var _a;
|
|
2372
|
-
var isInternalWorkerThread = ((_a = worker_threads == null ? void 0 : worker_threads.workerData) == null ? void 0 : _a.esbuildVersion) === "0.27.7";
|
|
2373
|
-
var esbuildCommandAndArgs = () => {
|
|
2374
|
-
if ((!ESBUILD_BINARY_PATH || false) && (path2.basename(__filename) !== "main.js" || path2.basename(__dirname) !== "lib")) throw new Error(`The esbuild JavaScript API cannot be bundled. Please mark the "esbuild" package as external so it's not included in the bundle.
|
|
2375
|
-
|
|
2376
|
-
More information: The file containing the code for esbuild's JavaScript API (${__filename}) does not appear to be inside the esbuild package on the file system, which usually means that the esbuild package was bundled into another file. This is problematic because the API needs to run a binary executable inside the esbuild package which is located using a relative path from the API code to the executable. If the esbuild package is bundled, the relative path will be incorrect and the executable won't be found.`);
|
|
2377
|
-
{
|
|
2378
|
-
const { binPath, isWASM } = generateBinPath();
|
|
2379
|
-
if (isWASM) return ["node", [binPath]];
|
|
2380
|
-
else return [binPath, []];
|
|
2381
|
-
}
|
|
2382
|
-
};
|
|
2383
|
-
var isTTY = () => tty.isatty(2);
|
|
2384
|
-
var fsSync = {
|
|
2385
|
-
readFile(tempFile, callback) {
|
|
2386
|
-
try {
|
|
2387
|
-
let contents = fs2.readFileSync(tempFile, "utf8");
|
|
2388
|
-
try {
|
|
2389
|
-
fs2.unlinkSync(tempFile);
|
|
2390
|
-
} catch {}
|
|
2391
|
-
callback(null, contents);
|
|
2392
|
-
} catch (err) {
|
|
2393
|
-
callback(err, null);
|
|
2394
|
-
}
|
|
2395
|
-
},
|
|
2396
|
-
writeFile(contents, callback) {
|
|
2397
|
-
try {
|
|
2398
|
-
let tempFile = randomFileName();
|
|
2399
|
-
fs2.writeFileSync(tempFile, contents);
|
|
2400
|
-
callback(tempFile);
|
|
2401
|
-
} catch {
|
|
2402
|
-
callback(null);
|
|
2403
|
-
}
|
|
2404
|
-
}
|
|
2405
|
-
};
|
|
2406
|
-
var fsAsync = {
|
|
2407
|
-
readFile(tempFile, callback) {
|
|
2408
|
-
try {
|
|
2409
|
-
fs2.readFile(tempFile, "utf8", (err, contents) => {
|
|
2410
|
-
try {
|
|
2411
|
-
fs2.unlink(tempFile, () => callback(err, contents));
|
|
2412
|
-
} catch {
|
|
2413
|
-
callback(err, contents);
|
|
2414
|
-
}
|
|
2415
|
-
});
|
|
2416
|
-
} catch (err) {
|
|
2417
|
-
callback(err, null);
|
|
2418
|
-
}
|
|
2419
|
-
},
|
|
2420
|
-
writeFile(contents, callback) {
|
|
2421
|
-
try {
|
|
2422
|
-
let tempFile = randomFileName();
|
|
2423
|
-
fs2.writeFile(tempFile, contents, (err) => err !== null ? callback(null) : callback(tempFile));
|
|
2424
|
-
} catch {
|
|
2425
|
-
callback(null);
|
|
2426
|
-
}
|
|
2427
|
-
}
|
|
2428
|
-
};
|
|
2429
|
-
var version = "0.27.7";
|
|
2430
|
-
var build = (options) => ensureServiceIsRunning().build(options);
|
|
2431
|
-
var context = (buildOptions) => ensureServiceIsRunning().context(buildOptions);
|
|
2432
|
-
var transform = (input, options) => ensureServiceIsRunning().transform(input, options);
|
|
2433
|
-
var formatMessages = (messages, options) => ensureServiceIsRunning().formatMessages(messages, options);
|
|
2434
|
-
var analyzeMetafile = (messages, options) => ensureServiceIsRunning().analyzeMetafile(messages, options);
|
|
2435
|
-
var buildSync = (options) => {
|
|
2436
|
-
if (worker_threads && !isInternalWorkerThread) {
|
|
2437
|
-
if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
|
|
2438
|
-
return workerThreadService.buildSync(options);
|
|
2439
|
-
}
|
|
2440
|
-
let result;
|
|
2441
|
-
runServiceSync((service) => service.buildOrContext({
|
|
2442
|
-
callName: "buildSync",
|
|
2443
|
-
refs: null,
|
|
2444
|
-
options,
|
|
2445
|
-
isTTY: isTTY(),
|
|
2446
|
-
defaultWD,
|
|
2447
|
-
callback: (err, res) => {
|
|
2448
|
-
if (err) throw err;
|
|
2449
|
-
result = res;
|
|
2450
|
-
}
|
|
2451
|
-
}));
|
|
2452
|
-
return result;
|
|
2453
|
-
};
|
|
2454
|
-
var transformSync = (input, options) => {
|
|
2455
|
-
if (worker_threads && !isInternalWorkerThread) {
|
|
2456
|
-
if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
|
|
2457
|
-
return workerThreadService.transformSync(input, options);
|
|
2458
|
-
}
|
|
2459
|
-
let result;
|
|
2460
|
-
runServiceSync((service) => service.transform({
|
|
2461
|
-
callName: "transformSync",
|
|
2462
|
-
refs: null,
|
|
2463
|
-
input,
|
|
2464
|
-
options: options || {},
|
|
2465
|
-
isTTY: isTTY(),
|
|
2466
|
-
fs: fsSync,
|
|
2467
|
-
callback: (err, res) => {
|
|
2468
|
-
if (err) throw err;
|
|
2469
|
-
result = res;
|
|
2470
|
-
}
|
|
2471
|
-
}));
|
|
2472
|
-
return result;
|
|
2473
|
-
};
|
|
2474
|
-
var formatMessagesSync = (messages, options) => {
|
|
2475
|
-
if (worker_threads && !isInternalWorkerThread) {
|
|
2476
|
-
if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
|
|
2477
|
-
return workerThreadService.formatMessagesSync(messages, options);
|
|
2478
|
-
}
|
|
2479
|
-
let result;
|
|
2480
|
-
runServiceSync((service) => service.formatMessages({
|
|
2481
|
-
callName: "formatMessagesSync",
|
|
2482
|
-
refs: null,
|
|
2483
|
-
messages,
|
|
2484
|
-
options,
|
|
2485
|
-
callback: (err, res) => {
|
|
2486
|
-
if (err) throw err;
|
|
2487
|
-
result = res;
|
|
2488
|
-
}
|
|
2489
|
-
}));
|
|
2490
|
-
return result;
|
|
2491
|
-
};
|
|
2492
|
-
var analyzeMetafileSync = (metafile, options) => {
|
|
2493
|
-
if (worker_threads && !isInternalWorkerThread) {
|
|
2494
|
-
if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
|
|
2495
|
-
return workerThreadService.analyzeMetafileSync(metafile, options);
|
|
2496
|
-
}
|
|
2497
|
-
let result;
|
|
2498
|
-
runServiceSync((service) => service.analyzeMetafile({
|
|
2499
|
-
callName: "analyzeMetafileSync",
|
|
2500
|
-
refs: null,
|
|
2501
|
-
metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
|
|
2502
|
-
options,
|
|
2503
|
-
callback: (err, res) => {
|
|
2504
|
-
if (err) throw err;
|
|
2505
|
-
result = res;
|
|
2506
|
-
}
|
|
2507
|
-
}));
|
|
2508
|
-
return result;
|
|
2509
|
-
};
|
|
2510
|
-
var stop = () => {
|
|
2511
|
-
if (stopService) stopService();
|
|
2512
|
-
if (workerThreadService) workerThreadService.stop();
|
|
2513
|
-
return Promise.resolve();
|
|
2514
|
-
};
|
|
2515
|
-
var initializeWasCalled = false;
|
|
2516
|
-
var initialize = (options) => {
|
|
2517
|
-
options = validateInitializeOptions(options || {});
|
|
2518
|
-
if (options.wasmURL) throw new Error(`The "wasmURL" option only works in the browser`);
|
|
2519
|
-
if (options.wasmModule) throw new Error(`The "wasmModule" option only works in the browser`);
|
|
2520
|
-
if (options.worker) throw new Error(`The "worker" option only works in the browser`);
|
|
2521
|
-
if (initializeWasCalled) throw new Error("Cannot call \"initialize\" more than once");
|
|
2522
|
-
ensureServiceIsRunning();
|
|
2523
|
-
initializeWasCalled = true;
|
|
2524
|
-
return Promise.resolve();
|
|
2525
|
-
};
|
|
2526
|
-
var defaultWD = process.cwd();
|
|
2527
|
-
var longLivedService;
|
|
2528
|
-
var stopService;
|
|
2529
|
-
var ensureServiceIsRunning = () => {
|
|
2530
|
-
if (longLivedService) return longLivedService;
|
|
2531
|
-
let [command, args] = esbuildCommandAndArgs();
|
|
2532
|
-
let child = child_process.spawn(command, args.concat(`--service=0.27.7`, "--ping"), {
|
|
2533
|
-
windowsHide: true,
|
|
2534
|
-
stdio: [
|
|
2535
|
-
"pipe",
|
|
2536
|
-
"pipe",
|
|
2537
|
-
"inherit"
|
|
2538
|
-
],
|
|
2539
|
-
cwd: defaultWD
|
|
2540
|
-
});
|
|
2541
|
-
let { readFromStdout, afterClose, service } = createChannel({
|
|
2542
|
-
writeToStdin(bytes) {
|
|
2543
|
-
child.stdin.write(bytes, (err) => {
|
|
2544
|
-
if (err) afterClose(err);
|
|
2545
|
-
});
|
|
2546
|
-
},
|
|
2547
|
-
readFileSync: fs2.readFileSync,
|
|
2548
|
-
isSync: false,
|
|
2549
|
-
hasFS: true,
|
|
2550
|
-
esbuild: node_exports
|
|
2551
|
-
});
|
|
2552
|
-
child.stdin.on("error", afterClose);
|
|
2553
|
-
child.on("error", afterClose);
|
|
2554
|
-
const stdin = child.stdin;
|
|
2555
|
-
const stdout = child.stdout;
|
|
2556
|
-
stdout.on("data", readFromStdout);
|
|
2557
|
-
stdout.on("end", afterClose);
|
|
2558
|
-
stopService = () => {
|
|
2559
|
-
stdin.destroy();
|
|
2560
|
-
stdout.destroy();
|
|
2561
|
-
child.kill();
|
|
2562
|
-
initializeWasCalled = false;
|
|
2563
|
-
longLivedService = void 0;
|
|
2564
|
-
stopService = void 0;
|
|
2565
|
-
};
|
|
2566
|
-
let refCount = 0;
|
|
2567
|
-
child.unref();
|
|
2568
|
-
if (stdin.unref) stdin.unref();
|
|
2569
|
-
if (stdout.unref) stdout.unref();
|
|
2570
|
-
const refs = {
|
|
2571
|
-
ref() {
|
|
2572
|
-
if (++refCount === 1) child.ref();
|
|
2573
|
-
},
|
|
2574
|
-
unref() {
|
|
2575
|
-
if (--refCount === 0) child.unref();
|
|
2576
|
-
}
|
|
2577
|
-
};
|
|
2578
|
-
longLivedService = {
|
|
2579
|
-
build: (options) => new Promise((resolve, reject) => {
|
|
2580
|
-
service.buildOrContext({
|
|
2581
|
-
callName: "build",
|
|
2582
|
-
refs,
|
|
2583
|
-
options,
|
|
2584
|
-
isTTY: isTTY(),
|
|
2585
|
-
defaultWD,
|
|
2586
|
-
callback: (err, res) => err ? reject(err) : resolve(res)
|
|
2587
|
-
});
|
|
2588
|
-
}),
|
|
2589
|
-
context: (options) => new Promise((resolve, reject) => service.buildOrContext({
|
|
2590
|
-
callName: "context",
|
|
2591
|
-
refs,
|
|
2592
|
-
options,
|
|
2593
|
-
isTTY: isTTY(),
|
|
2594
|
-
defaultWD,
|
|
2595
|
-
callback: (err, res) => err ? reject(err) : resolve(res)
|
|
2596
|
-
})),
|
|
2597
|
-
transform: (input, options) => new Promise((resolve, reject) => service.transform({
|
|
2598
|
-
callName: "transform",
|
|
2599
|
-
refs,
|
|
2600
|
-
input,
|
|
2601
|
-
options: options || {},
|
|
2602
|
-
isTTY: isTTY(),
|
|
2603
|
-
fs: fsAsync,
|
|
2604
|
-
callback: (err, res) => err ? reject(err) : resolve(res)
|
|
2605
|
-
})),
|
|
2606
|
-
formatMessages: (messages, options) => new Promise((resolve, reject) => service.formatMessages({
|
|
2607
|
-
callName: "formatMessages",
|
|
2608
|
-
refs,
|
|
2609
|
-
messages,
|
|
2610
|
-
options,
|
|
2611
|
-
callback: (err, res) => err ? reject(err) : resolve(res)
|
|
2612
|
-
})),
|
|
2613
|
-
analyzeMetafile: (metafile, options) => new Promise((resolve, reject) => service.analyzeMetafile({
|
|
2614
|
-
callName: "analyzeMetafile",
|
|
2615
|
-
refs,
|
|
2616
|
-
metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
|
|
2617
|
-
options,
|
|
2618
|
-
callback: (err, res) => err ? reject(err) : resolve(res)
|
|
2619
|
-
}))
|
|
2620
|
-
};
|
|
2621
|
-
return longLivedService;
|
|
2622
|
-
};
|
|
2623
|
-
var runServiceSync = (callback) => {
|
|
2624
|
-
let [command, args] = esbuildCommandAndArgs();
|
|
2625
|
-
let stdin = /* @__PURE__ */ new Uint8Array();
|
|
2626
|
-
let { readFromStdout, afterClose, service } = createChannel({
|
|
2627
|
-
writeToStdin(bytes) {
|
|
2628
|
-
if (stdin.length !== 0) throw new Error("Must run at most one command");
|
|
2629
|
-
stdin = bytes;
|
|
2630
|
-
},
|
|
2631
|
-
isSync: true,
|
|
2632
|
-
hasFS: true,
|
|
2633
|
-
esbuild: node_exports
|
|
2634
|
-
});
|
|
2635
|
-
callback(service);
|
|
2636
|
-
readFromStdout(child_process.execFileSync(command, args.concat(`--service=0.27.7`), {
|
|
2637
|
-
cwd: defaultWD,
|
|
2638
|
-
windowsHide: true,
|
|
2639
|
-
input: stdin,
|
|
2640
|
-
maxBuffer: +process.env.ESBUILD_MAX_BUFFER || 16777216
|
|
2641
|
-
}));
|
|
2642
|
-
afterClose(null);
|
|
2643
|
-
};
|
|
2644
|
-
var randomFileName = () => {
|
|
2645
|
-
return path2.join(os2.tmpdir(), `esbuild-${crypto.randomBytes(32).toString("hex")}`);
|
|
2646
|
-
};
|
|
2647
|
-
var workerThreadService = null;
|
|
2648
|
-
var startWorkerThreadService = (worker_threads2) => {
|
|
2649
|
-
let { port1: mainPort, port2: workerPort } = new worker_threads2.MessageChannel();
|
|
2650
|
-
let worker = new worker_threads2.Worker(__filename, {
|
|
2651
|
-
workerData: {
|
|
2652
|
-
workerPort,
|
|
2653
|
-
defaultWD,
|
|
2654
|
-
esbuildVersion: "0.27.7"
|
|
2655
|
-
},
|
|
2656
|
-
transferList: [workerPort],
|
|
2657
|
-
execArgv: []
|
|
2658
|
-
});
|
|
2659
|
-
let nextID = 0;
|
|
2660
|
-
let fakeBuildError = (text) => {
|
|
2661
|
-
let error = /* @__PURE__ */ new Error(`Build failed with 1 error:
|
|
2662
|
-
error: ${text}`);
|
|
2663
|
-
error.errors = [{
|
|
2664
|
-
id: "",
|
|
2665
|
-
pluginName: "",
|
|
2666
|
-
text,
|
|
2667
|
-
location: null,
|
|
2668
|
-
notes: [],
|
|
2669
|
-
detail: void 0
|
|
2670
|
-
}];
|
|
2671
|
-
error.warnings = [];
|
|
2672
|
-
return error;
|
|
2673
|
-
};
|
|
2674
|
-
let validateBuildSyncOptions = (options) => {
|
|
2675
|
-
if (!options) return;
|
|
2676
|
-
let plugins = options.plugins;
|
|
2677
|
-
if (plugins && plugins.length > 0) throw fakeBuildError(`Cannot use plugins in synchronous API calls`);
|
|
2678
|
-
};
|
|
2679
|
-
let applyProperties = (object, properties) => {
|
|
2680
|
-
for (let key in properties) object[key] = properties[key];
|
|
2681
|
-
};
|
|
2682
|
-
let runCallSync = (command, args) => {
|
|
2683
|
-
let id = nextID++;
|
|
2684
|
-
let sharedBuffer = new SharedArrayBuffer(8);
|
|
2685
|
-
let sharedBufferView = new Int32Array(sharedBuffer);
|
|
2686
|
-
let msg = {
|
|
2687
|
-
sharedBuffer,
|
|
2688
|
-
id,
|
|
2689
|
-
command,
|
|
2690
|
-
args
|
|
2691
|
-
};
|
|
2692
|
-
worker.postMessage(msg);
|
|
2693
|
-
let status = Atomics.wait(sharedBufferView, 0, 0);
|
|
2694
|
-
if (status !== "ok" && status !== "not-equal") throw new Error("Internal error: Atomics.wait() failed: " + status);
|
|
2695
|
-
let { message: { id: id2, resolve, reject, properties } } = worker_threads2.receiveMessageOnPort(mainPort);
|
|
2696
|
-
if (id !== id2) throw new Error(`Internal error: Expected id ${id} but got id ${id2}`);
|
|
2697
|
-
if (reject) {
|
|
2698
|
-
applyProperties(reject, properties);
|
|
2699
|
-
throw reject;
|
|
2700
|
-
}
|
|
2701
|
-
return resolve;
|
|
2702
|
-
};
|
|
2703
|
-
worker.unref();
|
|
2704
|
-
return {
|
|
2705
|
-
buildSync(options) {
|
|
2706
|
-
validateBuildSyncOptions(options);
|
|
2707
|
-
return runCallSync("build", [options]);
|
|
2708
|
-
},
|
|
2709
|
-
transformSync(input, options) {
|
|
2710
|
-
return runCallSync("transform", [input, options]);
|
|
2711
|
-
},
|
|
2712
|
-
formatMessagesSync(messages, options) {
|
|
2713
|
-
return runCallSync("formatMessages", [messages, options]);
|
|
2714
|
-
},
|
|
2715
|
-
analyzeMetafileSync(metafile, options) {
|
|
2716
|
-
return runCallSync("analyzeMetafile", [metafile, options]);
|
|
2717
|
-
},
|
|
2718
|
-
stop() {
|
|
2719
|
-
worker.terminate();
|
|
2720
|
-
workerThreadService = null;
|
|
2721
|
-
}
|
|
2722
|
-
};
|
|
2723
|
-
};
|
|
2724
|
-
var startSyncServiceWorker = () => {
|
|
2725
|
-
let workerPort = worker_threads.workerData.workerPort;
|
|
2726
|
-
let parentPort = worker_threads.parentPort;
|
|
2727
|
-
let extractProperties = (object) => {
|
|
2728
|
-
let properties = {};
|
|
2729
|
-
if (object && typeof object === "object") for (let key in object) properties[key] = object[key];
|
|
2730
|
-
return properties;
|
|
2731
|
-
};
|
|
2732
|
-
try {
|
|
2733
|
-
let service = ensureServiceIsRunning();
|
|
2734
|
-
defaultWD = worker_threads.workerData.defaultWD;
|
|
2735
|
-
parentPort.on("message", (msg) => {
|
|
2736
|
-
(async () => {
|
|
2737
|
-
let { sharedBuffer, id, command, args } = msg;
|
|
2738
|
-
let sharedBufferView = new Int32Array(sharedBuffer);
|
|
2739
|
-
try {
|
|
2740
|
-
switch (command) {
|
|
2741
|
-
case "build":
|
|
2742
|
-
workerPort.postMessage({
|
|
2743
|
-
id,
|
|
2744
|
-
resolve: await service.build(args[0])
|
|
2745
|
-
});
|
|
2746
|
-
break;
|
|
2747
|
-
case "transform":
|
|
2748
|
-
workerPort.postMessage({
|
|
2749
|
-
id,
|
|
2750
|
-
resolve: await service.transform(args[0], args[1])
|
|
2751
|
-
});
|
|
2752
|
-
break;
|
|
2753
|
-
case "formatMessages":
|
|
2754
|
-
workerPort.postMessage({
|
|
2755
|
-
id,
|
|
2756
|
-
resolve: await service.formatMessages(args[0], args[1])
|
|
2757
|
-
});
|
|
2758
|
-
break;
|
|
2759
|
-
case "analyzeMetafile":
|
|
2760
|
-
workerPort.postMessage({
|
|
2761
|
-
id,
|
|
2762
|
-
resolve: await service.analyzeMetafile(args[0], args[1])
|
|
2763
|
-
});
|
|
2764
|
-
break;
|
|
2765
|
-
default: throw new Error(`Invalid command: ${command}`);
|
|
2766
|
-
}
|
|
2767
|
-
} catch (reject) {
|
|
2768
|
-
workerPort.postMessage({
|
|
2769
|
-
id,
|
|
2770
|
-
reject,
|
|
2771
|
-
properties: extractProperties(reject)
|
|
2772
|
-
});
|
|
2773
|
-
}
|
|
2774
|
-
Atomics.add(sharedBufferView, 0, 1);
|
|
2775
|
-
Atomics.notify(sharedBufferView, 0, Infinity);
|
|
2776
|
-
})();
|
|
2777
|
-
});
|
|
2778
|
-
} catch (reject) {
|
|
2779
|
-
parentPort.on("message", (msg) => {
|
|
2780
|
-
let { sharedBuffer, id } = msg;
|
|
2781
|
-
let sharedBufferView = new Int32Array(sharedBuffer);
|
|
2782
|
-
workerPort.postMessage({
|
|
2783
|
-
id,
|
|
2784
|
-
reject,
|
|
2785
|
-
properties: extractProperties(reject)
|
|
2786
|
-
});
|
|
2787
|
-
Atomics.add(sharedBufferView, 0, 1);
|
|
2788
|
-
Atomics.notify(sharedBufferView, 0, Infinity);
|
|
2789
|
-
});
|
|
2790
|
-
}
|
|
2791
|
-
};
|
|
2792
|
-
if (isInternalWorkerThread) startSyncServiceWorker();
|
|
2793
|
-
var node_default = node_exports;
|
|
2794
|
-
0 && (module.exports = {
|
|
2795
|
-
analyzeMetafile,
|
|
2796
|
-
analyzeMetafileSync,
|
|
2797
|
-
build,
|
|
2798
|
-
buildSync,
|
|
2799
|
-
context,
|
|
2800
|
-
formatMessages,
|
|
2801
|
-
formatMessagesSync,
|
|
2802
|
-
initialize,
|
|
2803
|
-
stop,
|
|
2804
|
-
transform,
|
|
2805
|
-
transformSync,
|
|
2806
|
-
version
|
|
2807
|
-
});
|
|
2808
|
-
})))();
|
|
2809
|
-
const viteRawNamespace = "vitehub-vite-raw";
|
|
2810
|
-
const viteMarkdownTemplateNamespace = "vitehub-markdown-template";
|
|
403
|
+
//#region ../internal/src/build/bundle-options.ts
|
|
404
|
+
const encodedAliasPrefixMarker = "\0vitehub-prefix:";
|
|
405
|
+
const encodedAliasExactMarker = "\0vitehub-exact:";
|
|
406
|
+
/** Select the runtime constants from one resolved Vite configuration. */
|
|
407
|
+
function resolveViteHubBundleDefines(config) {
|
|
408
|
+
const defines = {};
|
|
409
|
+
for (const name of ["__VITEHUB_PUBLIC_URL__", "__VITEHUB_APP_BASE_URL__"]) {
|
|
410
|
+
const value = config.define?.[name];
|
|
411
|
+
if (typeof value === "string") defines[name] = value;
|
|
412
|
+
}
|
|
413
|
+
return defines;
|
|
414
|
+
}
|
|
415
|
+
//#endregion
|
|
416
|
+
//#region ../internal/src/build/ast-walk.ts
|
|
417
|
+
/** The oxc parser grammar for a file, from its extension. Defaults to TypeScript. */
|
|
418
|
+
function moduleLanguage(file) {
|
|
419
|
+
if (/\.(?:c|m)?tsx$/i.test(file)) return "tsx";
|
|
420
|
+
if (/\.(?:c|m)?jsx$/i.test(file)) return "jsx";
|
|
421
|
+
if (/\.(?:c|m)?js$/i.test(file)) return "js";
|
|
422
|
+
return "ts";
|
|
423
|
+
}
|
|
424
|
+
function isNode(value) {
|
|
425
|
+
return typeof value === "object" && value !== null && "type" in value && typeof value.type === "string";
|
|
426
|
+
}
|
|
427
|
+
/** Visits `node` and its descendants. Return `false` from `visit` to skip the children of a node. */
|
|
428
|
+
function walk(node, visit, parent) {
|
|
429
|
+
if (visit(node, parent) === false) return;
|
|
430
|
+
const fields = node;
|
|
431
|
+
for (const key in fields) {
|
|
432
|
+
const child = fields[key];
|
|
433
|
+
if (typeof child !== "object" || child === null || key === "parent") continue;
|
|
434
|
+
if (Array.isArray(child)) {
|
|
435
|
+
for (const item of child) if (isNode(item)) walk(item, visit, node);
|
|
436
|
+
} else if (isNode(child)) walk(child, visit, node);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
//#endregion
|
|
440
|
+
//#region ../internal/src/build/rolldown.ts
|
|
441
|
+
const viteRawPrefix = "\0vitehub-vite-raw:";
|
|
442
|
+
const markdownTemplatePrefix = "\0vitehub-markdown-template:";
|
|
2811
443
|
const markdownTemplateFileSuffix = ".template.md";
|
|
2812
444
|
const markdownTemplateModuleQuery = "markdown-template";
|
|
2813
445
|
const skipMarkdownTemplateResolve = "vitehubSkipMarkdownTemplateResolve";
|
|
2814
446
|
const skipResolvedAlias = "vitehubSkipResolvedAlias";
|
|
2815
|
-
const
|
|
2816
|
-
const encodedAliasExactMarker = "\0vitehub-exact:";
|
|
447
|
+
const resolvingViteAlias = "vitehubResolvingAlias";
|
|
2817
448
|
const markdownTemplateRuntimeSpecifier = "@vite-hub/markdown-template";
|
|
449
|
+
/**
|
|
450
|
+
* Vite 8 bundles with Rolldown, so the app already has it. Load the copy next to `vite`, or `vite/rolldown` with
|
|
451
|
+
* Vite+, instead of installing a second bundler.
|
|
452
|
+
*/
|
|
453
|
+
async function importRolldown() {
|
|
454
|
+
let entry;
|
|
455
|
+
try {
|
|
456
|
+
entry = createRequire(import.meta.resolve("vite")).resolve("rolldown");
|
|
457
|
+
} catch (error) {
|
|
458
|
+
if (!(error instanceof Error) || !("code" in error) || error.code !== "MODULE_NOT_FOUND") throw error;
|
|
459
|
+
entry = createRequire(import.meta.url).resolve("vite/rolldown");
|
|
460
|
+
}
|
|
461
|
+
return await import(pathToFileURL(entry).href);
|
|
462
|
+
}
|
|
2818
463
|
function normalizePathSeparators(path) {
|
|
2819
464
|
return path.replaceAll("\\", "/");
|
|
2820
465
|
}
|
|
2821
466
|
function escapeRegExp(value) {
|
|
2822
467
|
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
2823
468
|
}
|
|
469
|
+
function isRelativeSpecifier(path) {
|
|
470
|
+
return /^\.\.?[\\/]/.test(path);
|
|
471
|
+
}
|
|
472
|
+
function isBareSpecifier(id) {
|
|
473
|
+
return !/^(?:\.{1,2}(?:[\\/]|$)|[\\/]|[A-Za-z]:[\\/]|\0|#|[a-z][a-z0-9+.-]*:)/i.test(id);
|
|
474
|
+
}
|
|
475
|
+
/** The folder that a relative import of `importer` resolves from, as esbuild's `resolveDir`. */
|
|
476
|
+
function importerDir(importer, workingDir) {
|
|
477
|
+
return importer && isAbsolute(importer) ? dirname(importer) : workingDir;
|
|
478
|
+
}
|
|
479
|
+
/** Rolldown resolves a specifier from an importer file. A bundle entry has none, so use a file in the working folder. */
|
|
480
|
+
function importerFor(importer, workingDir) {
|
|
481
|
+
return importer ?? join(workingDir, "__vitehub_entry__.js");
|
|
482
|
+
}
|
|
483
|
+
function isFileResolution(resolved) {
|
|
484
|
+
return Boolean(resolved && !resolved.external && isAbsolute(resolved.id) && !resolved.id.startsWith("\0"));
|
|
485
|
+
}
|
|
2824
486
|
function collectPackageExportCandidates(packageName, exportsValue, packageRelativePath) {
|
|
2825
487
|
if (typeof exportsValue === "string") return normalizePathSeparators(exportsValue).replace(/^\.\//, "") === packageRelativePath ? [packageName] : [];
|
|
2826
|
-
if (!Array.isArray(exportsValue) && !
|
|
488
|
+
if (!Array.isArray(exportsValue) && !isRecord(exportsValue)) return [];
|
|
2827
489
|
const candidates = [];
|
|
2828
|
-
const exportEntries =
|
|
490
|
+
const exportEntries = isRecord(exportsValue) && Object.keys(exportsValue).some((exportKey) => exportKey.startsWith(".")) ? Object.entries(exportsValue) : [[".", exportsValue]];
|
|
2829
491
|
for (const [exportKey, target] of exportEntries) {
|
|
2830
492
|
const targets = [target];
|
|
2831
493
|
while (targets.length) {
|
|
@@ -2842,12 +504,28 @@ function collectPackageExportCandidates(packageName, exportsValue, packageRelati
|
|
|
2842
504
|
if (wildcard === void 0) continue;
|
|
2843
505
|
candidates.push(`${packageName}${exportKey.slice(1).replace("*", wildcard)}`);
|
|
2844
506
|
} else if (Array.isArray(value)) targets.push(...value);
|
|
2845
|
-
else if (
|
|
507
|
+
else if (isRecord(value)) targets.push(...Object.values(value));
|
|
2846
508
|
}
|
|
2847
509
|
}
|
|
2848
510
|
return candidates;
|
|
2849
511
|
}
|
|
2850
|
-
|
|
512
|
+
/**
|
|
513
|
+
* Resolves `specifier` from a resolveId hook without running that hook again. `flag` in `custom` also skips the hook in
|
|
514
|
+
* resolutions that other plugins start from this one. `skipSelf` is still needed: when two equal resolutions run at the
|
|
515
|
+
* same time, Rolldown 1.2 can give one of them no `custom`, and the hook would then wait on its own resolution.
|
|
516
|
+
*/
|
|
517
|
+
function resolveFrom(context, specifier, request, workingDir, flag) {
|
|
518
|
+
return context.resolve(specifier, importerFor(request.importer, workingDir), {
|
|
519
|
+
custom: {
|
|
520
|
+
...request.custom,
|
|
521
|
+
[flag]: true
|
|
522
|
+
},
|
|
523
|
+
isEntry: request.isEntry,
|
|
524
|
+
kind: request.kind,
|
|
525
|
+
skipSelf: true
|
|
526
|
+
});
|
|
527
|
+
}
|
|
528
|
+
function createResolvedAliasPlugin(aliases, aliasResolveDir, workingDir, resolveEntryPackageAliases = true) {
|
|
2851
529
|
const entries = Object.entries(aliases || {});
|
|
2852
530
|
if (!entries.length) return;
|
|
2853
531
|
const resolvedEntries = Promise.all(entries.map(async ([encodedSpecifier, replacement]) => {
|
|
@@ -2867,30 +545,39 @@ function createResolvedAliasPlugin(aliases, aliasResolveDir) {
|
|
|
2867
545
|
specifier: `${resolvedSpecifier}${prefix && !resolvedSpecifier.endsWith("/") ? "/" : ""}`
|
|
2868
546
|
};
|
|
2869
547
|
}));
|
|
548
|
+
const resolvedBareAliasPaths = /* @__PURE__ */ new Map();
|
|
2870
549
|
return {
|
|
2871
550
|
name: "vitehub-resolved-alias",
|
|
2872
|
-
|
|
2873
|
-
|
|
2874
|
-
|
|
2875
|
-
|
|
2876
|
-
|
|
2877
|
-
|
|
2878
|
-
|
|
2879
|
-
|
|
2880
|
-
|
|
2881
|
-
|
|
2882
|
-
|
|
2883
|
-
|
|
2884
|
-
|
|
2885
|
-
|
|
2886
|
-
|
|
2887
|
-
|
|
2888
|
-
|
|
2889
|
-
|
|
2890
|
-
|
|
2891
|
-
|
|
2892
|
-
|
|
2893
|
-
|
|
551
|
+
async resolveId(source, importer, extra) {
|
|
552
|
+
if (extra.custom?.[skipResolvedAlias]) return;
|
|
553
|
+
const request = {
|
|
554
|
+
custom: extra.custom,
|
|
555
|
+
importer,
|
|
556
|
+
isEntry: extra.isEntry,
|
|
557
|
+
kind: extra.kind
|
|
558
|
+
};
|
|
559
|
+
const resolveWithContext = (specifier) => resolveFrom(this, specifier, request, workingDir, skipResolvedAlias);
|
|
560
|
+
const resolveDir = importerDir(importer, workingDir);
|
|
561
|
+
const aliases = await resolvedEntries;
|
|
562
|
+
let match = aliases.find(({ prefix, specifier }) => isRelativeSpecifier(specifier) && (prefix ? source.startsWith(specifier) : source === specifier));
|
|
563
|
+
let matchedAlias = match?.specifier;
|
|
564
|
+
let matchedSpecifier = match ? source : void 0;
|
|
565
|
+
const specifier = isRelativeSpecifier(source) ? resolve(resolveDir, source) : source;
|
|
566
|
+
const normalizedSpecifier = isAbsolute(specifier) ? normalizePathSeparators(resolve(specifier)) : specifier;
|
|
567
|
+
let canonicalSpecifier = normalizedSpecifier;
|
|
568
|
+
const canonicalizeSpecifier = async () => {
|
|
569
|
+
canonicalSpecifier = normalizePathSeparators(await realpath(normalizedSpecifier).catch(() => normalizedSpecifier));
|
|
570
|
+
return canonicalSpecifier;
|
|
571
|
+
};
|
|
572
|
+
match ||= aliases.find(({ prefix, specifier }) => prefix ? normalizedSpecifier.startsWith(specifier) : normalizedSpecifier === specifier);
|
|
573
|
+
if (!match && isAbsolute(normalizedSpecifier) && aliases.some((alias) => isAbsolute(alias.specifier))) {
|
|
574
|
+
await canonicalizeSpecifier();
|
|
575
|
+
match = aliases.find(({ canonicalSpecifier: canonicalAlias, prefix }) => prefix ? canonicalSpecifier.startsWith(canonicalAlias) : canonicalSpecifier === canonicalAlias);
|
|
576
|
+
}
|
|
577
|
+
if (!match && (resolveEntryPackageAliases || !extra.isEntry) && isAbsolute(source)) {
|
|
578
|
+
const candidates = [];
|
|
579
|
+
for (const alias of aliases) {
|
|
580
|
+
if (isAbsolute(alias.specifier) || alias.prefix && alias.specifier.startsWith("#")) continue;
|
|
2894
581
|
const packageAlias = alias.prefix ? alias.specifier.replace(/\/$/, "") : alias.specifier;
|
|
2895
582
|
const aliasSegments = packageAlias.split("/");
|
|
2896
583
|
if (!alias.prefix && aliasSegments.length === 1 && packageAlias.startsWith("@")) continue;
|
|
@@ -2903,40 +590,31 @@ function createResolvedAliasPlugin(aliases, aliasResolveDir) {
|
|
|
2903
590
|
}
|
|
2904
591
|
const packageMarker = `/node_modules/${packageName}/`;
|
|
2905
592
|
const packageMarkerIndex = normalizedSpecifier.lastIndexOf(packageMarker);
|
|
593
|
+
if (alias.prefix && packageMarkerIndex === -1 && !isRelativeSpecifier(alias.specifier)) continue;
|
|
2906
594
|
const resolutionScope = packageMarkerIndex === -1 ? "" : normalizedSpecifier.slice(0, packageMarkerIndex + packageMarker.length);
|
|
2907
595
|
const cacheKey = [
|
|
2908
596
|
alias.specifier,
|
|
2909
597
|
alias.prefix,
|
|
2910
598
|
resolutionScope,
|
|
2911
|
-
|
|
2912
|
-
|
|
2913
|
-
|
|
2914
|
-
|
|
2915
|
-
JSON.stringify(args.with)
|
|
599
|
+
normalizedSpecifier,
|
|
600
|
+
importer,
|
|
601
|
+
extra.kind,
|
|
602
|
+
extra.isEntry
|
|
2916
603
|
].join("\0");
|
|
2917
|
-
|
|
604
|
+
const cacheable = !extra.custom || !Object.keys(extra.custom).length;
|
|
605
|
+
let resolution = cacheable ? resolvedBareAliasPaths.get(cacheKey) : void 0;
|
|
2918
606
|
if (!resolution) {
|
|
2919
607
|
resolution = (async () => {
|
|
2920
608
|
let resolvedAliasPath;
|
|
2921
|
-
if (alias.prefix &&
|
|
609
|
+
if (alias.prefix && isRelativeSpecifier(alias.specifier)) resolvedAliasPath = normalizePathSeparators(resolve(aliasResolveDir, alias.specifier));
|
|
2922
610
|
else if (resolutionScope) {
|
|
2923
611
|
const packageRelativePath = normalizedSpecifier.slice(resolutionScope.length);
|
|
2924
612
|
const parsedPackageJson = JSON.parse(await readFile(resolve(resolutionScope, "package.json"), "utf8"));
|
|
2925
|
-
if (!
|
|
613
|
+
if (!isRecord(parsedPackageJson)) return;
|
|
2926
614
|
const packageJson = parsedPackageJson;
|
|
2927
615
|
if (packageJson.exports === void 0 && !alias.prefix) {
|
|
2928
|
-
const resolvedCandidate = await
|
|
2929
|
-
|
|
2930
|
-
kind: args.kind,
|
|
2931
|
-
namespace: args.namespace,
|
|
2932
|
-
pluginData: {
|
|
2933
|
-
...args.pluginData,
|
|
2934
|
-
[skipResolvedAlias]: true
|
|
2935
|
-
},
|
|
2936
|
-
resolveDir: args.resolveDir,
|
|
2937
|
-
with: args.with
|
|
2938
|
-
});
|
|
2939
|
-
if (!resolvedCandidate.errors.length && !resolvedCandidate.external && resolvedCandidate.namespace === "file" && normalizePathSeparators(resolve(resolvedCandidate.path)) === normalizedSpecifier) return {
|
|
616
|
+
const resolvedCandidate = await resolveWithContext(alias.specifier);
|
|
617
|
+
if (isFileResolution(resolvedCandidate) && normalizePathSeparators(resolve(resolvedCandidate.id)) === normalizedSpecifier) return {
|
|
2940
618
|
canonical: alias.specifier,
|
|
2941
619
|
normalized: alias.specifier,
|
|
2942
620
|
publicSpecifier: alias.specifier
|
|
@@ -2945,19 +623,9 @@ function createResolvedAliasPlugin(aliases, aliasResolveDir) {
|
|
|
2945
623
|
}
|
|
2946
624
|
const matchingPublicSpecifiers = /* @__PURE__ */ new Set();
|
|
2947
625
|
for (const publicSpecifier of collectPackageExportCandidates(packageName, packageJson.exports, packageRelativePath)) {
|
|
2948
|
-
const resolvedCandidate = await
|
|
2949
|
-
|
|
2950
|
-
|
|
2951
|
-
namespace: args.namespace,
|
|
2952
|
-
pluginData: {
|
|
2953
|
-
...args.pluginData,
|
|
2954
|
-
[skipResolvedAlias]: true
|
|
2955
|
-
},
|
|
2956
|
-
resolveDir: args.resolveDir,
|
|
2957
|
-
with: args.with
|
|
2958
|
-
});
|
|
2959
|
-
if (resolvedCandidate.errors.length || resolvedCandidate.external || resolvedCandidate.namespace !== "file") continue;
|
|
2960
|
-
if (normalizePathSeparators(resolve(resolvedCandidate.path)) !== normalizedSpecifier) continue;
|
|
626
|
+
const resolvedCandidate = await resolveWithContext(publicSpecifier);
|
|
627
|
+
if (!isFileResolution(resolvedCandidate)) continue;
|
|
628
|
+
if (normalizePathSeparators(resolve(resolvedCandidate.id)) !== normalizedSpecifier) continue;
|
|
2961
629
|
matchingPublicSpecifiers.add(publicSpecifier);
|
|
2962
630
|
}
|
|
2963
631
|
if (matchingPublicSpecifiers.size === 1) {
|
|
@@ -2970,19 +638,9 @@ function createResolvedAliasPlugin(aliases, aliasResolveDir) {
|
|
|
2970
638
|
}
|
|
2971
639
|
return;
|
|
2972
640
|
} else {
|
|
2973
|
-
const resolvedAlias = await
|
|
2974
|
-
|
|
2975
|
-
|
|
2976
|
-
namespace: args.namespace,
|
|
2977
|
-
pluginData: {
|
|
2978
|
-
...args.pluginData,
|
|
2979
|
-
[skipResolvedAlias]: true
|
|
2980
|
-
},
|
|
2981
|
-
resolveDir: args.resolveDir,
|
|
2982
|
-
with: args.with
|
|
2983
|
-
});
|
|
2984
|
-
if (resolvedAlias.errors.length || resolvedAlias.external || resolvedAlias.namespace !== "file") return;
|
|
2985
|
-
resolvedAliasPath = normalizePathSeparators(resolve(resolvedAlias.path));
|
|
641
|
+
const resolvedAlias = await resolveWithContext(alias.specifier);
|
|
642
|
+
if (!isFileResolution(resolvedAlias)) return;
|
|
643
|
+
resolvedAliasPath = normalizePathSeparators(resolve(resolvedAlias.id));
|
|
2986
644
|
}
|
|
2987
645
|
const canonicalAliasPath = normalizePathSeparators(await realpath(resolvedAliasPath).catch(() => resolvedAliasPath));
|
|
2988
646
|
return {
|
|
@@ -2990,8 +648,15 @@ function createResolvedAliasPlugin(aliases, aliasResolveDir) {
|
|
|
2990
648
|
normalized: `${resolvedAliasPath}${alias.prefix && !resolvedAliasPath.endsWith("/") ? "/" : ""}`
|
|
2991
649
|
};
|
|
2992
650
|
})();
|
|
2993
|
-
if (
|
|
651
|
+
if (cacheable) resolvedBareAliasPaths.set(cacheKey, resolution);
|
|
2994
652
|
}
|
|
653
|
+
candidates.push({
|
|
654
|
+
alias,
|
|
655
|
+
resolution
|
|
656
|
+
});
|
|
657
|
+
}
|
|
658
|
+
await Promise.allSettled(candidates.map((candidate) => candidate.resolution));
|
|
659
|
+
for (const { alias, resolution } of candidates) {
|
|
2995
660
|
const paths = await resolution;
|
|
2996
661
|
if (!paths) continue;
|
|
2997
662
|
if (paths.publicSpecifier) {
|
|
@@ -3013,59 +678,42 @@ function createResolvedAliasPlugin(aliases, aliasResolveDir) {
|
|
|
3013
678
|
break;
|
|
3014
679
|
}
|
|
3015
680
|
}
|
|
3016
|
-
|
|
3017
|
-
|
|
3018
|
-
|
|
3019
|
-
|
|
3020
|
-
|
|
3021
|
-
|
|
3022
|
-
|
|
3023
|
-
|
|
3024
|
-
|
|
3025
|
-
|
|
3026
|
-
pluginData: {
|
|
3027
|
-
...args.pluginData,
|
|
3028
|
-
[skipResolvedAlias]: true
|
|
3029
|
-
},
|
|
3030
|
-
resolveDir: args.resolveDir,
|
|
3031
|
-
with: args.with
|
|
3032
|
-
});
|
|
3033
|
-
});
|
|
681
|
+
}
|
|
682
|
+
matchedAlias ||= match && canonicalSpecifier.startsWith(match.canonicalSpecifier) ? match.canonicalSpecifier : match?.specifier;
|
|
683
|
+
matchedSpecifier ||= matchedAlias === match?.canonicalSpecifier ? canonicalSpecifier : normalizedSpecifier;
|
|
684
|
+
if (!match) return;
|
|
685
|
+
const target = match.prefix ? matchedSpecifier.replace(matchedAlias.slice(0, -1), match.replacement.slice(0, -1)) : matchedSpecifier.replace(matchedAlias, match.replacement);
|
|
686
|
+
if (!target) return;
|
|
687
|
+
const resolvedTarget = isRelativeSpecifier(target) ? resolve(aliasResolveDir, target) : target;
|
|
688
|
+
const resolved = await resolveWithContext(resolvedTarget);
|
|
689
|
+
if (!resolved) this.error(`[vitehub] Could not resolve ${JSON.stringify(resolvedTarget)}, the alias of ${JSON.stringify(source)}.`);
|
|
690
|
+
return resolved;
|
|
3034
691
|
}
|
|
3035
692
|
};
|
|
3036
693
|
}
|
|
3037
|
-
function createViteAliasPlugin(aliases) {
|
|
694
|
+
function createViteAliasPlugin(aliases, workingDir) {
|
|
3038
695
|
if (!Array.isArray(aliases)) return;
|
|
3039
|
-
const resolvingAlias = "vitehubResolvingAlias";
|
|
3040
696
|
return {
|
|
3041
697
|
name: "vitehub-vite-alias",
|
|
3042
|
-
|
|
3043
|
-
|
|
3044
|
-
|
|
3045
|
-
|
|
3046
|
-
|
|
3047
|
-
|
|
3048
|
-
return find.test(args.path);
|
|
3049
|
-
});
|
|
3050
|
-
if (!alias) return;
|
|
3051
|
-
if (alias.customResolver) return { errors: [{ text: `[vitehub] Deno Schedule output cannot stage the Vite alias ${JSON.stringify(args.path)} because it uses customResolver.` }] };
|
|
3052
|
-
if (alias.find instanceof RegExp) alias.find.lastIndex = 0;
|
|
3053
|
-
const replacement = typeof alias.find === "string" ? `${alias.replacement}${args.path.slice(alias.find.length)}` : args.path.replace(alias.find, alias.replacement);
|
|
3054
|
-
const result = await build.resolve(replacement, {
|
|
3055
|
-
importer: args.importer,
|
|
3056
|
-
kind: args.kind,
|
|
3057
|
-
namespace: args.namespace,
|
|
3058
|
-
pluginData: Object.assign({}, args.pluginData && typeof args.pluginData === "object" ? args.pluginData : {}, { [resolvingAlias]: true }),
|
|
3059
|
-
resolveDir: args.resolveDir,
|
|
3060
|
-
with: args.with
|
|
3061
|
-
});
|
|
3062
|
-
const pluginData = Object.assign({}, result.pluginData);
|
|
3063
|
-
Reflect.deleteProperty(pluginData, resolvingAlias);
|
|
3064
|
-
return {
|
|
3065
|
-
...result,
|
|
3066
|
-
pluginData
|
|
3067
|
-
};
|
|
698
|
+
async resolveId(source, importer, extra) {
|
|
699
|
+
if (extra.custom?.[resolvingViteAlias]) return;
|
|
700
|
+
const alias = aliases.find(({ find }) => {
|
|
701
|
+
if (typeof find === "string") return source === find || source.startsWith(`${find}/`);
|
|
702
|
+
find.lastIndex = 0;
|
|
703
|
+
return find.test(source);
|
|
3068
704
|
});
|
|
705
|
+
if (!alias) return;
|
|
706
|
+
if (alias.customResolver) this.error(`[vitehub] Deno Schedule output cannot stage the Vite alias ${JSON.stringify(source)} because it uses customResolver.`);
|
|
707
|
+
if (alias.find instanceof RegExp) alias.find.lastIndex = 0;
|
|
708
|
+
const replacement = typeof alias.find === "string" ? `${alias.replacement}${source.slice(alias.find.length)}` : source.replace(alias.find, alias.replacement);
|
|
709
|
+
const resolved = await resolveFrom(this, replacement, {
|
|
710
|
+
custom: extra.custom,
|
|
711
|
+
importer,
|
|
712
|
+
isEntry: extra.isEntry,
|
|
713
|
+
kind: extra.kind
|
|
714
|
+
}, workingDir, resolvingViteAlias);
|
|
715
|
+
if (!resolved) this.error(`[vitehub] Could not resolve ${JSON.stringify(replacement)}, the alias of ${JSON.stringify(source)}.`);
|
|
716
|
+
return resolved;
|
|
3069
717
|
}
|
|
3070
718
|
};
|
|
3071
719
|
}
|
|
@@ -3104,153 +752,255 @@ async function resolveViteRawSpecifier(path, rootDir) {
|
|
|
3104
752
|
return resolve(rootDir, rootRelativePath);
|
|
3105
753
|
}
|
|
3106
754
|
}
|
|
3107
|
-
function createViteRawPlugin(rootDir, frameworkRuntime) {
|
|
755
|
+
function createViteRawPlugin(rootDir, frameworkRuntime, workingDir) {
|
|
3108
756
|
return {
|
|
3109
757
|
name: "vitehub-vite-raw",
|
|
3110
|
-
|
|
3111
|
-
|
|
3112
|
-
|
|
3113
|
-
|
|
3114
|
-
|
|
3115
|
-
|
|
3116
|
-
return build.resolve("vite-hub/_internal/markdown-template", {
|
|
3117
|
-
importer: args.importer,
|
|
3118
|
-
kind: args.kind,
|
|
3119
|
-
resolveDir: args.resolveDir
|
|
3120
|
-
});
|
|
3121
|
-
});
|
|
3122
|
-
build.onResolve({ filter: /\?|\.template\.md$/ }, async (args) => {
|
|
3123
|
-
if (args.pluginData?.[skipMarkdownTemplateResolve]) return;
|
|
3124
|
-
const markdownTemplate = parseMarkdownTemplateRequest(args.path);
|
|
3125
|
-
const raw = hasViteRawQuery(args.path);
|
|
3126
|
-
if (!markdownTemplate && !raw) return;
|
|
3127
|
-
const specifier = await resolveViteRawSpecifier(markdownTemplate?.path ?? args.path.slice(0, args.path.indexOf("?")), rootDir);
|
|
3128
|
-
let pluginData = args.pluginData;
|
|
3129
|
-
if (markdownTemplate) pluginData = {
|
|
3130
|
-
...args.pluginData,
|
|
3131
|
-
[skipMarkdownTemplateResolve]: true
|
|
3132
|
-
};
|
|
3133
|
-
const resolved = await build.resolve(specifier, {
|
|
3134
|
-
importer: args.importer,
|
|
3135
|
-
kind: args.kind,
|
|
3136
|
-
namespace: args.namespace,
|
|
3137
|
-
pluginData,
|
|
3138
|
-
resolveDir: args.resolveDir,
|
|
3139
|
-
with: args.with
|
|
758
|
+
async resolveId(source, importer, extra) {
|
|
759
|
+
if (source === markdownTemplateRuntimeSpecifier && importer?.startsWith(markdownTemplatePrefix)) {
|
|
760
|
+
if (!frameworkRuntime) return fileURLToPath(import.meta.resolve(markdownTemplateRuntimeSpecifier));
|
|
761
|
+
return await this.resolve("vite-hub/markdown-template", importer.slice(27), {
|
|
762
|
+
custom: extra.custom,
|
|
763
|
+
kind: extra.kind
|
|
3140
764
|
});
|
|
3141
|
-
|
|
3142
|
-
|
|
3143
|
-
|
|
3144
|
-
|
|
3145
|
-
|
|
3146
|
-
|
|
3147
|
-
|
|
3148
|
-
|
|
3149
|
-
|
|
3150
|
-
|
|
3151
|
-
|
|
3152
|
-
|
|
3153
|
-
|
|
3154
|
-
|
|
3155
|
-
|
|
3156
|
-
|
|
3157
|
-
|
|
3158
|
-
|
|
3159
|
-
|
|
3160
|
-
|
|
3161
|
-
|
|
3162
|
-
|
|
3163
|
-
|
|
3164
|
-
|
|
3165
|
-
|
|
3166
|
-
}
|
|
3167
|
-
|
|
3168
|
-
|
|
3169
|
-
|
|
3170
|
-
}
|
|
3171
|
-
contents: await readFile(args.path),
|
|
3172
|
-
loader: "text"
|
|
3173
|
-
}));
|
|
3174
|
-
build.onLoad({
|
|
3175
|
-
filter: /.*/,
|
|
3176
|
-
namespace: viteMarkdownTemplateNamespace
|
|
3177
|
-
}, async (args) => ({
|
|
3178
|
-
contents: renderMarkdownTemplateModule(await readFile(args.path, "utf8")),
|
|
3179
|
-
loader: "js",
|
|
3180
|
-
resolveDir: dirname(args.path)
|
|
3181
|
-
}));
|
|
765
|
+
}
|
|
766
|
+
if (extra.custom?.[skipMarkdownTemplateResolve]) return;
|
|
767
|
+
const markdownTemplate = parseMarkdownTemplateRequest(source);
|
|
768
|
+
const raw = hasViteRawQuery(source);
|
|
769
|
+
if (!markdownTemplate && !raw) return;
|
|
770
|
+
const specifier = await resolveViteRawSpecifier(markdownTemplate?.path ?? source.slice(0, source.indexOf("?")), rootDir);
|
|
771
|
+
const resolved = await resolveFrom(this, specifier, {
|
|
772
|
+
custom: extra.custom,
|
|
773
|
+
importer,
|
|
774
|
+
isEntry: extra.isEntry,
|
|
775
|
+
kind: extra.kind
|
|
776
|
+
}, workingDir, skipMarkdownTemplateResolve);
|
|
777
|
+
if (!resolved) this.error(`[vitehub] Could not resolve ${JSON.stringify(specifier)}, imported as ${JSON.stringify(source)}.`);
|
|
778
|
+
if (resolved.external) return {
|
|
779
|
+
id: resolved.id,
|
|
780
|
+
external: resolved.external
|
|
781
|
+
};
|
|
782
|
+
const resolvedId = resolved.id;
|
|
783
|
+
if (!isFileResolution(resolved)) this.error(markdownTemplate ? `[vitehub] Markdown template fallback cannot load ${JSON.stringify(source)} from the virtual module ${JSON.stringify(resolvedId)}. Handle this template import in a caller plugin.` : `[vitehub] Vite raw fallback cannot load ${JSON.stringify(source)} from the virtual module ${JSON.stringify(resolvedId)}. Handle this raw import in a caller plugin.`);
|
|
784
|
+
return `${markdownTemplate ? markdownTemplatePrefix : viteRawPrefix}${resolvedId}`;
|
|
785
|
+
},
|
|
786
|
+
async load(id) {
|
|
787
|
+
if (id.startsWith(viteRawPrefix)) return {
|
|
788
|
+
code: await readFile(id.slice(18), "utf8"),
|
|
789
|
+
moduleType: "text"
|
|
790
|
+
};
|
|
791
|
+
if (id.startsWith(markdownTemplatePrefix)) return {
|
|
792
|
+
code: renderMarkdownTemplateModule(await readFile(id.slice(27), "utf8")),
|
|
793
|
+
moduleType: "js"
|
|
794
|
+
};
|
|
3182
795
|
}
|
|
3183
796
|
};
|
|
3184
797
|
}
|
|
3185
|
-
/** Select the runtime constants from one resolved Vite configuration. */
|
|
3186
|
-
function resolveViteHubBundleDefines(config) {
|
|
3187
|
-
const defines = {};
|
|
3188
|
-
for (const name of ["__VITEHUB_PUBLIC_URL__", "__VITEHUB_APP_BASE_URL__"]) {
|
|
3189
|
-
const value = config.define?.[name];
|
|
3190
|
-
if (typeof value === "string") defines[name] = value;
|
|
3191
|
-
}
|
|
3192
|
-
return defines;
|
|
3193
|
-
}
|
|
3194
798
|
function createFileUrlPlugin() {
|
|
3195
799
|
return {
|
|
3196
800
|
name: "vitehub-file-url",
|
|
3197
|
-
|
|
3198
|
-
|
|
801
|
+
resolveId(source) {
|
|
802
|
+
if (source.startsWith("file:")) return fileURLToPath(source);
|
|
803
|
+
}
|
|
804
|
+
};
|
|
805
|
+
}
|
|
806
|
+
/**
|
|
807
|
+
* Copies a `.wasm?module` import next to the bundle and keeps it as a relative `.wasm` import. Wrangler and Nitro load
|
|
808
|
+
* such an import as a compiled WebAssembly module, which Workers need because they can't compile WebAssembly bytes.
|
|
809
|
+
* Node.js compiles WebAssembly bytes, so there the import becomes the bytes of the file.
|
|
810
|
+
*/
|
|
811
|
+
function createWasmModulePlugin(outdir, workingDir, copy) {
|
|
812
|
+
return {
|
|
813
|
+
name: "vitehub-wasm-module",
|
|
814
|
+
async resolveId(source, importer, extra) {
|
|
815
|
+
if (!source.endsWith(".wasm?module")) return;
|
|
816
|
+
const resolved = await this.resolve(source.slice(0, -7), importerFor(importer, workingDir), {
|
|
817
|
+
custom: extra.custom,
|
|
818
|
+
kind: extra.kind
|
|
819
|
+
});
|
|
820
|
+
if (!isFileResolution(resolved)) this.error(`[vitehub] Could not resolve ${JSON.stringify(source)}.`);
|
|
821
|
+
if (!copy) return resolved.id;
|
|
822
|
+
const bytes = await readFile(resolved.id);
|
|
823
|
+
const name = `${basename(resolved.id, ".wasm")}-${createHash("sha256").update(bytes).digest("hex").slice(0, 8)}.wasm`;
|
|
824
|
+
await mkdir(outdir, { recursive: true });
|
|
825
|
+
await copyFile(resolved.id, join(outdir, name));
|
|
826
|
+
return {
|
|
827
|
+
id: `./${name}`,
|
|
828
|
+
external: true
|
|
829
|
+
};
|
|
830
|
+
}
|
|
831
|
+
};
|
|
832
|
+
}
|
|
833
|
+
/**
|
|
834
|
+
* Leaves package imports external. Resolve package.json import mappings first, and preserve unmapped host imports.
|
|
835
|
+
*/
|
|
836
|
+
function createExternalPackagesPlugin() {
|
|
837
|
+
return {
|
|
838
|
+
name: "vitehub-external-packages",
|
|
839
|
+
async resolveId(source, importer, extra) {
|
|
840
|
+
if (source.startsWith("npm:") || source.startsWith("jsr:")) return {
|
|
841
|
+
id: source,
|
|
842
|
+
external: true
|
|
843
|
+
};
|
|
844
|
+
if (source.startsWith("#")) return await this.resolve(source, importer, {
|
|
845
|
+
custom: extra.custom,
|
|
846
|
+
kind: extra.kind
|
|
847
|
+
}) ?? {
|
|
848
|
+
id: source,
|
|
849
|
+
external: true
|
|
850
|
+
};
|
|
851
|
+
if (isBareSpecifier(source) && !isBuiltin(source)) return {
|
|
852
|
+
id: source,
|
|
853
|
+
external: true
|
|
854
|
+
};
|
|
855
|
+
}
|
|
856
|
+
};
|
|
857
|
+
}
|
|
858
|
+
function hasImportRejectionHandler(importNode, parents) {
|
|
859
|
+
let expression = importNode;
|
|
860
|
+
let parent = parents.get(expression);
|
|
861
|
+
while (parent?.type === "MemberExpression" && parent.object === expression) {
|
|
862
|
+
const call = parents.get(parent);
|
|
863
|
+
if (call?.type !== "CallExpression" || call.callee !== parent) break;
|
|
864
|
+
const method = parent.property.type === "Identifier" && !parent.computed ? parent.property.name : parent.property.type === "Literal" ? parent.property.value : void 0;
|
|
865
|
+
const handler = call.arguments[method === "then" ? 1 : 0];
|
|
866
|
+
if ((method === "then" || method === "catch") && handler && handler.type !== "SpreadElement") {
|
|
867
|
+
if (handler.type !== "Literal" && !(handler.type === "Identifier" && handler.name === "undefined")) return true;
|
|
868
|
+
}
|
|
869
|
+
if (method !== "then" && method !== "finally") break;
|
|
870
|
+
expression = call;
|
|
871
|
+
parent = parents.get(expression);
|
|
872
|
+
}
|
|
873
|
+
if (parent?.type !== "AwaitExpression") return false;
|
|
874
|
+
for (let child = parent, ancestor = parents.get(child); ancestor; ancestor = parents.get(child)) {
|
|
875
|
+
if (ancestor.type === "TryStatement" && ancestor.block === child && ancestor.handler) return true;
|
|
876
|
+
if (ancestor.type === "ArrowFunctionExpression" || ancestor.type === "FunctionExpression" || ancestor.type === "FunctionDeclaration") break;
|
|
877
|
+
child = ancestor;
|
|
878
|
+
}
|
|
879
|
+
return false;
|
|
880
|
+
}
|
|
881
|
+
function createOptionalImportPlugin() {
|
|
882
|
+
const prefix = "\0vitehub-optional-import:";
|
|
883
|
+
return {
|
|
884
|
+
name: "vitehub-optional-import",
|
|
885
|
+
resolveId(source) {
|
|
886
|
+
if (source.startsWith(prefix)) return {
|
|
887
|
+
id: source.slice(25),
|
|
888
|
+
external: "absolute"
|
|
889
|
+
};
|
|
890
|
+
},
|
|
891
|
+
transform: {
|
|
892
|
+
order: "post",
|
|
893
|
+
filter: { code: /\bimport\s*(?:\(|\/)/ },
|
|
894
|
+
async handler(code, id) {
|
|
895
|
+
const { parseSync } = await import("vite");
|
|
896
|
+
const module = parseSync(id, code, {
|
|
897
|
+
lang: moduleLanguage(id),
|
|
898
|
+
preserveParens: false,
|
|
899
|
+
sourceType: "module"
|
|
900
|
+
});
|
|
901
|
+
if (module.errors.length) return;
|
|
902
|
+
const parents = /* @__PURE__ */ new WeakMap();
|
|
903
|
+
const handled = [];
|
|
904
|
+
walk(module.program, (node, parent) => {
|
|
905
|
+
if (parent) parents.set(node, parent);
|
|
906
|
+
if (node.type !== "ImportExpression" || node.source.type !== "Literal" || typeof node.source.value !== "string") return;
|
|
907
|
+
if (hasImportRejectionHandler(node, parents)) handled.push({
|
|
908
|
+
source: node.source.value,
|
|
909
|
+
start: node.source.start,
|
|
910
|
+
end: node.source.end
|
|
911
|
+
});
|
|
912
|
+
});
|
|
913
|
+
if (!handled.length) return;
|
|
914
|
+
const resolved = await Promise.all(handled.map(({ source }) => this.resolve(source, id, { kind: "dynamic-import" })));
|
|
915
|
+
for (const [index, { source, start, end }] of [...handled.entries()].reverse()) if (!resolved[index]) code = code.slice(0, start) + JSON.stringify(prefix + source) + code.slice(end);
|
|
916
|
+
return code;
|
|
917
|
+
}
|
|
3199
918
|
}
|
|
3200
919
|
};
|
|
3201
920
|
}
|
|
921
|
+
/** Matches import paths as esbuild's `external` does: `*` is a wildcard, and a package name also matches its subpaths. */
|
|
922
|
+
function createExternalMatcher(patterns) {
|
|
923
|
+
if (!patterns?.length) return;
|
|
924
|
+
const matchers = patterns.map((pattern) => {
|
|
925
|
+
if (pattern.includes("*")) {
|
|
926
|
+
const expression = new RegExp(`^${pattern.split("*").map(escapeRegExp).join(".*")}$`);
|
|
927
|
+
return (id) => expression.test(id);
|
|
928
|
+
}
|
|
929
|
+
return isBareSpecifier(pattern) ? (id) => id === pattern || id.startsWith(`${pattern}/`) : (id) => id === pattern;
|
|
930
|
+
});
|
|
931
|
+
return (id) => matchers.some((matches) => matches(id));
|
|
932
|
+
}
|
|
3202
933
|
async function bundleEsmEntry(entryFile, outfile, options = {}) {
|
|
934
|
+
const { rolldown } = await importRolldown();
|
|
3203
935
|
options.signal?.throwIfAborted();
|
|
3204
936
|
const format = options.format || "esm";
|
|
3205
937
|
const platform = options.platform || "neutral";
|
|
3206
|
-
const
|
|
938
|
+
const workingDir = options.workingDir ?? process.cwd();
|
|
3207
939
|
const frameworkRuntime = (Array.isArray(options.alias) ? options.alias.flatMap((alias) => typeof alias.find === "string" ? [alias.find] : []) : Object.keys(options.alias || {})).some((specifier) => specifier === "vite-hub" || specifier.startsWith("vite-hub/"));
|
|
3208
940
|
const plugins = [];
|
|
3209
|
-
|
|
941
|
+
plugins.push(createWasmModulePlugin(dirname(outfile), workingDir, platform !== "node"));
|
|
942
|
+
const resolvedAliasPlugin = createResolvedAliasPlugin(Array.isArray(options.alias) ? void 0 : options.alias, options.workingDir ?? options.rootDir ?? process.cwd(), workingDir, options.resolveEntryPackageAliases);
|
|
3210
943
|
if (resolvedAliasPlugin) plugins.push(resolvedAliasPlugin);
|
|
3211
944
|
plugins.push(...options.plugins ?? [], createFileUrlPlugin());
|
|
945
|
+
const viteAliasPlugin = createViteAliasPlugin(options.alias, workingDir);
|
|
3212
946
|
if (viteAliasPlugin) plugins.push(viteAliasPlugin);
|
|
3213
|
-
plugins.push(createViteRawPlugin(options.rootDir, frameworkRuntime));
|
|
3214
|
-
|
|
3215
|
-
|
|
3216
|
-
|
|
3217
|
-
|
|
3218
|
-
|
|
3219
|
-
|
|
3220
|
-
|
|
3221
|
-
|
|
3222
|
-
|
|
3223
|
-
|
|
3224
|
-
|
|
3225
|
-
|
|
3226
|
-
|
|
3227
|
-
|
|
3228
|
-
|
|
3229
|
-
|
|
3230
|
-
|
|
3231
|
-
|
|
3232
|
-
|
|
3233
|
-
|
|
3234
|
-
|
|
3235
|
-
|
|
3236
|
-
|
|
3237
|
-
packages: options.packages,
|
|
947
|
+
plugins.push(createViteRawPlugin(options.rootDir, frameworkRuntime, workingDir));
|
|
948
|
+
if (options.packages === "external") plugins.push(createExternalPackagesPlugin());
|
|
949
|
+
plugins.push(createOptionalImportPlugin());
|
|
950
|
+
const isExternal = createExternalMatcher(options.external);
|
|
951
|
+
const minify = options.minifyIdentifiers || options.minifySyntax || options.minifyWhitespace ? {
|
|
952
|
+
compress: options.minifySyntax ?? false,
|
|
953
|
+
mangle: options.minifyIdentifiers ? { toplevel: true } : false,
|
|
954
|
+
codegen: { removeWhitespace: options.minifyWhitespace ?? false }
|
|
955
|
+
} : false;
|
|
956
|
+
const banner = [options.banner, ...format === "esm" && platform === "node" ? [
|
|
957
|
+
"if (globalThis.process?.getBuiltinModule && import.meta.url) {",
|
|
958
|
+
" globalThis.require = globalThis.process.getBuiltinModule(\"node:module\").createRequire(import.meta.url);",
|
|
959
|
+
" globalThis.__filename = globalThis.process.getBuiltinModule(\"node:url\").fileURLToPath(import.meta.url);",
|
|
960
|
+
" globalThis.__dirname = globalThis.process.getBuiltinModule(\"node:path\").dirname(globalThis.__filename);",
|
|
961
|
+
"}"
|
|
962
|
+
] : []].filter(Boolean).join("\n");
|
|
963
|
+
const bundle = await rolldown({
|
|
964
|
+
cwd: workingDir,
|
|
965
|
+
external: isExternal ? (id) => isExternal(id) : void 0,
|
|
966
|
+
input: entryFile,
|
|
967
|
+
onLog(level, log) {
|
|
968
|
+
if (log.code === "UNRESOLVED_IMPORT") throw Object.assign(new Error(log.message), { code: log.code });
|
|
969
|
+
},
|
|
970
|
+
moduleTypes: platform === "node" ? { ".wasm": "binary" } : void 0,
|
|
3238
971
|
platform,
|
|
3239
|
-
preserveSymlinks: options.preserveSymlinks,
|
|
3240
972
|
plugins,
|
|
3241
|
-
|
|
3242
|
-
|
|
3243
|
-
|
|
973
|
+
resolve: {
|
|
974
|
+
conditionNames: options.conditions ?? (platform === "node" ? ["node"] : void 0),
|
|
975
|
+
extensions: options.extensions,
|
|
976
|
+
mainFields: options.mainFields ?? (platform === "neutral" ? ["module", "main"] : void 0),
|
|
977
|
+
symlinks: !options.preserveSymlinks
|
|
978
|
+
},
|
|
979
|
+
transform: {
|
|
980
|
+
define: options.define,
|
|
981
|
+
target: "es2022"
|
|
982
|
+
},
|
|
983
|
+
tsconfig: options.tsconfig ?? true
|
|
3244
984
|
});
|
|
3245
|
-
|
|
3246
|
-
|
|
3247
|
-
|
|
3248
|
-
|
|
3249
|
-
|
|
3250
|
-
|
|
3251
|
-
|
|
3252
|
-
|
|
985
|
+
let output;
|
|
986
|
+
try {
|
|
987
|
+
output = (await bundle.generate({
|
|
988
|
+
banner: banner || void 0,
|
|
989
|
+
codeSplitting: false,
|
|
990
|
+
format,
|
|
991
|
+
keepNames: options.keepNames ?? Boolean(options.minifySyntax || options.minifyIdentifiers),
|
|
992
|
+
minify,
|
|
993
|
+
polyfillRequire: !(format === "esm" && platform === "node"),
|
|
994
|
+
sourcemap: false
|
|
995
|
+
})).output;
|
|
996
|
+
} finally {
|
|
997
|
+
await bundle.close();
|
|
3253
998
|
}
|
|
999
|
+
options.signal?.throwIfAborted();
|
|
1000
|
+
const chunk = output.find((file) => file.type === "chunk");
|
|
1001
|
+
await mkdir(dirname(outfile), { recursive: true });
|
|
1002
|
+
await writeFile(outfile, chunk.code, { signal: options.signal });
|
|
1003
|
+
options.signal?.throwIfAborted();
|
|
3254
1004
|
}
|
|
3255
1005
|
//#endregion
|
|
3256
1006
|
//#region ../internal/src/build/provider-output-sources.ts
|
|
@@ -3278,7 +1028,7 @@ function createNodeFunctionConfig(extra = {}) {
|
|
|
3278
1028
|
return {
|
|
3279
1029
|
handler: "index.mjs",
|
|
3280
1030
|
launcherType: "Nodejs",
|
|
3281
|
-
runtime: "
|
|
1031
|
+
runtime: "nodejs24.x",
|
|
3282
1032
|
shouldAddHelpers: false,
|
|
3283
1033
|
supportsResponseStreaming: true,
|
|
3284
1034
|
...extra
|
|
@@ -3347,13 +1097,6 @@ var ProviderOutputCatalog = class {
|
|
|
3347
1097
|
if (owner) this.#runtimeContributions.delete(owner);
|
|
3348
1098
|
else this.#runtimeContributions.clear();
|
|
3349
1099
|
}
|
|
3350
|
-
resetRuntimeContribution(product, generation) {
|
|
3351
|
-
if (!generation) {
|
|
3352
|
-
this.#runtimeContributions.delete(product);
|
|
3353
|
-
return;
|
|
3354
|
-
}
|
|
3355
|
-
this.#runtimeContributionsByGeneration.get(generation)?.delete(product);
|
|
3356
|
-
}
|
|
3357
1100
|
createDeploymentGeneration() {
|
|
3358
1101
|
const generation = { valid: true };
|
|
3359
1102
|
this.#trackDeploymentGeneration(generation);
|
|
@@ -3558,7 +1301,7 @@ function createDefaultCloudflareStaticOutputDir(rootDir) {
|
|
|
3558
1301
|
return resolve(rootDir, "dist", "client");
|
|
3559
1302
|
}
|
|
3560
1303
|
function resolveProviderOutputOwnershipFile(outputRoot, fileName) {
|
|
3561
|
-
if (!fileName || fileName.includes("/") || fileName.includes("\\") || fileName === "." || fileName === "..") throw
|
|
1304
|
+
if (!fileName || fileName.includes("/") || fileName.includes("\\") || fileName === "." || fileName === "..") throw invariantError(`ViteHub packages pass a plain Provider Output ownership file name (${JSON.stringify(fileName)})`);
|
|
3562
1305
|
return resolve(outputRoot, fileName);
|
|
3563
1306
|
}
|
|
3564
1307
|
async function readProviderOutputOwnershipFile(outputRoot, fileName) {
|
|
@@ -3589,7 +1332,7 @@ async function resolvePersistedProviderOutputOwnership(outputRoot, ownership, fi
|
|
|
3589
1332
|
const arrays = { ...ownership?.arrays };
|
|
3590
1333
|
await Promise.all(Object.entries(files).map(async ([field, fileName]) => {
|
|
3591
1334
|
const current = arrays[field];
|
|
3592
|
-
|
|
1335
|
+
invariant(current, `ViteHub packages pass a Provider Output ownership file only for a field that they own as an array (${JSON.stringify(field)})`);
|
|
3593
1336
|
arrays[field] = {
|
|
3594
1337
|
...current,
|
|
3595
1338
|
values: [...await readProviderOutputOwnershipFile(outputRoot, fileName), ...current.values ?? []]
|
|
@@ -3625,16 +1368,32 @@ function recoverNetlifyDeploymentOutput(rootDir) {
|
|
|
3625
1368
|
if (!existsSync(outputRoot) && existsSync(previousOutputRoot)) renameSync(previousOutputRoot, outputRoot);
|
|
3626
1369
|
}
|
|
3627
1370
|
function assertNetlifyFunctionName(functionName) {
|
|
3628
|
-
if (!functionName || functionName.includes("\\") || functionName.split("/").some((part) => !part || part === "." || part === "..")) throw
|
|
1371
|
+
if (!functionName || functionName.includes("\\") || functionName.split("/").some((part) => !part || part === "." || part === "..")) throw invariantError(`ViteHub writes Netlify function names from safe Definition names (${functionName})`);
|
|
3629
1372
|
}
|
|
3630
1373
|
function resolveNetlifyFunctionFile(functionsRoot, functionName) {
|
|
3631
1374
|
assertNetlifyFunctionName(functionName);
|
|
3632
1375
|
return resolve(functionsRoot, `${functionName}.mjs`);
|
|
3633
1376
|
}
|
|
1377
|
+
async function declaresTopLevelBinding(code, name) {
|
|
1378
|
+
const { parseSync } = await import("vite");
|
|
1379
|
+
return parseSync("bundle.mjs", code).program.body.some((statement) => {
|
|
1380
|
+
const node = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
|
|
1381
|
+
if (node?.type === "FunctionDeclaration" || node?.type === "ClassDeclaration") return node.id?.name === name;
|
|
1382
|
+
return node?.type === "VariableDeclaration" && node.declarations.some((declaration) => declaration.id.type === "Identifier" && declaration.id.name === name);
|
|
1383
|
+
});
|
|
1384
|
+
}
|
|
3634
1385
|
async function appendNetlifyFunctionConfig(outfile, config) {
|
|
3635
1386
|
if (!config) return;
|
|
3636
1387
|
const bundled = await readFile(outfile, "utf8");
|
|
3637
|
-
|
|
1388
|
+
const literal = stringifyProviderOutputConfig(config);
|
|
1389
|
+
let exported = `export const config = ${literal}`;
|
|
1390
|
+
if (await declaresTopLevelBinding(bundled, "config")) {
|
|
1391
|
+
const baseName = "vitehubNetlifyFunctionConfig";
|
|
1392
|
+
let name = baseName;
|
|
1393
|
+
for (let suffix = 2; bundled.includes(name); suffix++) name = `${baseName}${suffix}`;
|
|
1394
|
+
exported = `const ${name} = ${literal}\nexport { ${name} as config }`;
|
|
1395
|
+
}
|
|
1396
|
+
await writeFile(outfile, `${bundled.trimEnd()}\n\n${exported}\n`, "utf8");
|
|
3638
1397
|
}
|
|
3639
1398
|
async function writeCloudflareDeploymentOutput(options, signal) {
|
|
3640
1399
|
signal?.throwIfAborted();
|
|
@@ -3644,7 +1403,7 @@ async function writeCloudflareDeploymentOutput(options, signal) {
|
|
|
3644
1403
|
const copiesStaticOutput = Boolean(options.bundleEntry && staticIndex && resolve(clientDir) !== resolve(staticOutputDir));
|
|
3645
1404
|
const files = Object.entries(options.files ?? {});
|
|
3646
1405
|
const workerOutfile = options.bundleEntry ? resolve(outputRoot, options.bundleOutfileName ?? "index.js") : void 0;
|
|
3647
|
-
if (workerOutfile && files.some(([fileName]) => resolve(outputRoot, fileName) === workerOutfile)) throw
|
|
1406
|
+
if (workerOutfile && files.some(([fileName]) => resolve(outputRoot, fileName) === workerOutfile)) throw invariantError(`no Cloudflare output file that ViteHub writes has the name of the bundle file (${workerOutfile})`);
|
|
3648
1407
|
const backupRoot = copiesStaticOutput ? await mkdtemp(resolve(options.rootDir, ".vitehub-cloudflare-output-")) : void 0;
|
|
3649
1408
|
const previousOutputRoot = backupRoot ? resolve(backupRoot, "output") : `${outputRoot}.previous`;
|
|
3650
1409
|
const previousStaticOutputDir = backupRoot ? resolve(backupRoot, "static") : `${staticOutputDir}.previous`;
|
|
@@ -3699,6 +1458,7 @@ async function writeCloudflareDeploymentOutput(options, signal) {
|
|
|
3699
1458
|
});
|
|
3700
1459
|
await bundleEsmEntry(options.bundleEntry, stagedWorkerOutfile, {
|
|
3701
1460
|
...options.bundleOptions,
|
|
1461
|
+
resolveEntryPackageAliases: options.bundleOptions?.resolveEntryPackageAliases ?? false,
|
|
3702
1462
|
define: {
|
|
3703
1463
|
...options.bundleDefines,
|
|
3704
1464
|
...options.bundleOptions?.define
|
|
@@ -3819,6 +1579,7 @@ async function writeVercelDeploymentOutput(options, signal) {
|
|
|
3819
1579
|
}
|
|
3820
1580
|
await bundleEsmEntry(options.bundleEntry, serverEntry, {
|
|
3821
1581
|
...options.bundleOptions,
|
|
1582
|
+
resolveEntryPackageAliases: options.bundleOptions?.resolveEntryPackageAliases ?? false,
|
|
3822
1583
|
define: {
|
|
3823
1584
|
...options.bundleDefines,
|
|
3824
1585
|
...options.bundleOptions?.define
|
|
@@ -3933,6 +1694,7 @@ async function writeNetlifyDeploymentOutput(options, signal) {
|
|
|
3933
1694
|
await mkdir(dirname(outfile), { recursive: true });
|
|
3934
1695
|
await bundleEsmEntry(func.bundleEntry, outfile, {
|
|
3935
1696
|
...func.bundleOptions,
|
|
1697
|
+
resolveEntryPackageAliases: func.bundleOptions.resolveEntryPackageAliases ?? false,
|
|
3936
1698
|
conditions: func.bundleOptions.conditions ?? ["netlify", "node"],
|
|
3937
1699
|
define: {
|
|
3938
1700
|
...options.bundleDefines,
|
|
@@ -4513,33 +2275,84 @@ async function finalizeProviderDeploymentOutputs(catalog, options = {}) {
|
|
|
4513
2275
|
if (providerDeploymentOutputFinalizations.get(catalog) === active) providerDeploymentOutputFinalizations.delete(catalog);
|
|
4514
2276
|
}
|
|
4515
2277
|
}
|
|
4516
|
-
|
|
4517
|
-
|
|
4518
|
-
|
|
4519
|
-
|
|
4520
|
-
|
|
4521
|
-
|
|
4522
|
-
|
|
4523
|
-
|
|
4524
|
-
|
|
4525
|
-
|
|
4526
|
-
|
|
4527
|
-
|
|
4528
|
-
|
|
4529
|
-
|
|
4530
|
-
|
|
4531
|
-
|
|
4532
|
-
|
|
4533
|
-
|
|
4534
|
-
|
|
4535
|
-
|
|
4536
|
-
|
|
4537
|
-
|
|
4538
|
-
|
|
4539
|
-
|
|
2278
|
+
//#endregion
|
|
2279
|
+
//#region ../internal/src/hints.ts
|
|
2280
|
+
/**
|
|
2281
|
+
* The file that lists the hints of the last build or dev server, relative to the project root. A hint is a warning
|
|
2282
|
+
* about something that works now and fails later, such as counts that stay in one server's memory. Agents and CI read
|
|
2283
|
+
* the file instead of the terminal.
|
|
2284
|
+
*/
|
|
2285
|
+
const viteHubHintsFile = ".vitehub/hints.json";
|
|
2286
|
+
const VITEHUB_NUXT_HINTS = "__vitehubNuxtHints";
|
|
2287
|
+
const runsKey = Symbol.for("vitehub.hints.runs");
|
|
2288
|
+
const shared = globalThis;
|
|
2289
|
+
const runs = shared[runsKey] ??= /* @__PURE__ */ new Map();
|
|
2290
|
+
const startedKey = Symbol.for("vitehub.hints.started");
|
|
2291
|
+
const startedShared = globalThis;
|
|
2292
|
+
const started = startedShared[startedKey] ??= /* @__PURE__ */ new WeakSet();
|
|
2293
|
+
/**
|
|
2294
|
+
* The report of the ViteHub project root, where the other generated files go. A Nuxt app with `srcDir: "app"` has its
|
|
2295
|
+
* Vite root in `app/`, one folder below.
|
|
2296
|
+
*/
|
|
2297
|
+
function hintsFile(config) {
|
|
2298
|
+
const projectRoot = Reflect.get(config, VITEHUB_PROJECT_ROOT);
|
|
2299
|
+
return resolve(typeof projectRoot === "string" ? projectRoot : resolveViteHubProjectRoot(config.root), viteHubHintsFile);
|
|
2300
|
+
}
|
|
2301
|
+
function startRun(config) {
|
|
2302
|
+
const file = hintsFile(config);
|
|
2303
|
+
const run = {
|
|
2304
|
+
file,
|
|
2305
|
+
report: {
|
|
2306
|
+
version: 1,
|
|
2307
|
+
command: config.command,
|
|
2308
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2309
|
+
hints: []
|
|
2310
|
+
},
|
|
2311
|
+
keys: /* @__PURE__ */ new Set()
|
|
2312
|
+
};
|
|
2313
|
+
runs.set(file, run);
|
|
2314
|
+
return run;
|
|
2315
|
+
}
|
|
2316
|
+
function write(run) {
|
|
2317
|
+
mkdirSync(dirname(run.file), { recursive: true });
|
|
2318
|
+
writeFileSync(run.file, `${JSON.stringify(run.report, null, 2)}\n`);
|
|
2319
|
+
}
|
|
2320
|
+
/**
|
|
2321
|
+
* Reports a hint from a Vite plugin hook, or from a Nitro or Nuxt hook of the same build: prints it once with its fix and docs link, and adds it to
|
|
2322
|
+
* {@link viteHubHintsFile}. Build the diagnostic from the package's nostics catalog, so its code has a docs page.
|
|
2323
|
+
*/
|
|
2324
|
+
function reportViteHubHint(config, diagnostic) {
|
|
2325
|
+
if (skipHints(config)) return;
|
|
2326
|
+
const nuxt = config[VITEHUB_NUXT_HINTS];
|
|
2327
|
+
if (typeof nuxt === "function") return nuxt(diagnostic);
|
|
2328
|
+
const run = runs.get(hintsFile(config)) ?? startRun(config);
|
|
2329
|
+
const hint = {
|
|
2330
|
+
code: diagnostic.code,
|
|
2331
|
+
why: diagnostic.why,
|
|
2332
|
+
...diagnostic.fix ? { fix: diagnostic.fix } : {},
|
|
2333
|
+
...diagnostic.docs ? { docs: diagnostic.docs } : {},
|
|
2334
|
+
...diagnostic.sources?.length ? { sources: diagnostic.sources } : {}
|
|
2335
|
+
};
|
|
2336
|
+
const key = JSON.stringify([hint.code, hint.sources ?? []]);
|
|
2337
|
+
if (run.keys.has(key)) return;
|
|
2338
|
+
run.keys.add(key);
|
|
2339
|
+
run.report.hints.push(hint);
|
|
2340
|
+
write(run);
|
|
2341
|
+
(config.logger ?? console).warn(formatDiagnostic(diagnostic));
|
|
2342
|
+
}
|
|
2343
|
+
function skipHints(config) {
|
|
2344
|
+
return !config.command || Reflect.get(config, "__vitehubPrepare") === true || Reflect.get(config, "vitehubCliDiscovery") === true;
|
|
4540
2345
|
}
|
|
4541
|
-
|
|
4542
|
-
|
|
2346
|
+
/**
|
|
2347
|
+
* Starts the hints of a build or dev server: writes an empty {@link viteHubHintsFile}, so a run without hints does not
|
|
2348
|
+
* leave the hints of an earlier run in place. Every plugin that reports hints calls it from `configResolved`, so a
|
|
2349
|
+
* package used without `vitehub()` starts its own run. Nuxt uses the app instance as owner so its Vite builds and
|
|
2350
|
+
* separate Nitro build share one report; replay, prepare and discovery never reset it.
|
|
2351
|
+
*/
|
|
2352
|
+
function startViteHubHints(config, owner = config) {
|
|
2353
|
+
if (skipHints(config) || config["__vitehubNuxtHints"] || started.has(owner)) return;
|
|
2354
|
+
started.add(owner);
|
|
2355
|
+
write(startRun(config));
|
|
4543
2356
|
}
|
|
4544
2357
|
//#endregion
|
|
4545
2358
|
//#region ../internal/src/provision-state.ts
|
|
@@ -4569,14 +2382,14 @@ function readProvisionedId(state, provider, category, key) {
|
|
|
4569
2382
|
}
|
|
4570
2383
|
function parseProvisionState(raw) {
|
|
4571
2384
|
const parsed = JSON.parse(raw);
|
|
4572
|
-
if (!
|
|
2385
|
+
if (!isRecord(parsed)) return {};
|
|
4573
2386
|
const state = {};
|
|
4574
2387
|
for (const provider of ["cloudflare", "vercel"]) {
|
|
4575
2388
|
const categories = parsed[provider];
|
|
4576
|
-
if (!
|
|
2389
|
+
if (!isRecord(categories)) continue;
|
|
4577
2390
|
const validCategories = {};
|
|
4578
2391
|
for (const [category, ids] of Object.entries(categories)) {
|
|
4579
|
-
if (!
|
|
2392
|
+
if (!isRecord(ids)) continue;
|
|
4580
2393
|
const validIds = {};
|
|
4581
2394
|
for (const [key, id] of Object.entries(ids)) if (typeof id === "string") setOwn(validIds, key, id);
|
|
4582
2395
|
if (Object.keys(validIds).length) setOwn(validCategories, category, validIds);
|
|
@@ -4594,57 +2407,281 @@ function setOwn(target, key, value) {
|
|
|
4594
2407
|
});
|
|
4595
2408
|
}
|
|
4596
2409
|
//#endregion
|
|
4597
|
-
//#region ../internal/src/
|
|
4598
|
-
|
|
4599
|
-
|
|
4600
|
-
|
|
4601
|
-
|
|
2410
|
+
//#region ../internal/src/vite-stage.ts
|
|
2411
|
+
/**
|
|
2412
|
+
* Vite's `loadEnv(mode, envDir, "")`: every `.env` value of the mode and the whole shell. With `DEBUG=vite:env`, Vite
|
|
2413
|
+
* logs that result to stderr, secrets included. loadEnv is synchronous, so this drops only the writes of this call.
|
|
2414
|
+
*/
|
|
2415
|
+
function loadAllEnv(loadEnv, mode, envDir) {
|
|
2416
|
+
const write = process.stderr.write;
|
|
2417
|
+
process.stderr.write = () => true;
|
|
2418
|
+
try {
|
|
2419
|
+
return loadEnv(mode, envDir, "");
|
|
2420
|
+
} finally {
|
|
2421
|
+
process.stderr.write = write;
|
|
2422
|
+
}
|
|
4602
2423
|
}
|
|
4603
2424
|
function configureCloudflareKV(target, config, provisionState = {}) {
|
|
4604
2425
|
for (const [storeName, store] of Object.entries(config.stores || { default: config.store })) {
|
|
4605
|
-
if (store.driver !== "cloudflare
|
|
2426
|
+
if (store.driver !== "cloudflare") continue;
|
|
4606
2427
|
const { binding } = store;
|
|
4607
2428
|
const namespaceId = store.namespaceId ?? readProvisionedId(provisionState, "cloudflare", "kv", storeName);
|
|
4608
2429
|
target.cloudflare ||= {};
|
|
4609
2430
|
target.cloudflare.wrangler ||= {};
|
|
4610
2431
|
target.cloudflare.wrangler.kv_namespaces ||= [];
|
|
4611
|
-
|
|
2432
|
+
const namespaces = target.cloudflare.wrangler.kv_namespaces;
|
|
2433
|
+
const existing = namespaces.find((entry) => entry.binding === binding);
|
|
2434
|
+
if (existing) {
|
|
2435
|
+
if (store.remote || store.localBase) {
|
|
2436
|
+
delete existing.experimental_remote;
|
|
2437
|
+
if (store.remote) existing.remote = true;
|
|
2438
|
+
else delete existing.remote;
|
|
2439
|
+
}
|
|
2440
|
+
} else namespaces.push({
|
|
4612
2441
|
binding,
|
|
4613
|
-
...namespaceId ? { id: namespaceId } : {}
|
|
4614
|
-
|
|
2442
|
+
...namespaceId ? { id: namespaceId } : {},
|
|
2443
|
+
...store.remote ? { remote: true } : {}
|
|
2444
|
+
});
|
|
2445
|
+
}
|
|
2446
|
+
}
|
|
2447
|
+
//#endregion
|
|
2448
|
+
//#region src/inspect.ts
|
|
2449
|
+
function describeDevelopment(store) {
|
|
2450
|
+
switch (store.driver) {
|
|
2451
|
+
case "upstash": return "Remote. `vite dev` uses the real Upstash database, so writes change real data.";
|
|
2452
|
+
case "cloudflare": return store.localBase ? `Local. \`vite dev\` uses the \`${store.binding}\` binding of the dev runtime, or \`fs-lite\` in \`${store.localBase}\` when the runtime has no binding.` : `Remote. \`vite dev\` uses the real Cloudflare KV namespace through the \`${store.binding}\` binding, so writes change real data.`;
|
|
2453
|
+
case "deno-kv": return "Local. Deno KV.";
|
|
2454
|
+
case "fs-lite": return `Local. \`fs-lite\` in \`${store.base}\`.`;
|
|
2455
|
+
case "redis": return `The Redis server of \`${store.url.startsWith("env:") ? store.url.slice(4) : "url"}\`, the same as in production when it points there.`;
|
|
2456
|
+
case "database": return `The table \`vitehub_kv\` in the Database "${store.database}" of \`vite dev\`.`;
|
|
2457
|
+
}
|
|
2458
|
+
}
|
|
2459
|
+
/** One summary per KV store: the build driver and what `vite dev` uses. */
|
|
2460
|
+
function inspectKVStores(build, dev, file) {
|
|
2461
|
+
const devStores = dev.stores ?? { default: dev.store };
|
|
2462
|
+
return Object.entries(build.stores ?? { default: build.store }).map(([name, store]) => {
|
|
2463
|
+
const devStore = devStores[name];
|
|
2464
|
+
return {
|
|
2465
|
+
fields: [{
|
|
2466
|
+
label: "Driver",
|
|
2467
|
+
value: store.driver
|
|
2468
|
+
}, ...devStore ? [{
|
|
2469
|
+
label: "Development",
|
|
2470
|
+
value: describeDevelopment(devStore)
|
|
2471
|
+
}] : []],
|
|
2472
|
+
file,
|
|
2473
|
+
name,
|
|
2474
|
+
source: "kv"
|
|
2475
|
+
};
|
|
2476
|
+
});
|
|
2477
|
+
}
|
|
2478
|
+
function cloudflareStores(options, env) {
|
|
2479
|
+
const stores = /* @__PURE__ */ new Map();
|
|
2480
|
+
const kv = resolveKVViteConfig(options, { env }).kv;
|
|
2481
|
+
if (!kv) return stores;
|
|
2482
|
+
for (const [name, store] of Object.entries(kv.stores || { default: kv.store })) if (store.driver === "cloudflare") stores.set(name, store);
|
|
2483
|
+
return stores;
|
|
2484
|
+
}
|
|
2485
|
+
/** Lists the Workers KV namespaces that KV Stores bind, with where each id comes from. Reads local config and Provision State only. */
|
|
2486
|
+
function inspectKVResources(options, provisionRoot, env = process.env) {
|
|
2487
|
+
const stores = cloudflareStores(options, env);
|
|
2488
|
+
if (!stores.size) return [];
|
|
2489
|
+
const configured = cloudflareStores(options, {
|
|
2490
|
+
...env,
|
|
2491
|
+
KV_NAMESPACE_ID: void 0
|
|
2492
|
+
});
|
|
2493
|
+
const provisionState = readProvisionStateSync(provisionRoot);
|
|
2494
|
+
return [...stores].map(([storeName, store]) => {
|
|
2495
|
+
const configuredId = configured.get(storeName)?.namespaceId;
|
|
2496
|
+
const provisionedId = readProvisionedId(provisionState, "cloudflare", "kv", storeName);
|
|
2497
|
+
const id = store.namespaceId ?? provisionedId;
|
|
2498
|
+
return {
|
|
2499
|
+
binding: store.binding,
|
|
2500
|
+
definition: storeName,
|
|
2501
|
+
host: "cloudflare",
|
|
2502
|
+
kind: "cloudflare-kv-namespace",
|
|
2503
|
+
...store.namespaceName ? { name: store.namespaceName } : {},
|
|
2504
|
+
owner: "kv",
|
|
2505
|
+
...id ? { id } : {},
|
|
2506
|
+
...configuredId ? { source: "config" } : store.namespaceId ? {
|
|
2507
|
+
env: "KV_NAMESPACE_ID",
|
|
2508
|
+
source: "env"
|
|
2509
|
+
} : provisionedId ? { source: "provision-state" } : {}
|
|
2510
|
+
};
|
|
2511
|
+
});
|
|
2512
|
+
}
|
|
2513
|
+
//#endregion
|
|
2514
|
+
//#region ../internal/src/host-credentials.ts
|
|
2515
|
+
/** Reads host credentials from environment variables only. Returns undefined when the token is not set. */
|
|
2516
|
+
function readHostCredentialsFromEnv(host, env) {
|
|
2517
|
+
switch (host) {
|
|
2518
|
+
case "cloudflare": {
|
|
2519
|
+
const token = trimmed(env.CLOUDFLARE_API_TOKEN);
|
|
2520
|
+
const accountId = trimmed(env.CLOUDFLARE_ACCOUNT_ID);
|
|
2521
|
+
return token ? {
|
|
2522
|
+
token,
|
|
2523
|
+
...accountId && { accountId }
|
|
2524
|
+
} : void 0;
|
|
2525
|
+
}
|
|
2526
|
+
case "vercel": {
|
|
2527
|
+
const token = trimmed(env.VERCEL_TOKEN);
|
|
2528
|
+
const teamId = trimmed(env.VERCEL_TEAM_ID) ?? trimmed(env.VERCEL_ORG_ID);
|
|
2529
|
+
return token ? {
|
|
2530
|
+
token,
|
|
2531
|
+
...teamId && { teamId }
|
|
2532
|
+
} : void 0;
|
|
2533
|
+
}
|
|
2534
|
+
case "netlify": {
|
|
2535
|
+
const token = trimmed(env.NETLIFY_AUTH_TOKEN);
|
|
2536
|
+
return token ? { token } : void 0;
|
|
2537
|
+
}
|
|
2538
|
+
case "deno": {
|
|
2539
|
+
const token = trimmed(env.DENO_DEPLOY_TOKEN);
|
|
2540
|
+
return token ? { token } : void 0;
|
|
2541
|
+
}
|
|
2542
|
+
}
|
|
2543
|
+
}
|
|
2544
|
+
function trimmed(value) {
|
|
2545
|
+
const result = value?.trim();
|
|
2546
|
+
return result ? result : void 0;
|
|
2547
|
+
}
|
|
2548
|
+
//#endregion
|
|
2549
|
+
//#region ../internal/src/provider-failure.ts
|
|
2550
|
+
const cloudflareCodes = {
|
|
2551
|
+
d1: {},
|
|
2552
|
+
kv: { 10014: "conflict" },
|
|
2553
|
+
queues: {
|
|
2554
|
+
10104: "not-found",
|
|
2555
|
+
10106: "unauthorized",
|
|
2556
|
+
10107: "invalid",
|
|
2557
|
+
10201: "unavailable",
|
|
2558
|
+
10202: "invalid",
|
|
2559
|
+
10203: "invalid",
|
|
2560
|
+
10204: "invalid",
|
|
2561
|
+
10205: "invalid",
|
|
2562
|
+
10206: "invalid",
|
|
2563
|
+
10207: "invalid",
|
|
2564
|
+
10208: "invalid",
|
|
2565
|
+
10250: "throttled",
|
|
2566
|
+
10251: "throttled",
|
|
2567
|
+
10252: "throttled",
|
|
2568
|
+
10253: "throttled",
|
|
2569
|
+
15e3: "unavailable"
|
|
2570
|
+
},
|
|
2571
|
+
r2: {
|
|
2572
|
+
10001: "unavailable",
|
|
2573
|
+
10002: "unauthorized",
|
|
2574
|
+
10003: "unauthorized",
|
|
2575
|
+
10004: "conflict",
|
|
2576
|
+
10005: "invalid",
|
|
2577
|
+
10006: "not-found",
|
|
2578
|
+
10007: "not-found",
|
|
2579
|
+
10008: "conflict",
|
|
2580
|
+
10009: "invalid",
|
|
2581
|
+
10011: "invalid",
|
|
2582
|
+
10012: "invalid",
|
|
2583
|
+
10013: "invalid",
|
|
2584
|
+
10014: "invalid",
|
|
2585
|
+
10018: "unauthorized",
|
|
2586
|
+
10020: "invalid",
|
|
2587
|
+
10024: "not-found",
|
|
2588
|
+
10025: "invalid",
|
|
2589
|
+
10031: "conflict",
|
|
2590
|
+
10033: "invalid",
|
|
2591
|
+
10035: "unauthorized",
|
|
2592
|
+
10037: "invalid",
|
|
2593
|
+
10039: "invalid",
|
|
2594
|
+
10042: "unauthorized",
|
|
2595
|
+
10043: "unavailable",
|
|
2596
|
+
10048: "invalid",
|
|
2597
|
+
10054: "unavailable",
|
|
2598
|
+
10058: "throttled",
|
|
2599
|
+
10069: "conflict",
|
|
2600
|
+
10073: "conflict",
|
|
2601
|
+
100100: "invalid"
|
|
2602
|
+
}
|
|
2603
|
+
};
|
|
2604
|
+
const vercelCodes = {
|
|
2605
|
+
bad_request: "invalid",
|
|
2606
|
+
conflict_aliases: "conflict",
|
|
2607
|
+
forbidden: "unauthorized",
|
|
2608
|
+
internal_server_error: "unavailable",
|
|
2609
|
+
method_unknown: "invalid",
|
|
2610
|
+
not_found: "not-found",
|
|
2611
|
+
not_modified: "conflict",
|
|
2612
|
+
rate_limited: "throttled",
|
|
2613
|
+
service_unavailable: "unavailable"
|
|
2614
|
+
};
|
|
2615
|
+
function kindFromStatus(status) {
|
|
2616
|
+
if (status === 401 || status === 403) return "unauthorized";
|
|
2617
|
+
if (status === 404 || status === 410) return "not-found";
|
|
2618
|
+
if (status === 409 || status === 412) return "conflict";
|
|
2619
|
+
if (status === 429) return "throttled";
|
|
2620
|
+
if (status === 408 || status >= 500) return "unavailable";
|
|
2621
|
+
if (status >= 400) return "invalid";
|
|
2622
|
+
}
|
|
2623
|
+
/**
|
|
2624
|
+
* Classifies a failed provider call. A documented provider code wins over the HTTP status.
|
|
2625
|
+
* Returns `undefined` only when neither a known code nor an error status is present.
|
|
2626
|
+
*/
|
|
2627
|
+
function classifyProviderFailure(source, { codes = [], status }) {
|
|
2628
|
+
for (const code of codes) {
|
|
2629
|
+
const kind = source.host === "vercel" ? typeof code === "string" && Object.hasOwn(vercelCodes, code) ? vercelCodes[code] : void 0 : source.host === "cloudflare" && source.product && typeof code === "number" && Object.hasOwn(cloudflareCodes[source.product], code) ? cloudflareCodes[source.product][code] : void 0;
|
|
2630
|
+
if (kind) return kind;
|
|
4615
2631
|
}
|
|
2632
|
+
return status === void 0 ? void 0 : kindFromStatus(status);
|
|
2633
|
+
}
|
|
2634
|
+
/** Finds the Cloudflare product of an account API path, such as `/r2/buckets`. */
|
|
2635
|
+
function cloudflareProductOfPath(path) {
|
|
2636
|
+
if (path.startsWith("/r2/")) return "r2";
|
|
2637
|
+
if (path.startsWith("/storage/kv/")) return "kv";
|
|
2638
|
+
if (path.startsWith("/d1/")) return "d1";
|
|
2639
|
+
if (path === "/queues" || path.startsWith("/queues/") || path.startsWith("/queues?")) return "queues";
|
|
2640
|
+
}
|
|
2641
|
+
/**
|
|
2642
|
+
* Reads the error codes of a Cloudflare (`errors[].code`) or Vercel (`error.code`) error body.
|
|
2643
|
+
* Keeps only codes that are safe to print: numbers, and short strings without spaces or line breaks.
|
|
2644
|
+
*/
|
|
2645
|
+
function readProviderErrorCodes(body) {
|
|
2646
|
+
if (!body || typeof body !== "object") return [];
|
|
2647
|
+
const error = Reflect.get(body, "error");
|
|
2648
|
+
const errors = Reflect.get(body, "errors");
|
|
2649
|
+
return [error && typeof error === "object" ? Reflect.get(error, "code") : void 0, ...Array.isArray(errors) ? errors.map((entry) => entry && typeof entry === "object" ? Reflect.get(entry, "code") : void 0) : []].filter((code) => typeof code === "number" && Number.isFinite(code) || typeof code === "string" && /^[\w.-]{1,128}$/.test(code));
|
|
4616
2650
|
}
|
|
4617
2651
|
//#endregion
|
|
4618
2652
|
//#region ../internal/src/provision.ts
|
|
2653
|
+
/**
|
|
2654
|
+
* Whether a value from Provision State can appear in a copyable shell command as is.
|
|
2655
|
+
* The file is editable, so a hint shows a command only for plain names and ids.
|
|
2656
|
+
*/
|
|
2657
|
+
function isShellSafeProvisionValue(value) {
|
|
2658
|
+
return /^[A-Za-z0-9][\w.-]*$/.test(value);
|
|
2659
|
+
}
|
|
4619
2660
|
function resolveCloudflareProvisionConfig(env) {
|
|
4620
|
-
const
|
|
4621
|
-
|
|
4622
|
-
if (!accountId || !token) return;
|
|
2661
|
+
const credentials = readHostCredentialsFromEnv("cloudflare", env);
|
|
2662
|
+
if (!credentials?.accountId) return;
|
|
4623
2663
|
return {
|
|
4624
|
-
accountId,
|
|
4625
|
-
token
|
|
2664
|
+
accountId: credentials.accountId,
|
|
2665
|
+
token: credentials.token
|
|
4626
2666
|
};
|
|
4627
2667
|
}
|
|
4628
2668
|
function ownParser(options) {
|
|
4629
2669
|
if (!Object.hasOwn(options, "parse")) return;
|
|
4630
2670
|
return options.parse;
|
|
4631
2671
|
}
|
|
4632
|
-
|
|
4633
|
-
codes;
|
|
4634
|
-
status
|
|
4635
|
-
|
|
4636
|
-
|
|
4637
|
-
|
|
4638
|
-
|
|
4639
|
-
|
|
4640
|
-
|
|
4641
|
-
|
|
4642
|
-
|
|
4643
|
-
|
|
4644
|
-
|
|
4645
|
-
}
|
|
4646
|
-
};
|
|
4647
|
-
function createJsonClient(baseURL, headers, fetchImpl, baseQuery) {
|
|
2672
|
+
function provisionRequestError(method, path, status, codes, kind) {
|
|
2673
|
+
const suffix = codes.length ? ` Provider code${codes.length === 1 ? "" : "s"}: ${codes.join(", ")}.` : "";
|
|
2674
|
+
return Object.assign(internalErrorDiagnostics.INTERNAL_R0013({ message: `Provision request failed: ${method} ${path} (${status}).${suffix}` }), {
|
|
2675
|
+
codes,
|
|
2676
|
+
kind,
|
|
2677
|
+
status
|
|
2678
|
+
});
|
|
2679
|
+
}
|
|
2680
|
+
/** Whether `error` is a failed provider API call of provisioning. */
|
|
2681
|
+
function isProvisionRequestError(error) {
|
|
2682
|
+
return error instanceof Error && Reflect.get(error, "code") === "INTERNAL_R0013";
|
|
2683
|
+
}
|
|
2684
|
+
function createJsonClient(source, baseURL, headers, fetchImpl, baseQuery) {
|
|
4648
2685
|
return async function request(path, options = {}) {
|
|
4649
2686
|
const url = new URL(`${baseURL}${path}`);
|
|
4650
2687
|
const query = Object.hasOwn(options, "query") ? options.query : void 0;
|
|
@@ -4671,9 +2708,12 @@ function createJsonClient(baseURL, headers, fetchImpl, baseQuery) {
|
|
|
4671
2708
|
}
|
|
4672
2709
|
const response = await fetchImpl(url, init);
|
|
4673
2710
|
if (!response.ok) {
|
|
4674
|
-
const
|
|
4675
|
-
const
|
|
4676
|
-
|
|
2711
|
+
const codes = readProviderErrorCodes(await response.json().catch(() => void 0));
|
|
2712
|
+
const kind = classifyProviderFailure(source(path), {
|
|
2713
|
+
codes,
|
|
2714
|
+
status: response.status
|
|
2715
|
+
}) ?? "unavailable";
|
|
2716
|
+
throw provisionRequestError(method ?? "GET", path, response.status, codes, kind);
|
|
4677
2717
|
}
|
|
4678
2718
|
const value = await response.json();
|
|
4679
2719
|
const parse = ownParser(options);
|
|
@@ -4681,7 +2721,13 @@ function createJsonClient(baseURL, headers, fetchImpl, baseQuery) {
|
|
|
4681
2721
|
};
|
|
4682
2722
|
}
|
|
4683
2723
|
function createCloudflareProvisionClient(config, fetchImpl = globalThis.fetch) {
|
|
4684
|
-
|
|
2724
|
+
return createCloudflareClient(`https://api.cloudflare.com/client/v4/accounts/${config.accountId}`, config.token, fetchImpl);
|
|
2725
|
+
}
|
|
2726
|
+
function createCloudflareClient(baseURL, token, fetchImpl) {
|
|
2727
|
+
const client = createJsonClient((path) => ({
|
|
2728
|
+
host: "cloudflare",
|
|
2729
|
+
product: cloudflareProductOfPath(path)
|
|
2730
|
+
}), baseURL, { authorization: `Bearer ${token}` }, fetchImpl);
|
|
4685
2731
|
return async (path, options = {}) => {
|
|
4686
2732
|
const parse = ownParser(options) ?? ((value) => value);
|
|
4687
2733
|
return await client(path, {
|
|
@@ -4697,14 +2743,37 @@ function createCloudflareProvisionClient(config, fetchImpl = globalThis.fetch) {
|
|
|
4697
2743
|
});
|
|
4698
2744
|
};
|
|
4699
2745
|
}
|
|
4700
|
-
|
|
4701
|
-
|
|
4702
|
-
|
|
2746
|
+
/**
|
|
2747
|
+
* Reads every page of a Cloudflare list that pages with `page` and `result_info`.
|
|
2748
|
+
* R2 bucket lists page with a cursor instead and do not use this helper.
|
|
2749
|
+
*/
|
|
2750
|
+
async function listCloudflarePages(request, path, options) {
|
|
2751
|
+
const items = [];
|
|
2752
|
+
for (let page = 1;; page++) {
|
|
2753
|
+
const query = {
|
|
2754
|
+
...options.query,
|
|
2755
|
+
page: String(page)
|
|
2756
|
+
};
|
|
2757
|
+
if (options.perPage !== void 0) query.per_page = String(options.perPage);
|
|
2758
|
+
const listed = await request(path, {
|
|
2759
|
+
parse: options.parse,
|
|
2760
|
+
query
|
|
2761
|
+
});
|
|
2762
|
+
const pageItems = listed.result ?? [];
|
|
2763
|
+
items.push(...pageItems);
|
|
2764
|
+
const info = listed.result_info;
|
|
2765
|
+
if (info?.page !== void 0 && info.page !== page) throw internalErrorDiagnostics.INTERNAL_R0010({ message: `Cloudflare provisioning returned page ${info.page} of ${path} for page ${page}.` });
|
|
2766
|
+
if (!pageItems.length) return items;
|
|
2767
|
+
if (info?.total_pages !== void 0) {
|
|
2768
|
+
if (page >= info.total_pages) return items;
|
|
2769
|
+
} else if (info?.total_count !== void 0) {
|
|
2770
|
+
if (page * (info.per_page ?? options.perPage ?? pageItems.length) >= info.total_count) return items;
|
|
2771
|
+
} else if (options.perPage === void 0 || pageItems.length < options.perPage) return items;
|
|
2772
|
+
}
|
|
4703
2773
|
}
|
|
4704
2774
|
//#endregion
|
|
4705
2775
|
//#region src/provision.ts
|
|
4706
2776
|
const CLOUDFLARE_KV_NAMESPACE_LIST_PER_PAGE = 100;
|
|
4707
|
-
const CLOUDFLARE_KV_DUPLICATE_TITLE_CODE = 10014;
|
|
4708
2777
|
function parseNamespaces(value) {
|
|
4709
2778
|
if (!Array.isArray(value)) throw kvErrorDiagnostics.KV_PROVISION_FAILED({ problem: "Cloudflare returned an invalid KV namespace list." });
|
|
4710
2779
|
for (const namespace of value) {
|
|
@@ -4723,27 +2792,12 @@ function parseCreatedNamespace(value) {
|
|
|
4723
2792
|
}
|
|
4724
2793
|
async function listNamespaceIds(request) {
|
|
4725
2794
|
const ids = /* @__PURE__ */ new Map();
|
|
4726
|
-
|
|
4727
|
-
|
|
4728
|
-
|
|
4729
|
-
|
|
4730
|
-
|
|
4731
|
-
|
|
4732
|
-
}
|
|
4733
|
-
});
|
|
4734
|
-
const namespaces = listed.result ?? [];
|
|
4735
|
-
for (const namespace of namespaces) if (namespace.id && namespace.title && !ids.has(namespace.title)) ids.set(namespace.title, namespace.id);
|
|
4736
|
-
const resultInfo = listed.result_info;
|
|
4737
|
-
if (resultInfo?.total_pages !== void 0) {
|
|
4738
|
-
if (page >= resultInfo.total_pages) return ids;
|
|
4739
|
-
continue;
|
|
4740
|
-
}
|
|
4741
|
-
if (resultInfo?.total_count !== void 0) {
|
|
4742
|
-
if ((resultInfo.page ?? page) * (resultInfo.per_page ?? CLOUDFLARE_KV_NAMESPACE_LIST_PER_PAGE) < resultInfo.total_count) continue;
|
|
4743
|
-
return ids;
|
|
4744
|
-
}
|
|
4745
|
-
if (namespaces.length < CLOUDFLARE_KV_NAMESPACE_LIST_PER_PAGE) return ids;
|
|
4746
|
-
}
|
|
2795
|
+
const namespaces = await listCloudflarePages(request, "/storage/kv/namespaces", {
|
|
2796
|
+
parse: parseNamespaces,
|
|
2797
|
+
perPage: CLOUDFLARE_KV_NAMESPACE_LIST_PER_PAGE
|
|
2798
|
+
});
|
|
2799
|
+
for (const namespace of namespaces) if (namespace.id && namespace.title && !ids.has(namespace.title)) ids.set(namespace.title, namespace.id);
|
|
2800
|
+
return ids;
|
|
4747
2801
|
}
|
|
4748
2802
|
async function createNamespace(request, title) {
|
|
4749
2803
|
try {
|
|
@@ -4753,7 +2807,7 @@ async function createNamespace(request, title) {
|
|
|
4753
2807
|
parse: parseCreatedNamespace
|
|
4754
2808
|
})).result?.id;
|
|
4755
2809
|
} catch (error) {
|
|
4756
|
-
if (!(error
|
|
2810
|
+
if (!isProvisionRequestError(error) || error.kind !== "conflict") throw error;
|
|
4757
2811
|
const id = (await listNamespaceIds(request)).get(title);
|
|
4758
2812
|
if (!id) throw error;
|
|
4759
2813
|
return id;
|
|
@@ -4767,23 +2821,39 @@ function planStoresByNamespace(options, env) {
|
|
|
4767
2821
|
const storesByNamespace = /* @__PURE__ */ new Map();
|
|
4768
2822
|
if (!kv) return storesByNamespace;
|
|
4769
2823
|
for (const [storeName, store] of Object.entries(kv.stores || { default: kv.store })) {
|
|
4770
|
-
if (store.driver !== "cloudflare
|
|
2824
|
+
if (store.driver !== "cloudflare" || store.namespaceId || !store.namespaceName) continue;
|
|
4771
2825
|
const stores = storesByNamespace.get(store.namespaceName);
|
|
4772
2826
|
if (stores) stores.push(storeName);
|
|
4773
2827
|
else storesByNamespace.set(store.namespaceName, [storeName]);
|
|
4774
2828
|
}
|
|
4775
2829
|
return storesByNamespace;
|
|
4776
2830
|
}
|
|
2831
|
+
function cloudflareStoreNames(options, env) {
|
|
2832
|
+
const kv = resolveKVViteConfig(options, {
|
|
2833
|
+
env,
|
|
2834
|
+
hosting: "cloudflare"
|
|
2835
|
+
}).kv;
|
|
2836
|
+
if (!kv) return [];
|
|
2837
|
+
return Object.entries(kv.stores || { default: kv.store }).filter(([, store]) => store.driver === "cloudflare").map(([name]) => name);
|
|
2838
|
+
}
|
|
4777
2839
|
function createKVCloudflareProvisionStep(resolveOptions) {
|
|
4778
2840
|
return {
|
|
4779
2841
|
id: "kv:cloudflare-kv",
|
|
4780
2842
|
provider: "cloudflare",
|
|
2843
|
+
recordedState(context) {
|
|
2844
|
+
return [{
|
|
2845
|
+
category: "kv",
|
|
2846
|
+
declared: cloudflareStoreNames(resolveOptions(), context.env),
|
|
2847
|
+
deleteHint: ({ id }) => isShellSafeProvisionValue(id) ? `run \`wrangler kv namespace delete --namespace-id ${id}\`` : "delete the KV namespace in the Cloudflare dashboard"
|
|
2848
|
+
}];
|
|
2849
|
+
},
|
|
4781
2850
|
async plan(context) {
|
|
4782
2851
|
const storesByNamespace = planStoresByNamespace(resolveOptions(), context.env);
|
|
4783
2852
|
if (!storesByNamespace.size) return [];
|
|
4784
2853
|
const config = resolveCloudflareProvisionConfig(context.env);
|
|
4785
2854
|
if (!config) {
|
|
4786
2855
|
context.logger.warn("kv: skipping Cloudflare KV, missing CLOUDFLARE_ACCOUNT_ID/CLOUDFLARE_API_TOKEN.");
|
|
2856
|
+
context.markPlanUnchecked?.();
|
|
4787
2857
|
return [];
|
|
4788
2858
|
}
|
|
4789
2859
|
const request = createCloudflareProvisionClient(config, context.fetch);
|
|
@@ -4802,47 +2872,164 @@ function createKVCloudflareProvisionStep(resolveOptions) {
|
|
|
4802
2872
|
};
|
|
4803
2873
|
}
|
|
4804
2874
|
//#endregion
|
|
2875
|
+
//#region src/deployment-env.ts
|
|
2876
|
+
const owners = ["kv"];
|
|
2877
|
+
const maskedRuntimeValue = "********";
|
|
2878
|
+
function entry(names) {
|
|
2879
|
+
return {
|
|
2880
|
+
names,
|
|
2881
|
+
required: true,
|
|
2882
|
+
secret: true,
|
|
2883
|
+
hasDefault: false,
|
|
2884
|
+
owners
|
|
2885
|
+
};
|
|
2886
|
+
}
|
|
2887
|
+
function storeEntries(store) {
|
|
2888
|
+
if (store.driver === "upstash") return [...store.url === maskedRuntimeValue ? [entry(upstashUrlEnvNames)] : [], ...store.token === maskedRuntimeValue ? [entry(upstashTokenEnvNames)] : []];
|
|
2889
|
+
if (store.driver === "redis" && store.url.startsWith("env:")) return [entry([store.url.slice(4)])];
|
|
2890
|
+
return [];
|
|
2891
|
+
}
|
|
2892
|
+
/**
|
|
2893
|
+
* The variables that the KV stores read on the deployed host: the Upstash REST URL and token, and the Redis URL
|
|
2894
|
+
* variable. Cloudflare KV, Database, Deno KV, and `fs-lite` stores read none.
|
|
2895
|
+
*/
|
|
2896
|
+
function kvDeploymentEnv(config) {
|
|
2897
|
+
if (!config) return [];
|
|
2898
|
+
return Object.values(config.stores ?? { default: config.store }).flatMap(storeEntries);
|
|
2899
|
+
}
|
|
2900
|
+
//#endregion
|
|
4805
2901
|
//#region src/vite.ts
|
|
2902
|
+
const operationsModule = ownModule(import.meta.url, "operations");
|
|
4806
2903
|
const RESOLVED_KV_VIRTUAL_CONFIG_ID = `\0${KV_VIRTUAL_CONFIG_ID}`;
|
|
4807
2904
|
const RESOLVED_KV_RUNTIME_ID = `\0#vitehub/kv/runtime`;
|
|
4808
|
-
const KV_ERRORS_IMPORT_ID =
|
|
2905
|
+
const KV_ERRORS_IMPORT_ID = ownModule(import.meta.url, "errors");
|
|
4809
2906
|
const UPSTASH_DRIVER_IMPORT_ID = "@vite-hub/kv/runtime/upstash-driver";
|
|
4810
|
-
const
|
|
2907
|
+
const REDIS_DRIVER_IMPORT_ID = "@vite-hub/kv/runtime/redis-driver";
|
|
2908
|
+
const DATABASE_VITE_PLUGIN_NAME = "@vite-hub/database/vite";
|
|
2909
|
+
const CLOUDFLARE_KV_RUNTIME_IMPORT_ID = ownModule(import.meta.url, "runtime/cloudflare-kv");
|
|
2910
|
+
const KV_CLOUDFLARE_REQUEST_ENV_MIDDLEWARE = ownModule(import.meta.url, "runtime/cloudflare-request-env");
|
|
2911
|
+
/**
|
|
2912
|
+
* File path of the unstorage driver over a KV store. Options: `store` (default: the default store) and `base` (a key prefix).
|
|
2913
|
+
* ViteHub mounts it at `kv`, `kv-<store>`, and, with `cache: { driver: "kv" }`, at `cache`.
|
|
2914
|
+
*/
|
|
2915
|
+
const kvStorageDriver = ownModule(import.meta.url, "runtime/unstorage-driver");
|
|
2916
|
+
const KV_NITRO_PLUGIN = ownModule(import.meta.url, "runtime/nitro-plugin");
|
|
4811
2917
|
const mergeNoExternal = createNoExternalAddition("@vite-hub/kv");
|
|
4812
2918
|
const KV_CLOUDFLARE_BINDINGS_FILE = ".vitehub-kv-bindings.json";
|
|
4813
|
-
|
|
2919
|
+
const OPTIONAL_PEER_ID_PATTERN = /^(?:@vite-hub\/kv\/runtime\/(?:redis|upstash)-driver|cloudflare:workers)$/;
|
|
2920
|
+
const RESOLVE_ID_PATTERN = /^(?:@vite-hub\/kv(?:\/runtime\/(?:redis|upstash)-driver)?|cloudflare:workers|#vitehub\/kv\/config)$/;
|
|
2921
|
+
const LOAD_ID_PATTERN = /^\0#vitehub\/kv\/(?:runtime|config)$/;
|
|
2922
|
+
function hubKVOptionalPeerResolver() {
|
|
4814
2923
|
return {
|
|
4815
2924
|
name: "@vite-hub/kv/optional-peers",
|
|
4816
2925
|
enforce: "pre",
|
|
4817
|
-
resolveId
|
|
4818
|
-
|
|
4819
|
-
|
|
4820
|
-
|
|
4821
|
-
id
|
|
4822
|
-
|
|
2926
|
+
resolveId: {
|
|
2927
|
+
filter: { id: OPTIONAL_PEER_ID_PATTERN },
|
|
2928
|
+
handler(id, importer, resolveOptions) {
|
|
2929
|
+
if (!resolveOptions?.ssr) return;
|
|
2930
|
+
if (isKVOptionalDriverImport(UPSTASH_DRIVER_IMPORT_ID, id, importer) || isKVOptionalDriverImport(REDIS_DRIVER_IMPORT_ID, id, importer) || isUnstorageCloudflareWorkersImport(id, importer)) return {
|
|
2931
|
+
external: true,
|
|
2932
|
+
id
|
|
2933
|
+
};
|
|
2934
|
+
}
|
|
4823
2935
|
}
|
|
4824
2936
|
};
|
|
4825
2937
|
}
|
|
4826
|
-
function
|
|
2938
|
+
function kvStores(kv) {
|
|
2939
|
+
return kv ? Object.values(kv.stores || { default: kv.store }) : [];
|
|
2940
|
+
}
|
|
2941
|
+
/** Redis is selected explicitly at build time. */
|
|
2942
|
+
function hasRedisStore(kv) {
|
|
2943
|
+
return kvStores(kv).some((store) => store.driver === "redis");
|
|
2944
|
+
}
|
|
2945
|
+
function hasDatabaseStore(kv) {
|
|
2946
|
+
return kvStores(kv).some((store) => store.driver === "database");
|
|
2947
|
+
}
|
|
2948
|
+
function findDatabasePlugin(plugins) {
|
|
2949
|
+
return plugins?.find((plugin) => plugin.name === DATABASE_VITE_PLUGIN_NAME);
|
|
2950
|
+
}
|
|
2951
|
+
function serializeVirtualConfig(config, databaseImport, durabilityReportsStores, env) {
|
|
2952
|
+
const resolveStore = (store) => env && store.driver === "upstash" ? resolveUpstashRuntimeValues(store, env) : store;
|
|
2953
|
+
const kv = config.kv && env ? {
|
|
2954
|
+
...config.kv,
|
|
2955
|
+
store: resolveStore(config.kv.store),
|
|
2956
|
+
...config.kv.stores ? { stores: Object.fromEntries(Object.entries(config.kv.stores).map(([name, store]) => [name, resolveStore(store)])) } : {}
|
|
2957
|
+
} : config.kv;
|
|
4827
2958
|
return [
|
|
4828
2959
|
`export const hosting = ${JSON.stringify(config.hosting)};`,
|
|
4829
|
-
`export const kv = ${JSON.stringify(
|
|
2960
|
+
`export const kv = ${JSON.stringify(kv)};`,
|
|
2961
|
+
`export const durabilityReportsStores = ${durabilityReportsStores};`,
|
|
2962
|
+
hasDatabaseStore(config.kv) ? `export const loadDatabases = () => import(${JSON.stringify(databaseImport)}).then(module => module.databases);` : "export const loadDatabases = undefined;",
|
|
4830
2963
|
"export default { hosting, kv };"
|
|
4831
2964
|
].join("\n");
|
|
4832
2965
|
}
|
|
4833
2966
|
function isCloudflareKVConfig(kv) {
|
|
4834
2967
|
if (!kv) return false;
|
|
4835
|
-
return Object.values(kv.stores || { default: kv.store }).every((store) => store.driver === "cloudflare
|
|
2968
|
+
return Object.values(kv.stores || { default: kv.store }).every((store) => store.driver === "cloudflare");
|
|
4836
2969
|
}
|
|
4837
|
-
function
|
|
2970
|
+
function hasCloudflareKVStore(kv) {
|
|
4838
2971
|
if (!kv) return false;
|
|
4839
|
-
return Object.values(kv.stores || { default: kv.store }).some((store) => store.driver === "
|
|
2972
|
+
return Object.values(kv.stores || { default: kv.store }).some((store) => store.driver === "cloudflare");
|
|
2973
|
+
}
|
|
2974
|
+
/**
|
|
2975
|
+
* Registers the KV Nitro plugin for Redis connections and inferred-store boot notices. It prints the driver of each inferred store at boot, and
|
|
2976
|
+
* disposes the stores when the server closes. Without it, the open connection keeps a Node process alive after a stop
|
|
2977
|
+
* signal.
|
|
2978
|
+
*/
|
|
2979
|
+
function configureNitroPlugin(nitro, kv) {
|
|
2980
|
+
const plugins = (nitro.plugins ?? []).filter((plugin) => plugin !== KV_NITRO_PLUGIN);
|
|
2981
|
+
if (hasRedisStore(kv) || kvStores(kv).some((store) => "inferred" in store && store.inferred)) plugins.push(KV_NITRO_PLUGIN);
|
|
2982
|
+
if (plugins.length || nitro.plugins) nitro.plugins = plugins;
|
|
2983
|
+
}
|
|
2984
|
+
/** The Nitro storage mount of a store: `kv` for the default store, `kv-<name>` for a named store. */
|
|
2985
|
+
function kvStorageMountName(store) {
|
|
2986
|
+
const segment = store.replace(/[%:/\\?]/g, (character) => encodeURIComponent(character)) || "%";
|
|
2987
|
+
return store === "default" ? "kv" : `kv-${segment}`;
|
|
2988
|
+
}
|
|
2989
|
+
/**
|
|
2990
|
+
* Mounts each KV store in Nitro storage, so `useStorage("kv")` and modules that take a mount name use the store.
|
|
2991
|
+
* A mount that the app set in `kv` or the deprecated `storage` option wins.
|
|
2992
|
+
*/
|
|
2993
|
+
function configureNitroStorage(nitro, kv) {
|
|
2994
|
+
if (!kv) return;
|
|
2995
|
+
const names = Object.keys({
|
|
2996
|
+
default: kv.store,
|
|
2997
|
+
...kv.stores
|
|
2998
|
+
});
|
|
2999
|
+
const mounts = isRecord(nitro.kv) ? nitro.kv : {};
|
|
3000
|
+
const legacy = isRecord(nitro.storage) ? nitro.storage : {};
|
|
3001
|
+
for (const store of names) {
|
|
3002
|
+
const mount = kvStorageMountName(store);
|
|
3003
|
+
if (Object.hasOwn(mounts, mount) || Object.hasOwn(legacy, mount)) continue;
|
|
3004
|
+
mounts[mount] = store === "default" ? { driver: kvStorageDriver } : {
|
|
3005
|
+
driver: kvStorageDriver,
|
|
3006
|
+
store
|
|
3007
|
+
};
|
|
3008
|
+
}
|
|
3009
|
+
if (Object.keys(mounts).length || nitro.kv) nitro.kv = mounts;
|
|
3010
|
+
}
|
|
3011
|
+
/** Registers the middleware that installs the request's Cloudflare env, or removes it when no store uses a binding. */
|
|
3012
|
+
function configureNitroCloudflareRequestEnv(nitro, kv) {
|
|
3013
|
+
const handlers = Array.isArray(nitro.handlers) ? nitro.handlers.filter((handler) => !(isRecord(handler) && handler.handler === KV_CLOUDFLARE_REQUEST_ENV_MIDDLEWARE)) : [];
|
|
3014
|
+
if (hasCloudflareKVStore(kv)) handlers.unshift({
|
|
3015
|
+
handler: KV_CLOUDFLARE_REQUEST_ENV_MIDDLEWARE,
|
|
3016
|
+
middleware: true
|
|
3017
|
+
});
|
|
3018
|
+
if (handlers.length || Array.isArray(nitro.handlers)) nitro.handlers = handlers;
|
|
3019
|
+
}
|
|
3020
|
+
function hasUpstashStore(kv) {
|
|
3021
|
+
return kvStores(kv).some((store) => store.driver === "upstash");
|
|
4840
3022
|
}
|
|
4841
|
-
|
|
4842
|
-
|
|
3023
|
+
/** The import of a provider driver from the KV runtime. A build without a store on that provider keeps it external. */
|
|
3024
|
+
function isKVOptionalDriverImport(driver, id, importer) {
|
|
3025
|
+
if (id !== driver || !importer) return false;
|
|
4843
3026
|
const normalizedImporter = importer.replace(/\\/g, "/").split("?", 1)[0];
|
|
4844
3027
|
return normalizedImporter.endsWith("/packages/kv/src/runtime/driver.ts") || normalizedImporter.endsWith("/packages/kv/dist/index.js") || normalizedImporter.includes("/@vite-hub/kv/dist/index.js");
|
|
4845
3028
|
}
|
|
3029
|
+
function isUnstorageCloudflareWorkersImport(id, importer) {
|
|
3030
|
+
if (id !== "cloudflare:workers" || !importer) return false;
|
|
3031
|
+
return /[/\\]unstorage[/\\]dist[/\\]/.test(importer);
|
|
3032
|
+
}
|
|
4846
3033
|
function createCloudflareKVWranglerConfig(kv, provisionState) {
|
|
4847
3034
|
if (!kv) return;
|
|
4848
3035
|
const target = {};
|
|
@@ -4852,7 +3039,7 @@ function createCloudflareKVWranglerConfig(kv, provisionState) {
|
|
|
4852
3039
|
function serializeCloudflareRuntime(config) {
|
|
4853
3040
|
return [
|
|
4854
3041
|
`import { createCloudflareKVStorage } from ${JSON.stringify(CLOUDFLARE_KV_RUNTIME_IMPORT_ID)};`,
|
|
4855
|
-
`import { kvInvalidLimitError, kvResult, kvStoreNotFoundError, kvUnsupportedOperationError } from ${JSON.stringify(KV_ERRORS_IMPORT_ID)};`,
|
|
3042
|
+
`import { kvClearOptionsError, kvInvalidLimitError, kvKeyLimitCodes, kvListLimitInvalid, kvResult, kvStoreNotFoundError, kvStoreWithMode, kvUnsupportedOperationError, kvWriteLimitCodes, listKVKeys } from ${JSON.stringify(KV_ERRORS_IMPORT_ID)};`,
|
|
4856
3043
|
"",
|
|
4857
3044
|
`const kvConfig = ${JSON.stringify(config, null, 2)}`,
|
|
4858
3045
|
"const storages = new Map();",
|
|
@@ -4865,6 +3052,10 @@ function serializeCloudflareRuntime(config) {
|
|
|
4865
3052
|
" return store;",
|
|
4866
3053
|
"}",
|
|
4867
3054
|
"",
|
|
3055
|
+
"export async function getKVStoreDriver(name = \"default\") {",
|
|
3056
|
+
" return resolveStoreConfig(name).driver;",
|
|
3057
|
+
"}",
|
|
3058
|
+
"",
|
|
4868
3059
|
"function resolveStorage(name = \"default\") {",
|
|
4869
3060
|
" const store = resolveStoreConfig(name);",
|
|
4870
3061
|
" const existing = storages.get(name);",
|
|
@@ -4882,16 +3073,24 @@ function serializeCloudflareRuntime(config) {
|
|
|
4882
3073
|
"// kvResult throws config errors, for example an unknown store, and returns the other errors.",
|
|
4883
3074
|
"function createKVStorage(name = \"default\") {",
|
|
4884
3075
|
" return {",
|
|
4885
|
-
" async clear(
|
|
4886
|
-
"
|
|
4887
|
-
"
|
|
3076
|
+
" async clear(options) {",
|
|
3077
|
+
" const error = kvClearOptionsError(options);",
|
|
3078
|
+
" if (error) return [error, undefined];",
|
|
3079
|
+
" return kvResult(\"clear\", name, async () => { await resolveStorage(name).clear(options?.prefix); });",
|
|
3080
|
+
" },",
|
|
3081
|
+
" async delete(key, options) { return kvResult(\"delete\", name, async () => { await resolveStorage(name).removeItem(key, options); }, kvKeyLimitCodes); },",
|
|
3082
|
+
" async deleteIfEquals() { return unsupported(\"deleteIfEquals\", name); },",
|
|
3083
|
+
" async get(key, options) { return kvResult(\"get\", name, () => resolveStorage(name).getItem(key, options), kvKeyLimitCodes); },",
|
|
4888
3084
|
" async getAndDelete() { return unsupported(\"getAndDelete\", name); },",
|
|
4889
|
-
" async
|
|
3085
|
+
" async getMany(keys, options) { return kvResult(\"getMany\", name, () => resolveStorage(name).getMany(keys, options), kvKeyLimitCodes); },",
|
|
3086
|
+
" async has(key, options) { return kvResult(\"has\", name, () => resolveStorage(name).hasItem(key, options), kvKeyLimitCodes); },",
|
|
4890
3087
|
" async increment() { return unsupported(\"increment\", name); },",
|
|
4891
|
-
" async
|
|
4892
|
-
" async list(options) { if (
|
|
4893
|
-
" async set(key, value, options) { return kvResult(\"set\", name, async () => { await resolveStorage(name).setItem(key, value, options); }); },",
|
|
4894
|
-
"
|
|
3088
|
+
" lock() { return { async acquire() { return unsupported(\"lock\", name); }, async run() { return unsupported(\"lock\", name); } }; },",
|
|
3089
|
+
" async list(options = {}) { if (kvListLimitInvalid(options)) return [kvInvalidLimitError(), undefined]; return kvResult(\"list\", name, () => listKVKeys(page => resolveStorage(name).listKeys(page), options), [\"KV_INVALID_CURSOR\"]); },",
|
|
3090
|
+
" async set(key, value, options) { return kvResult(\"set\", name, async () => { await resolveStorage(name).setItem(key, value, options); }, kvWriteLimitCodes); },",
|
|
3091
|
+
" async setMany(entries, options) { return kvResult(\"setMany\", name, async () => { await resolveStorage(name).setMany(entries, options); }, kvWriteLimitCodes); },",
|
|
3092
|
+
" async setIfAbsent() { return unsupported(\"setIfAbsent\", name); },",
|
|
3093
|
+
" store(storeName, options) { return kvStoreWithMode(createKVStorage(storeName), options); },",
|
|
4895
3094
|
" };",
|
|
4896
3095
|
"}",
|
|
4897
3096
|
"",
|
|
@@ -4900,11 +3099,11 @@ function serializeCloudflareRuntime(config) {
|
|
|
4900
3099
|
].join("\n");
|
|
4901
3100
|
}
|
|
4902
3101
|
function getNitroCloudflareKVNamespaces(target) {
|
|
4903
|
-
if (!
|
|
3102
|
+
if (!isRecord(target)) return [];
|
|
4904
3103
|
const cloudflare = Reflect.get(target, "cloudflare");
|
|
4905
|
-
if (!
|
|
3104
|
+
if (!isRecord(cloudflare)) return [];
|
|
4906
3105
|
const wrangler = Reflect.get(cloudflare, "wrangler");
|
|
4907
|
-
if (!
|
|
3106
|
+
if (!isRecord(wrangler)) return [];
|
|
4908
3107
|
const namespaces = Reflect.get(wrangler, "kv_namespaces");
|
|
4909
3108
|
if (!Array.isArray(namespaces)) return [];
|
|
4910
3109
|
return namespaces.flatMap((namespace) => {
|
|
@@ -4919,10 +3118,12 @@ function getNitroCloudflareKVNamespaces(target) {
|
|
|
4919
3118
|
const id = Reflect.get(normalized, "id");
|
|
4920
3119
|
const previewId = Reflect.get(normalized, "preview_id");
|
|
4921
3120
|
const experimentalRemote = Reflect.get(normalized, "experimental_remote");
|
|
3121
|
+
const remote = Reflect.get(normalized, "remote");
|
|
4922
3122
|
if (typeof binding !== "string") return [];
|
|
4923
3123
|
if (id !== void 0 && typeof id !== "string") return [];
|
|
4924
3124
|
if (previewId !== void 0 && typeof previewId !== "string") return [];
|
|
4925
3125
|
if (experimentalRemote !== void 0 && typeof experimentalRemote !== "boolean") return [];
|
|
3126
|
+
if (remote !== void 0 && typeof remote !== "boolean") return [];
|
|
4926
3127
|
return [normalized];
|
|
4927
3128
|
});
|
|
4928
3129
|
}
|
|
@@ -4930,6 +3131,9 @@ function getResolvedNitroConfig(config) {
|
|
|
4930
3131
|
return Reflect.get(config, "nitro");
|
|
4931
3132
|
}
|
|
4932
3133
|
function reconcileNitroCloudflareKV(target, kv, ownedNamespaces, provisionState) {
|
|
3134
|
+
configureNitroCloudflareRequestEnv(target, kv);
|
|
3135
|
+
configureNitroPlugin(target, kv);
|
|
3136
|
+
configureNitroStorage(target, kv);
|
|
4933
3137
|
const namespaces = target.cloudflare?.wrangler?.kv_namespaces;
|
|
4934
3138
|
if (namespaces?.length && ownedNamespaces.size) for (const owned of ownedNamespaces) {
|
|
4935
3139
|
const ownedIndex = namespaces.findIndex((namespace) => namespace.binding === owned.binding && namespace.id === owned.id);
|
|
@@ -4937,14 +3141,17 @@ function reconcileNitroCloudflareKV(target, kv, ownedNamespaces, provisionState)
|
|
|
4937
3141
|
}
|
|
4938
3142
|
if (kv) configureCloudflareKV(target, kv, provisionState);
|
|
4939
3143
|
}
|
|
4940
|
-
function configureNitroCloudflareKV(config, options, ownedNamespaces, provisionState) {
|
|
4941
|
-
const
|
|
4942
|
-
if (!
|
|
3144
|
+
function configureNitroCloudflareKV(config, options, input, ownedNamespaces, provisionState) {
|
|
3145
|
+
const nitro = Reflect.get(config, "nitro");
|
|
3146
|
+
if (!isRecord(nitro)) return false;
|
|
4943
3147
|
const target = nitro;
|
|
4944
3148
|
const namespaces = target.cloudflare?.wrangler?.kv_namespaces;
|
|
4945
3149
|
if (namespaces && ownedNamespaces.size) target.cloudflare.wrangler.kv_namespaces = namespaces.filter((namespace) => !ownedNamespaces.has(namespace));
|
|
4946
3150
|
ownedNamespaces.clear();
|
|
4947
|
-
const kv = resolveKVViteConfig(
|
|
3151
|
+
const kv = resolveKVViteConfig(options, input).kv;
|
|
3152
|
+
configureNitroCloudflareRequestEnv(target, kv);
|
|
3153
|
+
configureNitroPlugin(target, kv);
|
|
3154
|
+
configureNitroStorage(target, kv);
|
|
4948
3155
|
if (kv) {
|
|
4949
3156
|
const existingNamespaces = new Set(target.cloudflare?.wrangler?.kv_namespaces);
|
|
4950
3157
|
configureCloudflareKV(target, kv, provisionState);
|
|
@@ -4952,33 +3159,118 @@ function configureNitroCloudflareKV(config, options, ownedNamespaces, provisionS
|
|
|
4952
3159
|
}
|
|
4953
3160
|
return true;
|
|
4954
3161
|
}
|
|
4955
|
-
|
|
3162
|
+
/** `input.hosting` names the host preset for driver inference, as `vitehub()` passes it. Without it, KV reads the host from env. */
|
|
3163
|
+
function hubKV(options, input = {}) {
|
|
3164
|
+
let command = "build";
|
|
3165
|
+
let mode = "development";
|
|
3166
|
+
let viteEnv;
|
|
3167
|
+
let databasePlugin;
|
|
3168
|
+
const databaseImport = input.databaseImport ?? "@vite-hub/database/runtime/registry";
|
|
3169
|
+
const postgresDatabase = () => databasePlugin?.api?.getConfig?.()?.databases.default?.dialect === "postgresql";
|
|
3170
|
+
const resolutionInput = () => ({
|
|
3171
|
+
dev: command === "serve",
|
|
3172
|
+
env: command === "serve" ? viteEnv : void 0,
|
|
3173
|
+
hosting: input.hosting,
|
|
3174
|
+
postgresDatabase: postgresDatabase()
|
|
3175
|
+
});
|
|
4956
3176
|
let nitroOwned = false;
|
|
4957
3177
|
let nitroOptions;
|
|
4958
3178
|
const ownedNitroNamespaces = /* @__PURE__ */ new Set();
|
|
4959
3179
|
let resolved;
|
|
4960
3180
|
let providerOutput;
|
|
4961
3181
|
let runtimeConfig;
|
|
4962
|
-
let configuredOptions = options;
|
|
4963
3182
|
let projectRoot = process.cwd();
|
|
4964
|
-
const getConfig = () => runtimeConfig ??= resolveKVViteConfig(options);
|
|
3183
|
+
const getConfig = () => runtimeConfig ??= resolveKVViteConfig(options, resolutionInput());
|
|
4965
3184
|
const providerOutputGenerations = createProviderDeploymentOutputGenerationState();
|
|
3185
|
+
function reportRedisEnvHint(config) {
|
|
3186
|
+
const hint = kvRedisEnvHint(options, {
|
|
3187
|
+
...resolutionInput(),
|
|
3188
|
+
env: {
|
|
3189
|
+
...viteEnv,
|
|
3190
|
+
...process.env
|
|
3191
|
+
},
|
|
3192
|
+
hosting: getConfig().hosting
|
|
3193
|
+
});
|
|
3194
|
+
if (hint) reportViteHubHint(config, hint);
|
|
3195
|
+
}
|
|
4966
3196
|
return {
|
|
4967
3197
|
name: KV_VITE_PLUGIN_NAME,
|
|
4968
3198
|
enforce: "post",
|
|
4969
|
-
api: {
|
|
3199
|
+
api: {
|
|
3200
|
+
deploymentEnv: () => kvDeploymentEnv(getConfig().kv),
|
|
3201
|
+
getBuildConfig: () => resolveKVViteConfig(options, {
|
|
3202
|
+
hosting: input.hosting,
|
|
3203
|
+
postgresDatabase: postgresDatabase()
|
|
3204
|
+
}),
|
|
3205
|
+
getConfig
|
|
3206
|
+
},
|
|
4970
3207
|
nitro: {
|
|
4971
3208
|
name: "@vite-hub/kv/cloudflare-bindings",
|
|
4972
3209
|
setup(nitro) {
|
|
4973
3210
|
nitroOptions = nitro.options;
|
|
4974
3211
|
if (runtimeConfig) reconcileNitroCloudflareKV(nitroOptions, runtimeConfig.kv, ownedNitroNamespaces, readProvisionStateSync(projectRoot));
|
|
3212
|
+
nitro.hooks?.hook("prerender:config", (config) => {
|
|
3213
|
+
const prerender = resolveKVViteConfig(options, {
|
|
3214
|
+
hosting: input.hosting,
|
|
3215
|
+
prerender: true
|
|
3216
|
+
});
|
|
3217
|
+
if (prerender.kv && Object.values({
|
|
3218
|
+
...prerender.kv.stores,
|
|
3219
|
+
default: prerender.kv.store
|
|
3220
|
+
}).some((store) => store.driver === "deno-kv")) return;
|
|
3221
|
+
config.virtual = {
|
|
3222
|
+
...config.virtual,
|
|
3223
|
+
[KV_VIRTUAL_CONFIG_ID]: () => serializeVirtualConfig(prerender, databaseImport, true)
|
|
3224
|
+
};
|
|
3225
|
+
});
|
|
4975
3226
|
}
|
|
4976
3227
|
},
|
|
4977
3228
|
vitehub: {
|
|
3229
|
+
durability: () => {
|
|
3230
|
+
const kv = getConfig().kv;
|
|
3231
|
+
if (!kv) return [];
|
|
3232
|
+
return [{
|
|
3233
|
+
export: "kvDurability",
|
|
3234
|
+
input: { stores: Object.fromEntries(Object.entries({
|
|
3235
|
+
default: kv.store,
|
|
3236
|
+
...kv.stores
|
|
3237
|
+
}).map(([name, store]) => {
|
|
3238
|
+
const database = Reflect.get(store, "database");
|
|
3239
|
+
return [name, {
|
|
3240
|
+
driver: store.driver,
|
|
3241
|
+
..."base" in store && store.base ? { base: store.base } : {},
|
|
3242
|
+
...typeof database === "string" ? { database } : {}
|
|
3243
|
+
}];
|
|
3244
|
+
})) },
|
|
3245
|
+
module: durabilityModuleFile(import.meta.url),
|
|
3246
|
+
primitive: "kv"
|
|
3247
|
+
}];
|
|
3248
|
+
},
|
|
3249
|
+
inspect: () => {
|
|
3250
|
+
const build = resolveKVViteConfig(options, {
|
|
3251
|
+
hosting: input.hosting,
|
|
3252
|
+
postgresDatabase: postgresDatabase()
|
|
3253
|
+
}).kv;
|
|
3254
|
+
const dev = resolveKVViteConfig(options, {
|
|
3255
|
+
dev: true,
|
|
3256
|
+
env: viteEnv,
|
|
3257
|
+
hosting: input.hosting
|
|
3258
|
+
}).kv;
|
|
3259
|
+
if (!build || !dev) return;
|
|
3260
|
+
const file = resolved?.configFile ? relativeDefinitionFile(projectRoot, resolved.configFile) : "vite.config.ts";
|
|
3261
|
+
return {
|
|
3262
|
+
definitions: [{
|
|
3263
|
+
kind: "kv",
|
|
3264
|
+
label: "KV stores",
|
|
3265
|
+
list: () => inspectKVStores(build, dev, file)
|
|
3266
|
+
}],
|
|
3267
|
+
resources: () => inspectKVResources(options, projectRoot)
|
|
3268
|
+
};
|
|
3269
|
+
},
|
|
4978
3270
|
operations: [{
|
|
4979
3271
|
export: "kvOperations",
|
|
4980
3272
|
load: async () => (await (import.meta.url.endsWith(".ts") ? import("./operations.js") : import("./operations.js"))).kvOperations,
|
|
4981
|
-
module:
|
|
3273
|
+
module: operationsModule
|
|
4982
3274
|
}],
|
|
4983
3275
|
cli: async () => {
|
|
4984
3276
|
const { createKVCliContributor } = await import(
|
|
@@ -4986,31 +3278,42 @@ function hubKv(options) {
|
|
|
4986
3278
|
"./cli.js"
|
|
4987
3279
|
);
|
|
4988
3280
|
return {
|
|
4989
|
-
...createKVCliContributor(),
|
|
4990
|
-
provision: [createKVCloudflareProvisionStep(() =>
|
|
3281
|
+
...createKVCliContributor({ projectRoot: () => projectRoot }),
|
|
3282
|
+
provision: [createKVCloudflareProvisionStep(() => options)]
|
|
4991
3283
|
};
|
|
4992
3284
|
}
|
|
4993
3285
|
},
|
|
4994
3286
|
config: {
|
|
4995
3287
|
order: "pre",
|
|
4996
|
-
handler(config, env) {
|
|
4997
|
-
|
|
3288
|
+
async handler(config, env) {
|
|
3289
|
+
command = env?.command ?? "build";
|
|
3290
|
+
mode = env?.mode ?? config.mode ?? (command === "serve" ? "development" : "production");
|
|
3291
|
+
runtimeConfig = void 0;
|
|
4998
3292
|
projectRoot = resolveViteHubProjectRoot(config.root || process.cwd());
|
|
4999
|
-
|
|
5000
|
-
|
|
3293
|
+
viteEnv = loadAllEnv((await import("vite")).loadEnv, mode, config.envDir === false ? false : resolve(config.root || process.cwd(), config.envDir ?? "."));
|
|
3294
|
+
nitroOwned = configureNitroCloudflareKV(config, options, resolutionInput(), ownedNitroNamespaces, readProvisionStateSync(projectRoot));
|
|
3295
|
+
return installStandaloneOperationRpc(config, env?.command ?? "build", operationsModule);
|
|
5001
3296
|
}
|
|
5002
3297
|
},
|
|
5003
3298
|
configResolved: {
|
|
5004
3299
|
order: "pre",
|
|
5005
|
-
handler(config) {
|
|
3300
|
+
async handler(config) {
|
|
5006
3301
|
resolved = config;
|
|
5007
|
-
|
|
3302
|
+
startViteHubHints(config);
|
|
3303
|
+
if (config.command) command = config.command;
|
|
3304
|
+
mode = config.mode ?? mode;
|
|
5008
3305
|
projectRoot = resolveViteHubProjectRoot(config.root || process.cwd());
|
|
3306
|
+
viteEnv = loadAllEnv((await import("vite")).loadEnv, mode, config.envDir === false ? false : resolve(config.root || process.cwd(), config.envDir ?? "."));
|
|
3307
|
+
databasePlugin = findDatabasePlugin(config.plugins);
|
|
5009
3308
|
providerOutput = useProviderOutputCatalog(config);
|
|
5010
|
-
runtimeConfig = resolveKVViteConfig(
|
|
3309
|
+
runtimeConfig = resolveKVViteConfig(options, resolutionInput());
|
|
5011
3310
|
const provisionState = readProvisionStateSync(projectRoot);
|
|
5012
3311
|
if (nitroOptions) reconcileNitroCloudflareKV(nitroOptions, runtimeConfig.kv, ownedNitroNamespaces, provisionState);
|
|
5013
|
-
if (hasNitroConfigContext(config) ||
|
|
3312
|
+
if (hasNitroConfigContext(config) || isRecord(getResolvedNitroConfig(config))) nitroOwned = configureNitroCloudflareKV(config, options, resolutionInput(), ownedNitroNamespaces, provisionState);
|
|
3313
|
+
if (!config.command && command === "build" && Reflect.get(config, "__vitehubNuxtHints")) reportRedisEnvHint({
|
|
3314
|
+
...config,
|
|
3315
|
+
command
|
|
3316
|
+
});
|
|
5014
3317
|
}
|
|
5015
3318
|
},
|
|
5016
3319
|
configureServer(server) {
|
|
@@ -5025,29 +3328,45 @@ function hubKv(options) {
|
|
|
5025
3328
|
},
|
|
5026
3329
|
resolveId: {
|
|
5027
3330
|
order: "pre",
|
|
3331
|
+
filter: { id: RESOLVE_ID_PATTERN },
|
|
5028
3332
|
handler(id, importer, resolveOptions) {
|
|
5029
|
-
if (id === UPSTASH_DRIVER_IMPORT_ID && resolveOptions?.ssr && !hasUpstashStore(getConfig().kv) &&
|
|
3333
|
+
if (id === UPSTASH_DRIVER_IMPORT_ID && resolveOptions?.ssr && !hasUpstashStore(getConfig().kv) && isKVOptionalDriverImport(UPSTASH_DRIVER_IMPORT_ID, id, importer)) return {
|
|
3334
|
+
external: true,
|
|
3335
|
+
id
|
|
3336
|
+
};
|
|
3337
|
+
if (id === REDIS_DRIVER_IMPORT_ID && resolveOptions?.ssr && !hasRedisStore(getConfig().kv) && isKVOptionalDriverImport(REDIS_DRIVER_IMPORT_ID, id, importer)) return {
|
|
5030
3338
|
external: true,
|
|
5031
3339
|
id
|
|
5032
3340
|
};
|
|
5033
|
-
if (
|
|
3341
|
+
if (resolveOptions?.ssr && isUnstorageCloudflareWorkersImport(id, importer)) return {
|
|
3342
|
+
external: true,
|
|
3343
|
+
id
|
|
3344
|
+
};
|
|
3345
|
+
if (id === "@vite-hub/kv" && command === "build" && isCloudflareKVConfig(getConfig().kv)) return RESOLVED_KV_RUNTIME_ID;
|
|
5034
3346
|
if (id === "#vitehub/kv/config") return RESOLVED_KV_VIRTUAL_CONFIG_ID;
|
|
5035
3347
|
}
|
|
5036
3348
|
},
|
|
5037
3349
|
load: {
|
|
5038
3350
|
order: "pre",
|
|
5039
|
-
|
|
3351
|
+
filter: { id: LOAD_ID_PATTERN },
|
|
3352
|
+
handler(id, options) {
|
|
5040
3353
|
if (id === RESOLVED_KV_RUNTIME_ID) {
|
|
5041
3354
|
const kv = getConfig().kv;
|
|
5042
|
-
if (isCloudflareKVConfig(kv)) return serializeCloudflareRuntime(kv);
|
|
3355
|
+
if (command === "build" && isCloudflareKVConfig(kv)) return serializeCloudflareRuntime(kv);
|
|
3356
|
+
}
|
|
3357
|
+
if (id === RESOLVED_KV_VIRTUAL_CONFIG_ID) {
|
|
3358
|
+
const durabilityReportsStores = command === "build" && (resolved?.plugins?.some((plugin) => plugin.name === "vite-hub/durability/nitro") ?? false);
|
|
3359
|
+
return serializeVirtualConfig(getConfig(), databaseImport, durabilityReportsStores, command === "serve" && options?.ssr ? viteEnv : void 0);
|
|
5043
3360
|
}
|
|
5044
|
-
if (id === RESOLVED_KV_VIRTUAL_CONFIG_ID) return serializeVirtualConfig(getConfig());
|
|
5045
3361
|
}
|
|
5046
3362
|
},
|
|
5047
3363
|
buildStart: {
|
|
5048
3364
|
order: "pre",
|
|
5049
3365
|
handler() {
|
|
3366
|
+
runtimeConfig = void 0;
|
|
5050
3367
|
providerOutputGenerations.capture(this, providerOutput);
|
|
3368
|
+
if (command !== "build" || !resolved) return;
|
|
3369
|
+
reportRedisEnvHint(resolved);
|
|
5051
3370
|
}
|
|
5052
3371
|
},
|
|
5053
3372
|
buildEnd: {
|
|
@@ -5057,7 +3376,7 @@ function hubKv(options) {
|
|
|
5057
3376
|
await providerOutputGenerations.reset(this, providerOutput, error);
|
|
5058
3377
|
return;
|
|
5059
3378
|
}
|
|
5060
|
-
if (!resolved || shouldSkipViteProviderBuild(resolved.command
|
|
3379
|
+
if (!resolved || shouldSkipViteProviderBuild(resolved.command)) return;
|
|
5061
3380
|
const rootDir = resolved.root;
|
|
5062
3381
|
const clientOutDir = resolved.build.outDir;
|
|
5063
3382
|
const wranglerConfig = nitroOwned ? void 0 : createCloudflareKVWranglerConfig(getConfig().kv, readProvisionStateSync(projectRoot));
|
|
@@ -5097,11 +3416,11 @@ function hubKv(options) {
|
|
|
5097
3416
|
order: "post",
|
|
5098
3417
|
sequential: true,
|
|
5099
3418
|
async handler() {
|
|
5100
|
-
if (!resolved || shouldSkipViteProviderBuild(resolved.command
|
|
3419
|
+
if (!resolved || shouldSkipViteProviderBuild(resolved.command)) return;
|
|
5101
3420
|
await finalizeProviderDeploymentOutputs(providerOutput);
|
|
5102
3421
|
}
|
|
5103
3422
|
}
|
|
5104
3423
|
};
|
|
5105
3424
|
}
|
|
5106
3425
|
//#endregion
|
|
5107
|
-
export { KV_VIRTUAL_CONFIG_ID, KV_VITE_PLUGIN_NAME,
|
|
3426
|
+
export { KV_VIRTUAL_CONFIG_ID, KV_VITE_PLUGIN_NAME, hubKV, hubKVOptionalPeerResolver, kvStorageDriver, resolveKVViteConfig };
|