@vite-hub/rate-limit 0.1.0 → 0.3.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.
Files changed (39) hide show
  1. package/README.md +18 -14
  2. package/dist/cli-szm60zN5.d.ts +163 -0
  3. package/dist/cli.d.ts +1 -1
  4. package/dist/cli.js +12 -26
  5. package/dist/{cloudflare-DUDRACVB.js → cloudflare-otBvOPv4.js} +5 -4
  6. package/dist/{counters-pKORpgGd.d.ts → counters-DXpF67J_.d.ts} +3 -3
  7. package/dist/{counters-wdEMxDEY.js → counters-DgVdHwdL.js} +13 -6
  8. package/dist/dev-peer-CHafxbtj.js +238 -0
  9. package/dist/drivers/cloudflare.d.ts +1 -1
  10. package/dist/drivers/cloudflare.js +1 -1
  11. package/dist/drivers/kv.d.ts +2 -0
  12. package/dist/drivers/kv.js +92 -0
  13. package/dist/drivers/memory.d.ts +1 -1
  14. package/dist/drivers/memory.js +5 -5
  15. package/dist/durability.d.ts +12 -0
  16. package/dist/durability.js +35 -0
  17. package/dist/error-diagnostics-MgAnhRTP.js +234 -0
  18. package/dist/index.d.ts +16 -7
  19. package/dist/index.js +108 -38
  20. package/dist/{inspect-D-FzyM_x.js → inspect-B6gTdgy9.js} +7 -1
  21. package/dist/kv-C1wpLulE.d.ts +29 -0
  22. package/dist/{limiter-DBrMI4vi.js → kv-provider-C1S6dRTR.js} +16 -9
  23. package/dist/{operations-tNUdj3G4.d.ts → operation-definition-8gOe-ubD.d.ts} +37 -15
  24. package/dist/operations-BYRa7wpx.js +1355 -0
  25. package/dist/{operations-Bu-xulNd.js → operations-CLI9w3rO.js} +9 -14
  26. package/dist/operations.d.ts +9 -4
  27. package/dist/operations.js +51 -23
  28. package/dist/runtime.d.ts +21 -3
  29. package/dist/runtime.js +2 -2
  30. package/dist/state-BU-zcLNY.js +89 -0
  31. package/dist/{types-CQEJpgtz.d.ts → types-CMyR1JeW.d.ts} +43 -23
  32. package/dist/vite.d.ts +131 -21
  33. package/dist/vite.js +349 -2479
  34. package/package.json +21 -17
  35. package/dist/cli-Cniq99iX.d.ts +0 -85
  36. package/dist/error-diagnostics-CTAC_bbr.js +0 -56
  37. package/dist/h3-v1-request-qoGwJr5-.js +0 -235
  38. package/dist/operations-B09NnEjT.js +0 -1438
  39. package/dist/state-Ct7zR8fD.js +0 -43
package/dist/vite.js CHANGED
@@ -1,21 +1,121 @@
1
- import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-CTAC_bbr.js";
2
- import { i as rateLimitPolicyKeys, n as declaredRateLimitPolicy, r as normalizeRateLimitPolicy, t as createRateLimiter } from "./limiter-DBrMI4vi.js";
1
+ import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-MgAnhRTP.js";
2
+ import { a as rateLimitPolicyKeys, i as normalizeRateLimitPolicy, n as createRateLimiter, r as declaredRateLimitPolicy, t as resolveKVRateLimitDriver } from "./kv-provider-C1S6dRTR.js";
3
+ import { kvRateLimitDriver } from "./drivers/kv.js";
3
4
  import { memoryRateLimitDriver } from "./drivers/memory.js";
4
- import { n as getCloudflareRateLimitBindingName, t as cloudflareRateLimitDriver } from "./cloudflare-DUDRACVB.js";
5
- import { n as relativeDefinitionFile, r as resolve$1 } from "./inspect-D-FzyM_x.js";
6
- import { S as isPlainObject, _ as shouldSkipViteProviderBuild, b as removeViteHubDevServerFile, c as operationRpcPath, g as resolveViteHubProjectRoot, h as isServerEnvironment, m as createNoExternalAddition, p as internalErrorDiagnostics, r as collectOperationContributions, v as readViteHubDevServerFile, x as writeViteHubDevServerFile } from "./operations-B09NnEjT.js";
7
- import { createRequire } from "node:module";
8
- import { existsSync, readFileSync, readdirSync } from "node:fs";
9
- import { basename, relative, resolve } from "node:path";
5
+ import { n as getCloudflareRateLimitBindingName, t as cloudflareRateLimitDriver } from "./cloudflare-otBvOPv4.js";
6
+ import { i as resolve$1, n as relativeDefinitionFile, r as dirname$1 } from "./inspect-B6gTdgy9.js";
7
+ import { C as isServerEnvironment, D as readViteHubDevServerFile, M as cloneRecord, N as isRecord, P as isRecordOrFunction, S as getResolvedFeatureOptions, T as shouldSkipViteProviderBuild, _ as invariant, b as createNoExternalAddition, j as writeViteHubDevServerFile, k as removeViteHubDevServerFile, m as operationRpcPath, r as collectOperationContributions, v as internalErrorDiagnostics, w as resolveViteHubProjectRoot, x as getDeploymentHost, y as VITEHUB_PROJECT_ROOT } from "./operations-BYRa7wpx.js";
8
+ import { t as addViteHubDevPeerDevHandler } from "./dev-peer-CHafxbtj.js";
9
+ import { formatDiagnostic } from "nostics";
10
+ import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
10
11
  import { mkdir, readFile, writeFile } from "node:fs/promises";
12
+ import { basename, dirname, relative, resolve } from "node:path";
13
+ import { fileURLToPath } from "node:url";
11
14
  import { Visitor, parseSync } from "vite";
12
- //#region \0rolldown/runtime.js
13
- var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
14
- var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
15
+ //#region ../internal/src/hints.ts
16
+ /**
17
+ * The file that lists the hints of the last build or dev server, relative to the project root. A hint is a warning
18
+ * about something that works now and fails later, such as counts that stay in one server's memory. Agents and CI read
19
+ * the file instead of the terminal.
20
+ */
21
+ const viteHubHintsFile = ".vitehub/hints.json";
22
+ const runsKey = Symbol.for("vitehub.hints.runs");
23
+ const shared = globalThis;
24
+ const runs = shared[runsKey] ??= /* @__PURE__ */ new Map();
25
+ const startedKey = Symbol.for("vitehub.hints.started");
26
+ const startedShared = globalThis;
27
+ const started = startedShared[startedKey] ??= /* @__PURE__ */ new WeakSet();
28
+ /**
29
+ * The report of the ViteHub project root, where the other generated files go. A Nuxt app with `srcDir: "app"` has its
30
+ * Vite root in `app/`, one folder below.
31
+ */
32
+ function hintsFile(config) {
33
+ const projectRoot = Reflect.get(config, VITEHUB_PROJECT_ROOT);
34
+ return resolve(typeof projectRoot === "string" ? projectRoot : resolveViteHubProjectRoot(config.root), viteHubHintsFile);
35
+ }
36
+ function startRun(config) {
37
+ const file = hintsFile(config);
38
+ const run = {
39
+ file,
40
+ report: {
41
+ version: 1,
42
+ command: config.command,
43
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
44
+ hints: []
45
+ },
46
+ keys: /* @__PURE__ */ new Set()
47
+ };
48
+ runs.set(file, run);
49
+ return run;
50
+ }
51
+ function write(run) {
52
+ mkdirSync(dirname(run.file), { recursive: true });
53
+ writeFileSync(run.file, `${JSON.stringify(run.report, null, 2)}\n`);
54
+ }
55
+ /**
56
+ * Reports a hint from a Vite plugin hook: prints it once with its fix and docs link, and adds it to
57
+ * {@link viteHubHintsFile}. Build the diagnostic from the package's nostics catalog, so its code has a docs page.
58
+ */
59
+ function reportViteHubHint(config, diagnostic) {
60
+ const run = runs.get(hintsFile(config)) ?? startRun(config);
61
+ const hint = {
62
+ code: diagnostic.code,
63
+ why: diagnostic.why,
64
+ ...diagnostic.fix ? { fix: diagnostic.fix } : {},
65
+ ...diagnostic.docs ? { docs: diagnostic.docs } : {},
66
+ ...diagnostic.sources?.length ? { sources: diagnostic.sources } : {}
67
+ };
68
+ const key = JSON.stringify([hint.code, hint.sources ?? []]);
69
+ if (run.keys.has(key)) return;
70
+ run.keys.add(key);
71
+ run.report.hints.push(hint);
72
+ write(run);
73
+ config.logger.warn(formatDiagnostic(diagnostic));
74
+ }
75
+ /**
76
+ * Starts the hints of a build or dev server: writes an empty {@link viteHubHintsFile}, so a run without hints does not
77
+ * leave the hints of an earlier run in place. Every plugin that reports hints calls it from `configResolved`, so a
78
+ * package used without `vitehub()` starts its own run. The first call for a resolved config starts the run, and the
79
+ * calls of other plugins of the same build keep it.
80
+ */
81
+ function startViteHubHints(config) {
82
+ if (started.has(config)) return;
83
+ started.add(config);
84
+ write(startRun(config));
85
+ }
86
+ //#endregion
87
+ //#region ../internal/src/build/paths.ts
88
+ function resolveRuntimeModule(packageDir, modulePath) {
89
+ const distFile = resolve$1(packageDir, "dist", `${modulePath}.js`);
90
+ return existsSync(distFile) ? distFile : resolve$1(packageDir, "src", `${modulePath}.ts`);
91
+ }
92
+ const packageDirs = /* @__PURE__ */ new Map();
93
+ function findPackageDir(file) {
94
+ const start = dirname$1(file);
95
+ const cached = packageDirs.get(start);
96
+ if (cached) return cached;
97
+ let dir = start;
98
+ while (!existsSync(resolve$1(dir, "package.json"))) {
99
+ const parent = dirname$1(dir);
100
+ invariant(parent !== dir, `a file that a package resolver found has a package.json above it (${file})`);
101
+ dir = parent;
102
+ }
103
+ packageDirs.set(start, dir);
104
+ return dir;
105
+ }
106
+ /**
107
+ * The absolute path of a module that the calling package builds, such as `ownModule(import.meta.url, "runtime/state")`.
108
+ * Owner plugins write this path into generated code, so the module needs no package export, and an app resolves it
109
+ * only when the owner's feature is on. It is the `dist` file, or the `src` file before the package is built.
110
+ */
111
+ function ownModule(importMetaUrl, modulePath) {
112
+ return resolveRuntimeModule(findPackageDir(fileURLToPath(importMetaUrl)), modulePath);
113
+ }
15
114
  //#endregion
16
115
  //#region ../internal/src/definition-catalog.ts
17
116
  const sourceFilePattern = /\.(?:c|m)?[jt]sx?$/i;
18
117
  const declarationFilePattern = /\.d\.(?:c|m)?[jt]sx?$/i;
118
+ const testFilePattern = /\.(?:test|spec)\.(?:c|m)?[jt]sx?$/i;
19
119
  const ignoredDirs = /* @__PURE__ */ new Set([
20
120
  "node_modules",
21
121
  "dist",
@@ -55,9 +155,14 @@ function listMatchingFiles(root, predicate, options = {}) {
55
155
  }
56
156
  return files.sort();
57
157
  }
158
+ /** A module that a Definitions folder can hold: JavaScript or TypeScript, and not a declaration, test, or spec file. */
159
+ function isDefinitionSourceFile(name) {
160
+ return sourceFilePattern.test(name) && !declarationFilePattern.test(name) && !testFilePattern.test(name);
161
+ }
58
162
  function listSourceFiles(root, options = {}) {
59
- return listMatchingFiles(root, (name) => sourceFilePattern.test(name) && !declarationFilePattern.test(name), options);
163
+ return listMatchingFiles(root, isDefinitionSourceFile, options);
60
164
  }
165
+ /** `writeFileIfChangedSync` for async callers. */
61
166
  async function writeFileIfChanged(file, contents) {
62
167
  if (await readFile(file, "utf8").catch(() => void 0) === contents) return;
63
168
  await mkdir(resolve$1(file, ".."), { recursive: true });
@@ -68,15 +173,12 @@ async function writeFileIfChanged(file, contents) {
68
173
  function cloneArray(value) {
69
174
  return Array.isArray(value) ? [...value] : [];
70
175
  }
71
- function isRecord(value) {
72
- return Object(value) === value && !Array.isArray(value);
73
- }
74
176
  function sameHandler(left, right) {
75
177
  return left.handler === right.handler && left.route === right.route && left.method === right.method && left.middleware === right.middleware;
76
178
  }
77
179
  /** Create a Nitro 3 configuration builder for generated ViteHub output. */
78
180
  function createNitroServerKit(value = {}) {
79
- const config = isRecord(value) ? { ...value } : {};
181
+ const config = isRecordOrFunction(value) ? { ...value } : {};
80
182
  const handlers = cloneArray(config.handlers);
81
183
  const plugins = cloneArray(config.plugins);
82
184
  config.handlers = handlers;
@@ -84,7 +186,7 @@ function createNitroServerKit(value = {}) {
84
186
  return {
85
187
  config,
86
188
  addHandler(handler, position = "end") {
87
- if (handlers.some((candidate) => isRecord(candidate) && sameHandler(candidate, handler))) return;
189
+ if (handlers.some((candidate) => isRecordOrFunction(candidate) && sameHandler(candidate, handler))) return;
88
190
  if (position === "start") handlers.unshift({ ...handler });
89
191
  else handlers.push({ ...handler });
90
192
  },
@@ -105,7 +207,7 @@ async function flattenPlugins(value, plugins, seen) {
105
207
  for (const item of value) await flattenPlugins(item, plugins, seen);
106
208
  return;
107
209
  }
108
- if (!isPlainObject(value) || seen.has(value)) return;
210
+ if (!isRecord(value) || seen.has(value)) return;
109
211
  seen.add(value);
110
212
  if (isThenable(value)) {
111
213
  await flattenPlugins(await value, plugins, seen);
@@ -126,16 +228,18 @@ async function flattenPluginOptions(plugins) {
126
228
  //#endregion
127
229
  //#region ../internal/src/operations-vite.ts
128
230
  const owners = /* @__PURE__ */ new Set([
129
- "@vite-hub/kv/operations",
130
- "@vite-hub/blob/operations",
131
- "@vite-hub/email/operations",
132
- "@vite-hub/rate-limit/operations"
231
+ "@vite-hub/kv/vite",
232
+ "@vite-hub/blob/vite",
233
+ "@vite-hub/email/vite",
234
+ "@vite-hub/rate-limit/vite",
235
+ "@vite-hub/forms/vite",
236
+ "@vite-hub/sync/vite"
133
237
  ]);
134
238
  const discoveryInstalled = Symbol.for("vitehub.operations.dev.discovery");
135
239
  /** Publish only the elected standalone transport; other Console policies retain their own discovery hook. */
136
240
  function publishStandaloneOperationServer(server) {
137
241
  const http = server.httpServer;
138
- if (!http || Reflect.get(server, discoveryInstalled)) return;
242
+ if (!http || server.config.server.middlewareMode || Reflect.get(server, discoveryInstalled)) return;
139
243
  const root = resolve(server.config.root);
140
244
  const handlers = Reflect.get(Object(Reflect.get(server.config, "nitro")), "handlers");
141
245
  if (!Array.isArray(handlers) || !handlers.some((handler) => handler?.handler === resolve(root, ".vitehub/nitro/operations/rpc.mjs"))) return;
@@ -168,11 +272,12 @@ async function installStandaloneOperationRpc(config, command, module) {
168
272
  const plugins = await flattenPluginOptions(config.plugins);
169
273
  if (plugins.some((plugin) => Reflect.get(plugin, "name") === "vite-hub/dependencies" || Reflect.get(plugin, "name") === "vite-hub/console")) return;
170
274
  const contributions = (await collectOperationContributions(plugins)).filter((source) => source.runtime !== false);
171
- if (contributions.find((source) => owners.has(source.module))?.module !== module) return;
275
+ const owner = contributions.find((source) => owners.has(source.plugin));
276
+ if (!owner || !contributions.some((source) => source.module === module && owners.has(source.plugin))) return;
172
277
  const root = resolve(config.root ?? process.cwd());
173
278
  const handler = resolve(root, ".vitehub/nitro/operations/rpc.mjs");
174
279
  await writeFileIfChanged(handler, [
175
- `import { createStandaloneOperationHandler } from ${JSON.stringify(module)}`,
280
+ `import { createStandaloneOperationHandler } from ${JSON.stringify(owner.module)}`,
176
281
  ...contributions.map((entry, index) => `import * as source${index} from ${JSON.stringify(entry.module)}`),
177
282
  `export default createStandaloneOperationHandler([${contributions.map((entry, index) => `{ operations: source${index}[${JSON.stringify(entry.export)}], plugin: ${JSON.stringify(entry.plugin)} }`).join(", ")}], ${JSON.stringify(root)})`,
178
283
  ""
@@ -182,35 +287,17 @@ async function installStandaloneOperationRpc(config, command, module) {
182
287
  handler,
183
288
  route: operationRpcPath
184
289
  });
290
+ const devHandlers = kit.config.devHandlers;
291
+ const signed = Array.isArray(devHandlers) ? [...devHandlers] : [];
292
+ addViteHubDevPeerDevHandler(signed);
293
+ kit.config.devHandlers = signed;
185
294
  Reflect.set(config, "nitro", kit.config);
186
295
  }
187
- const VITEHUB_MODES = {
188
- e2e: "e2e",
189
- blob: "blob",
190
- chat: "chat",
191
- db: "db",
192
- env: "env",
193
- kv: "kv",
194
- queue: "queue",
195
- schedule: "schedule",
196
- sandbox: "sandbox",
197
- workspace: "workspace",
198
- workflow: "workflow"
199
- };
200
- function isViteCli(argv) {
201
- return argv.some((arg) => /(?:^|[/\\])vite(?:\.[cm]?js)?$/.test(arg) || arg === "vite");
202
- }
203
- function getViteCliMode(argv = process.argv) {
204
- if (!isViteCli(argv)) return;
205
- const modes = new Set(Object.values(VITEHUB_MODES));
206
- for (let index = 0; index < argv.length; index += 1) {
207
- const arg = argv[index];
208
- const mode = arg === "--mode" || arg === "-m" ? argv[index + 1] : arg.startsWith("--mode=") ? arg.slice(7) : void 0;
209
- if (mode && modes.has(mode)) return mode;
210
- }
211
- }
212
- function getViteMode(env = process.env) {
213
- return env["VITEHUB_VITE_MODE"] ?? getViteCliMode();
296
+ //#endregion
297
+ //#region ../internal/src/durability.ts
298
+ /** The `durability` module next to the Vite plugin module at `importMetaUrl`, in source and in `dist`. */
299
+ function durabilityModuleFile(importMetaUrl) {
300
+ return fileURLToPath(new URL(importMetaUrl.endsWith(".ts") ? "./durability.ts" : "./durability.js", importMetaUrl));
214
301
  }
215
302
  //#endregion
216
303
  //#region ../internal/src/build/provider-output-config.ts
@@ -300,2354 +387,8 @@ function mergeProviderOutputConfig(existing, value, ownership = {}) {
300
387
  ...mergeOwnedArrays(existing, value, ownership.arrays)
301
388
  };
302
389
  }
303
- (/* @__PURE__ */ __commonJSMin(((exports, module) => {
304
- var __defProp = Object.defineProperty;
305
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
306
- var __getOwnPropNames = Object.getOwnPropertyNames;
307
- var __hasOwnProp = Object.prototype.hasOwnProperty;
308
- var __export = (target, all) => {
309
- for (var name in all) __defProp(target, name, {
310
- get: all[name],
311
- enumerable: true
312
- });
313
- };
314
- var __copyProps = (to, from, except, desc) => {
315
- if (from && typeof from === "object" || typeof from === "function") {
316
- for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
317
- get: () => from[key],
318
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
319
- });
320
- }
321
- return to;
322
- };
323
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
324
- var node_exports = {};
325
- __export(node_exports, {
326
- analyzeMetafile: () => analyzeMetafile,
327
- analyzeMetafileSync: () => analyzeMetafileSync,
328
- build: () => build,
329
- buildSync: () => buildSync,
330
- context: () => context,
331
- default: () => node_default,
332
- formatMessages: () => formatMessages,
333
- formatMessagesSync: () => formatMessagesSync,
334
- initialize: () => initialize,
335
- stop: () => stop,
336
- transform: () => transform,
337
- transformSync: () => transformSync,
338
- version: () => version
339
- });
340
- module.exports = __toCommonJS(node_exports);
341
- function encodePacket(packet) {
342
- let visit = (value) => {
343
- if (value === null) bb.write8(0);
344
- else if (typeof value === "boolean") {
345
- bb.write8(1);
346
- bb.write8(+value);
347
- } else if (typeof value === "number") {
348
- bb.write8(2);
349
- bb.write32(value | 0);
350
- } else if (typeof value === "string") {
351
- bb.write8(3);
352
- bb.write(encodeUTF8(value));
353
- } else if (value instanceof Uint8Array) {
354
- bb.write8(4);
355
- bb.write(value);
356
- } else if (value instanceof Array) {
357
- bb.write8(5);
358
- bb.write32(value.length);
359
- for (let item of value) visit(item);
360
- } else {
361
- let keys = Object.keys(value);
362
- bb.write8(6);
363
- bb.write32(keys.length);
364
- for (let key of keys) {
365
- bb.write(encodeUTF8(key));
366
- visit(value[key]);
367
- }
368
- }
369
- };
370
- let bb = new ByteBuffer();
371
- bb.write32(0);
372
- bb.write32(packet.id << 1 | +!packet.isRequest);
373
- visit(packet.value);
374
- writeUInt32LE(bb.buf, bb.len - 4, 0);
375
- return bb.buf.subarray(0, bb.len);
376
- }
377
- function decodePacket(bytes) {
378
- let visit = () => {
379
- switch (bb.read8()) {
380
- case 0: return null;
381
- case 1: return !!bb.read8();
382
- case 2: return bb.read32();
383
- case 3: return decodeUTF8(bb.read());
384
- case 4: return bb.read();
385
- case 5: {
386
- let count = bb.read32();
387
- let value2 = [];
388
- for (let i = 0; i < count; i++) value2.push(visit());
389
- return value2;
390
- }
391
- case 6: {
392
- let count = bb.read32();
393
- let value2 = {};
394
- for (let i = 0; i < count; i++) value2[decodeUTF8(bb.read())] = visit();
395
- return value2;
396
- }
397
- default: throw new Error("Invalid packet");
398
- }
399
- };
400
- let bb = new ByteBuffer(bytes);
401
- let id = bb.read32();
402
- let isRequest = (id & 1) === 0;
403
- id >>>= 1;
404
- let value = visit();
405
- if (bb.ptr !== bytes.length) throw new Error("Invalid packet");
406
- return {
407
- id,
408
- isRequest,
409
- value
410
- };
411
- }
412
- var ByteBuffer = class {
413
- constructor(buf = /* @__PURE__ */ new Uint8Array(1024)) {
414
- this.buf = buf;
415
- this.len = 0;
416
- this.ptr = 0;
417
- }
418
- _write(delta) {
419
- if (this.len + delta > this.buf.length) {
420
- let clone = new Uint8Array((this.len + delta) * 2);
421
- clone.set(this.buf);
422
- this.buf = clone;
423
- }
424
- this.len += delta;
425
- return this.len - delta;
426
- }
427
- write8(value) {
428
- let offset = this._write(1);
429
- this.buf[offset] = value;
430
- }
431
- write32(value) {
432
- let offset = this._write(4);
433
- writeUInt32LE(this.buf, value, offset);
434
- }
435
- write(bytes) {
436
- let offset = this._write(4 + bytes.length);
437
- writeUInt32LE(this.buf, bytes.length, offset);
438
- this.buf.set(bytes, offset + 4);
439
- }
440
- _read(delta) {
441
- if (this.ptr + delta > this.buf.length) throw new Error("Invalid packet");
442
- this.ptr += delta;
443
- return this.ptr - delta;
444
- }
445
- read8() {
446
- return this.buf[this._read(1)];
447
- }
448
- read32() {
449
- return readUInt32LE(this.buf, this._read(4));
450
- }
451
- read() {
452
- let length = this.read32();
453
- let bytes = new Uint8Array(length);
454
- let ptr = this._read(bytes.length);
455
- bytes.set(this.buf.subarray(ptr, ptr + length));
456
- return bytes;
457
- }
458
- };
459
- var encodeUTF8;
460
- var decodeUTF8;
461
- var encodeInvariant;
462
- if (typeof TextEncoder !== "undefined" && typeof TextDecoder !== "undefined") {
463
- let encoder = new TextEncoder();
464
- let decoder = new TextDecoder();
465
- encodeUTF8 = (text) => encoder.encode(text);
466
- decodeUTF8 = (bytes) => decoder.decode(bytes);
467
- encodeInvariant = "new TextEncoder().encode(\"\")";
468
- } else if (typeof Buffer !== "undefined") {
469
- encodeUTF8 = (text) => Buffer.from(text);
470
- decodeUTF8 = (bytes) => {
471
- let { buffer, byteOffset, byteLength } = bytes;
472
- return Buffer.from(buffer, byteOffset, byteLength).toString();
473
- };
474
- encodeInvariant = "Buffer.from(\"\")";
475
- } else throw new Error("No UTF-8 codec found");
476
- if (!(encodeUTF8("") instanceof Uint8Array)) throw new Error(`Invariant violation: "${encodeInvariant} instanceof Uint8Array" is incorrectly false
477
-
478
- This indicates that your JavaScript environment is broken. You cannot use
479
- esbuild in this environment because esbuild relies on this invariant. This
480
- is not a problem with esbuild. You need to fix your environment instead.
481
- `);
482
- function readUInt32LE(buffer, offset) {
483
- return (buffer[offset++] | buffer[offset++] << 8 | buffer[offset++] << 16 | buffer[offset++] << 24) >>> 0;
484
- }
485
- function writeUInt32LE(buffer, value, offset) {
486
- buffer[offset++] = value;
487
- buffer[offset++] = value >> 8;
488
- buffer[offset++] = value >> 16;
489
- buffer[offset++] = value >> 24;
490
- }
491
- var fromCharCode = String.fromCharCode;
492
- function throwSyntaxError(bytes, index, message) {
493
- const c = bytes[index];
494
- let line = 1;
495
- let column = 0;
496
- for (let i = 0; i < index; i++) if (bytes[i] === 10) {
497
- line++;
498
- column = 0;
499
- } else column++;
500
- 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})`);
501
- }
502
- function JSON_parse(bytes) {
503
- if (!(bytes instanceof Uint8Array)) throw new Error(`JSON input must be a Uint8Array`);
504
- const propertyStack = [];
505
- const objectStack = [];
506
- const stateStack = [];
507
- const length = bytes.length;
508
- let property = null;
509
- let state = 0;
510
- let object;
511
- let i = 0;
512
- while (i < length) {
513
- let c = bytes[i++];
514
- if (c <= 32) continue;
515
- let value;
516
- if (state === 2 && property === null && c !== 34 && c !== 125) throwSyntaxError(bytes, --i);
517
- switch (c) {
518
- case 116:
519
- if (bytes[i++] !== 114 || bytes[i++] !== 117 || bytes[i++] !== 101) throwSyntaxError(bytes, --i);
520
- value = true;
521
- break;
522
- case 102:
523
- if (bytes[i++] !== 97 || bytes[i++] !== 108 || bytes[i++] !== 115 || bytes[i++] !== 101) throwSyntaxError(bytes, --i);
524
- value = false;
525
- break;
526
- case 110:
527
- if (bytes[i++] !== 117 || bytes[i++] !== 108 || bytes[i++] !== 108) throwSyntaxError(bytes, --i);
528
- value = null;
529
- break;
530
- case 45:
531
- case 46:
532
- case 48:
533
- case 49:
534
- case 50:
535
- case 51:
536
- case 52:
537
- case 53:
538
- case 54:
539
- case 55:
540
- case 56:
541
- case 57: {
542
- let index = i;
543
- value = fromCharCode(c);
544
- c = bytes[i];
545
- while (true) {
546
- switch (c) {
547
- case 43:
548
- case 45:
549
- case 46:
550
- case 48:
551
- case 49:
552
- case 50:
553
- case 51:
554
- case 52:
555
- case 53:
556
- case 54:
557
- case 55:
558
- case 56:
559
- case 57:
560
- case 101:
561
- case 69:
562
- value += fromCharCode(c);
563
- c = bytes[++i];
564
- continue;
565
- }
566
- break;
567
- }
568
- value = +value;
569
- if (isNaN(value)) throwSyntaxError(bytes, --index, "Invalid number");
570
- break;
571
- }
572
- case 34:
573
- value = "";
574
- while (true) {
575
- if (i >= length) throwSyntaxError(bytes, length);
576
- c = bytes[i++];
577
- if (c === 34) break;
578
- else if (c === 92) switch (bytes[i++]) {
579
- case 34:
580
- value += "\"";
581
- break;
582
- case 47:
583
- value += "/";
584
- break;
585
- case 92:
586
- value += "\\";
587
- break;
588
- case 98:
589
- value += "\b";
590
- break;
591
- case 102:
592
- value += "\f";
593
- break;
594
- case 110:
595
- value += "\n";
596
- break;
597
- case 114:
598
- value += "\r";
599
- break;
600
- case 116:
601
- value += " ";
602
- break;
603
- case 117: {
604
- let code = 0;
605
- for (let j = 0; j < 4; j++) {
606
- c = bytes[i++];
607
- code <<= 4;
608
- if (c >= 48 && c <= 57) code |= c - 48;
609
- else if (c >= 97 && c <= 102) code |= c + -87;
610
- else if (c >= 65 && c <= 70) code |= c + -55;
611
- else throwSyntaxError(bytes, --i);
612
- }
613
- value += fromCharCode(code);
614
- break;
615
- }
616
- default: throwSyntaxError(bytes, --i);
617
- }
618
- else if (c <= 127) value += fromCharCode(c);
619
- else if ((c & 224) === 192) value += fromCharCode((c & 31) << 6 | bytes[i++] & 63);
620
- else if ((c & 240) === 224) value += fromCharCode((c & 15) << 12 | (bytes[i++] & 63) << 6 | bytes[i++] & 63);
621
- else if ((c & 248) == 240) {
622
- let codePoint = (c & 7) << 18 | (bytes[i++] & 63) << 12 | (bytes[i++] & 63) << 6 | bytes[i++] & 63;
623
- if (codePoint > 65535) {
624
- codePoint -= 65536;
625
- value += fromCharCode(codePoint >> 10 & 1023 | 55296);
626
- codePoint = 56320 | codePoint & 1023;
627
- }
628
- value += fromCharCode(codePoint);
629
- }
630
- }
631
- value[0];
632
- break;
633
- case 91:
634
- value = [];
635
- propertyStack.push(property);
636
- objectStack.push(object);
637
- stateStack.push(state);
638
- property = null;
639
- object = value;
640
- state = 1;
641
- continue;
642
- case 123:
643
- value = {};
644
- propertyStack.push(property);
645
- objectStack.push(object);
646
- stateStack.push(state);
647
- property = null;
648
- object = value;
649
- state = 2;
650
- continue;
651
- case 93:
652
- if (state !== 1) throwSyntaxError(bytes, --i);
653
- value = object;
654
- property = propertyStack.pop();
655
- object = objectStack.pop();
656
- state = stateStack.pop();
657
- break;
658
- case 125:
659
- if (state !== 2) throwSyntaxError(bytes, --i);
660
- value = object;
661
- property = propertyStack.pop();
662
- object = objectStack.pop();
663
- state = stateStack.pop();
664
- break;
665
- default: throwSyntaxError(bytes, --i);
666
- }
667
- c = bytes[i];
668
- while (c <= 32) c = bytes[++i];
669
- switch (state) {
670
- case 0:
671
- if (i === length) return value;
672
- break;
673
- case 1:
674
- object.push(value);
675
- if (c === 44) {
676
- i++;
677
- continue;
678
- }
679
- if (c === 93) continue;
680
- break;
681
- case 2: if (property === null) {
682
- property = value;
683
- if (c === 58) {
684
- i++;
685
- continue;
686
- }
687
- } else {
688
- object[property] = value;
689
- property = null;
690
- if (c === 44) {
691
- i++;
692
- continue;
693
- }
694
- if (c === 125) continue;
695
- }
696
- }
697
- break;
698
- }
699
- throwSyntaxError(bytes, i);
700
- }
701
- var quote = JSON.stringify;
702
- var buildLogLevelDefault = "warning";
703
- var transformLogLevelDefault = "silent";
704
- function validateAndJoinStringArray(values, what) {
705
- const toJoin = [];
706
- for (const value of values) {
707
- validateStringValue(value, what);
708
- if (value.indexOf(",") >= 0) throw new Error(`Invalid ${what}: ${value}`);
709
- toJoin.push(value);
710
- }
711
- return toJoin.join(",");
712
- }
713
- var canBeAnything = () => null;
714
- var mustBeBoolean = (value) => typeof value === "boolean" ? null : "a boolean";
715
- var mustBeString = (value) => typeof value === "string" ? null : "a string";
716
- var mustBeRegExp = (value) => value instanceof RegExp ? null : "a RegExp object";
717
- var mustBeInteger = (value) => typeof value === "number" && value === (value | 0) ? null : "an integer";
718
- var mustBeValidPortNumber = (value) => typeof value === "number" && value === (value | 0) && value >= 0 && value <= 65535 ? null : "a valid port number";
719
- var mustBeFunction = (value) => typeof value === "function" ? null : "a function";
720
- var mustBeArray = (value) => Array.isArray(value) ? null : "an array";
721
- var mustBeArrayOfStrings = (value) => Array.isArray(value) && value.every((x) => typeof x === "string") ? null : "an array of strings";
722
- var mustBeObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? null : "an object";
723
- var mustBeEntryPoints = (value) => typeof value === "object" && value !== null ? null : "an array or an object";
724
- var mustBeWebAssemblyModule = (value) => value instanceof WebAssembly.Module ? null : "a WebAssembly.Module";
725
- var mustBeObjectOrNull = (value) => typeof value === "object" && !Array.isArray(value) ? null : "an object or null";
726
- var mustBeStringOrBoolean = (value) => typeof value === "string" || typeof value === "boolean" ? null : "a string or a boolean";
727
- var mustBeStringOrObject = (value) => typeof value === "string" || typeof value === "object" && value !== null && !Array.isArray(value) ? null : "a string or an object";
728
- var mustBeStringOrArrayOfStrings = (value) => typeof value === "string" || Array.isArray(value) && value.every((x) => typeof x === "string") ? null : "a string or an array of strings";
729
- var mustBeStringOrUint8Array = (value) => typeof value === "string" || value instanceof Uint8Array ? null : "a string or a Uint8Array";
730
- var mustBeStringOrURL = (value) => typeof value === "string" || value instanceof URL ? null : "a string or a URL";
731
- function getFlag(object, keys, key, mustBeFn) {
732
- let value = object[key];
733
- keys[key + ""] = true;
734
- if (value === void 0) return void 0;
735
- let mustBe = mustBeFn(value);
736
- if (mustBe !== null) throw new Error(`${quote(key)} must be ${mustBe}`);
737
- return value;
738
- }
739
- function checkForInvalidFlags(object, keys, where) {
740
- for (let key in object) if (!(key in keys)) throw new Error(`Invalid option ${where}: ${quote(key)}`);
741
- }
742
- function validateInitializeOptions(options) {
743
- let keys = /* @__PURE__ */ Object.create(null);
744
- let wasmURL = getFlag(options, keys, "wasmURL", mustBeStringOrURL);
745
- let wasmModule = getFlag(options, keys, "wasmModule", mustBeWebAssemblyModule);
746
- let worker = getFlag(options, keys, "worker", mustBeBoolean);
747
- checkForInvalidFlags(options, keys, "in initialize() call");
748
- return {
749
- wasmURL,
750
- wasmModule,
751
- worker
752
- };
753
- }
754
- function validateMangleCache(mangleCache) {
755
- let validated;
756
- if (mangleCache !== void 0) {
757
- validated = /* @__PURE__ */ Object.create(null);
758
- for (let key in mangleCache) {
759
- let value = mangleCache[key];
760
- if (typeof value === "string" || value === false) validated[key] = value;
761
- else throw new Error(`Expected ${quote(key)} in mangle cache to map to either a string or false`);
762
- }
763
- }
764
- return validated;
765
- }
766
- function pushLogFlags(flags, options, keys, isTTY2, logLevelDefault) {
767
- let color = getFlag(options, keys, "color", mustBeBoolean);
768
- let logLevel = getFlag(options, keys, "logLevel", mustBeString);
769
- let logLimit = getFlag(options, keys, "logLimit", mustBeInteger);
770
- if (color !== void 0) flags.push(`--color=${color}`);
771
- else if (isTTY2) flags.push(`--color=true`);
772
- flags.push(`--log-level=${logLevel || logLevelDefault}`);
773
- flags.push(`--log-limit=${logLimit || 0}`);
774
- }
775
- function validateStringValue(value, what, key) {
776
- if (typeof value !== "string") throw new Error(`Expected value for ${what}${key !== void 0 ? " " + quote(key) : ""} to be a string, got ${typeof value} instead`);
777
- return value;
778
- }
779
- function pushCommonFlags(flags, options, keys) {
780
- let legalComments = getFlag(options, keys, "legalComments", mustBeString);
781
- let sourceRoot = getFlag(options, keys, "sourceRoot", mustBeString);
782
- let sourcesContent = getFlag(options, keys, "sourcesContent", mustBeBoolean);
783
- let target = getFlag(options, keys, "target", mustBeStringOrArrayOfStrings);
784
- let format = getFlag(options, keys, "format", mustBeString);
785
- let globalName = getFlag(options, keys, "globalName", mustBeString);
786
- let mangleProps = getFlag(options, keys, "mangleProps", mustBeRegExp);
787
- let reserveProps = getFlag(options, keys, "reserveProps", mustBeRegExp);
788
- let mangleQuoted = getFlag(options, keys, "mangleQuoted", mustBeBoolean);
789
- let minify = getFlag(options, keys, "minify", mustBeBoolean);
790
- let minifySyntax = getFlag(options, keys, "minifySyntax", mustBeBoolean);
791
- let minifyWhitespace = getFlag(options, keys, "minifyWhitespace", mustBeBoolean);
792
- let minifyIdentifiers = getFlag(options, keys, "minifyIdentifiers", mustBeBoolean);
793
- let lineLimit = getFlag(options, keys, "lineLimit", mustBeInteger);
794
- let drop = getFlag(options, keys, "drop", mustBeArrayOfStrings);
795
- let dropLabels = getFlag(options, keys, "dropLabels", mustBeArrayOfStrings);
796
- let charset = getFlag(options, keys, "charset", mustBeString);
797
- let treeShaking = getFlag(options, keys, "treeShaking", mustBeBoolean);
798
- let ignoreAnnotations = getFlag(options, keys, "ignoreAnnotations", mustBeBoolean);
799
- let jsx = getFlag(options, keys, "jsx", mustBeString);
800
- let jsxFactory = getFlag(options, keys, "jsxFactory", mustBeString);
801
- let jsxFragment = getFlag(options, keys, "jsxFragment", mustBeString);
802
- let jsxImportSource = getFlag(options, keys, "jsxImportSource", mustBeString);
803
- let jsxDev = getFlag(options, keys, "jsxDev", mustBeBoolean);
804
- let jsxSideEffects = getFlag(options, keys, "jsxSideEffects", mustBeBoolean);
805
- let define = getFlag(options, keys, "define", mustBeObject);
806
- let logOverride = getFlag(options, keys, "logOverride", mustBeObject);
807
- let supported = getFlag(options, keys, "supported", mustBeObject);
808
- let pure = getFlag(options, keys, "pure", mustBeArrayOfStrings);
809
- let keepNames = getFlag(options, keys, "keepNames", mustBeBoolean);
810
- let platform = getFlag(options, keys, "platform", mustBeString);
811
- let tsconfigRaw = getFlag(options, keys, "tsconfigRaw", mustBeStringOrObject);
812
- let absPaths = getFlag(options, keys, "absPaths", mustBeArrayOfStrings);
813
- if (legalComments) flags.push(`--legal-comments=${legalComments}`);
814
- if (sourceRoot !== void 0) flags.push(`--source-root=${sourceRoot}`);
815
- if (sourcesContent !== void 0) flags.push(`--sources-content=${sourcesContent}`);
816
- if (target) flags.push(`--target=${validateAndJoinStringArray(Array.isArray(target) ? target : [target], "target")}`);
817
- if (format) flags.push(`--format=${format}`);
818
- if (globalName) flags.push(`--global-name=${globalName}`);
819
- if (platform) flags.push(`--platform=${platform}`);
820
- if (tsconfigRaw) flags.push(`--tsconfig-raw=${typeof tsconfigRaw === "string" ? tsconfigRaw : JSON.stringify(tsconfigRaw)}`);
821
- if (minify) flags.push("--minify");
822
- if (minifySyntax) flags.push("--minify-syntax");
823
- if (minifyWhitespace) flags.push("--minify-whitespace");
824
- if (minifyIdentifiers) flags.push("--minify-identifiers");
825
- if (lineLimit) flags.push(`--line-limit=${lineLimit}`);
826
- if (charset) flags.push(`--charset=${charset}`);
827
- if (treeShaking !== void 0) flags.push(`--tree-shaking=${treeShaking}`);
828
- if (ignoreAnnotations) flags.push(`--ignore-annotations`);
829
- if (drop) for (let what of drop) flags.push(`--drop:${validateStringValue(what, "drop")}`);
830
- if (dropLabels) flags.push(`--drop-labels=${validateAndJoinStringArray(dropLabels, "drop label")}`);
831
- if (absPaths) flags.push(`--abs-paths=${validateAndJoinStringArray(absPaths, "abs paths")}`);
832
- if (mangleProps) flags.push(`--mangle-props=${jsRegExpToGoRegExp(mangleProps)}`);
833
- if (reserveProps) flags.push(`--reserve-props=${jsRegExpToGoRegExp(reserveProps)}`);
834
- if (mangleQuoted !== void 0) flags.push(`--mangle-quoted=${mangleQuoted}`);
835
- if (jsx) flags.push(`--jsx=${jsx}`);
836
- if (jsxFactory) flags.push(`--jsx-factory=${jsxFactory}`);
837
- if (jsxFragment) flags.push(`--jsx-fragment=${jsxFragment}`);
838
- if (jsxImportSource) flags.push(`--jsx-import-source=${jsxImportSource}`);
839
- if (jsxDev) flags.push(`--jsx-dev`);
840
- if (jsxSideEffects) flags.push(`--jsx-side-effects`);
841
- if (define) for (let key in define) {
842
- if (key.indexOf("=") >= 0) throw new Error(`Invalid define: ${key}`);
843
- flags.push(`--define:${key}=${validateStringValue(define[key], "define", key)}`);
844
- }
845
- if (logOverride) for (let key in logOverride) {
846
- if (key.indexOf("=") >= 0) throw new Error(`Invalid log override: ${key}`);
847
- flags.push(`--log-override:${key}=${validateStringValue(logOverride[key], "log override", key)}`);
848
- }
849
- if (supported) for (let key in supported) {
850
- if (key.indexOf("=") >= 0) throw new Error(`Invalid supported: ${key}`);
851
- const value = supported[key];
852
- if (typeof value !== "boolean") throw new Error(`Expected value for supported ${quote(key)} to be a boolean, got ${typeof value} instead`);
853
- flags.push(`--supported:${key}=${value}`);
854
- }
855
- if (pure) for (let fn of pure) flags.push(`--pure:${validateStringValue(fn, "pure")}`);
856
- if (keepNames) flags.push(`--keep-names`);
857
- }
858
- function flagsForBuildOptions(callName, options, isTTY2, logLevelDefault, writeDefault) {
859
- var _a2;
860
- let flags = [];
861
- let entries = [];
862
- let keys = /* @__PURE__ */ Object.create(null);
863
- let stdinContents = null;
864
- let stdinResolveDir = null;
865
- pushLogFlags(flags, options, keys, isTTY2, logLevelDefault);
866
- pushCommonFlags(flags, options, keys);
867
- let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
868
- let bundle = getFlag(options, keys, "bundle", mustBeBoolean);
869
- let splitting = getFlag(options, keys, "splitting", mustBeBoolean);
870
- let preserveSymlinks = getFlag(options, keys, "preserveSymlinks", mustBeBoolean);
871
- let metafile = getFlag(options, keys, "metafile", mustBeBoolean);
872
- let outfile = getFlag(options, keys, "outfile", mustBeString);
873
- let outdir = getFlag(options, keys, "outdir", mustBeString);
874
- let outbase = getFlag(options, keys, "outbase", mustBeString);
875
- let tsconfig = getFlag(options, keys, "tsconfig", mustBeString);
876
- let resolveExtensions = getFlag(options, keys, "resolveExtensions", mustBeArrayOfStrings);
877
- let nodePathsInput = getFlag(options, keys, "nodePaths", mustBeArrayOfStrings);
878
- let mainFields = getFlag(options, keys, "mainFields", mustBeArrayOfStrings);
879
- let conditions = getFlag(options, keys, "conditions", mustBeArrayOfStrings);
880
- let external = getFlag(options, keys, "external", mustBeArrayOfStrings);
881
- let packages = getFlag(options, keys, "packages", mustBeString);
882
- let alias = getFlag(options, keys, "alias", mustBeObject);
883
- let loader = getFlag(options, keys, "loader", mustBeObject);
884
- let outExtension = getFlag(options, keys, "outExtension", mustBeObject);
885
- let publicPath = getFlag(options, keys, "publicPath", mustBeString);
886
- let entryNames = getFlag(options, keys, "entryNames", mustBeString);
887
- let chunkNames = getFlag(options, keys, "chunkNames", mustBeString);
888
- let assetNames = getFlag(options, keys, "assetNames", mustBeString);
889
- let inject = getFlag(options, keys, "inject", mustBeArrayOfStrings);
890
- let banner = getFlag(options, keys, "banner", mustBeObject);
891
- let footer = getFlag(options, keys, "footer", mustBeObject);
892
- let entryPoints = getFlag(options, keys, "entryPoints", mustBeEntryPoints);
893
- let absWorkingDir = getFlag(options, keys, "absWorkingDir", mustBeString);
894
- let stdin = getFlag(options, keys, "stdin", mustBeObject);
895
- let write = (_a2 = getFlag(options, keys, "write", mustBeBoolean)) != null ? _a2 : writeDefault;
896
- let allowOverwrite = getFlag(options, keys, "allowOverwrite", mustBeBoolean);
897
- let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
898
- keys.plugins = true;
899
- checkForInvalidFlags(options, keys, `in ${callName}() call`);
900
- if (sourcemap) flags.push(`--sourcemap${sourcemap === true ? "" : `=${sourcemap}`}`);
901
- if (bundle) flags.push("--bundle");
902
- if (allowOverwrite) flags.push("--allow-overwrite");
903
- if (splitting) flags.push("--splitting");
904
- if (preserveSymlinks) flags.push("--preserve-symlinks");
905
- if (metafile) flags.push(`--metafile`);
906
- if (outfile) flags.push(`--outfile=${outfile}`);
907
- if (outdir) flags.push(`--outdir=${outdir}`);
908
- if (outbase) flags.push(`--outbase=${outbase}`);
909
- if (tsconfig) flags.push(`--tsconfig=${tsconfig}`);
910
- if (packages) flags.push(`--packages=${packages}`);
911
- if (resolveExtensions) flags.push(`--resolve-extensions=${validateAndJoinStringArray(resolveExtensions, "resolve extension")}`);
912
- if (publicPath) flags.push(`--public-path=${publicPath}`);
913
- if (entryNames) flags.push(`--entry-names=${entryNames}`);
914
- if (chunkNames) flags.push(`--chunk-names=${chunkNames}`);
915
- if (assetNames) flags.push(`--asset-names=${assetNames}`);
916
- if (mainFields) flags.push(`--main-fields=${validateAndJoinStringArray(mainFields, "main field")}`);
917
- if (conditions) flags.push(`--conditions=${validateAndJoinStringArray(conditions, "condition")}`);
918
- if (external) for (let name of external) flags.push(`--external:${validateStringValue(name, "external")}`);
919
- if (alias) for (let old in alias) {
920
- if (old.indexOf("=") >= 0) throw new Error(`Invalid package name in alias: ${old}`);
921
- flags.push(`--alias:${old}=${validateStringValue(alias[old], "alias", old)}`);
922
- }
923
- if (banner) for (let type in banner) {
924
- if (type.indexOf("=") >= 0) throw new Error(`Invalid banner file type: ${type}`);
925
- flags.push(`--banner:${type}=${validateStringValue(banner[type], "banner", type)}`);
926
- }
927
- if (footer) for (let type in footer) {
928
- if (type.indexOf("=") >= 0) throw new Error(`Invalid footer file type: ${type}`);
929
- flags.push(`--footer:${type}=${validateStringValue(footer[type], "footer", type)}`);
930
- }
931
- if (inject) for (let path3 of inject) flags.push(`--inject:${validateStringValue(path3, "inject")}`);
932
- if (loader) for (let ext in loader) {
933
- if (ext.indexOf("=") >= 0) throw new Error(`Invalid loader extension: ${ext}`);
934
- flags.push(`--loader:${ext}=${validateStringValue(loader[ext], "loader", ext)}`);
935
- }
936
- if (outExtension) for (let ext in outExtension) {
937
- if (ext.indexOf("=") >= 0) throw new Error(`Invalid out extension: ${ext}`);
938
- flags.push(`--out-extension:${ext}=${validateStringValue(outExtension[ext], "out extension", ext)}`);
939
- }
940
- if (entryPoints) {
941
- if (Array.isArray(entryPoints)) for (let i = 0, n = entryPoints.length; i < n; i++) {
942
- let entryPoint = entryPoints[i];
943
- if (typeof entryPoint === "object" && entryPoint !== null) {
944
- let entryPointKeys = /* @__PURE__ */ Object.create(null);
945
- let input = getFlag(entryPoint, entryPointKeys, "in", mustBeString);
946
- let output = getFlag(entryPoint, entryPointKeys, "out", mustBeString);
947
- checkForInvalidFlags(entryPoint, entryPointKeys, "in entry point at index " + i);
948
- if (input === void 0) throw new Error("Missing property \"in\" for entry point at index " + i);
949
- if (output === void 0) throw new Error("Missing property \"out\" for entry point at index " + i);
950
- entries.push([output, input]);
951
- } else entries.push(["", validateStringValue(entryPoint, "entry point at index " + i)]);
952
- }
953
- else for (let key in entryPoints) entries.push([key, validateStringValue(entryPoints[key], "entry point", key)]);
954
- }
955
- if (stdin) {
956
- let stdinKeys = /* @__PURE__ */ Object.create(null);
957
- let contents = getFlag(stdin, stdinKeys, "contents", mustBeStringOrUint8Array);
958
- let resolveDir = getFlag(stdin, stdinKeys, "resolveDir", mustBeString);
959
- let sourcefile = getFlag(stdin, stdinKeys, "sourcefile", mustBeString);
960
- let loader2 = getFlag(stdin, stdinKeys, "loader", mustBeString);
961
- checkForInvalidFlags(stdin, stdinKeys, "in \"stdin\" object");
962
- if (sourcefile) flags.push(`--sourcefile=${sourcefile}`);
963
- if (loader2) flags.push(`--loader=${loader2}`);
964
- if (resolveDir) stdinResolveDir = resolveDir;
965
- if (typeof contents === "string") stdinContents = encodeUTF8(contents);
966
- else if (contents instanceof Uint8Array) stdinContents = contents;
967
- }
968
- let nodePaths = [];
969
- if (nodePathsInput) for (let value of nodePathsInput) {
970
- value += "";
971
- nodePaths.push(value);
972
- }
973
- return {
974
- entries,
975
- flags,
976
- write,
977
- stdinContents,
978
- stdinResolveDir,
979
- absWorkingDir,
980
- nodePaths,
981
- mangleCache: validateMangleCache(mangleCache)
982
- };
983
- }
984
- function flagsForTransformOptions(callName, options, isTTY2, logLevelDefault) {
985
- let flags = [];
986
- let keys = /* @__PURE__ */ Object.create(null);
987
- pushLogFlags(flags, options, keys, isTTY2, logLevelDefault);
988
- pushCommonFlags(flags, options, keys);
989
- let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
990
- let sourcefile = getFlag(options, keys, "sourcefile", mustBeString);
991
- let loader = getFlag(options, keys, "loader", mustBeString);
992
- let banner = getFlag(options, keys, "banner", mustBeString);
993
- let footer = getFlag(options, keys, "footer", mustBeString);
994
- let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
995
- checkForInvalidFlags(options, keys, `in ${callName}() call`);
996
- if (sourcemap) flags.push(`--sourcemap=${sourcemap === true ? "external" : sourcemap}`);
997
- if (sourcefile) flags.push(`--sourcefile=${sourcefile}`);
998
- if (loader) flags.push(`--loader=${loader}`);
999
- if (banner) flags.push(`--banner=${banner}`);
1000
- if (footer) flags.push(`--footer=${footer}`);
1001
- return {
1002
- flags,
1003
- mangleCache: validateMangleCache(mangleCache)
1004
- };
1005
- }
1006
- function createChannel(streamIn) {
1007
- const requestCallbacksByKey = {};
1008
- const closeData = {
1009
- didClose: false,
1010
- reason: ""
1011
- };
1012
- let responseCallbacks = {};
1013
- let nextRequestID = 0;
1014
- let nextBuildKey = 0;
1015
- let stdout = /* @__PURE__ */ new Uint8Array(16384);
1016
- let stdoutUsed = 0;
1017
- let readFromStdout = (chunk) => {
1018
- let limit = stdoutUsed + chunk.length;
1019
- if (limit > stdout.length) {
1020
- let swap = new Uint8Array(limit * 2);
1021
- swap.set(stdout);
1022
- stdout = swap;
1023
- }
1024
- stdout.set(chunk, stdoutUsed);
1025
- stdoutUsed += chunk.length;
1026
- let offset = 0;
1027
- while (offset + 4 <= stdoutUsed) {
1028
- let length = readUInt32LE(stdout, offset);
1029
- if (offset + 4 + length > stdoutUsed) break;
1030
- offset += 4;
1031
- handleIncomingPacket(stdout.subarray(offset, offset + length));
1032
- offset += length;
1033
- }
1034
- if (offset > 0) {
1035
- stdout.copyWithin(0, offset, stdoutUsed);
1036
- stdoutUsed -= offset;
1037
- }
1038
- };
1039
- let afterClose = (error) => {
1040
- closeData.didClose = true;
1041
- if (error) closeData.reason = ": " + (error.message || error);
1042
- const text = "The service was stopped" + closeData.reason;
1043
- for (let id in responseCallbacks) responseCallbacks[id](text, null);
1044
- responseCallbacks = {};
1045
- };
1046
- let sendRequest = (refs, value, callback) => {
1047
- if (closeData.didClose) return callback("The service is no longer running" + closeData.reason, null);
1048
- let id = nextRequestID++;
1049
- responseCallbacks[id] = (error, response) => {
1050
- try {
1051
- callback(error, response);
1052
- } finally {
1053
- if (refs) refs.unref();
1054
- }
1055
- };
1056
- if (refs) refs.ref();
1057
- streamIn.writeToStdin(encodePacket({
1058
- id,
1059
- isRequest: true,
1060
- value
1061
- }));
1062
- };
1063
- let sendResponse = (id, value) => {
1064
- if (closeData.didClose) throw new Error("The service is no longer running" + closeData.reason);
1065
- streamIn.writeToStdin(encodePacket({
1066
- id,
1067
- isRequest: false,
1068
- value
1069
- }));
1070
- };
1071
- let handleRequest = async (id, request) => {
1072
- try {
1073
- if (request.command === "ping") {
1074
- sendResponse(id, {});
1075
- return;
1076
- }
1077
- if (typeof request.key === "number") {
1078
- const requestCallbacks = requestCallbacksByKey[request.key];
1079
- if (!requestCallbacks) return;
1080
- const callback = requestCallbacks[request.command];
1081
- if (callback) {
1082
- await callback(id, request);
1083
- return;
1084
- }
1085
- }
1086
- throw new Error(`Invalid command: ` + request.command);
1087
- } catch (e) {
1088
- const errors = [extractErrorMessageV8(e, streamIn, null, void 0, "")];
1089
- try {
1090
- sendResponse(id, { errors });
1091
- } catch {}
1092
- }
1093
- };
1094
- let isFirstPacket = true;
1095
- let handleIncomingPacket = (bytes) => {
1096
- if (isFirstPacket) {
1097
- isFirstPacket = false;
1098
- let binaryVersion = String.fromCharCode(...bytes);
1099
- if (binaryVersion !== "0.27.7") throw new Error(`Cannot start service: Host version "0.27.7" does not match binary version ${quote(binaryVersion)}`);
1100
- return;
1101
- }
1102
- let packet = decodePacket(bytes);
1103
- if (packet.isRequest) handleRequest(packet.id, packet.value);
1104
- else {
1105
- let callback = responseCallbacks[packet.id];
1106
- delete responseCallbacks[packet.id];
1107
- if (packet.value.error) callback(packet.value.error, {});
1108
- else callback(null, packet.value);
1109
- }
1110
- };
1111
- let buildOrContext = ({ callName, refs, options, isTTY: isTTY2, defaultWD: defaultWD2, callback }) => {
1112
- let refCount = 0;
1113
- const buildKey = nextBuildKey++;
1114
- const requestCallbacks = {};
1115
- const buildRefs = {
1116
- ref() {
1117
- if (++refCount === 1) {
1118
- if (refs) refs.ref();
1119
- }
1120
- },
1121
- unref() {
1122
- if (--refCount === 0) {
1123
- delete requestCallbacksByKey[buildKey];
1124
- if (refs) refs.unref();
1125
- }
1126
- }
1127
- };
1128
- requestCallbacksByKey[buildKey] = requestCallbacks;
1129
- buildRefs.ref();
1130
- buildOrContextImpl(callName, buildKey, sendRequest, sendResponse, buildRefs, streamIn, requestCallbacks, options, isTTY2, defaultWD2, (err, res) => {
1131
- try {
1132
- callback(err, res);
1133
- } finally {
1134
- buildRefs.unref();
1135
- }
1136
- });
1137
- };
1138
- let transform2 = ({ callName, refs, input, options, isTTY: isTTY2, fs: fs3, callback }) => {
1139
- const details = createObjectStash();
1140
- let start = (inputPath) => {
1141
- try {
1142
- if (typeof input !== "string" && !(input instanceof Uint8Array)) throw new Error("The input to \"transform\" must be a string or a Uint8Array");
1143
- let { flags, mangleCache } = flagsForTransformOptions(callName, options, isTTY2, transformLogLevelDefault);
1144
- let request = {
1145
- command: "transform",
1146
- flags,
1147
- inputFS: inputPath !== null,
1148
- input: inputPath !== null ? encodeUTF8(inputPath) : typeof input === "string" ? encodeUTF8(input) : input
1149
- };
1150
- if (mangleCache) request.mangleCache = mangleCache;
1151
- sendRequest(refs, request, (error, response) => {
1152
- if (error) return callback(new Error(error), null);
1153
- let errors = replaceDetailsInMessages(response.errors, details);
1154
- let warnings = replaceDetailsInMessages(response.warnings, details);
1155
- let outstanding = 1;
1156
- let next = () => {
1157
- if (--outstanding === 0) {
1158
- let result = {
1159
- warnings,
1160
- code: response.code,
1161
- map: response.map,
1162
- mangleCache: void 0,
1163
- legalComments: void 0
1164
- };
1165
- if ("legalComments" in response) result.legalComments = response == null ? void 0 : response.legalComments;
1166
- if (response.mangleCache) result.mangleCache = response == null ? void 0 : response.mangleCache;
1167
- callback(null, result);
1168
- }
1169
- };
1170
- if (errors.length > 0) return callback(failureErrorWithLog("Transform failed", errors, warnings), null);
1171
- if (response.codeFS) {
1172
- outstanding++;
1173
- fs3.readFile(response.code, (err, contents) => {
1174
- if (err !== null) callback(err, null);
1175
- else {
1176
- response.code = contents;
1177
- next();
1178
- }
1179
- });
1180
- }
1181
- if (response.mapFS) {
1182
- outstanding++;
1183
- fs3.readFile(response.map, (err, contents) => {
1184
- if (err !== null) callback(err, null);
1185
- else {
1186
- response.map = contents;
1187
- next();
1188
- }
1189
- });
1190
- }
1191
- next();
1192
- });
1193
- } catch (e) {
1194
- let flags = [];
1195
- try {
1196
- pushLogFlags(flags, options, {}, isTTY2, transformLogLevelDefault);
1197
- } catch {}
1198
- const error = extractErrorMessageV8(e, streamIn, details, void 0, "");
1199
- sendRequest(refs, {
1200
- command: "error",
1201
- flags,
1202
- error
1203
- }, () => {
1204
- error.detail = details.load(error.detail);
1205
- callback(failureErrorWithLog("Transform failed", [error], []), null);
1206
- });
1207
- }
1208
- };
1209
- if ((typeof input === "string" || input instanceof Uint8Array) && input.length > 1048576) {
1210
- let next = start;
1211
- start = () => fs3.writeFile(input, next);
1212
- }
1213
- start(null);
1214
- };
1215
- let formatMessages2 = ({ callName, refs, messages, options, callback }) => {
1216
- if (!options) throw new Error(`Missing second argument in ${callName}() call`);
1217
- let keys = {};
1218
- let kind = getFlag(options, keys, "kind", mustBeString);
1219
- let color = getFlag(options, keys, "color", mustBeBoolean);
1220
- let terminalWidth = getFlag(options, keys, "terminalWidth", mustBeInteger);
1221
- checkForInvalidFlags(options, keys, `in ${callName}() call`);
1222
- if (kind === void 0) throw new Error(`Missing "kind" in ${callName}() call`);
1223
- if (kind !== "error" && kind !== "warning") throw new Error(`Expected "kind" to be "error" or "warning" in ${callName}() call`);
1224
- let request = {
1225
- command: "format-msgs",
1226
- messages: sanitizeMessages(messages, "messages", null, "", terminalWidth),
1227
- isWarning: kind === "warning"
1228
- };
1229
- if (color !== void 0) request.color = color;
1230
- if (terminalWidth !== void 0) request.terminalWidth = terminalWidth;
1231
- sendRequest(refs, request, (error, response) => {
1232
- if (error) return callback(new Error(error), null);
1233
- callback(null, response.messages);
1234
- });
1235
- };
1236
- let analyzeMetafile2 = ({ callName, refs, metafile, options, callback }) => {
1237
- if (options === void 0) options = {};
1238
- let keys = {};
1239
- let color = getFlag(options, keys, "color", mustBeBoolean);
1240
- let verbose = getFlag(options, keys, "verbose", mustBeBoolean);
1241
- checkForInvalidFlags(options, keys, `in ${callName}() call`);
1242
- let request = {
1243
- command: "analyze-metafile",
1244
- metafile
1245
- };
1246
- if (color !== void 0) request.color = color;
1247
- if (verbose !== void 0) request.verbose = verbose;
1248
- sendRequest(refs, request, (error, response) => {
1249
- if (error) return callback(new Error(error), null);
1250
- callback(null, response.result);
1251
- });
1252
- };
1253
- return {
1254
- readFromStdout,
1255
- afterClose,
1256
- service: {
1257
- buildOrContext,
1258
- transform: transform2,
1259
- formatMessages: formatMessages2,
1260
- analyzeMetafile: analyzeMetafile2
1261
- }
1262
- };
1263
- }
1264
- function buildOrContextImpl(callName, buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options, isTTY2, defaultWD2, callback) {
1265
- const details = createObjectStash();
1266
- const isContext = callName === "context";
1267
- const handleError = (e, pluginName) => {
1268
- const flags = [];
1269
- try {
1270
- pushLogFlags(flags, options, {}, isTTY2, buildLogLevelDefault);
1271
- } catch {}
1272
- const message = extractErrorMessageV8(e, streamIn, details, void 0, pluginName);
1273
- sendRequest(refs, {
1274
- command: "error",
1275
- flags,
1276
- error: message
1277
- }, () => {
1278
- message.detail = details.load(message.detail);
1279
- callback(failureErrorWithLog(isContext ? "Context failed" : "Build failed", [message], []), null);
1280
- });
1281
- };
1282
- let plugins;
1283
- if (typeof options === "object") {
1284
- const value = options.plugins;
1285
- if (value !== void 0) {
1286
- if (!Array.isArray(value)) return handleError(/* @__PURE__ */ new Error(`"plugins" must be an array`), "");
1287
- plugins = value;
1288
- }
1289
- }
1290
- if (plugins && plugins.length > 0) {
1291
- if (streamIn.isSync) return handleError(/* @__PURE__ */ new Error("Cannot use plugins in synchronous API calls"), "");
1292
- handlePlugins(buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options, plugins, details).then((result) => {
1293
- if (!result.ok) return handleError(result.error, result.pluginName);
1294
- try {
1295
- buildOrContextContinue(result.requestPlugins, result.runOnEndCallbacks, result.scheduleOnDisposeCallbacks);
1296
- } catch (e) {
1297
- handleError(e, "");
1298
- }
1299
- }, (e) => handleError(e, ""));
1300
- return;
1301
- }
1302
- try {
1303
- buildOrContextContinue(null, (result, done) => done([], []), () => {});
1304
- } catch (e) {
1305
- handleError(e, "");
1306
- }
1307
- function buildOrContextContinue(requestPlugins, runOnEndCallbacks, scheduleOnDisposeCallbacks) {
1308
- const writeDefault = streamIn.hasFS;
1309
- const { entries, flags, write, stdinContents, stdinResolveDir, absWorkingDir, nodePaths, mangleCache } = flagsForBuildOptions(callName, options, isTTY2, buildLogLevelDefault, writeDefault);
1310
- if (write && !streamIn.hasFS) throw new Error(`The "write" option is unavailable in this environment`);
1311
- const request = {
1312
- command: "build",
1313
- key: buildKey,
1314
- entries,
1315
- flags,
1316
- write,
1317
- stdinContents,
1318
- stdinResolveDir,
1319
- absWorkingDir: absWorkingDir || defaultWD2,
1320
- nodePaths,
1321
- context: isContext
1322
- };
1323
- if (requestPlugins) request.plugins = requestPlugins;
1324
- if (mangleCache) request.mangleCache = mangleCache;
1325
- const buildResponseToResult = (response, callback2) => {
1326
- const result = {
1327
- errors: replaceDetailsInMessages(response.errors, details),
1328
- warnings: replaceDetailsInMessages(response.warnings, details),
1329
- outputFiles: void 0,
1330
- metafile: void 0,
1331
- mangleCache: void 0
1332
- };
1333
- const originalErrors = result.errors.slice();
1334
- const originalWarnings = result.warnings.slice();
1335
- if (response.outputFiles) result.outputFiles = response.outputFiles.map(convertOutputFiles);
1336
- if (response.metafile && response.metafile.length) result.metafile = parseJSON(response.metafile);
1337
- if (response.mangleCache) result.mangleCache = response.mangleCache;
1338
- if (response.writeToStdout !== void 0) console.log(decodeUTF8(response.writeToStdout).replace(/\n$/, ""));
1339
- runOnEndCallbacks(result, (onEndErrors, onEndWarnings) => {
1340
- if (originalErrors.length > 0 || onEndErrors.length > 0) return callback2(failureErrorWithLog("Build failed", originalErrors.concat(onEndErrors), originalWarnings.concat(onEndWarnings)), null, onEndErrors, onEndWarnings);
1341
- callback2(null, result, onEndErrors, onEndWarnings);
1342
- });
1343
- };
1344
- let latestResultPromise;
1345
- let provideLatestResult;
1346
- if (isContext) requestCallbacks["on-end"] = (id, request2) => new Promise((resolve) => {
1347
- buildResponseToResult(request2, (err, result, onEndErrors, onEndWarnings) => {
1348
- const response = {
1349
- errors: onEndErrors,
1350
- warnings: onEndWarnings
1351
- };
1352
- if (provideLatestResult) provideLatestResult(err, result);
1353
- latestResultPromise = void 0;
1354
- provideLatestResult = void 0;
1355
- sendResponse(id, response);
1356
- resolve();
1357
- });
1358
- });
1359
- sendRequest(refs, request, (error, response) => {
1360
- if (error) return callback(new Error(error), null);
1361
- if (!isContext) return buildResponseToResult(response, (err, res) => {
1362
- scheduleOnDisposeCallbacks();
1363
- return callback(err, res);
1364
- });
1365
- if (response.errors.length > 0) return callback(failureErrorWithLog("Context failed", response.errors, response.warnings), null);
1366
- let didDispose = false;
1367
- const result = {
1368
- rebuild: () => {
1369
- if (!latestResultPromise) latestResultPromise = new Promise((resolve, reject) => {
1370
- let settlePromise;
1371
- provideLatestResult = (err, result2) => {
1372
- if (!settlePromise) settlePromise = () => err ? reject(err) : resolve(result2);
1373
- };
1374
- const triggerAnotherBuild = () => {
1375
- sendRequest(refs, {
1376
- command: "rebuild",
1377
- key: buildKey
1378
- }, (error2, response2) => {
1379
- if (error2) reject(new Error(error2));
1380
- else if (settlePromise) settlePromise();
1381
- else triggerAnotherBuild();
1382
- });
1383
- };
1384
- triggerAnotherBuild();
1385
- });
1386
- return latestResultPromise;
1387
- },
1388
- watch: (options2 = {}) => new Promise((resolve, reject) => {
1389
- if (!streamIn.hasFS) throw new Error(`Cannot use the "watch" API in this environment`);
1390
- const keys = {};
1391
- const delay = getFlag(options2, keys, "delay", mustBeInteger);
1392
- checkForInvalidFlags(options2, keys, `in watch() call`);
1393
- const request2 = {
1394
- command: "watch",
1395
- key: buildKey
1396
- };
1397
- if (delay) request2.delay = delay;
1398
- sendRequest(refs, request2, (error2) => {
1399
- if (error2) reject(new Error(error2));
1400
- else resolve(void 0);
1401
- });
1402
- }),
1403
- serve: (options2 = {}) => new Promise((resolve, reject) => {
1404
- if (!streamIn.hasFS) throw new Error(`Cannot use the "serve" API in this environment`);
1405
- const keys = {};
1406
- const port = getFlag(options2, keys, "port", mustBeValidPortNumber);
1407
- const host = getFlag(options2, keys, "host", mustBeString);
1408
- const servedir = getFlag(options2, keys, "servedir", mustBeString);
1409
- const keyfile = getFlag(options2, keys, "keyfile", mustBeString);
1410
- const certfile = getFlag(options2, keys, "certfile", mustBeString);
1411
- const fallback = getFlag(options2, keys, "fallback", mustBeString);
1412
- const cors = getFlag(options2, keys, "cors", mustBeObject);
1413
- const onRequest = getFlag(options2, keys, "onRequest", mustBeFunction);
1414
- checkForInvalidFlags(options2, keys, `in serve() call`);
1415
- const request2 = {
1416
- command: "serve",
1417
- key: buildKey,
1418
- onRequest: !!onRequest
1419
- };
1420
- if (port !== void 0) request2.port = port;
1421
- if (host !== void 0) request2.host = host;
1422
- if (servedir !== void 0) request2.servedir = servedir;
1423
- if (keyfile !== void 0) request2.keyfile = keyfile;
1424
- if (certfile !== void 0) request2.certfile = certfile;
1425
- if (fallback !== void 0) request2.fallback = fallback;
1426
- if (cors) {
1427
- const corsKeys = {};
1428
- const origin = getFlag(cors, corsKeys, "origin", mustBeStringOrArrayOfStrings);
1429
- checkForInvalidFlags(cors, corsKeys, `on "cors" object`);
1430
- if (Array.isArray(origin)) request2.corsOrigin = origin;
1431
- else if (origin !== void 0) request2.corsOrigin = [origin];
1432
- }
1433
- sendRequest(refs, request2, (error2, response2) => {
1434
- if (error2) return reject(new Error(error2));
1435
- if (onRequest) requestCallbacks["serve-request"] = (id, request3) => {
1436
- onRequest(request3.args);
1437
- sendResponse(id, {});
1438
- };
1439
- resolve(response2);
1440
- });
1441
- }),
1442
- cancel: () => new Promise((resolve) => {
1443
- if (didDispose) return resolve();
1444
- sendRequest(refs, {
1445
- command: "cancel",
1446
- key: buildKey
1447
- }, () => {
1448
- resolve();
1449
- });
1450
- }),
1451
- dispose: () => new Promise((resolve) => {
1452
- if (didDispose) return resolve();
1453
- didDispose = true;
1454
- sendRequest(refs, {
1455
- command: "dispose",
1456
- key: buildKey
1457
- }, () => {
1458
- resolve();
1459
- scheduleOnDisposeCallbacks();
1460
- refs.unref();
1461
- });
1462
- })
1463
- };
1464
- refs.ref();
1465
- callback(null, result);
1466
- });
1467
- }
1468
- }
1469
- var handlePlugins = async (buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, initialOptions, plugins, details) => {
1470
- let onStartCallbacks = [];
1471
- let onEndCallbacks = [];
1472
- let onResolveCallbacks = {};
1473
- let onLoadCallbacks = {};
1474
- let onDisposeCallbacks = [];
1475
- let nextCallbackID = 0;
1476
- let i = 0;
1477
- let requestPlugins = [];
1478
- let isSetupDone = false;
1479
- plugins = [...plugins];
1480
- for (let item of plugins) {
1481
- let keys = {};
1482
- if (typeof item !== "object") throw new Error(`Plugin at index ${i} must be an object`);
1483
- const name = getFlag(item, keys, "name", mustBeString);
1484
- if (typeof name !== "string" || name === "") throw new Error(`Plugin at index ${i} is missing a name`);
1485
- try {
1486
- let setup = getFlag(item, keys, "setup", mustBeFunction);
1487
- if (typeof setup !== "function") throw new Error(`Plugin is missing a setup function`);
1488
- checkForInvalidFlags(item, keys, `on plugin ${quote(name)}`);
1489
- let plugin = {
1490
- name,
1491
- onStart: false,
1492
- onEnd: false,
1493
- onResolve: [],
1494
- onLoad: []
1495
- };
1496
- i++;
1497
- let resolve = (path3, options = {}) => {
1498
- if (!isSetupDone) throw new Error("Cannot call \"resolve\" before plugin setup has completed");
1499
- if (typeof path3 !== "string") throw new Error(`The path to resolve must be a string`);
1500
- let keys2 = /* @__PURE__ */ Object.create(null);
1501
- let pluginName = getFlag(options, keys2, "pluginName", mustBeString);
1502
- let importer = getFlag(options, keys2, "importer", mustBeString);
1503
- let namespace = getFlag(options, keys2, "namespace", mustBeString);
1504
- let resolveDir = getFlag(options, keys2, "resolveDir", mustBeString);
1505
- let kind = getFlag(options, keys2, "kind", mustBeString);
1506
- let pluginData = getFlag(options, keys2, "pluginData", canBeAnything);
1507
- let importAttributes = getFlag(options, keys2, "with", mustBeObject);
1508
- checkForInvalidFlags(options, keys2, "in resolve() call");
1509
- return new Promise((resolve2, reject) => {
1510
- const request = {
1511
- command: "resolve",
1512
- path: path3,
1513
- key: buildKey,
1514
- pluginName: name
1515
- };
1516
- if (pluginName != null) request.pluginName = pluginName;
1517
- if (importer != null) request.importer = importer;
1518
- if (namespace != null) request.namespace = namespace;
1519
- if (resolveDir != null) request.resolveDir = resolveDir;
1520
- if (kind != null) request.kind = kind;
1521
- else throw new Error(`Must specify "kind" when calling "resolve"`);
1522
- if (pluginData != null) request.pluginData = details.store(pluginData);
1523
- if (importAttributes != null) request.with = sanitizeStringMap(importAttributes, "with");
1524
- sendRequest(refs, request, (error, response) => {
1525
- if (error !== null) reject(new Error(error));
1526
- else resolve2({
1527
- errors: replaceDetailsInMessages(response.errors, details),
1528
- warnings: replaceDetailsInMessages(response.warnings, details),
1529
- path: response.path,
1530
- external: response.external,
1531
- sideEffects: response.sideEffects,
1532
- namespace: response.namespace,
1533
- suffix: response.suffix,
1534
- pluginData: details.load(response.pluginData)
1535
- });
1536
- });
1537
- });
1538
- };
1539
- let promise = setup({
1540
- initialOptions,
1541
- resolve,
1542
- onStart(callback) {
1543
- let registeredNote = extractCallerV8(/* @__PURE__ */ new Error(`This error came from the "onStart" callback registered here:`), streamIn, "onStart");
1544
- onStartCallbacks.push({
1545
- name,
1546
- callback,
1547
- note: registeredNote
1548
- });
1549
- plugin.onStart = true;
1550
- },
1551
- onEnd(callback) {
1552
- let registeredNote = extractCallerV8(/* @__PURE__ */ new Error(`This error came from the "onEnd" callback registered here:`), streamIn, "onEnd");
1553
- onEndCallbacks.push({
1554
- name,
1555
- callback,
1556
- note: registeredNote
1557
- });
1558
- plugin.onEnd = true;
1559
- },
1560
- onResolve(options, callback) {
1561
- let registeredNote = extractCallerV8(/* @__PURE__ */ new Error(`This error came from the "onResolve" callback registered here:`), streamIn, "onResolve");
1562
- let keys2 = {};
1563
- let filter = getFlag(options, keys2, "filter", mustBeRegExp);
1564
- let namespace = getFlag(options, keys2, "namespace", mustBeString);
1565
- checkForInvalidFlags(options, keys2, `in onResolve() call for plugin ${quote(name)}`);
1566
- if (filter == null) throw new Error(`onResolve() call is missing a filter`);
1567
- let id = nextCallbackID++;
1568
- onResolveCallbacks[id] = {
1569
- name,
1570
- callback,
1571
- note: registeredNote
1572
- };
1573
- plugin.onResolve.push({
1574
- id,
1575
- filter: jsRegExpToGoRegExp(filter),
1576
- namespace: namespace || ""
1577
- });
1578
- },
1579
- onLoad(options, callback) {
1580
- let registeredNote = extractCallerV8(/* @__PURE__ */ new Error(`This error came from the "onLoad" callback registered here:`), streamIn, "onLoad");
1581
- let keys2 = {};
1582
- let filter = getFlag(options, keys2, "filter", mustBeRegExp);
1583
- let namespace = getFlag(options, keys2, "namespace", mustBeString);
1584
- checkForInvalidFlags(options, keys2, `in onLoad() call for plugin ${quote(name)}`);
1585
- if (filter == null) throw new Error(`onLoad() call is missing a filter`);
1586
- let id = nextCallbackID++;
1587
- onLoadCallbacks[id] = {
1588
- name,
1589
- callback,
1590
- note: registeredNote
1591
- };
1592
- plugin.onLoad.push({
1593
- id,
1594
- filter: jsRegExpToGoRegExp(filter),
1595
- namespace: namespace || ""
1596
- });
1597
- },
1598
- onDispose(callback) {
1599
- onDisposeCallbacks.push(callback);
1600
- },
1601
- esbuild: streamIn.esbuild
1602
- });
1603
- if (promise) await promise;
1604
- requestPlugins.push(plugin);
1605
- } catch (e) {
1606
- return {
1607
- ok: false,
1608
- error: e,
1609
- pluginName: name
1610
- };
1611
- }
1612
- }
1613
- requestCallbacks["on-start"] = async (id, request) => {
1614
- details.clear();
1615
- let response = {
1616
- errors: [],
1617
- warnings: []
1618
- };
1619
- await Promise.all(onStartCallbacks.map(async ({ name, callback, note }) => {
1620
- try {
1621
- let result = await callback();
1622
- if (result != null) {
1623
- if (typeof result !== "object") throw new Error(`Expected onStart() callback in plugin ${quote(name)} to return an object`);
1624
- let keys = {};
1625
- let errors = getFlag(result, keys, "errors", mustBeArray);
1626
- let warnings = getFlag(result, keys, "warnings", mustBeArray);
1627
- checkForInvalidFlags(result, keys, `from onStart() callback in plugin ${quote(name)}`);
1628
- if (errors != null) response.errors.push(...sanitizeMessages(errors, "errors", details, name, void 0));
1629
- if (warnings != null) response.warnings.push(...sanitizeMessages(warnings, "warnings", details, name, void 0));
1630
- }
1631
- } catch (e) {
1632
- response.errors.push(extractErrorMessageV8(e, streamIn, details, note && note(), name));
1633
- }
1634
- }));
1635
- sendResponse(id, response);
1636
- };
1637
- requestCallbacks["on-resolve"] = async (id, request) => {
1638
- let response = {}, name = "", callback, note;
1639
- for (let id2 of request.ids) try {
1640
- ({name, callback, note} = onResolveCallbacks[id2]);
1641
- let result = await callback({
1642
- path: request.path,
1643
- importer: request.importer,
1644
- namespace: request.namespace,
1645
- resolveDir: request.resolveDir,
1646
- kind: request.kind,
1647
- pluginData: details.load(request.pluginData),
1648
- with: request.with
1649
- });
1650
- if (result != null) {
1651
- if (typeof result !== "object") throw new Error(`Expected onResolve() callback in plugin ${quote(name)} to return an object`);
1652
- let keys = {};
1653
- let pluginName = getFlag(result, keys, "pluginName", mustBeString);
1654
- let path3 = getFlag(result, keys, "path", mustBeString);
1655
- let namespace = getFlag(result, keys, "namespace", mustBeString);
1656
- let suffix = getFlag(result, keys, "suffix", mustBeString);
1657
- let external = getFlag(result, keys, "external", mustBeBoolean);
1658
- let sideEffects = getFlag(result, keys, "sideEffects", mustBeBoolean);
1659
- let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
1660
- let errors = getFlag(result, keys, "errors", mustBeArray);
1661
- let warnings = getFlag(result, keys, "warnings", mustBeArray);
1662
- let watchFiles = getFlag(result, keys, "watchFiles", mustBeArrayOfStrings);
1663
- let watchDirs = getFlag(result, keys, "watchDirs", mustBeArrayOfStrings);
1664
- checkForInvalidFlags(result, keys, `from onResolve() callback in plugin ${quote(name)}`);
1665
- response.id = id2;
1666
- if (pluginName != null) response.pluginName = pluginName;
1667
- if (path3 != null) response.path = path3;
1668
- if (namespace != null) response.namespace = namespace;
1669
- if (suffix != null) response.suffix = suffix;
1670
- if (external != null) response.external = external;
1671
- if (sideEffects != null) response.sideEffects = sideEffects;
1672
- if (pluginData != null) response.pluginData = details.store(pluginData);
1673
- if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name, void 0);
1674
- if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
1675
- if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
1676
- if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
1677
- break;
1678
- }
1679
- } catch (e) {
1680
- response = {
1681
- id: id2,
1682
- errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)]
1683
- };
1684
- break;
1685
- }
1686
- sendResponse(id, response);
1687
- };
1688
- requestCallbacks["on-load"] = async (id, request) => {
1689
- let response = {}, name = "", callback, note;
1690
- for (let id2 of request.ids) try {
1691
- ({name, callback, note} = onLoadCallbacks[id2]);
1692
- let result = await callback({
1693
- path: request.path,
1694
- namespace: request.namespace,
1695
- suffix: request.suffix,
1696
- pluginData: details.load(request.pluginData),
1697
- with: request.with
1698
- });
1699
- if (result != null) {
1700
- if (typeof result !== "object") throw new Error(`Expected onLoad() callback in plugin ${quote(name)} to return an object`);
1701
- let keys = {};
1702
- let pluginName = getFlag(result, keys, "pluginName", mustBeString);
1703
- let contents = getFlag(result, keys, "contents", mustBeStringOrUint8Array);
1704
- let resolveDir = getFlag(result, keys, "resolveDir", mustBeString);
1705
- let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
1706
- let loader = getFlag(result, keys, "loader", mustBeString);
1707
- let errors = getFlag(result, keys, "errors", mustBeArray);
1708
- let warnings = getFlag(result, keys, "warnings", mustBeArray);
1709
- let watchFiles = getFlag(result, keys, "watchFiles", mustBeArrayOfStrings);
1710
- let watchDirs = getFlag(result, keys, "watchDirs", mustBeArrayOfStrings);
1711
- checkForInvalidFlags(result, keys, `from onLoad() callback in plugin ${quote(name)}`);
1712
- response.id = id2;
1713
- if (pluginName != null) response.pluginName = pluginName;
1714
- if (contents instanceof Uint8Array) response.contents = contents;
1715
- else if (contents != null) response.contents = encodeUTF8(contents);
1716
- if (resolveDir != null) response.resolveDir = resolveDir;
1717
- if (pluginData != null) response.pluginData = details.store(pluginData);
1718
- if (loader != null) response.loader = loader;
1719
- if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name, void 0);
1720
- if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
1721
- if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
1722
- if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
1723
- break;
1724
- }
1725
- } catch (e) {
1726
- response = {
1727
- id: id2,
1728
- errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)]
1729
- };
1730
- break;
1731
- }
1732
- sendResponse(id, response);
1733
- };
1734
- let runOnEndCallbacks = (result, done) => done([], []);
1735
- if (onEndCallbacks.length > 0) runOnEndCallbacks = (result, done) => {
1736
- (async () => {
1737
- const onEndErrors = [];
1738
- const onEndWarnings = [];
1739
- for (const { name, callback, note } of onEndCallbacks) {
1740
- let newErrors;
1741
- let newWarnings;
1742
- try {
1743
- const value = await callback(result);
1744
- if (value != null) {
1745
- if (typeof value !== "object") throw new Error(`Expected onEnd() callback in plugin ${quote(name)} to return an object`);
1746
- let keys = {};
1747
- let errors = getFlag(value, keys, "errors", mustBeArray);
1748
- let warnings = getFlag(value, keys, "warnings", mustBeArray);
1749
- checkForInvalidFlags(value, keys, `from onEnd() callback in plugin ${quote(name)}`);
1750
- if (errors != null) newErrors = sanitizeMessages(errors, "errors", details, name, void 0);
1751
- if (warnings != null) newWarnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
1752
- }
1753
- } catch (e) {
1754
- newErrors = [extractErrorMessageV8(e, streamIn, details, note && note(), name)];
1755
- }
1756
- if (newErrors) {
1757
- onEndErrors.push(...newErrors);
1758
- try {
1759
- result.errors.push(...newErrors);
1760
- } catch {}
1761
- }
1762
- if (newWarnings) {
1763
- onEndWarnings.push(...newWarnings);
1764
- try {
1765
- result.warnings.push(...newWarnings);
1766
- } catch {}
1767
- }
1768
- }
1769
- done(onEndErrors, onEndWarnings);
1770
- })();
1771
- };
1772
- let scheduleOnDisposeCallbacks = () => {
1773
- for (const cb of onDisposeCallbacks) setTimeout(() => cb(), 0);
1774
- };
1775
- isSetupDone = true;
1776
- return {
1777
- ok: true,
1778
- requestPlugins,
1779
- runOnEndCallbacks,
1780
- scheduleOnDisposeCallbacks
1781
- };
1782
- };
1783
- function createObjectStash() {
1784
- const map = /* @__PURE__ */ new Map();
1785
- let nextID = 0;
1786
- return {
1787
- clear() {
1788
- map.clear();
1789
- },
1790
- load(id) {
1791
- return map.get(id);
1792
- },
1793
- store(value) {
1794
- if (value === void 0) return -1;
1795
- const id = nextID++;
1796
- map.set(id, value);
1797
- return id;
1798
- }
1799
- };
1800
- }
1801
- function extractCallerV8(e, streamIn, ident) {
1802
- let note;
1803
- let tried = false;
1804
- return () => {
1805
- if (tried) return note;
1806
- tried = true;
1807
- try {
1808
- let lines = (e.stack + "").split("\n");
1809
- lines.splice(1, 1);
1810
- let location = parseStackLinesV8(streamIn, lines, ident);
1811
- if (location) {
1812
- note = {
1813
- text: e.message,
1814
- location
1815
- };
1816
- return note;
1817
- }
1818
- } catch {}
1819
- };
1820
- }
1821
- function extractErrorMessageV8(e, streamIn, stash, note, pluginName) {
1822
- let text = "Internal error";
1823
- let location = null;
1824
- try {
1825
- text = (e && e.message || e) + "";
1826
- } catch {}
1827
- try {
1828
- location = parseStackLinesV8(streamIn, (e.stack + "").split("\n"), "");
1829
- } catch {}
1830
- return {
1831
- id: "",
1832
- pluginName,
1833
- text,
1834
- location,
1835
- notes: note ? [note] : [],
1836
- detail: stash ? stash.store(e) : -1
1837
- };
1838
- }
1839
- function parseStackLinesV8(streamIn, lines, ident) {
1840
- let at = " at ";
1841
- if (streamIn.readFileSync && !lines[0].startsWith(at) && lines[1].startsWith(at)) for (let i = 1; i < lines.length; i++) {
1842
- let line = lines[i];
1843
- if (!line.startsWith(at)) continue;
1844
- line = line.slice(7);
1845
- while (true) {
1846
- let match = /^(?:new |async )?\S+ \((.*)\)$/.exec(line);
1847
- if (match) {
1848
- line = match[1];
1849
- continue;
1850
- }
1851
- match = /^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec(line);
1852
- if (match) {
1853
- line = match[1];
1854
- continue;
1855
- }
1856
- match = /^(\S+):(\d+):(\d+)$/.exec(line);
1857
- if (match) {
1858
- let contents;
1859
- try {
1860
- contents = streamIn.readFileSync(match[1], "utf8");
1861
- } catch {
1862
- break;
1863
- }
1864
- let lineText = contents.split(/\r\n|\r|\n|\u2028|\u2029/)[+match[2] - 1] || "";
1865
- let column = +match[3] - 1;
1866
- let length = lineText.slice(column, column + ident.length) === ident ? ident.length : 0;
1867
- return {
1868
- file: match[1],
1869
- namespace: "file",
1870
- line: +match[2],
1871
- column: encodeUTF8(lineText.slice(0, column)).length,
1872
- length: encodeUTF8(lineText.slice(column, column + length)).length,
1873
- lineText: lineText + "\n" + lines.slice(1).join("\n"),
1874
- suggestion: ""
1875
- };
1876
- }
1877
- break;
1878
- }
1879
- }
1880
- return null;
1881
- }
1882
- function failureErrorWithLog(text, errors, warnings) {
1883
- let limit = 5;
1884
- text += errors.length < 1 ? "" : ` with ${errors.length} error${errors.length < 2 ? "" : "s"}:` + errors.slice(0, 6).map((e, i) => {
1885
- if (i === limit) return "\n...";
1886
- if (!e.location) return `
1887
- error: ${e.text}`;
1888
- let { file, line, column } = e.location;
1889
- return `
1890
- ${file}:${line}:${column}: ERROR: ${e.pluginName ? `[plugin: ${e.pluginName}] ` : ""}${e.text}`;
1891
- }).join("");
1892
- let error = new Error(text);
1893
- for (const [key, value] of [["errors", errors], ["warnings", warnings]]) Object.defineProperty(error, key, {
1894
- configurable: true,
1895
- enumerable: true,
1896
- get: () => value,
1897
- set: (value2) => Object.defineProperty(error, key, {
1898
- configurable: true,
1899
- enumerable: true,
1900
- value: value2
1901
- })
1902
- });
1903
- return error;
1904
- }
1905
- function replaceDetailsInMessages(messages, stash) {
1906
- for (const message of messages) message.detail = stash.load(message.detail);
1907
- return messages;
1908
- }
1909
- function sanitizeLocation(location, where, terminalWidth) {
1910
- if (location == null) return null;
1911
- let keys = {};
1912
- let file = getFlag(location, keys, "file", mustBeString);
1913
- let namespace = getFlag(location, keys, "namespace", mustBeString);
1914
- let line = getFlag(location, keys, "line", mustBeInteger);
1915
- let column = getFlag(location, keys, "column", mustBeInteger);
1916
- let length = getFlag(location, keys, "length", mustBeInteger);
1917
- let lineText = getFlag(location, keys, "lineText", mustBeString);
1918
- let suggestion = getFlag(location, keys, "suggestion", mustBeString);
1919
- checkForInvalidFlags(location, keys, where);
1920
- if (lineText) {
1921
- const relevantASCII = lineText.slice(0, (column && column > 0 ? column : 0) + (length && length > 0 ? length : 0) + (terminalWidth && terminalWidth > 0 ? terminalWidth : 80));
1922
- if (!/[\x7F-\uFFFF]/.test(relevantASCII) && !/\n/.test(lineText)) lineText = relevantASCII;
1923
- }
1924
- return {
1925
- file: file || "",
1926
- namespace: namespace || "",
1927
- line: line || 0,
1928
- column: column || 0,
1929
- length: length || 0,
1930
- lineText: lineText || "",
1931
- suggestion: suggestion || ""
1932
- };
1933
- }
1934
- function sanitizeMessages(messages, property, stash, fallbackPluginName, terminalWidth) {
1935
- let messagesClone = [];
1936
- let index = 0;
1937
- for (const message of messages) {
1938
- let keys = {};
1939
- let id = getFlag(message, keys, "id", mustBeString);
1940
- let pluginName = getFlag(message, keys, "pluginName", mustBeString);
1941
- let text = getFlag(message, keys, "text", mustBeString);
1942
- let location = getFlag(message, keys, "location", mustBeObjectOrNull);
1943
- let notes = getFlag(message, keys, "notes", mustBeArray);
1944
- let detail = getFlag(message, keys, "detail", canBeAnything);
1945
- let where = `in element ${index} of "${property}"`;
1946
- checkForInvalidFlags(message, keys, where);
1947
- let notesClone = [];
1948
- if (notes) for (const note of notes) {
1949
- let noteKeys = {};
1950
- let noteText = getFlag(note, noteKeys, "text", mustBeString);
1951
- let noteLocation = getFlag(note, noteKeys, "location", mustBeObjectOrNull);
1952
- checkForInvalidFlags(note, noteKeys, where);
1953
- notesClone.push({
1954
- text: noteText || "",
1955
- location: sanitizeLocation(noteLocation, where, terminalWidth)
1956
- });
1957
- }
1958
- messagesClone.push({
1959
- id: id || "",
1960
- pluginName: pluginName || fallbackPluginName,
1961
- text: text || "",
1962
- location: sanitizeLocation(location, where, terminalWidth),
1963
- notes: notesClone,
1964
- detail: stash ? stash.store(detail) : -1
1965
- });
1966
- index++;
1967
- }
1968
- return messagesClone;
1969
- }
1970
- function sanitizeStringArray(values, property) {
1971
- const result = [];
1972
- for (const value of values) {
1973
- if (typeof value !== "string") throw new Error(`${quote(property)} must be an array of strings`);
1974
- result.push(value);
1975
- }
1976
- return result;
1977
- }
1978
- function sanitizeStringMap(map, property) {
1979
- const result = /* @__PURE__ */ Object.create(null);
1980
- for (const key in map) {
1981
- const value = map[key];
1982
- if (typeof value !== "string") throw new Error(`key ${quote(key)} in object ${quote(property)} must be a string`);
1983
- result[key] = value;
1984
- }
1985
- return result;
1986
- }
1987
- function convertOutputFiles({ path: path3, contents, hash }) {
1988
- let text = null;
1989
- return {
1990
- path: path3,
1991
- contents,
1992
- hash,
1993
- get text() {
1994
- const binary = this.contents;
1995
- if (text === null || binary !== contents) {
1996
- contents = binary;
1997
- text = decodeUTF8(binary);
1998
- }
1999
- return text;
2000
- }
2001
- };
2002
- }
2003
- function jsRegExpToGoRegExp(regexp) {
2004
- let result = regexp.source;
2005
- if (regexp.flags) result = `(?${regexp.flags})${result}`;
2006
- return result;
2007
- }
2008
- function parseJSON(bytes) {
2009
- let text;
2010
- try {
2011
- text = decodeUTF8(bytes);
2012
- } catch {
2013
- return JSON_parse(bytes);
2014
- }
2015
- return JSON.parse(text);
2016
- }
2017
- var fs = __require("fs");
2018
- var os = __require("os");
2019
- var path = __require("path");
2020
- var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH;
2021
- var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild";
2022
- var packageDarwin_arm64 = "@esbuild/darwin-arm64";
2023
- var packageDarwin_x64 = "@esbuild/darwin-x64";
2024
- var knownWindowsPackages = {
2025
- "win32 arm64 LE": "@esbuild/win32-arm64",
2026
- "win32 ia32 LE": "@esbuild/win32-ia32",
2027
- "win32 x64 LE": "@esbuild/win32-x64"
2028
- };
2029
- var knownUnixlikePackages = {
2030
- "aix ppc64 BE": "@esbuild/aix-ppc64",
2031
- "android arm64 LE": "@esbuild/android-arm64",
2032
- "darwin arm64 LE": "@esbuild/darwin-arm64",
2033
- "darwin x64 LE": "@esbuild/darwin-x64",
2034
- "freebsd arm64 LE": "@esbuild/freebsd-arm64",
2035
- "freebsd x64 LE": "@esbuild/freebsd-x64",
2036
- "linux arm LE": "@esbuild/linux-arm",
2037
- "linux arm64 LE": "@esbuild/linux-arm64",
2038
- "linux ia32 LE": "@esbuild/linux-ia32",
2039
- "linux mips64el LE": "@esbuild/linux-mips64el",
2040
- "linux ppc64 LE": "@esbuild/linux-ppc64",
2041
- "linux riscv64 LE": "@esbuild/linux-riscv64",
2042
- "linux s390x BE": "@esbuild/linux-s390x",
2043
- "linux x64 LE": "@esbuild/linux-x64",
2044
- "linux loong64 LE": "@esbuild/linux-loong64",
2045
- "netbsd arm64 LE": "@esbuild/netbsd-arm64",
2046
- "netbsd x64 LE": "@esbuild/netbsd-x64",
2047
- "openbsd arm64 LE": "@esbuild/openbsd-arm64",
2048
- "openbsd x64 LE": "@esbuild/openbsd-x64",
2049
- "sunos x64 LE": "@esbuild/sunos-x64"
2050
- };
2051
- var knownWebAssemblyFallbackPackages = {
2052
- "android arm LE": "@esbuild/android-arm",
2053
- "android x64 LE": "@esbuild/android-x64",
2054
- "openharmony arm64 LE": "@esbuild/openharmony-arm64"
2055
- };
2056
- function pkgAndSubpathForCurrentPlatform() {
2057
- let pkg;
2058
- let subpath;
2059
- let isWASM = false;
2060
- let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`;
2061
- if (platformKey in knownWindowsPackages) {
2062
- pkg = knownWindowsPackages[platformKey];
2063
- subpath = "esbuild.exe";
2064
- } else if (platformKey in knownUnixlikePackages) {
2065
- pkg = knownUnixlikePackages[platformKey];
2066
- subpath = "bin/esbuild";
2067
- } else if (platformKey in knownWebAssemblyFallbackPackages) {
2068
- pkg = knownWebAssemblyFallbackPackages[platformKey];
2069
- subpath = "bin/esbuild";
2070
- isWASM = true;
2071
- } else throw new Error(`Unsupported platform: ${platformKey}`);
2072
- return {
2073
- pkg,
2074
- subpath,
2075
- isWASM
2076
- };
2077
- }
2078
- function pkgForSomeOtherPlatform() {
2079
- const libMainJS = __require.resolve("esbuild");
2080
- const nodeModulesDirectory = path.dirname(path.dirname(path.dirname(libMainJS)));
2081
- if (path.basename(nodeModulesDirectory) === "node_modules") {
2082
- for (const unixKey in knownUnixlikePackages) try {
2083
- const pkg = knownUnixlikePackages[unixKey];
2084
- if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) return pkg;
2085
- } catch {}
2086
- for (const windowsKey in knownWindowsPackages) try {
2087
- const pkg = knownWindowsPackages[windowsKey];
2088
- if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) return pkg;
2089
- } catch {}
2090
- }
2091
- return null;
2092
- }
2093
- function downloadedBinPath(pkg, subpath) {
2094
- const esbuildLibDir = path.dirname(__require.resolve("esbuild"));
2095
- return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`);
2096
- }
2097
- function generateBinPath() {
2098
- if (isValidBinaryPath(ESBUILD_BINARY_PATH)) {
2099
- if (!fs.existsSync(ESBUILD_BINARY_PATH)) console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`);
2100
- else return {
2101
- binPath: ESBUILD_BINARY_PATH,
2102
- isWASM: false
2103
- };
2104
- }
2105
- const { pkg, subpath, isWASM } = pkgAndSubpathForCurrentPlatform();
2106
- let binPath;
2107
- try {
2108
- binPath = __require.resolve(`${pkg}/${subpath}`);
2109
- } catch (e) {
2110
- binPath = downloadedBinPath(pkg, subpath);
2111
- if (!fs.existsSync(binPath)) {
2112
- try {
2113
- __require.resolve(pkg);
2114
- } catch {
2115
- const otherPkg = pkgForSomeOtherPlatform();
2116
- if (otherPkg) {
2117
- let suggestions = `
2118
- Specifically the "${otherPkg}" package is present but this platform
2119
- needs the "${pkg}" package instead. People often get into this
2120
- situation by installing esbuild on Windows or macOS and copying "node_modules"
2121
- into a Docker image that runs Linux, or by copying "node_modules" between
2122
- Windows and WSL environments.
2123
-
2124
- If you are installing with npm, you can try not copying the "node_modules"
2125
- directory when you copy the files over, and running "npm ci" or "npm install"
2126
- on the destination platform after the copy. Or you could consider using yarn
2127
- instead of npm which has built-in support for installing a package on multiple
2128
- platforms simultaneously.
2129
-
2130
- If you are installing with yarn, you can try listing both this platform and the
2131
- other platform in your ".yarnrc.yml" file using the "supportedArchitectures"
2132
- feature: https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
2133
- Keep in mind that this means multiple copies of esbuild will be present.
2134
- `;
2135
- if (pkg === packageDarwin_x64 && otherPkg === packageDarwin_arm64 || pkg === packageDarwin_arm64 && otherPkg === packageDarwin_x64) suggestions = `
2136
- Specifically the "${otherPkg}" package is present but this platform
2137
- needs the "${pkg}" package instead. People often get into this
2138
- situation by installing esbuild with npm running inside of Rosetta 2 and then
2139
- trying to use it with node running outside of Rosetta 2, or vice versa (Rosetta
2140
- 2 is Apple's on-the-fly x86_64-to-arm64 translation service).
2141
-
2142
- If you are installing with npm, you can try ensuring that both npm and node are
2143
- not running under Rosetta 2 and then reinstalling esbuild. This likely involves
2144
- changing how you installed npm and/or node. For example, installing node with
2145
- the universal installer here should work: https://nodejs.org/en/download/. Or
2146
- you could consider using yarn instead of npm which has built-in support for
2147
- installing a package on multiple platforms simultaneously.
2148
-
2149
- If you are installing with yarn, you can try listing both "arm64" and "x64"
2150
- in your ".yarnrc.yml" file using the "supportedArchitectures" feature:
2151
- https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
2152
- Keep in mind that this means multiple copies of esbuild will be present.
2153
- `;
2154
- throw new Error(`
2155
- You installed esbuild for another platform than the one you're currently using.
2156
- This won't work because esbuild is written with native code and needs to
2157
- install a platform-specific binary executable.
2158
- ${suggestions}
2159
- Another alternative is to use the "esbuild-wasm" package instead, which works
2160
- the same way on all platforms. But it comes with a heavy performance cost and
2161
- can sometimes be 10x slower than the "esbuild" package, so you may also not
2162
- want to do that.
2163
- `);
2164
- }
2165
- throw new Error(`The package "${pkg}" could not be found, and is needed by esbuild.
2166
-
2167
- If you are installing esbuild with npm, make sure that you don't specify the
2168
- "--no-optional" or "--omit=optional" flags. The "optionalDependencies" feature
2169
- of "package.json" is used by esbuild to install the correct binary executable
2170
- for your current platform.`);
2171
- }
2172
- throw e;
2173
- }
2174
- }
2175
- if (/\.zip\//.test(binPath)) {
2176
- let pnpapi;
2177
- try {
2178
- pnpapi = __require("pnpapi");
2179
- } catch (e) {}
2180
- if (pnpapi) {
2181
- const root = pnpapi.getPackageInformation(pnpapi.topLevel).packageLocation;
2182
- const binTargetPath = path.join(root, "node_modules", ".cache", "esbuild", `pnpapi-${pkg.replace("/", "-")}-0.27.7-${path.basename(subpath)}`);
2183
- if (!fs.existsSync(binTargetPath)) {
2184
- fs.mkdirSync(path.dirname(binTargetPath), { recursive: true });
2185
- fs.copyFileSync(binPath, binTargetPath);
2186
- fs.chmodSync(binTargetPath, 493);
2187
- }
2188
- return {
2189
- binPath: binTargetPath,
2190
- isWASM
2191
- };
2192
- }
2193
- }
2194
- return {
2195
- binPath,
2196
- isWASM
2197
- };
2198
- }
2199
- var child_process = __require("child_process");
2200
- var crypto = __require("crypto");
2201
- var path2 = __require("path");
2202
- var fs2 = __require("fs");
2203
- var os2 = __require("os");
2204
- var tty = __require("tty");
2205
- var worker_threads;
2206
- if (process.env.ESBUILD_WORKER_THREADS !== "0") {
2207
- try {
2208
- worker_threads = __require("worker_threads");
2209
- } catch {}
2210
- let [major, minor] = process.versions.node.split(".");
2211
- if (+major < 12 || +major === 12 && +minor < 17 || +major === 13 && +minor < 13) worker_threads = void 0;
2212
- }
2213
- var _a;
2214
- var isInternalWorkerThread = ((_a = worker_threads == null ? void 0 : worker_threads.workerData) == null ? void 0 : _a.esbuildVersion) === "0.27.7";
2215
- var esbuildCommandAndArgs = () => {
2216
- 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.
2217
-
2218
- 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.`);
2219
- {
2220
- const { binPath, isWASM } = generateBinPath();
2221
- if (isWASM) return ["node", [binPath]];
2222
- else return [binPath, []];
2223
- }
2224
- };
2225
- var isTTY = () => tty.isatty(2);
2226
- var fsSync = {
2227
- readFile(tempFile, callback) {
2228
- try {
2229
- let contents = fs2.readFileSync(tempFile, "utf8");
2230
- try {
2231
- fs2.unlinkSync(tempFile);
2232
- } catch {}
2233
- callback(null, contents);
2234
- } catch (err) {
2235
- callback(err, null);
2236
- }
2237
- },
2238
- writeFile(contents, callback) {
2239
- try {
2240
- let tempFile = randomFileName();
2241
- fs2.writeFileSync(tempFile, contents);
2242
- callback(tempFile);
2243
- } catch {
2244
- callback(null);
2245
- }
2246
- }
2247
- };
2248
- var fsAsync = {
2249
- readFile(tempFile, callback) {
2250
- try {
2251
- fs2.readFile(tempFile, "utf8", (err, contents) => {
2252
- try {
2253
- fs2.unlink(tempFile, () => callback(err, contents));
2254
- } catch {
2255
- callback(err, contents);
2256
- }
2257
- });
2258
- } catch (err) {
2259
- callback(err, null);
2260
- }
2261
- },
2262
- writeFile(contents, callback) {
2263
- try {
2264
- let tempFile = randomFileName();
2265
- fs2.writeFile(tempFile, contents, (err) => err !== null ? callback(null) : callback(tempFile));
2266
- } catch {
2267
- callback(null);
2268
- }
2269
- }
2270
- };
2271
- var version = "0.27.7";
2272
- var build = (options) => ensureServiceIsRunning().build(options);
2273
- var context = (buildOptions) => ensureServiceIsRunning().context(buildOptions);
2274
- var transform = (input, options) => ensureServiceIsRunning().transform(input, options);
2275
- var formatMessages = (messages, options) => ensureServiceIsRunning().formatMessages(messages, options);
2276
- var analyzeMetafile = (messages, options) => ensureServiceIsRunning().analyzeMetafile(messages, options);
2277
- var buildSync = (options) => {
2278
- if (worker_threads && !isInternalWorkerThread) {
2279
- if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
2280
- return workerThreadService.buildSync(options);
2281
- }
2282
- let result;
2283
- runServiceSync((service) => service.buildOrContext({
2284
- callName: "buildSync",
2285
- refs: null,
2286
- options,
2287
- isTTY: isTTY(),
2288
- defaultWD,
2289
- callback: (err, res) => {
2290
- if (err) throw err;
2291
- result = res;
2292
- }
2293
- }));
2294
- return result;
2295
- };
2296
- var transformSync = (input, options) => {
2297
- if (worker_threads && !isInternalWorkerThread) {
2298
- if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
2299
- return workerThreadService.transformSync(input, options);
2300
- }
2301
- let result;
2302
- runServiceSync((service) => service.transform({
2303
- callName: "transformSync",
2304
- refs: null,
2305
- input,
2306
- options: options || {},
2307
- isTTY: isTTY(),
2308
- fs: fsSync,
2309
- callback: (err, res) => {
2310
- if (err) throw err;
2311
- result = res;
2312
- }
2313
- }));
2314
- return result;
2315
- };
2316
- var formatMessagesSync = (messages, options) => {
2317
- if (worker_threads && !isInternalWorkerThread) {
2318
- if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
2319
- return workerThreadService.formatMessagesSync(messages, options);
2320
- }
2321
- let result;
2322
- runServiceSync((service) => service.formatMessages({
2323
- callName: "formatMessagesSync",
2324
- refs: null,
2325
- messages,
2326
- options,
2327
- callback: (err, res) => {
2328
- if (err) throw err;
2329
- result = res;
2330
- }
2331
- }));
2332
- return result;
2333
- };
2334
- var analyzeMetafileSync = (metafile, options) => {
2335
- if (worker_threads && !isInternalWorkerThread) {
2336
- if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
2337
- return workerThreadService.analyzeMetafileSync(metafile, options);
2338
- }
2339
- let result;
2340
- runServiceSync((service) => service.analyzeMetafile({
2341
- callName: "analyzeMetafileSync",
2342
- refs: null,
2343
- metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
2344
- options,
2345
- callback: (err, res) => {
2346
- if (err) throw err;
2347
- result = res;
2348
- }
2349
- }));
2350
- return result;
2351
- };
2352
- var stop = () => {
2353
- if (stopService) stopService();
2354
- if (workerThreadService) workerThreadService.stop();
2355
- return Promise.resolve();
2356
- };
2357
- var initializeWasCalled = false;
2358
- var initialize = (options) => {
2359
- options = validateInitializeOptions(options || {});
2360
- if (options.wasmURL) throw new Error(`The "wasmURL" option only works in the browser`);
2361
- if (options.wasmModule) throw new Error(`The "wasmModule" option only works in the browser`);
2362
- if (options.worker) throw new Error(`The "worker" option only works in the browser`);
2363
- if (initializeWasCalled) throw new Error("Cannot call \"initialize\" more than once");
2364
- ensureServiceIsRunning();
2365
- initializeWasCalled = true;
2366
- return Promise.resolve();
2367
- };
2368
- var defaultWD = process.cwd();
2369
- var longLivedService;
2370
- var stopService;
2371
- var ensureServiceIsRunning = () => {
2372
- if (longLivedService) return longLivedService;
2373
- let [command, args] = esbuildCommandAndArgs();
2374
- let child = child_process.spawn(command, args.concat(`--service=0.27.7`, "--ping"), {
2375
- windowsHide: true,
2376
- stdio: [
2377
- "pipe",
2378
- "pipe",
2379
- "inherit"
2380
- ],
2381
- cwd: defaultWD
2382
- });
2383
- let { readFromStdout, afterClose, service } = createChannel({
2384
- writeToStdin(bytes) {
2385
- child.stdin.write(bytes, (err) => {
2386
- if (err) afterClose(err);
2387
- });
2388
- },
2389
- readFileSync: fs2.readFileSync,
2390
- isSync: false,
2391
- hasFS: true,
2392
- esbuild: node_exports
2393
- });
2394
- child.stdin.on("error", afterClose);
2395
- child.on("error", afterClose);
2396
- const stdin = child.stdin;
2397
- const stdout = child.stdout;
2398
- stdout.on("data", readFromStdout);
2399
- stdout.on("end", afterClose);
2400
- stopService = () => {
2401
- stdin.destroy();
2402
- stdout.destroy();
2403
- child.kill();
2404
- initializeWasCalled = false;
2405
- longLivedService = void 0;
2406
- stopService = void 0;
2407
- };
2408
- let refCount = 0;
2409
- child.unref();
2410
- if (stdin.unref) stdin.unref();
2411
- if (stdout.unref) stdout.unref();
2412
- const refs = {
2413
- ref() {
2414
- if (++refCount === 1) child.ref();
2415
- },
2416
- unref() {
2417
- if (--refCount === 0) child.unref();
2418
- }
2419
- };
2420
- longLivedService = {
2421
- build: (options) => new Promise((resolve, reject) => {
2422
- service.buildOrContext({
2423
- callName: "build",
2424
- refs,
2425
- options,
2426
- isTTY: isTTY(),
2427
- defaultWD,
2428
- callback: (err, res) => err ? reject(err) : resolve(res)
2429
- });
2430
- }),
2431
- context: (options) => new Promise((resolve, reject) => service.buildOrContext({
2432
- callName: "context",
2433
- refs,
2434
- options,
2435
- isTTY: isTTY(),
2436
- defaultWD,
2437
- callback: (err, res) => err ? reject(err) : resolve(res)
2438
- })),
2439
- transform: (input, options) => new Promise((resolve, reject) => service.transform({
2440
- callName: "transform",
2441
- refs,
2442
- input,
2443
- options: options || {},
2444
- isTTY: isTTY(),
2445
- fs: fsAsync,
2446
- callback: (err, res) => err ? reject(err) : resolve(res)
2447
- })),
2448
- formatMessages: (messages, options) => new Promise((resolve, reject) => service.formatMessages({
2449
- callName: "formatMessages",
2450
- refs,
2451
- messages,
2452
- options,
2453
- callback: (err, res) => err ? reject(err) : resolve(res)
2454
- })),
2455
- analyzeMetafile: (metafile, options) => new Promise((resolve, reject) => service.analyzeMetafile({
2456
- callName: "analyzeMetafile",
2457
- refs,
2458
- metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
2459
- options,
2460
- callback: (err, res) => err ? reject(err) : resolve(res)
2461
- }))
2462
- };
2463
- return longLivedService;
2464
- };
2465
- var runServiceSync = (callback) => {
2466
- let [command, args] = esbuildCommandAndArgs();
2467
- let stdin = /* @__PURE__ */ new Uint8Array();
2468
- let { readFromStdout, afterClose, service } = createChannel({
2469
- writeToStdin(bytes) {
2470
- if (stdin.length !== 0) throw new Error("Must run at most one command");
2471
- stdin = bytes;
2472
- },
2473
- isSync: true,
2474
- hasFS: true,
2475
- esbuild: node_exports
2476
- });
2477
- callback(service);
2478
- readFromStdout(child_process.execFileSync(command, args.concat(`--service=0.27.7`), {
2479
- cwd: defaultWD,
2480
- windowsHide: true,
2481
- input: stdin,
2482
- maxBuffer: +process.env.ESBUILD_MAX_BUFFER || 16777216
2483
- }));
2484
- afterClose(null);
2485
- };
2486
- var randomFileName = () => {
2487
- return path2.join(os2.tmpdir(), `esbuild-${crypto.randomBytes(32).toString("hex")}`);
2488
- };
2489
- var workerThreadService = null;
2490
- var startWorkerThreadService = (worker_threads2) => {
2491
- let { port1: mainPort, port2: workerPort } = new worker_threads2.MessageChannel();
2492
- let worker = new worker_threads2.Worker(__filename, {
2493
- workerData: {
2494
- workerPort,
2495
- defaultWD,
2496
- esbuildVersion: "0.27.7"
2497
- },
2498
- transferList: [workerPort],
2499
- execArgv: []
2500
- });
2501
- let nextID = 0;
2502
- let fakeBuildError = (text) => {
2503
- let error = /* @__PURE__ */ new Error(`Build failed with 1 error:
2504
- error: ${text}`);
2505
- error.errors = [{
2506
- id: "",
2507
- pluginName: "",
2508
- text,
2509
- location: null,
2510
- notes: [],
2511
- detail: void 0
2512
- }];
2513
- error.warnings = [];
2514
- return error;
2515
- };
2516
- let validateBuildSyncOptions = (options) => {
2517
- if (!options) return;
2518
- let plugins = options.plugins;
2519
- if (plugins && plugins.length > 0) throw fakeBuildError(`Cannot use plugins in synchronous API calls`);
2520
- };
2521
- let applyProperties = (object, properties) => {
2522
- for (let key in properties) object[key] = properties[key];
2523
- };
2524
- let runCallSync = (command, args) => {
2525
- let id = nextID++;
2526
- let sharedBuffer = new SharedArrayBuffer(8);
2527
- let sharedBufferView = new Int32Array(sharedBuffer);
2528
- let msg = {
2529
- sharedBuffer,
2530
- id,
2531
- command,
2532
- args
2533
- };
2534
- worker.postMessage(msg);
2535
- let status = Atomics.wait(sharedBufferView, 0, 0);
2536
- if (status !== "ok" && status !== "not-equal") throw new Error("Internal error: Atomics.wait() failed: " + status);
2537
- let { message: { id: id2, resolve, reject, properties } } = worker_threads2.receiveMessageOnPort(mainPort);
2538
- if (id !== id2) throw new Error(`Internal error: Expected id ${id} but got id ${id2}`);
2539
- if (reject) {
2540
- applyProperties(reject, properties);
2541
- throw reject;
2542
- }
2543
- return resolve;
2544
- };
2545
- worker.unref();
2546
- return {
2547
- buildSync(options) {
2548
- validateBuildSyncOptions(options);
2549
- return runCallSync("build", [options]);
2550
- },
2551
- transformSync(input, options) {
2552
- return runCallSync("transform", [input, options]);
2553
- },
2554
- formatMessagesSync(messages, options) {
2555
- return runCallSync("formatMessages", [messages, options]);
2556
- },
2557
- analyzeMetafileSync(metafile, options) {
2558
- return runCallSync("analyzeMetafile", [metafile, options]);
2559
- },
2560
- stop() {
2561
- worker.terminate();
2562
- workerThreadService = null;
2563
- }
2564
- };
2565
- };
2566
- var startSyncServiceWorker = () => {
2567
- let workerPort = worker_threads.workerData.workerPort;
2568
- let parentPort = worker_threads.parentPort;
2569
- let extractProperties = (object) => {
2570
- let properties = {};
2571
- if (object && typeof object === "object") for (let key in object) properties[key] = object[key];
2572
- return properties;
2573
- };
2574
- try {
2575
- let service = ensureServiceIsRunning();
2576
- defaultWD = worker_threads.workerData.defaultWD;
2577
- parentPort.on("message", (msg) => {
2578
- (async () => {
2579
- let { sharedBuffer, id, command, args } = msg;
2580
- let sharedBufferView = new Int32Array(sharedBuffer);
2581
- try {
2582
- switch (command) {
2583
- case "build":
2584
- workerPort.postMessage({
2585
- id,
2586
- resolve: await service.build(args[0])
2587
- });
2588
- break;
2589
- case "transform":
2590
- workerPort.postMessage({
2591
- id,
2592
- resolve: await service.transform(args[0], args[1])
2593
- });
2594
- break;
2595
- case "formatMessages":
2596
- workerPort.postMessage({
2597
- id,
2598
- resolve: await service.formatMessages(args[0], args[1])
2599
- });
2600
- break;
2601
- case "analyzeMetafile":
2602
- workerPort.postMessage({
2603
- id,
2604
- resolve: await service.analyzeMetafile(args[0], args[1])
2605
- });
2606
- break;
2607
- default: throw new Error(`Invalid command: ${command}`);
2608
- }
2609
- } catch (reject) {
2610
- workerPort.postMessage({
2611
- id,
2612
- reject,
2613
- properties: extractProperties(reject)
2614
- });
2615
- }
2616
- Atomics.add(sharedBufferView, 0, 1);
2617
- Atomics.notify(sharedBufferView, 0, Infinity);
2618
- })();
2619
- });
2620
- } catch (reject) {
2621
- parentPort.on("message", (msg) => {
2622
- let { sharedBuffer, id } = msg;
2623
- let sharedBufferView = new Int32Array(sharedBuffer);
2624
- workerPort.postMessage({
2625
- id,
2626
- reject,
2627
- properties: extractProperties(reject)
2628
- });
2629
- Atomics.add(sharedBufferView, 0, 1);
2630
- Atomics.notify(sharedBufferView, 0, Infinity);
2631
- });
2632
- }
2633
- };
2634
- if (isInternalWorkerThread) startSyncServiceWorker();
2635
- var node_default = node_exports;
2636
- 0 && (module.exports = {
2637
- analyzeMetafile,
2638
- analyzeMetafileSync,
2639
- build,
2640
- buildSync,
2641
- context,
2642
- formatMessages,
2643
- formatMessagesSync,
2644
- initialize,
2645
- stop,
2646
- transform,
2647
- transformSync,
2648
- version
2649
- });
2650
- })))();
390
+ //#endregion
391
+ //#region ../internal/src/build/bundle-options.ts
2651
392
  /** Select the runtime constants from one resolved Vite configuration. */
2652
393
  function resolveViteHubBundleDefines(config) {
2653
394
  const defines = {};
@@ -2672,9 +413,6 @@ function isDeepStrictEqual(left, right) {
2672
413
  }
2673
414
  const providerOutputCatalogRegistry$1 = globalThis;
2674
415
  const providerOutputCatalogByNitroValue = providerOutputCatalogRegistry$1.__vitehubProviderOutputCatalogsByNitroValue ??= /* @__PURE__ */ new WeakMap();
2675
- function cloneRecord(value) {
2676
- return value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
2677
- }
2678
416
  function cloneProviderRecord(value) {
2679
417
  if (!value || typeof value !== "object" || Array.isArray(value)) return {};
2680
418
  return Object.fromEntries(Object.entries(value).flatMap(([key, entry]) => typeof entry === "undefined" ? [] : [[key, cloneProviderValue(entry)]]));
@@ -2897,13 +635,6 @@ var ProviderOutputCatalog = class {
2897
635
  if (owner) this.#runtimeContributions.delete(owner);
2898
636
  else this.#runtimeContributions.clear();
2899
637
  }
2900
- resetRuntimeContribution(product, generation) {
2901
- if (!generation) {
2902
- this.#runtimeContributions.delete(product);
2903
- return;
2904
- }
2905
- this.#runtimeContributionsByGeneration.get(generation)?.delete(product);
2906
- }
2907
638
  createDeploymentGeneration() {
2908
639
  const generation = { valid: true };
2909
640
  this.#trackDeploymentGeneration(generation);
@@ -3074,7 +805,8 @@ function contributeCloudflareProviderOutput(catalog, contribution) {
3074
805
  const { owner, ...value } = contribution;
3075
806
  catalog.replaceCloudflareContribution(owner, value);
3076
807
  }
3077
- function deploymentPresetFromNitro(value) {
808
+ /** Maps a host name or a Nitro preset name, such as `cloudflare-module` or `node-server`, to its ViteHub host. */
809
+ function hostFromNitroPreset(value) {
3078
810
  const normalized = value?.trim().toLowerCase().replaceAll("_", "-");
3079
811
  if (!normalized) return;
3080
812
  if (normalized.startsWith("cloudflare")) return "cloudflare";
@@ -3087,7 +819,7 @@ function deploymentPresetFromNitro(value) {
3087
819
  //#region ../internal/src/hosting.ts
3088
820
  /**
3089
821
  * Returns the Nitro preset name that this build targets, as the developer wrote it.
3090
- * The order is `nitro.preset`, `hosting`, `NITRO_PRESET`, `SERVER_PRESET`, then `VITEHUB_HOSTING`.
822
+ * The order is `nitro.preset`, `hosting`, `NITRO_PRESET`, `SERVER_PRESET`, then `VITEHUB_HOST`.
3091
823
  * Empty values are skipped.
3092
824
  */
3093
825
  function resolveHostPreset(input = {}) {
@@ -3098,17 +830,17 @@ function resolveHostPreset(input = {}) {
3098
830
  input.hosting,
3099
831
  env.NITRO_PRESET,
3100
832
  env.SERVER_PRESET,
3101
- env.VITEHUB_HOSTING
833
+ env.VITEHUB_HOST
3102
834
  ]) if (typeof value === "string" && value.trim()) return value.trim();
3103
835
  }
3104
836
  /** Returns the host that this build targets: `cloudflare`, `deno`, `netlify`, `node`, or `vercel`. */
3105
837
  function resolveHost(input = {}) {
3106
- return deploymentPresetFromNitro(resolveHostPreset(input));
838
+ return hostFromNitroPreset(resolveHostPreset(input));
3107
839
  }
3108
- /** Narrows a preset or host name to the hosts that have a native provider: Cloudflare, Netlify, or Vercel. */
840
+ /** Narrows a ViteHub host or Nitro preset name to the hosts that have a native provider: Cloudflare, Netlify, or Vercel. */
3109
841
  function getHostingProvider(hosting) {
3110
- const preset = deploymentPresetFromNitro(hosting);
3111
- if (preset === "cloudflare" || preset === "netlify" || preset === "vercel") return preset;
842
+ const host = hostFromNitroPreset(hosting);
843
+ if (host === "cloudflare" || host === "netlify" || host === "vercel") return host;
3112
844
  }
3113
845
  //#endregion
3114
846
  //#region src/discovery.ts
@@ -3163,6 +895,14 @@ function resolveDirectGuard(name, scopes) {
3163
895
  if (scope.shadows.has(name)) return void 0;
3164
896
  }
3165
897
  }
898
+ /** The literal value of the `const` that `name` reads in this scope, or `undefined` for any other binding. */
899
+ function resolveConstant(name, scopes) {
900
+ for (let index = scopes.length - 1; index >= 0; index -= 1) {
901
+ const scope = scopes[index];
902
+ if (scope.constants.has(name)) return scope.constants.get(name);
903
+ if (scope.shadows.has(name)) return void 0;
904
+ }
905
+ }
3166
906
  function resolveNamespace(name, scopes) {
3167
907
  for (let index = scopes.length - 1; index >= 0; index -= 1) {
3168
908
  const scope = scopes[index];
@@ -3215,6 +955,19 @@ function addDynamicRateLimitBindingsFromStatements(statements, scope) {
3215
955
  if (declaration) addDynamicRateLimitBindings(declaration, scope);
3216
956
  }
3217
957
  }
958
+ function literalConstants(statements) {
959
+ const constants = /* @__PURE__ */ new Map();
960
+ for (const statement of statements) {
961
+ const declaration = variableDeclaration(statement);
962
+ if (declaration?.kind !== "const" || declaration.declare) continue;
963
+ for (const { id, init } of declaration.declarations) {
964
+ if (id.type !== "Identifier" || !init) continue;
965
+ const value = staticScalar(init, []);
966
+ if (value !== void 0) constants.set(id.name, value);
967
+ }
968
+ }
969
+ return constants;
970
+ }
3218
971
  function addBindingNames(pattern, names) {
3219
972
  if (pattern.type === "Identifier") {
3220
973
  names.add(pattern.name);
@@ -3355,7 +1108,14 @@ function staticString(expression) {
3355
1108
  if (value.type === "Literal" && typeof value.value === "string") return value.value;
3356
1109
  if (value.type === "TemplateLiteral" && value.expressions.length === 0) return value.quasis[0]?.value.cooked ?? value.quasis[0]?.value.raw;
3357
1110
  }
3358
- function staticPolicy(call, guard, file, source) {
1111
+ /** A string or number literal, or an identifier that reads a `const` with one. */
1112
+ function staticScalar(expression, scopes) {
1113
+ const value = unwrapStaticExpression(expression);
1114
+ if (value.type === "Literal" && typeof value.value === "number") return value.value;
1115
+ if (value.type === "Identifier") return resolveConstant(value.name, scopes);
1116
+ return staticString(value);
1117
+ }
1118
+ function staticPolicy(call, guard, scopes, file, source) {
3359
1119
  const policyArgument = call.arguments[2];
3360
1120
  const policyNode = policyArgument?.type === "SpreadElement" ? policyArgument : policyArgument && unwrapStaticExpression(policyArgument);
3361
1121
  if (!policyNode || policyNode.type !== "ObjectExpression") throw declarationError(file, source, call, `\`${guard}()\` requires a static options object as its third argument.`);
@@ -3363,11 +1123,10 @@ function staticPolicy(call, guard, file, source) {
3363
1123
  for (const property of policyNode.properties) {
3364
1124
  if (property.type !== "Property") throw declarationError(file, source, property, `\`${guard}()\` options cannot use object spreads.`);
3365
1125
  const name = staticPropertyName(property);
3366
- if (name === "key") continue;
1126
+ if (name === "key" || guard === "requireRateLimit" && (name === "message" || name === "code")) continue;
3367
1127
  if (!name || !rateLimitPolicyKeys.has(name)) throw declarationError(file, source, property, `\`${guard}()\` does not support the ${name ? `"${name}"` : "dynamic"} option.`);
3368
- const value = unwrapStaticExpression(property.value);
3369
- const literal = value.type === "Literal" && typeof value.value === "number" ? value.value : staticString(value);
3370
- if (literal === void 0) throw declarationError(file, source, property.value, `\`${guard}()\` policy option "${name}" must be a static literal.`);
1128
+ const literal = staticScalar(property.value, scopes);
1129
+ if (literal === void 0) throw declarationError(file, source, property.value, `\`${guard}()\` policy option "${name}" must be a static literal, or a \`const\` with a literal value in the same file.`);
3371
1130
  values.set(name, literal);
3372
1131
  }
3373
1132
  const policy = {
@@ -3392,12 +1151,14 @@ function extractRateLimitDeclarations(file, source) {
3392
1151
  const declarations = [];
3393
1152
  const scopes = [{
3394
1153
  ...bindings,
1154
+ constants: literalConstants(parsed.program.body),
3395
1155
  shadows: rootShadows
3396
1156
  }];
3397
1157
  const functionBodies = /* @__PURE__ */ new WeakSet();
3398
1158
  addDynamicRateLimitBindingsFromStatements(parsed.program.body, scopes[0]);
3399
- const enterScope = (shadows) => {
1159
+ const enterScope = (shadows, statements = []) => {
3400
1160
  scopes.push({
1161
+ constants: literalConstants(statements),
3401
1162
  direct: /* @__PURE__ */ new Map(),
3402
1163
  namespaces: /* @__PURE__ */ new Set(),
3403
1164
  shadows
@@ -3414,7 +1175,7 @@ function extractRateLimitDeclarations(file, source) {
3414
1175
  ArrowFunctionExpression: enterFunction,
3415
1176
  "ArrowFunctionExpression:exit": exitScope,
3416
1177
  BlockStatement(block) {
3417
- enterScope(functionBodies.has(block) ? scopedStatementBindings(block.body) : blockBindings(block));
1178
+ enterScope(functionBodies.has(block) ? scopedStatementBindings(block.body) : blockBindings(block), block.body);
3418
1179
  addDynamicRateLimitBindingsFromStatements(block.body, scopes.at(-1));
3419
1180
  },
3420
1181
  "BlockStatement:exit": exitScope,
@@ -3433,13 +1194,13 @@ function extractRateLimitDeclarations(file, source) {
3433
1194
  if (!guard) return;
3434
1195
  if (call.arguments.length !== 3) throw declarationError(file, source, call, `\`${guard}()\` requires an event, a stable ID, and a static options object.`);
3435
1196
  const idNode = call.arguments[1];
3436
- const staticId = idNode?.type === "SpreadElement" ? void 0 : idNode && staticString(idNode);
3437
- if (!staticId?.trim()) throw declarationError(file, source, idNode ?? call, `\`${guard}()\` requires a non-empty static string ID.`);
1197
+ const staticId = idNode?.type === "SpreadElement" || !idNode ? void 0 : staticScalar(idNode, scopes);
1198
+ if (typeof staticId !== "string" || !staticId.trim()) throw declarationError(file, source, idNode ?? call, `\`${guard}()\` requires a non-empty static string ID.`);
3438
1199
  const id = staticId.trim();
3439
1200
  const sourceLocation = location(source, call.start);
3440
1201
  declarations.push({
3441
1202
  name: id,
3442
- policy: staticPolicy(call, guard, file, source),
1203
+ policy: staticPolicy(call, guard, scopes, file, source),
3443
1204
  source: {
3444
1205
  file,
3445
1206
  ...sourceLocation
@@ -3463,30 +1224,43 @@ function extractRateLimitDeclarations(file, source) {
3463
1224
  },
3464
1225
  "ForStatement:exit": exitScope,
3465
1226
  SwitchStatement(node) {
3466
- enterScope(switchBindings(node));
1227
+ enterScope(switchBindings(node), node.cases.flatMap((switchCase) => switchCase.consequent));
3467
1228
  for (const switchCase of node.cases) addDynamicRateLimitBindingsFromStatements(switchCase.consequent, scopes.at(-1));
3468
1229
  },
3469
1230
  "SwitchStatement:exit": exitScope,
3470
1231
  StaticBlock(node) {
3471
- enterScope(scopedStatementBindings(node.body));
1232
+ enterScope(scopedStatementBindings(node.body), node.body);
3472
1233
  addDynamicRateLimitBindingsFromStatements(node.body, scopes.at(-1));
3473
1234
  },
3474
1235
  "StaticBlock:exit": exitScope,
3475
1236
  TSModuleBlock(node) {
3476
- enterScope(scopedStatementBindings(node.body));
1237
+ enterScope(scopedStatementBindings(node.body), node.body);
3477
1238
  addDynamicRateLimitBindingsFromStatements(node.body, scopes.at(-1));
3478
1239
  },
3479
1240
  "TSModuleBlock:exit": exitScope
3480
1241
  }).visit(parsed.program);
3481
1242
  return declarations;
3482
1243
  }
3483
- function discoverRateLimitCatalog(options) {
1244
+ function createRateLimitCatalogDiscovery() {
1245
+ const snapshots = /* @__PURE__ */ new Map();
1246
+ return (options) => discoverRateLimitCatalog(options, snapshots);
1247
+ }
1248
+ function discoverRateLimitCatalog(options, snapshots = /* @__PURE__ */ new Map()) {
3484
1249
  const declarations = /* @__PURE__ */ new Map();
3485
1250
  const sourceFiles = new Set(resolveDefinitionScanRoots(options.rootDir, options.scanDirs).flatMap((root) => listSourceFiles(root).filter((file) => isApplicationSource(root, file))));
1251
+ for (const file of snapshots.keys()) if (!sourceFiles.has(file)) snapshots.delete(file);
3486
1252
  const declarationFiles = /* @__PURE__ */ new Set();
3487
1253
  for (const file of sourceFiles) {
3488
- const extracted = extractRateLimitDeclarations(file, readFileSync(file, "utf8"));
3489
- if (extracted.length > 0) declarationFiles.add(file);
1254
+ const source = readFileSync(file, "utf8");
1255
+ const snapshot = snapshots.get(file);
1256
+ const extracted = snapshot?.source === source ? snapshot.declarations : extractRateLimitDeclarations(file, source);
1257
+ if (extracted.length > 0) {
1258
+ declarationFiles.add(file);
1259
+ snapshots.set(file, {
1260
+ source,
1261
+ declarations: extracted
1262
+ });
1263
+ } else snapshots.delete(file);
3490
1264
  for (const declaration of extracted) {
3491
1265
  const existing = declarations.get(declaration.name);
3492
1266
  if (existing && JSON.stringify(existing.policy) !== JSON.stringify(declaration.policy)) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0003({ message: [
@@ -3499,7 +1273,11 @@ function discoverRateLimitCatalog(options) {
3499
1273
  }
3500
1274
  return {
3501
1275
  declarationFiles,
3502
- declarations: [...declarations.values()].sort((left, right) => left.name.localeCompare(right.name))
1276
+ declarations: [...declarations.values()].sort((left, right) => left.name.localeCompare(right.name)).map((declaration) => ({
1277
+ ...declaration,
1278
+ policy: { ...declaration.policy },
1279
+ source: { ...declaration.source }
1280
+ }))
3503
1281
  };
3504
1282
  }
3505
1283
  function discoverRateLimitDeclarations(options) {
@@ -3546,20 +1324,25 @@ function inspectRateLimitDefinitions(options) {
3546
1324
  /** Console section that lists discovered Rate Limit Definitions. `vitehub inspect definitions` reads the same data. */
3547
1325
  const rateLimitConsoleSection = {
3548
1326
  description: "Inspect discovered Rate Limit policies and their source locations.",
3549
- icon: "i-lucide-gauge",
1327
+ icon: "i-vitehub-rate-limit",
3550
1328
  id: "rate-limits",
3551
1329
  label: "Rate Limits",
3552
1330
  read: inspectRateLimitDefinitions,
3553
1331
  view: {
3554
1332
  kind: "definition-catalog",
3555
- notice: "The page lists the policies. Enter a key to read its live counter or to reset it. Counters depend on the provider: a Cloudflare binding cannot be read or reset, and a memory counter exists only in this server process."
1333
+ notice: "The page lists the policies. Enter a key to read its live counter or to reset it. Counters depend on the provider: a Cloudflare binding cannot be read or reset, a memory counter exists only in this server process, and a kv counter is shared by every process that uses the KV store."
3556
1334
  }
3557
1335
  };
3558
1336
  //#endregion
3559
1337
  //#region src/internal/manifest.ts
3560
1338
  const rateLimitManifestPath = ".vitehub/rate-limit/manifest.json";
1339
+ const unusedResult = async () => [void 0, void 0];
3561
1340
  function resolveProviderCapabilities(provider) {
3562
- const driver = provider === "cloudflare" ? cloudflareRateLimitDriver({ binding: { limit: async () => ({ success: true }) } }) : memoryRateLimitDriver();
1341
+ const driver = provider === "cloudflare" ? cloudflareRateLimitDriver({ binding: { limit: async () => ({ success: true }) } }) : provider === "kv" ? kvRateLimitDriver({ storage: {
1342
+ delete: unusedResult,
1343
+ get: unusedResult,
1344
+ increment: async () => [void 0, 0]
1345
+ } }) : memoryRateLimitDriver();
3563
1346
  return createRateLimiter({
3564
1347
  driver,
3565
1348
  limit: 1,
@@ -3591,37 +1374,46 @@ function namespaceId(namespace, rateLimitId) {
3591
1374
  }
3592
1375
  return String(hash >>> 0 || 1);
3593
1376
  }
1377
+ function cloudflareSimpleLimit(declaration) {
1378
+ const policy = normalizeRateLimitPolicy(declaration.policy);
1379
+ if (policy.enforcement === "strict") throw rateLimitErrorDiagnostics.RATE_LIMIT_R0015({ message: `Rate Limit "${declaration.name}" requires strict enforcement, but Cloudflare's native Rate Limiting binding is best-effort.` });
1380
+ const period = policy.windowMs / 1e3;
1381
+ if (period !== 10 && period !== 60) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0016({ message: `Rate Limit "${declaration.name}" uses ${policy.window}, but Cloudflare Rate Limiting supports only 10s and 1m windows.` });
1382
+ return {
1383
+ limit: policy.limit,
1384
+ period
1385
+ };
1386
+ }
1387
+ /** Throws the build error for the first policy that a Cloudflare Rate Limiting binding cannot run. */
1388
+ function assertCloudflareRateLimitPolicies(declarations) {
1389
+ for (const declaration of declarations) cloudflareSimpleLimit(declaration);
1390
+ }
3594
1391
  function createCloudflareRateLimitBindings(declarations, namespace) {
3595
- return declarations.map((declaration) => {
3596
- const policy = normalizeRateLimitPolicy(declaration.policy);
3597
- if (policy.enforcement === "strict") throw rateLimitErrorDiagnostics.RATE_LIMIT_R0015({ message: `Rate Limit "${declaration.name}" requires strict enforcement, but Cloudflare's native Rate Limiting binding is best-effort.` });
3598
- const period = policy.windowMs / 1e3;
3599
- if (period !== 10 && period !== 60) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0016({ message: `Rate Limit "${declaration.name}" uses ${policy.window}, but Cloudflare Rate Limiting supports only 10s and 1m windows.` });
3600
- return {
3601
- name: getCloudflareRateLimitBindingName(declaration.name),
3602
- namespace_id: namespaceId(namespace, declaration.name),
3603
- simple: {
3604
- limit: policy.limit,
3605
- period
3606
- }
3607
- };
3608
- });
1392
+ return declarations.map((declaration) => ({
1393
+ name: getCloudflareRateLimitBindingName(declaration.name),
1394
+ namespace_id: namespaceId(namespace, declaration.name),
1395
+ simple: cloudflareSimpleLimit(declaration)
1396
+ }));
3609
1397
  }
3610
1398
  //#endregion
3611
1399
  //#region src/vite.ts
1400
+ const operationsModule = ownModule(import.meta.url, "operations");
1401
+ const runtimeModule = ownModule(import.meta.url, "runtime");
3612
1402
  const packageName = "@vite-hub/rate-limit";
3613
1403
  const pluginName = "@vite-hub/rate-limit/vite";
3614
1404
  const generatedNitroPlugin = ".vitehub/nitro/rate-limit/plugin.ts";
3615
1405
  const mergeNoExternal = createNoExternalAddition(packageName);
3616
- function cloneNitroConfig(value) {
3617
- return value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
1406
+ function effectiveDriver(driver, config) {
1407
+ if (driver !== "kv") return driver;
1408
+ const kv = (config.plugins?.find((plugin) => plugin.name === "@vite-hub/kv/vite"))?.api?.getConfig?.().kv;
1409
+ return resolveKVRateLimitDriver(kv ? kv.store.driver : void 0);
3618
1410
  }
3619
- function mergeNitroConfig(config, value, declarations, namespace, provider, nitroCloudflare, projectRoot) {
1411
+ function mergeNitroConfig(config, value, declarations, namespace, driver, nitroCloudflare, projectRoot) {
3620
1412
  const providerOutput = useProviderOutputCatalog(config);
3621
- const kit = createNitroServerKit(cloneNitroConfig(value));
1413
+ const kit = createNitroServerKit(cloneRecord(value));
3622
1414
  kit.addPlugin(resolve(projectRoot, generatedNitroPlugin), "start");
3623
1415
  const baseNitro = kit.config;
3624
- if (!nitroCloudflare || provider !== "cloudflare" || declarations.length === 0) {
1416
+ if (!nitroCloudflare || driver !== "cloudflare" || declarations.length === 0) {
3625
1417
  contributeCloudflareProviderOutput(providerOutput, { owner: "rate-limit" });
3626
1418
  return composeNitroCloudflareProviderOutput(providerOutput, baseNitro, value);
3627
1419
  }
@@ -3632,10 +1424,10 @@ function mergeNitroConfig(config, value, declarations, namespace, provider, nitr
3632
1424
  });
3633
1425
  return composeNitroCloudflareProviderOutput(providerOutput, baseNitro, value);
3634
1426
  }
3635
- function renderRuntimeInstaller(runtimeConfig, importBase) {
3636
- return [
1427
+ function renderRuntimeInstaller(runtimeConfig, kvImport) {
1428
+ if (runtimeConfig.driver !== "kv") return [
3637
1429
  "import { definePlugin } from 'nitro'",
3638
- `import { setRateLimitRuntimeConfig } from ${JSON.stringify(`${importBase}/runtime`)}`,
1430
+ `import { setRateLimitRuntimeConfig } from ${JSON.stringify(runtimeModule)}`,
3639
1431
  "",
3640
1432
  `const config = ${JSON.stringify(runtimeConfig)}`,
3641
1433
  "export default definePlugin(() => {",
@@ -3643,27 +1435,51 @@ function renderRuntimeInstaller(runtimeConfig, importBase) {
3643
1435
  "})",
3644
1436
  ""
3645
1437
  ].join("\n");
1438
+ return [
1439
+ "import { definePlugin } from 'nitro'",
1440
+ `import { resolveRateLimitDriver, setRateLimitRuntimeConfig } from ${JSON.stringify(runtimeModule)}`,
1441
+ `import { getKVStoreDriver, kv } from ${JSON.stringify(kvImport)}`,
1442
+ "",
1443
+ `const config = ${JSON.stringify(runtimeConfig)}`,
1444
+ "export default definePlugin(() => {",
1445
+ " setRateLimitRuntimeConfig(config, { driver: () => getKVStoreDriver(), storage: kv, store: 'default' })",
1446
+ " void resolveRateLimitDriver().catch(error => console.error('[vitehub] Rate Limit could not read the KV store. Each request tries again.', error))",
1447
+ "})",
1448
+ ""
1449
+ ].join("\n");
3646
1450
  }
3647
1451
  function resolveRateLimitNamespace(configured) {
3648
1452
  return configured?.trim() || void 0;
3649
1453
  }
3650
- function resolveProvider(options, command, nitro, deferUnknown = false) {
3651
- if (options.provider && options.provider !== "auto") return options.provider;
1454
+ function resolveDriver(options, command, nitro, deferUnknown = false) {
1455
+ if (options.driver === void 0 && Object.hasOwn(options, "provider")) {
1456
+ const provider = options.provider;
1457
+ throw rateLimitErrorDiagnostics.RATE_LIMIT_RENAMED_PROVIDER_KEY({ value: JSON.stringify(provider) ?? String(provider) });
1458
+ }
1459
+ if (options.driver && options.driver !== "auto") return options.driver;
3652
1460
  if (command === "serve") return "memory";
3653
1461
  const hosting = getHostingProvider(resolveHost({ nitro }));
3654
1462
  if (hosting === "cloudflare") return "cloudflare";
3655
1463
  if (hosting) throw rateLimitErrorDiagnostics.RATE_LIMIT_B0002({ message: `[vitehub] Rate Limit has no native ${hosting} driver. Configure a custom Rate Limiter instead of falling back to per-instance memory.` });
3656
1464
  if (deferUnknown) return;
3657
- throw rateLimitErrorDiagnostics.RATE_LIMIT_B0003({ message: "[vitehub] Rate Limit provider cannot be inferred for a production build. Set rateLimit.provider to \"cloudflare\" or explicitly choose \"memory\" for a known single-process deployment." });
1465
+ throw rateLimitErrorDiagnostics.RATE_LIMIT_B0003({ message: "[vitehub] Rate Limit driver cannot be inferred for a production build. Set rateLimit.driver to \"cloudflare\" or explicitly choose \"memory\" for a known single-process deployment." });
1466
+ }
1467
+ function buildTargetsCloudflare(config, configured, nitro) {
1468
+ if (getDeploymentHost(config) === "cloudflare") return true;
1469
+ if (configured.driver === "cloudflare") return true;
1470
+ return (configured.driver ?? "auto") === "auto" && getHostingProvider(resolveHost({ nitro })) === "cloudflare";
3658
1471
  }
3659
1472
  function hubRateLimit(options = {}) {
3660
- const importBase = options.importBase ?? packageName;
1473
+ const kvImport = options.kvImport ?? "@vite-hub/kv";
3661
1474
  let rateLimit = options;
3662
1475
  let declarations = [];
3663
1476
  let cloudflareBindings = false;
3664
- let provider = "memory";
1477
+ let checkCloudflarePolicies = false;
1478
+ let driver = "memory";
3665
1479
  let projectRoot;
3666
1480
  let resolved;
1481
+ let warnedAboutMemory = false;
1482
+ const discoverRateLimitCatalog = createRateLimitCatalogDiscovery();
3667
1483
  const collectDeclarations = () => {
3668
1484
  if (!projectRoot) return;
3669
1485
  declarations = discoverRateLimitCatalog({
@@ -3674,17 +1490,48 @@ function hubRateLimit(options = {}) {
3674
1490
  const refreshDeclarations = async () => {
3675
1491
  if (!projectRoot || !resolved) return;
3676
1492
  collectDeclarations();
3677
- await writeRateLimitManifest(projectRoot, declarations, provider);
1493
+ if (checkCloudflarePolicies) assertCloudflareRateLimitPolicies(declarations);
1494
+ await writeRateLimitManifest(projectRoot, declarations, effectiveDriver(driver, resolved));
1495
+ };
1496
+ const assertBuildDriver = () => {
1497
+ if (!resolved || resolved.command !== "build") return;
1498
+ if (effectiveDriver(driver, resolved) !== "memory") return;
1499
+ if (driver === "kv" && !rateLimit.memoryFallback) {
1500
+ const kv = resolved.plugins.find((plugin) => plugin.name === "@vite-hub/kv/vite")?.api?.getConfig?.().kv;
1501
+ const store = kv ? `the default KV store uses ${kv.store.driver}, which has no shared atomic increment` : "the app has no KV store";
1502
+ throw rateLimitErrorDiagnostics.RATE_LIMIT_KV_STORE_UNSUPPORTED({ message: `[vitehub] rateLimit.driver is "kv", but ${store}. Each server process would count in its own memory.` });
1503
+ }
1504
+ const strict = declarations.find((declaration) => normalizeRateLimitPolicy(declaration.policy).enforcement === "strict");
1505
+ if (strict) throw rateLimitErrorDiagnostics.RATE_LIMIT_MEMORY_STRICT_UNSUPPORTED({ message: `[vitehub] Rate Limit "${strict.name}" requires strict enforcement, but this build counts in the memory of each server process, so several instances each allow the full limit.` });
1506
+ };
1507
+ const warnAboutMemory = () => {
1508
+ if (!resolved || warnedAboutMemory || resolved.command !== "build" || declarations.length === 0 || effectiveDriver(driver, resolved) !== "memory") return;
1509
+ reportViteHubHint(resolved, rateLimitErrorDiagnostics.RATE_LIMIT_MEMORY_PER_PROCESS());
1510
+ warnedAboutMemory = true;
3678
1511
  };
3679
1512
  const inspectionRoot = () => projectRoot ?? resolveViteHubProjectRoot(process.cwd(), { projectRoot: rateLimit.projectRoot });
3680
1513
  return {
1514
+ api: { validateNitroBuild(config) {
1515
+ resolved = config;
1516
+ rateLimit = getResolvedFeatureOptions(config, "rateLimit") ?? rateLimit;
1517
+ projectRoot = resolveViteHubProjectRoot(config.root, { projectRoot: rateLimit.projectRoot });
1518
+ driver = resolveDriver(rateLimit, config.command, config.nitro);
1519
+ collectDeclarations();
1520
+ assertBuildDriver();
1521
+ } },
3681
1522
  name: pluginName,
3682
1523
  enforce: "pre",
3683
1524
  vitehub: {
1525
+ durability: () => [{
1526
+ export: "rateLimitDurability",
1527
+ input: { driver },
1528
+ module: durabilityModuleFile(import.meta.url),
1529
+ primitive: "rate-limit"
1530
+ }],
3684
1531
  operations: [{
3685
1532
  export: "rateLimitOperations",
3686
1533
  load: async () => (await (import.meta.url.endsWith(".ts") ? import("./operations.js") : import("./operations.js"))).rateLimitOperations,
3687
- module: "@vite-hub/rate-limit/operations"
1534
+ module: operationsModule
3688
1535
  }],
3689
1536
  cli: async () => {
3690
1537
  const { createRateLimitCliContributor } = await import(
@@ -3713,28 +1560,47 @@ function hubRateLimit(options = {}) {
3713
1560
  config: {
3714
1561
  order: "pre",
3715
1562
  handler(config, env) {
3716
- rateLimit = config.rateLimit ?? rateLimit;
1563
+ rateLimit = getResolvedFeatureOptions(config, "rateLimit") ?? rateLimit;
3717
1564
  const configuredNitro = config.nitro;
3718
1565
  projectRoot = resolveViteHubProjectRoot(config.root || process.cwd(), { projectRoot: rateLimit.projectRoot });
3719
- const configuredProvider = resolveProvider(rateLimit, env?.command ?? "serve", configuredNitro, true);
3720
- if (configuredProvider) provider = configuredProvider;
1566
+ const configuredDriver = resolveDriver(rateLimit, env?.command ?? "serve", configuredNitro, true);
1567
+ if (configuredDriver) driver = configuredDriver;
3721
1568
  collectDeclarations();
3722
- config.nitro = mergeNitroConfig(config, configuredNitro, declarations, resolveRateLimitNamespace(rateLimit.namespace), configuredProvider, resolveHost({ nitro: configuredNitro }) === "cloudflare", projectRoot);
3723
- return installStandaloneOperationRpc(config, env?.command ?? "build", "@vite-hub/rate-limit/operations");
1569
+ config.nitro = mergeNitroConfig(config, configuredNitro, declarations, resolveRateLimitNamespace(rateLimit.namespace), configuredDriver, resolveHost({ nitro: configuredNitro }) === "cloudflare", projectRoot);
1570
+ return installStandaloneOperationRpc(config, env?.command ?? "build", operationsModule);
3724
1571
  }
3725
1572
  },
3726
1573
  async configResolved(config) {
1574
+ startViteHubHints(config);
3727
1575
  resolved = config;
3728
- rateLimit = config.rateLimit ?? rateLimit;
1576
+ warnedAboutMemory = false;
1577
+ rateLimit = getResolvedFeatureOptions(config, "rateLimit") ?? rateLimit;
3729
1578
  projectRoot = resolveViteHubProjectRoot(config.root, { projectRoot: rateLimit.projectRoot });
3730
1579
  const configuredNitro = config.nitro;
3731
1580
  const nitroCloudflare = resolveHost({ nitro: configuredNitro }) === "cloudflare";
3732
- provider = resolveProvider(rateLimit, config.command, configuredNitro);
3733
- cloudflareBindings = nitroCloudflare && provider === "cloudflare";
1581
+ driver = resolveDriver(rateLimit, config.command, configuredNitro);
1582
+ cloudflareBindings = nitroCloudflare && driver === "cloudflare";
1583
+ checkCloudflarePolicies = config.command === "serve" && buildTargetsCloudflare(config, rateLimit, configuredNitro);
3734
1584
  collectDeclarations();
3735
- config.nitro = mergeNitroConfig(config, configuredNitro, declarations, resolveRateLimitNamespace(rateLimit.namespace), provider, nitroCloudflare, projectRoot);
3736
- await writeRateLimitManifest(projectRoot, declarations, provider);
3737
- await writeFileIfChanged(resolve(projectRoot, generatedNitroPlugin), renderRuntimeInstaller({ provider }, importBase));
1585
+ if (checkCloudflarePolicies) assertCloudflareRateLimitPolicies(declarations);
1586
+ config.nitro = mergeNitroConfig(config, configuredNitro, declarations, resolveRateLimitNamespace(rateLimit.namespace), driver, nitroCloudflare, projectRoot);
1587
+ await writeRateLimitManifest(projectRoot, declarations, effectiveDriver(driver, config));
1588
+ const pluginFile = resolve(projectRoot, generatedNitroPlugin);
1589
+ const memoryFallback = driver === "kv" && (rateLimit.memoryFallback === true || config.command === "serve");
1590
+ await writeFileIfChanged(pluginFile, renderRuntimeInstaller(memoryFallback ? {
1591
+ memoryFallback,
1592
+ driver
1593
+ } : { driver }, kvImport));
1594
+ if (driver !== "kv") {
1595
+ assertBuildDriver();
1596
+ warnAboutMemory();
1597
+ }
1598
+ },
1599
+ async buildStart() {
1600
+ if (driver !== "kv") return;
1601
+ await refreshDeclarations();
1602
+ assertBuildDriver();
1603
+ warnAboutMemory();
3738
1604
  },
3739
1605
  configureServer(server) {
3740
1606
  publishStandaloneOperationServer(server);
@@ -3746,10 +1612,14 @@ function hubRateLimit(options = {}) {
3746
1612
  async handleHotUpdate(context) {
3747
1613
  if (!/\.(?:c|m)?[jt]sx?$/i.test(context.file)) return;
3748
1614
  resolved = context.server.config;
3749
- await refreshDeclarations();
1615
+ try {
1616
+ await refreshDeclarations();
1617
+ } catch (error) {
1618
+ context.server.config.logger.error(String(error), { error: error instanceof Error ? error : void 0 });
1619
+ }
3750
1620
  },
3751
1621
  buildEnd(error) {
3752
- if (error || !cloudflareBindings || !resolved || shouldSkipViteProviderBuild(resolved.command, getViteMode())) return;
1622
+ if (error || !cloudflareBindings || !resolved || shouldSkipViteProviderBuild(resolved.command)) return;
3753
1623
  const configuredDeclarations = declarations;
3754
1624
  collectDeclarations();
3755
1625
  if (JSON.stringify(declarations) !== JSON.stringify(configuredDeclarations)) throw rateLimitErrorDiagnostics.RATE_LIMIT_B0004({ message: "[vitehub] Nitro Cloudflare Rate Limit declarations changed after config resolution. Generate Rate Limit source files before Vite config resolves." });