@vite-hub/sandbox 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 (54) hide show
  1. package/README.md +118 -53
  2. package/dist/abortable-CR01hzfi.js +57 -0
  3. package/dist/cloudflare-Cog_r2Me.js +910 -0
  4. package/dist/cloudflare-env-lookup-DzI6Xv1Y.js +16 -0
  5. package/dist/cloudflare-failure-CFQhalfh.js +50 -0
  6. package/dist/container-CqfD8yuE.js +868 -0
  7. package/dist/{crabbox-BFCdf41h.js → crabbox-sbV3Zjuo.js} +10 -6
  8. package/dist/error-diagnostics-5QT_BjbQ.js +354 -0
  9. package/dist/error-diagnostics-BJtLRL9w.js +536 -0
  10. package/dist/{file-listing-DECFTdSl.js → file-listing-CHtRrfo1.js} +1 -1
  11. package/dist/{file-lock-CxyVl4Cv.js → file-lock-D0-XPogS.js} +3 -2
  12. package/dist/{index-CXej1Bt0.d.ts → index-DsoQAUb7.d.ts} +94 -19
  13. package/dist/index.d.ts +2 -2
  14. package/dist/index.js +15 -10
  15. package/dist/internal/cloudflare.d.ts +173 -1
  16. package/dist/internal/cloudflare.js +4 -12
  17. package/dist/internal/host-toolchain.d.ts +1 -1
  18. package/dist/internal/host-toolchain.js +6 -7
  19. package/dist/internal/vercel.d.ts +1 -1
  20. package/dist/internal/vercel.js +3 -11
  21. package/dist/invariant-DolT9EEx.js +22 -0
  22. package/dist/module-types-B0LQ5H2S.js +7 -0
  23. package/dist/module-types-DCeJbS9Z.d.ts +110 -0
  24. package/dist/process-sweep-CMaujWE5.js +33 -0
  25. package/dist/provider-resolution-C6AQzuFG.js +133 -0
  26. package/dist/{remote-1Jz2oUMK.js → remote-70ZVZZlq.js} +32 -14
  27. package/dist/runtime-type-Deo4qzxN.js +9 -0
  28. package/dist/{session-DD0S1PDC.js → session-e0lyzjJ3.js} +2 -1
  29. package/dist/size-7AkVwGZb.js +118 -0
  30. package/dist/ssh.d.ts +8 -0
  31. package/dist/ssh.js +107 -40
  32. package/dist/task/index.d.ts +19 -17
  33. package/dist/task/index.js +92 -201
  34. package/dist/task/runtime/provider-loader.d.ts +7 -9
  35. package/dist/task/runtime/provider-loader.js +2 -5
  36. package/dist/task/runtime/providers/cloudflare.d.ts +5 -19
  37. package/dist/task/runtime/providers/cloudflare.js +7 -6
  38. package/dist/task/runtime/providers/vercel.d.ts +3 -3
  39. package/dist/task/runtime/providers/vercel.js +35 -4
  40. package/dist/task/runtime/state.d.ts +4 -1
  41. package/dist/task/runtime/state.js +11 -2
  42. package/dist/task/vite.d.ts +143 -17
  43. package/dist/task/vite.js +723 -400
  44. package/dist/{toolchain-BUVXtQ2m.js → toolchain-BIVGMRty.js} +12 -11
  45. package/dist/{trusted-host-DNMJ-Oig.js → trusted-host-kxkpaQcs.js} +21 -179
  46. package/dist/{vercel-Jtxa9TJx.js → vercel-BGGrNpza.js} +107 -34
  47. package/package.json +15 -12
  48. package/dist/cloudflare-DO0h3Ncf.js +0 -281
  49. package/dist/cloudflare-env-BBJaBbuQ.js +0 -39
  50. package/dist/error-diagnostics-BSysPv-D.js +0 -166
  51. package/dist/error-diagnostics-dGQqfgLt.js +0 -99
  52. package/dist/module-types-BfyRBaiP.js +0 -7
  53. package/dist/module-types-Cis4hrF1.d.ts +0 -95
  54. package/dist/runtime-type-DrmrW5m5.js +0 -42
package/dist/task/vite.js CHANGED
@@ -1,19 +1,42 @@
1
- import { t as sandboxTaskErrorDiagnostics } from "../error-diagnostics-dGQqfgLt.js";
2
- import { t as getSandboxTaskFeatureProvider } from "../module-types-BfyRBaiP.js";
3
- import { builtinModules, createRequire } from "node:module";
1
+ import { n as invariantError, t as invariant } from "../invariant-DolT9EEx.js";
2
+ import { t as sandboxTaskErrorDiagnostics } from "../error-diagnostics-5QT_BjbQ.js";
3
+ import { t as getSandboxTaskFeatureDriver } from "../module-types-B0LQ5H2S.js";
4
+ import { a as resolveVercelSandboxTaskVcpus, i as resolveCloudflareSandboxTaskInstanceType, n as describeCloudflareInstanceType, r as readSandboxTaskSize, t as assertCloudflareInstanceTypeFits } from "../size-7AkVwGZb.js";
5
+ import { builtinModules, createRequire, isBuiltin } from "node:module";
4
6
  import { createHash, randomUUID } from "node:crypto";
5
7
  import { copyFile, glob, lstat, mkdir, mkdtemp, open, readFile, readdir, readlink, realpath, rename, rm, stat, symlink, writeFile } from "node:fs/promises";
6
- import { basename, dirname, matchesGlob, parse, relative, resolve } from "node:path";
8
+ import { basename, dirname, parse, relative, resolve } from "node:path";
7
9
  import { defineDiagnostics } from "nostics";
10
+ import { setTimeout } from "node:timers/promises";
8
11
  import { hostname, tmpdir } from "node:os";
9
12
  import { basename as basename$1, dirname as dirname$1, isAbsolute as isAbsolute$1, join as join$1, normalize, relative as relative$1, resolve as resolve$1, sep as sep$1 } from "pathe";
10
13
  import { fileURLToPath, pathToFileURL } from "node:url";
11
- import { existsSync, readdirSync, realpathSync, statSync } from "node:fs";
14
+ import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
12
15
  import { findDynamicImports, resolvePathSync } from "mlly";
13
16
  import { resolveModule } from "local-pkg";
14
17
  import { dirname as dirname$2, join as join$2, normalize as normalize$1 } from "node:path/posix";
15
- import { parse as parse$1 } from "yaml";
16
- import { setTimeout } from "node:timers/promises";
18
+ import picomatch from "picomatch";
19
+ //#region ../internal/src/build/paths.ts
20
+ function generatedDirSegments(productName) {
21
+ return [".vitehub", productName];
22
+ }
23
+ function ensureGeneratedDir(rootDir, productName) {
24
+ return resolve$1(rootDir, ...generatedDirSegments(productName));
25
+ }
26
+ function createImportPath(fromFile, targetFile) {
27
+ const fromDir = realpathIfExists(dirname$1(fromFile));
28
+ const target = realpathIfExists(targetFile);
29
+ const importPath = relative$1(fromDir, target);
30
+ return importPath.startsWith(".") ? importPath : `./${importPath}`;
31
+ }
32
+ function realpathIfExists(path) {
33
+ try {
34
+ return realpathSync.native(path);
35
+ } catch {
36
+ return resolve$1(path);
37
+ }
38
+ }
39
+ //#endregion
17
40
  //#region ../internal/src/build/vite.ts
18
41
  const projectRootDirectoryMarkers = [
19
42
  ["server", "agents"],
@@ -43,6 +66,17 @@ function isServerEnvironment(name, config) {
43
66
  return name === "ssr" || config.consumer === "server";
44
67
  }
45
68
  const VITEHUB_PROJECT_ROOT = "__vitehubProjectRoot";
69
+ /**
70
+ * Feature options that `vitehub()` and `vite-hub/nuxt` resolve for owner plugins during config hooks, such as the Queue
71
+ * provider of the host. Apps set features only in `vitehub()`, so this key is private.
72
+ */
73
+ const VITEHUB_FEATURES = "__vitehubFeatures";
74
+ /** The options that ViteHub resolved for a feature on this Vite config. The owner plugin names their type. */
75
+ function getResolvedFeatureOptions(config, feature) {
76
+ const features = Reflect.get(config, VITEHUB_FEATURES);
77
+ if (!features || typeof features !== "object") return void 0;
78
+ return Reflect.get(features, feature);
79
+ }
46
80
  function includesNitroVitePlugin(value) {
47
81
  if (Array.isArray(value)) return value.some(includesNitroVitePlugin);
48
82
  if (!value || typeof value !== "object") return false;
@@ -101,10 +135,16 @@ function hasProjectRootFileMarker(root, markers) {
101
135
  //#region ../internal/src/error-diagnostics.ts
102
136
  const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
103
137
  const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
104
- docsBase: () => "https://vitehub.dev/docs/reference/diagnostics",
138
+ docsBase: "https://vitehub.dev/docs/development/diagnostics",
105
139
  codes: {
106
- INTERNAL_R0012: dynamicError,
107
- INTERNAL_R0013: dynamicError,
140
+ INTERNAL_R0012: {
141
+ ...dynamicError,
142
+ fix: "Check the URL, the headers, and the credentials of the HTTP request. `error.status` holds the status that the server sent."
143
+ },
144
+ INTERNAL_R0013: {
145
+ ...dynamicError,
146
+ fix: "Check that the provider token can manage the resource in the path that the message names. `error.kind` and `error.codes` hold the provider failure."
147
+ },
108
148
  INTERNAL_R0014: {
109
149
  why: ({ path }) => `Cannot read Provision State from "${path}".`,
110
150
  fix: "Check file access and restore valid JSON while preserving existing resource IDs."
@@ -122,60 +162,101 @@ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
122
162
  why: ({ message }) => message === void 0 ? "" : String(message)
123
163
  },
124
164
  INTERNAL_R0024: {
125
- fix: "Start the dev server with `vite dev`, or pass `--url <origin>` of a deployed app with credentials in VITEHUB_CONSOLE_AUTHORIZATION, VITEHUB_CONSOLE_COOKIE, or CF_ACCESS_CLIENT_ID and CF_ACCESS_CLIENT_SECRET.",
165
+ fix: "Start the dev server with `vite dev`, or pass `--url <origin>` of a deployed app and set VITEHUB_CONSOLE_PRIVATE_KEY_<NAME> to a private key whose public key the app has in VITEHUB_CONSOLE_KEY_<NAME>.",
126
166
  why: ({ message }) => message === void 0 ? "" : String(message)
127
167
  },
128
168
  INTERNAL_R0023: {
129
169
  fix: "Ask for access to the section of this operation.",
130
170
  why: ({ message }) => message === void 0 ? "" : String(message)
131
171
  },
132
- INTERNAL_B0001: dynamicError,
133
- INTERNAL_B0002: dynamicError,
134
- INTERNAL_B0003: dynamicError,
135
- INTERNAL_B0004: dynamicError,
136
- INTERNAL_B0005: dynamicError,
137
- INTERNAL_B0006: dynamicError,
138
- INTERNAL_B0007: dynamicError,
139
- INTERNAL_B0008: dynamicError,
140
- INTERNAL_B0009: dynamicError,
141
- INTERNAL_B0010: dynamicError,
142
- INTERNAL_B0011: dynamicError,
143
- INTERNAL_B0012: dynamicError,
144
- INTERNAL_B0013: dynamicError,
145
- INTERNAL_B0014: dynamicError,
146
- INTERNAL_B0015: dynamicError,
147
- INTERNAL_B0016: dynamicError,
148
- INTERNAL_B0017: dynamicError,
149
- INTERNAL_B0018: dynamicError,
150
- INTERNAL_B0019: dynamicError,
151
- INTERNAL_B0020: dynamicError,
152
- INTERNAL_B0021: dynamicError,
153
- INTERNAL_B0022: dynamicError,
154
- INTERNAL_B0023: dynamicError,
155
- INTERNAL_B0024: dynamicError,
156
- INTERNAL_B0025: dynamicError,
157
- INTERNAL_B0026: dynamicError,
158
- INTERNAL_B0027: dynamicError,
159
- INTERNAL_B0028: dynamicError,
160
- INTERNAL_B0029: dynamicError,
161
- INTERNAL_B0030: dynamicError,
162
- INTERNAL_B0031: dynamicError,
163
- INTERNAL_B0032: dynamicError,
164
- INTERNAL_B0033: dynamicError,
165
- INTERNAL_B0034: dynamicError,
166
- INTERNAL_B0035: dynamicError,
167
- INTERNAL_B0036: dynamicError,
168
- INTERNAL_B0037: dynamicError,
169
- INTERNAL_B0038: dynamicError,
170
- INTERNAL_B0039: dynamicError,
171
- INTERNAL_B0040: dynamicError,
172
- INTERNAL_B0041: dynamicError,
173
- INTERNAL_B0042: dynamicError,
174
- INTERNAL_B0043: dynamicError,
175
- INTERNAL_B0044: dynamicError,
176
- INTERNAL_B0045: dynamicError,
177
- INTERNAL_B0046: dynamicError,
178
- INTERNAL_B0047: dynamicError,
172
+ INTERNAL_B0001: {
173
+ ...dynamicError,
174
+ fix: "Give the resource that the message names another name or binding in the `vitehub()` options of its feature, so that two different Cloudflare resources do not share one name."
175
+ },
176
+ INTERNAL_B0015: {
177
+ ...dynamicError,
178
+ fix: "Install one version of the package that the message names, for example with `pnpm dedupe` or an `overrides` entry in `package.json`."
179
+ },
180
+ INTERNAL_B0016: {
181
+ ...dynamicError,
182
+ fix: "Correct the field that the message names in the `package.json` of a runtime dependency of the app, such as a workspace package, or run `pnpm install` again to restore an installed package."
183
+ },
184
+ INTERNAL_B0017: {
185
+ ...dynamicError,
186
+ fix: "Correct the field that the message names in the `package.json` of a runtime dependency of the app, such as a workspace package, or run `pnpm install` again to restore an installed package."
187
+ },
188
+ INTERNAL_B0018: {
189
+ ...dynamicError,
190
+ fix: "Correct the field that the message names in the `package.json` of a runtime dependency of the app, such as a workspace package, or run `pnpm install` again to restore an installed package."
191
+ },
192
+ INTERNAL_B0019: {
193
+ ...dynamicError,
194
+ fix: "Correct the field that the message names in the `package.json` of a runtime dependency of the app, such as a workspace package, or run `pnpm install` again to restore an installed package."
195
+ },
196
+ INTERNAL_B0020: {
197
+ ...dynamicError,
198
+ fix: "Correct the field that the message names in the `package.json` of a runtime dependency of the app, such as a workspace package, or run `pnpm install` again to restore an installed package."
199
+ },
200
+ INTERNAL_B0021: {
201
+ ...dynamicError,
202
+ fix: "Install the package that the message names in the app, for example with `pnpm add <name>`, then build again."
203
+ },
204
+ INTERNAL_B0022: {
205
+ ...dynamicError,
206
+ fix: "Install one version of the package that the message names, for example with `pnpm dedupe` or an `overrides` entry in `package.json`."
207
+ },
208
+ INTERNAL_B0025: {
209
+ ...dynamicError,
210
+ fix: "Replace the `new URL(\"./...\", import.meta.url)` in the project-root `main.ts`, or in a Schedule file of `server/schedules/` and the files it imports, with a static `import` of that file."
211
+ },
212
+ INTERNAL_B0026: {
213
+ ...dynamicError,
214
+ fix: "Replace the computed `import()` in the project-root `main.ts`, or in a Schedule file of `server/schedules/` and the files it imports, with a static `import` or with `import(\"<literal path>\")`."
215
+ },
216
+ INTERNAL_B0027: {
217
+ ...dynamicError,
218
+ fix: "Replace the computed `require()` in the project-root `main.ts`, or in a Schedule file of `server/schedules/` and the files it imports, with a static `import`."
219
+ },
220
+ INTERNAL_B0028: {
221
+ ...dynamicError,
222
+ fix: "Wait for the other build of this app to finish, or stop the process that the message names, then build again."
223
+ },
224
+ INTERNAL_B0029: {
225
+ ...dynamicError,
226
+ fix: "Stop the other builds that write the same Deno output folder, delete the `.vitehub-lock` folder next to that output folder, such as `.output.vitehub-lock`, then build again."
227
+ },
228
+ INTERNAL_B0031: {
229
+ ...dynamicError,
230
+ fix: "Import `./schedule/deno-cron.mjs` at the top level of the project-root `main.ts`, for example with `await import(new URL(\"./schedule/deno-cron.mjs\", import.meta.url).href)` outside any condition."
231
+ },
232
+ INTERNAL_B0032: {
233
+ ...dynamicError,
234
+ fix: "Import `./server/index.mjs` at the top level of the project-root `main.ts`, for example with `await import(new URL(\"./server/index.mjs\", import.meta.url).href)` outside any condition."
235
+ },
236
+ INTERNAL_B0035: {
237
+ ...dynamicError,
238
+ fix: "Delete the provider output folder that holds the file that the message names, such as `dist/<app>` for Cloudflare, and build again."
239
+ },
240
+ INTERNAL_B0039: {
241
+ ...dynamicError,
242
+ fix: "Fix the build error that ViteHub showed before this one. ViteHub stops writing the provider output when another part of the build fails."
243
+ },
244
+ INTERNAL_B0040: {
245
+ ...dynamicError,
246
+ fix: "Remove the custom Nitro `output.serverDir`, so that the Nitro preset of the host writes the server entry that the message names."
247
+ },
248
+ INTERNAL_B0043: {
249
+ ...dynamicError,
250
+ fix: "Delete the build output folder, such as `.output` or `.vercel/output`, and build again."
251
+ },
252
+ INTERNAL_B0046: {
253
+ ...dynamicError,
254
+ fix: "Install the package that the message names in the app, for example with `pnpm add <name>`, then build again."
255
+ },
256
+ INTERNAL_B0047: {
257
+ ...dynamicError,
258
+ fix: "Correct the `package.json` file that the message names so that it holds one JSON object, or run `pnpm install` again to restore an installed package."
259
+ },
179
260
  INTERNAL_B0048: {
180
261
  fix: "Rename one of the two operations. A name is `<section>.<verb>` and is unique in the app.",
181
262
  why: ({ message }) => message === void 0 ? "" : String(message)
@@ -188,6 +269,14 @@ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
188
269
  fix: "Rename one of the two operations, or set `mcp: false` on it. MCP tool names replace every character outside letters, digits, `_`, and `-` with `_`.",
189
270
  why: ({ message }) => message === void 0 ? "" : String(message)
190
271
  },
272
+ INTERNAL_B0051: {
273
+ why: ({ field, generated, name, path, project, scope }) => `The Cloudflare ${path} entry "${name}"${scope} is written by ViteHub and by the project's Wrangler config with a different ${field}: ${generated} and ${project}.`,
274
+ fix: "Remove the entry from the project's Wrangler config, since ViteHub writes it, or give one of them another name."
275
+ },
276
+ INTERNAL_B0052: {
277
+ why: ({ column, section }) => `The column "${column}" of the Console section "${section}" needs both \`format: "switch"\` and a \`switch\` operation name such as "skills.set".`,
278
+ fix: "Give a switch column `format: \"switch\"` and `switch: { operation, input }` with a registered operation name, or remove both."
279
+ },
191
280
  INTERNAL_R0025: {
192
281
  fix: "Start `vite dev` in the project that you run the command from, or pass `--url` of that server.",
193
282
  why: ({ message }) => message === void 0 ? "" : String(message)
@@ -196,22 +285,118 @@ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
196
285
  why: "The server parsed a destructive operation that the CLI did not confirm.",
197
286
  fix: "Review the operation, then run it again with --yes to confirm the change."
198
287
  },
199
- INTERNAL_C0001: dynamicError,
200
- INTERNAL_C0002: dynamicError,
201
- INTERNAL_R0001: dynamicError,
202
- INTERNAL_R0002: dynamicError,
203
- INTERNAL_R0003: dynamicError,
204
- INTERNAL_R0004: dynamicError,
205
- INTERNAL_R0005: dynamicError,
206
- INTERNAL_R0006: dynamicError,
207
- INTERNAL_R0007: dynamicError,
208
- INTERNAL_R0008: dynamicError,
209
- INTERNAL_R0009: dynamicError,
210
- INTERNAL_R0010: dynamicError,
211
- INTERNAL_R0011: dynamicError
288
+ INTERNAL_C0001: {
289
+ ...dynamicError,
290
+ fix: "Rename or remove one of the two files that the message lists. ViteHub takes the Definition name from the file path."
291
+ },
292
+ INTERNAL_C0002: {
293
+ ...dynamicError,
294
+ fix: "Rename or remove one of the two files that the message lists. ViteHub takes the Definition name from the file path."
295
+ },
296
+ INTERNAL_R0001: {
297
+ ...dynamicError,
298
+ fix: "Set `host` in `vitehub()`, or in the `vitehub` options of `nuxt.config.ts`, to `cloudflare`, `deno`, `netlify`, `node`, or `vercel`. Or remove `host` so that ViteHub finds the host from the environment."
299
+ },
300
+ INTERNAL_R0002: {
301
+ ...dynamicError,
302
+ fix: "Stop using the feature that the message names, or set `host` in `vitehub()` to a host that provides it. For Blob, you can also set `blob: { driver: \"s3\" }` with a remote store."
303
+ },
304
+ INTERNAL_R0004: {
305
+ ...dynamicError,
306
+ fix: "Set a larger `maxResponseBytes` on the HTTP request, such as the `fetch()` Source options, or ask the server for a smaller response."
307
+ },
308
+ INTERNAL_R0005: {
309
+ ...dynamicError,
310
+ fix: "Set `method` of the HTTP request to `GET`, `HEAD`, or `POST`."
311
+ },
312
+ INTERNAL_R0006: {
313
+ ...dynamicError,
314
+ fix: "Set `timeout` of the HTTP request to a number of milliseconds from 1 to 2147483647, or remove it to use the default."
315
+ },
316
+ INTERNAL_R0007: {
317
+ ...dynamicError,
318
+ fix: "Set `maxResponseBytes` of the HTTP request to a positive integer no greater than the limit that the message names, or remove it to use the default."
319
+ },
320
+ INTERNAL_R0008: {
321
+ ...dynamicError,
322
+ fix: "Make the value that the message names match its schema: the input, query, or body that you send, or the response schema that you declare for the request."
323
+ },
324
+ INTERNAL_R0009: {
325
+ ...dynamicError,
326
+ fix: "Use a Standard Schema whose `validate()` returns `{ value }` or `{ issues }` for the value that the message names."
327
+ },
328
+ INTERNAL_R0010: {
329
+ ...dynamicError,
330
+ fix: "Run the command again. If the error stays, check the Cloudflare API status, because Cloudflare sent a response that ViteHub cannot read."
331
+ },
332
+ INTERNAL_R0011: {
333
+ ...dynamicError,
334
+ fix: "Pass an h3 app, an object with a `fetch(request)` method, or a fetch function as `app`."
335
+ },
336
+ INTERNAL_CONSOLE_KEY_NAME_INVALID: {
337
+ why: ({ name }) => `[vitehub] The Console key name ${JSON.stringify(name)} must be 1 to 64 of A-Z, 0-9, and _.`,
338
+ fix: "Name the Console key with 1 to 64 characters from A-Z, 0-9, and _, such as `CI`. The app reads its public key from `VITEHUB_CONSOLE_KEY_<NAME>`."
339
+ },
340
+ INTERNAL_CONSOLE_PRIVATE_KEY_INVALID: {
341
+ why: "[vitehub] A Console private key is the 32-byte Ed25519 seed as base64url (43 characters). `vitehub secret console-key` makes one.",
342
+ fix: "Run `vitehub secret console-key` and use the 43-character private key that it prints, without spaces or quotes."
343
+ },
344
+ INTERNAL_CONSOLE_PRIVATE_KEY_VARIABLES_MULTIPLE: {
345
+ why: ({ prefix, variables }) => `[vitehub] Set one ${prefix}<NAME> variable. This environment has ${variables}.`,
346
+ fix: "Keep one `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>` variable in the environment of the command, and unset the others that the message names."
347
+ },
348
+ INTERNAL_CONSOLE_PRIVATE_KEY_VARIABLE_INVALID: {
349
+ why: ({ variable }) => `[vitehub] ${variable} must be the 43-character private key that \`vitehub secret console-key\` prints, and its name 1 to 64 of A-Z, 0-9, and _.`,
350
+ fix: "Set the variable that the message names to the private key that `vitehub secret console-key` prints, and name it `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>` with A-Z, 0-9, and _ in `<NAME>`."
351
+ },
352
+ INTERNAL_FORGE_NOT_INSTALLED: {
353
+ why: ({ feature }) => `${feature} needs @vite-hub/forge, and the app did not install it.`,
354
+ fix: "Install Forge in your app with `pnpm add @vite-hub/forge`, then build again."
355
+ },
356
+ INTERNAL_MCP_ARGUMENTS_INVALID: {
357
+ why: ({ detail }) => detail,
358
+ fix: "Pass the prompt or resource the arguments that `prompts/list` or `resources/templates/list` describes for it."
359
+ },
360
+ INTERNAL_MCP_METHOD_FAILED: {
361
+ why: ({ name }) => `${name} failed on the server.`,
362
+ fix: "Read the server log for the error of the MCP prompt or resource that the message names, and fix its handler."
363
+ },
364
+ INTERNAL_MCP_RESOURCE_NOT_FOUND: {
365
+ why: ({ uri }) => `Resource not found: ${uri}. Call resources/list or resources/templates/list for the resources of this server.`,
366
+ fix: "Call `resources/list` or `resources/templates/list`, and read a URI that one of them returns."
367
+ },
368
+ INTERNAL_PRESET_OPTION_UNKNOWN: {
369
+ why: ({ key, label }) => `[vitehub] Unknown ${label} option "${key}".`,
370
+ fix: "Remove the option that the message names from the preset options, or correct its spelling to an option that the preset declares."
371
+ },
372
+ INTERNAL_PRESET_TUPLE_INVALID: {
373
+ why: ({ owner }) => `[vitehub] ${owner} extends tuple requires [preset, options] with an options object.`,
374
+ fix: "Set `extends` to a preset, or to a two-item tuple `[preset, { ...options }]` whose second item is a plain object."
375
+ },
376
+ INTERNAL_SECRET_PURPOSE_MISSING: {
377
+ why: "[vitehub] A derived secret requires a purpose.",
378
+ fix: "Pass a non-empty purpose to `deriveSecret()`, such as `deriveSecret(\"my-module:session\")`."
379
+ },
380
+ INTERNAL_SECRET_TOO_SHORT: {
381
+ why: ({ minimum }) => `[vitehub] VITEHUB_SECRET must be at least ${minimum} characters. Generate one with \`openssl rand -base64 32\`.`,
382
+ fix: "Set `VITEHUB_SECRET` to the output of `openssl rand -base64 32`, which has 44 characters."
383
+ },
384
+ INTERNAL_SQLITE_ARGUMENT_INVALID: {
385
+ why: ({ value }) => value === "undefined" ? "undefined cannot be passed as argument to the database" : "Only finite numbers (not Infinity or NaN) can be passed as arguments",
386
+ fix: "Pass query arguments as finite numbers, strings, booleans, bigints, dates, byte arrays, or null. Replace undefined with null, and check numbers with `Number.isFinite()` before the query."
387
+ },
388
+ INTERNAL_SQLITE_INTEGER_UNSAFE: {
389
+ why: "Received integer which cannot be safely represented as a JavaScript number",
390
+ fix: "Create the client with `intMode: \"bigint\"` or `intMode: \"string\"`, or read the column with `CAST(column AS TEXT)` in the query."
391
+ },
392
+ INTERNAL_VALIBOT_JSON_SCHEMA_TARGET_UNSUPPORTED: {
393
+ why: ({ target }) => `[vitehub] Valibot cannot convert a schema to the ${target} JSON Schema target.`,
394
+ fix: "Ask for the `draft-07`, `draft-2020-12`, or `openapi-3.0` JSON Schema target, or pass one of them as `withValibotJsonSchema(schema, { target })`."
395
+ }
212
396
  }
213
397
  });
214
- function deploymentPresetFromNitro(value) {
398
+ /** Maps a host name or a Nitro preset name, such as `cloudflare-module` or `node-server`, to its ViteHub host. */
399
+ function hostFromNitroPreset(value) {
215
400
  const normalized = value?.trim().toLowerCase().replaceAll("_", "-");
216
401
  if (!normalized) return;
217
402
  if (normalized.startsWith("cloudflare")) return "cloudflare";
@@ -224,7 +409,7 @@ function deploymentPresetFromNitro(value) {
224
409
  //#region ../internal/src/hosting.ts
225
410
  /**
226
411
  * Returns the Nitro preset name that this build targets, as the developer wrote it.
227
- * The order is `nitro.preset`, `hosting`, `NITRO_PRESET`, `SERVER_PRESET`, then `VITEHUB_HOSTING`.
412
+ * The order is `nitro.preset`, `hosting`, `NITRO_PRESET`, `SERVER_PRESET`, then `VITEHUB_HOST`.
228
413
  * Empty values are skipped.
229
414
  */
230
415
  function resolveHostPreset(input = {}) {
@@ -235,7 +420,7 @@ function resolveHostPreset(input = {}) {
235
420
  input.hosting,
236
421
  env.NITRO_PRESET,
237
422
  env.SERVER_PRESET,
238
- env.VITEHUB_HOSTING
423
+ env.VITEHUB_HOST
239
424
  ]) if (typeof value === "string" && value.trim()) return value.trim();
240
425
  }
241
426
  function normalizeHosting(hosting) {
@@ -243,10 +428,10 @@ function normalizeHosting(hosting) {
243
428
  if (normalized === "cloudflare") return "cloudflare-module";
244
429
  return normalized;
245
430
  }
246
- /** Narrows a preset or host name to the hosts that have a native provider: Cloudflare, Netlify, or Vercel. */
431
+ /** Narrows a ViteHub host or Nitro preset name to the hosts that have a native provider: Cloudflare, Netlify, or Vercel. */
247
432
  function getHostingProvider(hosting) {
248
- const preset = deploymentPresetFromNitro(hosting);
249
- if (preset === "cloudflare" || preset === "netlify" || preset === "vercel") return preset;
433
+ const host = hostFromNitroPreset(hosting);
434
+ if (host === "cloudflare" || host === "netlify" || host === "vercel") return host;
250
435
  }
251
436
  function getSupportedHostingProvider(hosting, supportedProviders) {
252
437
  const provider = getHostingProvider(hosting);
@@ -255,41 +440,21 @@ function getSupportedHostingProvider(hosting, supportedProviders) {
255
440
  }
256
441
  //#endregion
257
442
  //#region ../internal/src/object.ts
258
- function isPlainObject$1(value) {
259
- if (value === null || Object(value) !== value || Array.isArray(value)) return false;
260
- return typeof value === "object";
443
+ /** A non-null object that is not an array. Functions do not pass. */
444
+ function isRecord(value) {
445
+ return typeof value === "object" && value !== null && !Array.isArray(value);
261
446
  }
262
447
  function isPlainRecord(value) {
263
- if (!isPlainObject$1(value)) return false;
448
+ if (!isRecord(value)) return false;
264
449
  const prototype = Object.getPrototypeOf(value);
265
450
  if (prototype === null) return true;
266
451
  return Object.getPrototypeOf(prototype) === null && Object.hasOwn(prototype, "constructor") && prototype.constructor?.name === "Object";
267
452
  }
268
453
  //#endregion
269
- //#region ../internal/src/build/paths.ts
270
- function generatedDirSegments(productName) {
271
- return [".vitehub", productName];
272
- }
273
- function ensureGeneratedDir(rootDir, productName) {
274
- return resolve$1(rootDir, ...generatedDirSegments(productName));
275
- }
276
- function createImportPath(fromFile, targetFile) {
277
- const fromDir = realpathIfExists(dirname$1(fromFile));
278
- const target = realpathIfExists(targetFile);
279
- const importPath = relative$1(fromDir, target);
280
- return importPath.startsWith(".") ? importPath : `./${importPath}`;
281
- }
282
- function realpathIfExists(path) {
283
- try {
284
- return realpathSync.native(path);
285
- } catch {
286
- return resolve$1(path);
287
- }
288
- }
289
- //#endregion
290
454
  //#region ../internal/src/definition-catalog.ts
291
455
  const sourceFilePattern = /\.(?:c|m)?[jt]sx?$/i;
292
456
  const declarationFilePattern = /\.d\.(?:c|m)?[jt]sx?$/i;
457
+ const testFilePattern = /\.(?:test|spec)\.(?:c|m)?[jt]sx?$/i;
293
458
  const ignoredDirs = /* @__PURE__ */ new Set([
294
459
  "node_modules",
295
460
  "dist",
@@ -339,8 +504,12 @@ function listMatchingFiles(root, predicate, options = {}) {
339
504
  }
340
505
  return files.sort();
341
506
  }
507
+ /** A module that a Definitions folder can hold: JavaScript or TypeScript, and not a declaration, test, or spec file. */
508
+ function isDefinitionSourceFile(name) {
509
+ return sourceFilePattern.test(name) && !declarationFilePattern.test(name) && !testFilePattern.test(name);
510
+ }
342
511
  function listSourceFiles(root, options = {}) {
343
- return listMatchingFiles(root, (name) => sourceFilePattern.test(name) && !declarationFilePattern.test(name), options);
512
+ return listMatchingFiles(root, isDefinitionSourceFile, options);
344
513
  }
345
514
  function normalizePathDefinitionName(rootDir, file) {
346
515
  return relative$1(rootDir, file).replace(sourceFilePattern, "").replace(/\/index$/i, "");
@@ -408,12 +577,23 @@ function scanDirectoryDefinitions(feature, source) {
408
577
  function discoverDefinitions(feature, sources) {
409
578
  return mergeDefinitions(feature, ...sources.map((source) => source.kind === "suffix" ? scanSuffixDefinitions(feature, source) : scanDirectoryDefinitions(feature, source)));
410
579
  }
580
+ /** `writeFileIfChangedSync` for async callers. */
411
581
  async function writeFileIfChanged(file, contents) {
412
582
  if (await readFile(file, "utf8").catch(() => void 0) === contents) return;
413
583
  await mkdir(resolve$1(file, ".."), { recursive: true });
414
584
  await writeFile(file, contents, "utf8");
415
585
  }
416
586
  //#endregion
587
+ //#region ../internal/src/nitro-kit.ts
588
+ /** Add one module id to a Nitro or Rollup `external` option, in each form that option takes. */
589
+ function mergeNitroExternal(value, addition) {
590
+ if (typeof value === "undefined") return [addition];
591
+ if (Array.isArray(value)) return value.includes(addition) ? [...value] : [...value, addition];
592
+ if (typeof value === "string" || value instanceof RegExp) return [value, addition];
593
+ if (typeof value === "function") return (source, importer, isResolved) => source === addition || Boolean(value(source, importer, isResolved));
594
+ return value;
595
+ }
596
+ //#endregion
417
597
  //#region src/task/internal/shared/cloudflare-wrangler.ts
418
598
  function compareNumericStrings(left, right) {
419
599
  return left.localeCompare(right, void 0, { numeric: true });
@@ -422,7 +602,7 @@ function isSameKVNamespace(left, right) {
422
602
  return left.binding === right.binding && left.id === right.id && left.preview_id === right.preview_id && left.experimental_remote === right.experimental_remote;
423
603
  }
424
604
  function isSameContainer(left, right) {
425
- return left.class_name === right.class_name && left.image === right.image && left.image_build_context === right.image_build_context && left.instance_type === right.instance_type && left.max_instances === right.max_instances && left.name === right.name;
605
+ return left.class_name === right.class_name && left.image === right.image && left.image_build_context === right.image_build_context && JSON.stringify(left.instance_type) === JSON.stringify(right.instance_type) && left.max_instances === right.max_instances && left.name === right.name;
426
606
  }
427
607
  function isSameDurableObjectBinding(left, right) {
428
608
  return left.name === right.name && left.class_name === right.class_name && left.script_name === right.script_name && left.environment === right.environment;
@@ -518,38 +698,48 @@ function finalizeCloudflareWranglerConfig(target) {
518
698
  const defaultCloudflareSandboxBinding = "SANDBOX";
519
699
  const defaultCloudflareSandboxClassName = "Sandbox";
520
700
  const defaultCloudflareSandboxMaxInstances = 12;
521
- const require$1 = createRequire(import.meta.url);
701
+ const cloudflareSandboxNodeImage = "24-bookworm-slim";
702
+ const cloudflareSandboxPackages = "ca-certificates curl file git jq procps tini unzip wget zip";
703
+ const durableObjectModule = "@vite-hub/sandbox/_internal/cloudflare";
704
+ function resolveModule$1(id) {
705
+ return resolvePathSync(id, {
706
+ conditions: [
707
+ "workerd",
708
+ "worker",
709
+ "import",
710
+ "default"
711
+ ],
712
+ url: import.meta.url
713
+ });
714
+ }
522
715
  function resolveCloudflareSandboxEntrypoint() {
523
716
  try {
524
- return require$1.resolve("@cloudflare/sandbox");
717
+ return resolveModule$1("@cloudflare/sandbox");
525
718
  } catch {
526
719
  throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0003({ message: "[vitehub] The Cloudflare Sandbox provider requires @cloudflare/sandbox. Install a supported version before building." });
527
720
  }
528
721
  }
529
722
  function resolveCloudflareSandboxVersion() {
530
723
  const entry = resolveCloudflareSandboxEntrypoint();
531
- const pkg = require$1(join$1(entry, "..", "..", "package.json"));
724
+ const pkg = JSON.parse(readFileSync(join$1(entry, "..", "..", "package.json"), "utf8"));
532
725
  if (typeof pkg?.version !== "string") throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0004({ message: "[vitehub] Could not resolve the installed @cloudflare/sandbox version." });
533
726
  return pkg.version;
534
727
  }
535
728
  function resolveCloudflareSandboxEntrypointOptions(options = {}) {
536
- if (options.className === "ContainerProxy") throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0005({ message: "[vitehub] Cloudflare Sandbox className \"ContainerProxy\" is reserved by @cloudflare/sandbox. Configure a different className." });
537
729
  return {
538
730
  binding: options.binding || "SANDBOX",
539
731
  className: options.className || "Sandbox",
540
732
  migrationTag: options.migrationTag || "v1",
541
- name: options.name || void 0
733
+ name: options.name || void 0,
734
+ cpu: options.cpu,
735
+ memory: options.memory,
736
+ maxInstances: options.maxInstances
542
737
  };
543
738
  }
544
- function mergeRollupExternal(value, addition) {
545
- if (typeof value === "undefined") return [addition];
546
- if (Array.isArray(value)) return value.includes(addition) ? [...value] : [...value, addition];
547
- if (typeof value === "string" || value instanceof RegExp) return [value, addition];
548
- if (typeof value === "function") return (source, importer, isResolved) => source === addition || Boolean(value(source, importer, isResolved));
549
- return value;
550
- }
551
739
  function configureCloudflareSandbox(target, options = {}) {
552
- const { binding, className, migrationTag, name } = resolveCloudflareSandboxEntrypointOptions(options);
740
+ const { binding, className, migrationTag, name, ...size } = resolveCloudflareSandboxEntrypointOptions(options);
741
+ const instanceType = resolveCloudflareSandboxTaskInstanceType(size);
742
+ const { maxInstances } = readSandboxTaskSize(size);
553
743
  if (typeof target.cloudflare?.wrangler?.exports !== "undefined") throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0006({ message: "[vitehub] Cloudflare Sandbox cannot compose legacy migrations with an existing Wrangler exports configuration. Remove exports or configure the Sandbox Durable Object explicitly." });
554
744
  const existingMigrations = target.cloudflare?.wrangler?.migrations;
555
745
  if (!existingMigrations?.some((entry) => entry.new_sqlite_classes?.includes(className)) && existingMigrations?.some((entry) => entry.tag === migrationTag)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0007({ message: `[vitehub] Cloudflare migration tag ${JSON.stringify(migrationTag)} is already in use. Configure a unique sandbox migrationTag.` });
@@ -565,14 +755,21 @@ function configureCloudflareSandbox(target, options = {}) {
565
755
  if (!containers.some((entry) => entry.class_name === className)) containers.push({
566
756
  class_name: className,
567
757
  image,
568
- instance_type: "lite",
569
- max_instances: defaultCloudflareSandboxMaxInstances,
758
+ instance_type: instanceType,
759
+ max_instances: maxInstances ?? defaultCloudflareSandboxMaxInstances,
570
760
  ...name ? { name } : {}
571
761
  });
572
762
  else {
573
763
  const container = containers.find((entry) => entry.class_name === className);
574
764
  container.image ??= image;
575
- if (typeof container.max_instances !== "number") container.max_instances = defaultCloudflareSandboxMaxInstances;
765
+ if (container.instance_type === void 0) container.instance_type = instanceType;
766
+ else assertCloudflareInstanceTypeFits(container.instance_type, size, className);
767
+ if (typeof container.max_instances !== "number") container.max_instances = maxInstances ?? defaultCloudflareSandboxMaxInstances;
768
+ else if (maxInstances !== void 0 && maxInstances !== container.max_instances) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_CLOUDFLARE_MAX_INSTANCES_CONFLICT({
769
+ className,
770
+ configured: container.max_instances,
771
+ requested: maxInstances
772
+ });
576
773
  if (name) container.name ??= name;
577
774
  }
578
775
  const bindings = target.cloudflare.wrangler.durable_objects.bindings;
@@ -586,9 +783,15 @@ function configureCloudflareSandbox(target, options = {}) {
586
783
  new_sqlite_classes: [className]
587
784
  });
588
785
  }
786
+ /** The Worker entrypoint that sends the allowed outbound requests of a Sandbox Container on unchanged. */
787
+ function cloudflareSandboxOutboundEntrypoint(className) {
788
+ return `${className}Outbound`;
789
+ }
589
790
  function createCloudflareSandboxRollupPlugin(options = {}) {
590
791
  const { className } = resolveCloudflareSandboxEntrypointOptions(options);
792
+ const outboundEntrypoint = cloudflareSandboxOutboundEntrypoint(className);
591
793
  const cloudflareSandboxEntrypoint = resolveCloudflareSandboxEntrypoint();
794
+ const durableObjectEntrypoint = resolveModule$1(durableObjectModule);
592
795
  const moduleId = "virtual:vitehub-sandbox-task-cloudflare-exports";
593
796
  const resolvedModuleId = "\0virtual:vitehub-sandbox-task-cloudflare-exports";
594
797
  return {
@@ -600,24 +803,33 @@ function createCloudflareSandboxRollupPlugin(options = {}) {
600
803
  fileName: "sandbox-task-cloudflare-exports.mjs"
601
804
  });
602
805
  },
603
- resolveId(id) {
604
- if (id === moduleId) return resolvedModuleId;
605
- if (id === "@cloudflare/sandbox") return cloudflareSandboxEntrypoint;
806
+ resolveId: {
807
+ filter: { id: /^(?:virtual:vitehub-sandbox-task-cloudflare-exports|@cloudflare\/sandbox|@vite-hub\/sandbox\/_internal\/cloudflare)$/ },
808
+ handler(id) {
809
+ if (id === moduleId) return resolvedModuleId;
810
+ if (id === "@cloudflare/sandbox") return cloudflareSandboxEntrypoint;
811
+ if (id === durableObjectModule) return durableObjectEntrypoint;
812
+ }
606
813
  },
607
- load(id) {
608
- if (id === resolvedModuleId) return [
609
- `import { Sandbox as CloudflareSandbox } from '@cloudflare/sandbox'`,
610
- `export { ContainerProxy } from '@cloudflare/sandbox'`,
611
- ``,
612
- `export class ${className} extends CloudflareSandbox {}`,
613
- ``
614
- ].join("\n");
814
+ load: {
815
+ filter: { id: /^\0virtual:vitehub-sandbox-task-cloudflare-exports$/ },
816
+ handler(id) {
817
+ if (id === resolvedModuleId) return [
818
+ `import { DurableObject, WorkerEntrypoint } from 'cloudflare:workers'`,
819
+ `import { Files, SandboxFileError } from '@cloudflare/sandbox'`,
820
+ `import { createCloudflareSandboxDurableObject, createCloudflareSandboxOutbound } from '${durableObjectModule}'`,
821
+ ``,
822
+ `export class ${outboundEntrypoint} extends createCloudflareSandboxOutbound({ WorkerEntrypoint }) {}`,
823
+ `export class ${className} extends createCloudflareSandboxDurableObject({ DurableObject, Files, outboundEntrypoint: '${outboundEntrypoint}', SandboxFileError }) {}`,
824
+ ``
825
+ ].join("\n");
826
+ }
615
827
  },
616
828
  renderChunk(code, chunk) {
617
829
  if (!chunk.isEntry) return null;
618
830
  const exportedNames = new Set(chunk.exports);
619
- const missingExports = [className, "ContainerProxy"].filter((name) => !exportedNames.has(name));
620
- if (!missingExports.length) return null;
831
+ if (exportedNames.has(className)) return null;
832
+ const missingExports = [className, outboundEntrypoint].filter((name) => !exportedNames.has(name));
621
833
  const exportsPath = relative$1(dirname$1(chunk.fileName), "sandbox-task-cloudflare-exports.mjs").replace(/\\/g, "/");
622
834
  const importPath = exportsPath.startsWith(".") ? exportsPath : `./${exportsPath}`;
623
835
  return {
@@ -640,8 +852,15 @@ function installCloudflareSandboxEntrypoint(target, options = {}) {
640
852
  async function writeCloudflareSandboxDockerfile(serverDir) {
641
853
  const dockerfilePath = join$1(serverDir, "Dockerfile");
642
854
  await writeFileIfChanged(dockerfilePath, [
643
- `FROM docker.io/cloudflare/sandbox:${resolveCloudflareSandboxVersion()}`,
644
- "RUN npm install --global corepack@0.34.5 && corepack enable pnpm yarn",
855
+ `FROM docker.io/cloudflare/sandbox:${resolveCloudflareSandboxVersion()} AS sandbox-tools`,
856
+ "",
857
+ `FROM docker.io/library/node:${cloudflareSandboxNodeImage}`,
858
+ `RUN apt-get update && apt-get install -y --no-install-recommends ${cloudflareSandboxPackages} && rm -rf /var/lib/apt/lists/*`,
859
+ "COPY --from=sandbox-tools /usr/local/bin/sandbox-shim /usr/local/bin/sandbox-shim",
860
+ "RUN npm install --global corepack@0.34.5 && corepack enable pnpm yarn && mkdir -p /workspace",
861
+ "WORKDIR /workspace",
862
+ "ENTRYPOINT [\"/usr/bin/tini\", \"--\"]",
863
+ "CMD [\"sleep\", \"infinity\"]",
645
864
  ""
646
865
  ].join("\n"));
647
866
  return dockerfilePath;
@@ -665,97 +884,12 @@ async function configureCloudflareSandboxNitro(targetValue, rootDir, options = {
665
884
  wrangler.compatibility_flags = Array.isArray(wrangler.compatibility_flags) ? [...wrangler.compatibility_flags] : [];
666
885
  if (!wrangler.compatibility_flags.includes("nodejs_compat")) wrangler.compatibility_flags.push("nodejs_compat");
667
886
  target.rollupConfig ||= {};
668
- target.rollupConfig.external = mergeRollupExternal(target.rollupConfig.external, "cloudflare:workers");
887
+ target.rollupConfig.external = mergeNitroExternal(target.rollupConfig.external, "cloudflare:workers");
669
888
  installCloudflareSandboxEntrypoint(target, resolvedOptions);
670
889
  if (finalizeWrangler) finalizeCloudflareWranglerConfig(target);
671
890
  return target;
672
891
  }
673
892
  //#endregion
674
- //#region src/task/internal/shared/discovered-definition/bundler.ts
675
- const builtinModuleSet$2 = /* @__PURE__ */ new Set([...builtinModules, ...builtinModules.map((name) => `node:${name}`)]);
676
- function resolveDefinitionLoader(options) {
677
- let loader = options.loader;
678
- if (!loader) {
679
- const f = options.filename;
680
- if (f.endsWith(".tsx")) loader = "tsx";
681
- else if (f.endsWith(".jsx")) loader = "jsx";
682
- else if (f.endsWith(".js") || f.endsWith(".mjs") || f.endsWith(".cjs")) loader = "js";
683
- else loader = "ts";
684
- }
685
- return loader;
686
- }
687
- function isJsxDefinitionLoader(options) {
688
- const loader = resolveDefinitionLoader(options);
689
- return loader === "tsx" || loader === "jsx";
690
- }
691
- function usesRuntimeModuleResolution(contents) {
692
- return findDynamicImports(contents).some((imported) => !imported.expression.startsWith("\"")) || /\bimport\.meta\.resolve\s*\(/.test(contents) || /\bcreateRequire\b/.test(contents);
693
- }
694
- async function bundleDiscoveredDefinitionModule(options) {
695
- const { build } = await import("esbuild");
696
- const output = (await build({
697
- alias: options.alias,
698
- stdin: {
699
- contents: options.source,
700
- loader: resolveDefinitionLoader(options),
701
- resolveDir: dirname$1(options.filename),
702
- sourcefile: options.filename
703
- },
704
- bundle: true,
705
- write: false,
706
- format: "esm",
707
- platform: "node",
708
- target: "es2022",
709
- logLevel: "silent",
710
- jsx: isJsxDefinitionLoader(options) ? "automatic" : void 0,
711
- jsxImportSource: isJsxDefinitionLoader(options) ? "react" : void 0,
712
- packages: options.packages === "external" ? "external" : void 0,
713
- external: [...builtinModuleSet$2, ...options.external || []],
714
- plugins: options.plugins
715
- })).outputFiles?.[0]?.text;
716
- if (!output) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0047({ message: `[vitehub] Failed to bundle discovered definition "${options.filename}".` });
717
- return output;
718
- }
719
- async function bundleDiscoveredDefinitionModuleGraph(options) {
720
- const outdir = resolve$1(dirname$1(options.filename), ".vitehub-discovered-definition");
721
- const { build } = await import("esbuild");
722
- const result = await build({
723
- alias: options.alias,
724
- stdin: {
725
- contents: options.source,
726
- loader: resolveDefinitionLoader(options),
727
- resolveDir: dirname$1(options.filename),
728
- sourcefile: options.filename
729
- },
730
- bundle: true,
731
- splitting: true,
732
- entryNames: "definition",
733
- chunkNames: "chunks/[name]-[hash]",
734
- outdir,
735
- write: false,
736
- format: "esm",
737
- platform: "node",
738
- target: "es2022",
739
- metafile: true,
740
- logLevel: "silent",
741
- jsx: isJsxDefinitionLoader(options) ? "automatic" : void 0,
742
- jsxImportSource: isJsxDefinitionLoader(options) ? "react" : void 0,
743
- packages: options.packages === "external" ? "external" : void 0,
744
- external: [...builtinModuleSet$2, ...options.external || []],
745
- plugins: options.plugins
746
- });
747
- const modules = Object.fromEntries((result.outputFiles || []).map((outputFile) => {
748
- return [relative$1(outdir, outputFile.path), outputFile.text];
749
- }));
750
- if (!modules["definition.js"]) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0048({ message: `[vitehub] Failed to bundle discovered definition graph "${options.filename}".` });
751
- return {
752
- entry: "definition.js",
753
- externalImports: [...new Set(Object.values(result.metafile.outputs).flatMap((output) => output.imports).filter((imported) => imported.external).map((imported) => imported.path))].sort(),
754
- hasRuntimeModuleResolution: Object.values(modules).some(usesRuntimeModuleResolution),
755
- modules
756
- };
757
- }
758
- //#endregion
759
893
  //#region src/task/internal/typescript.ts
760
894
  const require = createRequire(import.meta.url);
761
895
  function loadTypeScript() {
@@ -1277,6 +1411,80 @@ function isServerAutoImportEnabled(imports) {
1277
1411
  return imports !== false && imports?.autoImport !== false;
1278
1412
  }
1279
1413
  //#endregion
1414
+ //#region src/task/internal/shared/discovered-definition/bundler.ts
1415
+ function isJsxDefinition(filename) {
1416
+ return filename.endsWith(".tsx") || filename.endsWith(".jsx");
1417
+ }
1418
+ function isBareSpecifier(id) {
1419
+ return !/^(?:\.{1,2}(?:\/|$)|\/|[A-Za-z]:[\\/]|\0)/.test(id);
1420
+ }
1421
+ /**
1422
+ * Vite 8 bundles with Rolldown, so the app already has it. Load the copy next to `vite`, or `vite/rolldown` with
1423
+ * Vite+, instead of installing a second bundler.
1424
+ */
1425
+ async function importRolldown() {
1426
+ let entry;
1427
+ try {
1428
+ entry = createRequire(import.meta.resolve("vite")).resolve("rolldown");
1429
+ } catch (error) {
1430
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "MODULE_NOT_FOUND") throw error;
1431
+ entry = createRequire(import.meta.url).resolve("vite/rolldown");
1432
+ }
1433
+ return await import(pathToFileURL(entry).href);
1434
+ }
1435
+ function usesRuntimeModuleResolution(contents) {
1436
+ return findDynamicImports(contents).some((imported) => !imported.expression.startsWith("\"")) || /\bimport\.meta\.resolve\s*\(/.test(contents) || /\bcreateRequire\b/.test(contents);
1437
+ }
1438
+ async function bundleDiscoveredDefinitionModuleGraph(options) {
1439
+ const { rolldown } = await importRolldown();
1440
+ const aliases = Object.keys(options.alias || {});
1441
+ const bundle = await rolldown({
1442
+ input: { definition: options.filename },
1443
+ platform: "node",
1444
+ logLevel: "silent",
1445
+ resolve: { alias: options.alias },
1446
+ transform: {
1447
+ target: "es2022",
1448
+ jsx: isJsxDefinition(options.filename) ? {
1449
+ runtime: "automatic",
1450
+ importSource: "react"
1451
+ } : void 0
1452
+ },
1453
+ plugins: [...options.plugins || [], {
1454
+ name: "vitehub-sandbox-task-definition-source",
1455
+ resolveId(id) {
1456
+ if (id === options.filename) return id;
1457
+ if (options.packages === "external" && isBareSpecifier(id) && !isBuiltin(id) && !aliases.some((alias) => id === alias || id.startsWith(`${alias}/`))) return {
1458
+ id,
1459
+ external: true
1460
+ };
1461
+ },
1462
+ load(id) {
1463
+ if (id === options.filename) return options.source;
1464
+ }
1465
+ }]
1466
+ });
1467
+ let output;
1468
+ try {
1469
+ output = (await bundle.generate({
1470
+ format: "esm",
1471
+ entryFileNames: "[name].js",
1472
+ chunkFileNames: "chunks/[name]-[hash].js"
1473
+ })).output;
1474
+ } finally {
1475
+ await bundle.close();
1476
+ }
1477
+ const chunks = output.filter((file) => file.type === "chunk");
1478
+ const modules = Object.fromEntries(chunks.map((chunk) => [chunk.fileName, chunk.code]));
1479
+ if (!modules["definition.js"]) throw invariantError("the bundle input is named `definition`, so Rolldown emits `definition.js` or throws first");
1480
+ return {
1481
+ entry: "definition.js",
1482
+ externalImports: [...new Set(chunks.flatMap((chunk) => [...chunk.imports, ...chunk.dynamicImports]).filter((imported) => !Object.hasOwn(modules, imported)))].sort(),
1483
+ hasRuntimeModuleResolution: Object.values(modules).some(usesRuntimeModuleResolution),
1484
+ modules
1485
+ };
1486
+ }
1487
+ //#endregion
1280
1488
  //#region src/task/internal/shared/discovered-definition.ts
1281
1489
  function normalizeDir(rootDir, dir) {
1282
1490
  if (typeof dir === "string") return isAbsolute$1(dir) ? dir : resolve$1(rootDir, dir);
@@ -1352,32 +1560,16 @@ async function createDiscoveredDefinitionCompiler(options = {}) {
1352
1560
  serverImports: options.serverImports,
1353
1561
  featureImports: options.featureImports || []
1354
1562
  };
1355
- if (!isServerAutoImportEnabled(resolvedOptions.serverImports)) return {
1356
- enabled: false,
1357
- async injectSource(source) {
1358
- return source;
1359
- },
1360
- async readSource(id) {
1361
- return await readFile(id, "utf8");
1362
- },
1363
- async bundleModule(bundleOptions) {
1364
- return await bundleDiscoveredDefinitionModule(bundleOptions);
1365
- }
1366
- };
1563
+ if (!isServerAutoImportEnabled(resolvedOptions.serverImports)) return { async readSource(id) {
1564
+ return await readFile(id, "utf8");
1565
+ } };
1367
1566
  const unimport = await createInitializedUnimport(resolvedOptions);
1368
1567
  const injectSource = async (source, id) => {
1369
1568
  return await injectTypeImportsFromUnimport((await unimport.injectImports(source, id)).code, id, await unimport.getImports());
1370
1569
  };
1371
- return {
1372
- enabled: true,
1373
- injectSource,
1374
- async readSource(id) {
1375
- return await injectSource(await readFile(id, "utf8"), id);
1376
- },
1377
- async bundleModule(bundleOptions) {
1378
- return await bundleDiscoveredDefinitionModule(bundleOptions);
1379
- }
1380
- };
1570
+ return { async readSource(id) {
1571
+ return await injectSource(await readFile(id, "utf8"), id);
1572
+ } };
1381
1573
  }
1382
1574
  //#endregion
1383
1575
  //#region src/task/internal/shared/feature-definitions.ts
@@ -1405,19 +1597,19 @@ function tryResolveFromRuntime(id) {
1405
1597
  return false;
1406
1598
  }
1407
1599
  }
1600
+ /** The resolved path of `id`, or `undefined` when no resolver finds it. */
1408
1601
  function tryResolveModule(id, options = {}) {
1409
1602
  const paths = normalizePaths(options.paths);
1410
1603
  const runtimeResolved = tryResolveFromRuntime(id);
1411
- if (runtimeResolved === false) return [sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0050({ message: `Unable to resolve module "${id}" using the active runtime resolver` }), void 0];
1412
- if (runtimeResolved) return [null, runtimeResolved];
1604
+ if (runtimeResolved === false) return void 0;
1605
+ if (runtimeResolved) return runtimeResolved;
1413
1606
  const resolved = resolveModule(id, { paths });
1414
- if (resolved) return [null, resolved];
1607
+ if (resolved) return resolved;
1415
1608
  for (const url of paths) try {
1416
- return [null, resolvePathSync(id, { url })];
1609
+ return resolvePathSync(id, { url });
1417
1610
  } catch {
1418
1611
  continue;
1419
1612
  }
1420
- return [sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0051({ message: paths.length > 0 ? `Unable to resolve module "${id}" from ${paths.join(", ")}` : `Unable to resolve module "${id}" without explicit resolution paths` }), void 0];
1421
1613
  }
1422
1614
  //#endregion
1423
1615
  //#region src/task/internal/shared/feature-runtime-path.ts
@@ -1441,15 +1633,15 @@ function resolveFeatureRuntimePath(importMetaUrl, packageId, sourceRelativePath,
1441
1633
  const targetsSourceTree = /(?:^|\/)\.\.\/src(?:\/|$)|^\.\/*src(?:\/|$)/.test(sourceRelativePath);
1442
1634
  const resolvedSourcePath = resolveExistingModulePath(sourcePath);
1443
1635
  if ((!importerUsesDist || !targetsSourceTree) && resolvedSourcePath) return resolvedSourcePath;
1444
- const [packageJsonError, packageJsonPath] = tryResolveModule(`${packageId}/package.json`);
1445
- if (!packageJsonError) {
1636
+ const packageJsonPath = tryResolveModule(`${packageId}/package.json`);
1637
+ if (packageJsonPath) {
1446
1638
  const packageRoot = dirname$1(packageJsonPath);
1447
1639
  const resolvedPackageSourcePath = resolveExistingModulePath(join$1(packageRoot, "src", sourceRelativePath.replace(/^(\.\.\/)+src\//, "").replace(/^\.\//, "")));
1448
1640
  if ((!importerUsesDist || !targetsSourceTree) && resolvedPackageSourcePath) return resolvedPackageSourcePath;
1449
1641
  return join$1(dirname$1(packageJsonPath), "dist", distRelativePath);
1450
1642
  }
1451
- const [packageError, packagePath] = tryResolveModule(packageId);
1452
- if (!packageError) return join$1(dirname$1(packagePath), distRelativePath);
1643
+ const packagePath = tryResolveModule(packageId);
1644
+ if (packagePath) return join$1(dirname$1(packagePath), distRelativePath);
1453
1645
  return sourcePath;
1454
1646
  }
1455
1647
  //#endregion
@@ -1532,15 +1724,12 @@ function parseManifest(source, path) {
1532
1724
  });
1533
1725
  }
1534
1726
  }
1535
- function isPlainObject(value) {
1536
- return !!value && typeof value === "object" && !Array.isArray(value);
1537
- }
1538
1727
  function parseSandboxTaskProjectOptions(manifest, path) {
1539
1728
  if (typeof manifest.vitehub === "undefined") return void 0;
1540
- if (!isPlainObject(manifest.vitehub)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0057({ message: `[vitehub] Sandbox package manifest "vitehub" must be an object: ${path}` });
1729
+ if (!isRecord(manifest.vitehub)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0057({ message: `[vitehub] Sandbox package manifest "vitehub" must be an object: ${path}` });
1541
1730
  const sandbox = manifest.vitehub.sandboxTask;
1542
1731
  if (typeof sandbox === "undefined") return void 0;
1543
- if (!isPlainObject(sandbox)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0058({ message: `[vitehub] Sandbox package manifest "vitehub.sandboxTask" must be an object: ${path}` });
1732
+ if (!isRecord(sandbox)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0058({ message: `[vitehub] Sandbox package manifest "vitehub.sandboxTask" must be an object: ${path}` });
1544
1733
  const unsupported = Object.keys(sandbox).filter((key) => key !== "timeout");
1545
1734
  if (unsupported.length) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0059({ message: `[vitehub] Sandbox package manifest "vitehub.sandboxTask" has unsupported keys: ${unsupported.join(", ")}.` });
1546
1735
  const timeout = sandbox.timeout;
@@ -1550,13 +1739,14 @@ function parseSandboxTaskProjectOptions(manifest, path) {
1550
1739
  return { timeout: numericTimeout };
1551
1740
  }
1552
1741
  function pnpmPatchPaths(manifest) {
1553
- if (!isPlainObject(manifest.pnpm) || !isPlainObject(manifest.pnpm.patchedDependencies)) return [];
1742
+ if (!isRecord(manifest.pnpm) || !isRecord(manifest.pnpm.patchedDependencies)) return [];
1554
1743
  return Object.values(manifest.pnpm.patchedDependencies).filter((value) => typeof value === "string");
1555
1744
  }
1556
- function parsePnpmWorkspacePatchPaths(source) {
1557
- const workspace = parse$1(source);
1558
- const patchedDependencies = isPlainObject(workspace) ? Reflect.get(workspace, "patchedDependencies") : void 0;
1559
- if (!isPlainObject(patchedDependencies)) return [];
1745
+ async function parsePnpmWorkspacePatchPaths(source) {
1746
+ const { parse: parseYaml } = await import("yaml");
1747
+ const workspace = parseYaml(source);
1748
+ const patchedDependencies = isRecord(workspace) ? Reflect.get(workspace, "patchedDependencies") : void 0;
1749
+ if (!isRecord(patchedDependencies)) return [];
1560
1750
  return Object.values(patchedDependencies).filter((value) => value === String(value)).map(String);
1561
1751
  }
1562
1752
  function parsePnpmWorkspacePackages(source) {
@@ -1580,7 +1770,9 @@ function parsePnpmWorkspacePackages(source) {
1580
1770
  return patterns;
1581
1771
  }
1582
1772
  function isWorkspacePackage(path, patterns) {
1583
- return patterns.filter((pattern) => !pattern.startsWith("!")).some((pattern) => matchesGlob(path, pattern)) && !patterns.filter((pattern) => pattern.startsWith("!")).some((pattern) => matchesGlob(path, pattern.slice(1)));
1773
+ const included = patterns.filter((pattern) => !pattern.startsWith("!"));
1774
+ const excluded = patterns.filter((pattern) => pattern.startsWith("!")).map((pattern) => pattern.slice(1));
1775
+ return included.length > 0 && picomatch(included)(path) && !(excluded.length > 0 && picomatch(excluded)(path));
1584
1776
  }
1585
1777
  async function findPnpmWorkspaceRoot(packageRoot, root) {
1586
1778
  for (const directory of ancestors(packageRoot, root)) {
@@ -1676,7 +1868,7 @@ async function resolveSandboxTaskProject(definitionFile, scanRoot, options = {})
1676
1868
  if (!isInside(installRoot, resolve(installRoot, patchPath))) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0064({ message: `[vitehub] Sandbox pnpm patch must stay inside its install root: ${patchPath}` });
1677
1869
  await addProjectFile(files, installRoot, resolve(installRoot, patchPath), root);
1678
1870
  }
1679
- if (workspace) for (const patchPath of parsePnpmWorkspacePatchPaths(workspace.source)) {
1871
+ if (workspace) for (const patchPath of await parsePnpmWorkspacePatchPaths(workspace.source)) {
1680
1872
  if (!isInside(installRoot, resolve(installRoot, patchPath))) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0065({ message: `[vitehub] Sandbox pnpm patch must stay inside its install root: ${patchPath}` });
1681
1873
  await addProjectFile(files, installRoot, resolve(installRoot, patchPath), root);
1682
1874
  }
@@ -2056,6 +2248,7 @@ function prepareExecutablePackageProject(project, entry) {
2056
2248
  //#endregion
2057
2249
  //#region src/task/bundle.ts
2058
2250
  const SHIM_NAMESPACE = "vitehub-sandbox-task-runtime-shim";
2251
+ const SHIM_ID = `\0${SHIM_NAMESPACE}`;
2059
2252
  const builtinModuleSet$1 = /* @__PURE__ */ new Set([...builtinModules, ...builtinModules.map((name) => `node:${name}`)]);
2060
2253
  function isRelativeFilesystemPath(path) {
2061
2254
  return !!path && !/^[/\\]/.test(path) && !/^[A-Za-z]:[/\\]/.test(path) && !/^[A-Za-z][A-Za-z\d+.-]*:/.test(path);
@@ -2110,72 +2303,66 @@ async function bundleSandboxTaskDefinition(source, file, options = {}) {
2110
2303
  source,
2111
2304
  plugins: [{
2112
2305
  name: SHIM_NAMESPACE,
2113
- setup(pluginBuild) {
2114
- pluginBuild.onResolve({ filter: /^@vite-hub\/sandbox\/task(?:\/runtime\/public)?$/ }, () => ({
2115
- path: "sandbox-task-runtime-shim",
2116
- namespace: SHIM_NAMESPACE
2117
- }));
2118
- pluginBuild.onLoad({
2119
- filter: /.*/,
2120
- namespace: SHIM_NAMESPACE
2121
- }, () => ({
2122
- contents: [
2123
- "function hasStandardValidator(value) {",
2124
- " if (!value || typeof value !== \"object\") return false",
2125
- " const standard = value[\"~standard\"]",
2126
- " return Object.hasOwn(value, \"~standard\") && !!standard && typeof standard === \"object\" && typeof standard.validate === \"function\"",
2127
- "}",
2128
- "",
2129
- "function isErrorWithHttpMetadata(error) {",
2130
- " if (!(error instanceof Error)) return false",
2131
- " return typeof error.status === \"number\" || typeof error.statusCode === \"number\" || typeof error.statusText === \"string\" || typeof error.statusMessage === \"string\"",
2132
- "}",
2133
- "",
2134
- "function createValidationError(cause) {",
2135
- " if (isErrorWithHttpMetadata(cause)) return cause",
2136
- " const message = cause instanceof Error",
2137
- " ? cause.message || \"Validation failed\"",
2138
- " : cause && typeof cause === \"object\" && typeof cause.message === \"string\" && cause.message",
2139
- " ? cause.message",
2140
- " : \"Validation failed\"",
2141
- " const error = new Error(message, { cause })",
2142
- " if (cause && typeof cause === \"object\")",
2143
- " Object.assign(error, cause)",
2144
- " error.code = \"SANDBOX_TASK_VALIDATION_ERROR\"",
2145
- " return error",
2146
- "}",
2147
- "",
2148
- "export async function readValidatedPayload(payload, validate) {",
2149
- " if (hasStandardValidator(validate)) {",
2150
- " let result",
2151
- " try {",
2152
- " result = await validate[\"~standard\"].validate(payload)",
2153
- " }",
2154
- " catch (error) {",
2155
- " throw createValidationError(error)",
2156
- " }",
2157
- " if (result.issues !== undefined)",
2158
- " throw createValidationError({ message: \"Validation failed\", issues: result.issues })",
2159
- " return result.value",
2160
- " }",
2161
- " try {",
2162
- " const result = await validate(payload)",
2163
- " if (result === false)",
2164
- " throw createValidationError({ message: \"Validation failed\" })",
2165
- " return result === true || result == null ? payload : result",
2166
- " }",
2167
- " catch (error) {",
2168
- " throw createValidationError(error)",
2169
- " }",
2170
- "}",
2171
- "",
2172
- "export function defineSandboxTask(input) {",
2173
- " const { project: _project, run, ...options } = input",
2174
- " return { run, options: Object.keys(options).length ? options : undefined }",
2175
- "}"
2176
- ].join("\n"),
2177
- loader: "js"
2178
- }));
2306
+ resolveId(id) {
2307
+ if (/^@vite-hub\/sandbox\/task(?:\/runtime\/public)?$/.test(id)) return SHIM_ID;
2308
+ },
2309
+ load(id) {
2310
+ if (id !== SHIM_ID) return;
2311
+ return [
2312
+ "function hasStandardValidator(value) {",
2313
+ " if (!value || typeof value !== \"object\") return false",
2314
+ " const standard = value[\"~standard\"]",
2315
+ " return Object.hasOwn(value, \"~standard\") && !!standard && typeof standard === \"object\" && typeof standard.validate === \"function\"",
2316
+ "}",
2317
+ "",
2318
+ "function isErrorWithHttpMetadata(error) {",
2319
+ " if (!(error instanceof Error)) return false",
2320
+ " return typeof error.status === \"number\" || typeof error.statusCode === \"number\" || typeof error.statusText === \"string\" || typeof error.statusMessage === \"string\"",
2321
+ "}",
2322
+ "",
2323
+ "function createValidationError(cause) {",
2324
+ " if (isErrorWithHttpMetadata(cause)) return cause",
2325
+ " const message = cause instanceof Error",
2326
+ " ? cause.message || \"Validation failed\"",
2327
+ " : cause && typeof cause === \"object\" && typeof cause.message === \"string\" && cause.message",
2328
+ " ? cause.message",
2329
+ " : \"Validation failed\"",
2330
+ " const error = new Error(message, { cause })",
2331
+ " if (cause && typeof cause === \"object\")",
2332
+ " Object.assign(error, cause)",
2333
+ " error.code = \"SANDBOX_TASK_VALIDATION_ERROR\"",
2334
+ " return error",
2335
+ "}",
2336
+ "",
2337
+ "export async function readValidatedPayload(payload, validate) {",
2338
+ " if (hasStandardValidator(validate)) {",
2339
+ " let result",
2340
+ " try {",
2341
+ " result = await validate[\"~standard\"].validate(payload)",
2342
+ " }",
2343
+ " catch (error) {",
2344
+ " throw createValidationError(error)",
2345
+ " }",
2346
+ " if (result.issues !== undefined)",
2347
+ " throw createValidationError({ message: \"Validation failed\", issues: result.issues })",
2348
+ " return result.value",
2349
+ " }",
2350
+ " try {",
2351
+ " const result = await validate(payload)",
2352
+ " if (result === false)",
2353
+ " throw createValidationError({ message: \"Validation failed\" })",
2354
+ " return result === true || result == null ? payload : result",
2355
+ " }",
2356
+ " catch (error) {",
2357
+ " throw createValidationError(error)",
2358
+ " }",
2359
+ "}",
2360
+ "",
2361
+ "export function defineSandboxTask(input) {",
2362
+ " const { project: _project, handler, ...options } = input",
2363
+ " return { handler, options: Object.keys(options).length ? options : undefined }",
2364
+ "}"
2365
+ ].join("\n");
2179
2366
  }
2180
2367
  }]
2181
2368
  });
@@ -2211,7 +2398,7 @@ async function bundleSandboxTaskDefinition(source, file, options = {}) {
2211
2398
  }
2212
2399
  //#endregion
2213
2400
  //#region src/task/definition-options.ts
2214
- const sandboxTaskDefinitionSyntax = "`defineSandboxTask({ run, ...options })`";
2401
+ const sandboxTaskDefinitionSyntax = "`defineSandboxTask({ handler, ...options })`";
2215
2402
  function readStaticValue(node) {
2216
2403
  const ts = loadTypeScript();
2217
2404
  if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) return node.text;
@@ -2306,20 +2493,25 @@ function propertyName(property) {
2306
2493
  async function extractSandboxTaskDefinitionMetadata(file) {
2307
2494
  const source = await readFile(file, "utf8");
2308
2495
  const ts = loadTypeScript();
2309
- const input = readDefinitionObject(ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS));
2496
+ const sourceFile = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
2497
+ const input = readDefinitionObject(sourceFile);
2310
2498
  if (!input) return void 0;
2311
2499
  const options = {};
2312
2500
  let project;
2313
- let hasRun = false;
2501
+ let hasHandler = false;
2314
2502
  for (const property of input.properties) {
2315
2503
  const key = propertyName(property);
2316
- if (key === "run" && ts.isShorthandPropertyAssignment(property)) {
2317
- hasRun = true;
2504
+ if (key === "run") {
2505
+ const { line } = sourceFile.getLineAndCharacterOfPosition(property.getStart(sourceFile));
2506
+ throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_C0014({ message: `[vitehub] ${file}:${line + 1}: \`defineSandboxTask({ run })\` was renamed. Pass the Sandbox handler as \`handler\`: \`defineSandboxTask({ handler })\`.` });
2507
+ }
2508
+ if (key === "handler" && ts.isShorthandPropertyAssignment(property)) {
2509
+ hasHandler = true;
2318
2510
  continue;
2319
2511
  }
2320
2512
  if (!key || !ts.isPropertyAssignment(property) && !ts.isMethodDeclaration(property)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_C0006({ message: `[vitehub] ${sandboxTaskDefinitionSyntax} requires explicit object properties.` });
2321
- if (key === "run") {
2322
- hasRun = true;
2513
+ if (key === "handler") {
2514
+ hasHandler = true;
2323
2515
  continue;
2324
2516
  }
2325
2517
  if (!ts.isPropertyAssignment(property)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_C0007({ message: `[vitehub] ${sandboxTaskDefinitionSyntax} options must use static values.` });
@@ -2334,7 +2526,7 @@ async function extractSandboxTaskDefinitionMetadata(file) {
2334
2526
  writable: true
2335
2527
  });
2336
2528
  }
2337
- if (!hasRun) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_C0009({ message: `[vitehub] ${sandboxTaskDefinitionSyntax} requires a \`run\` handler.` });
2529
+ if (!hasHandler) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_C0009({ message: `[vitehub] ${sandboxTaskDefinitionSyntax} requires a \`handler\`.` });
2338
2530
  const runtimeOptions = Object.keys(options).length ? options : void 0;
2339
2531
  return runtimeOptions || project !== void 0 ? {
2340
2532
  ...runtimeOptions ? { options: runtimeOptions } : {},
@@ -2345,7 +2537,7 @@ async function extractSandboxTaskDefinitionMetadata(file) {
2345
2537
  //#region src/task/type-template.ts
2346
2538
  function createDefinitionContract(definition) {
2347
2539
  const module = `typeof import(${JSON.stringify(definition.handler)})`;
2348
- if (definition.kind === "definition") return `{ payload: Parameters<${module}['default']['run']>[0], result: Awaited<ReturnType<${module}['default']['run']>> }`;
2540
+ if (definition.kind === "definition") return `{ payload: Parameters<${module}['default']['handler']>[0], result: Awaited<ReturnType<${module}['default']['handler']>> }`;
2349
2541
  return `SandboxTaskPackageContract<${module}['default']>`;
2350
2542
  }
2351
2543
  function createSandboxTaskTypeTemplateContents(definitions) {
@@ -2503,15 +2695,15 @@ function sandboxTaskProviderRuntimeExport(provider) {
2503
2695
  return provider === "cloudflare" ? "resolveCloudflareTaskSandbox" : "resolveVercelTaskSandbox";
2504
2696
  }
2505
2697
  function resolveSandboxTaskFeatureConfig(sandboxTaskConfig, hosting) {
2506
- if (getSandboxTaskFeatureProvider(sandboxTaskConfig)?.provider) return { ...sandboxTaskConfig };
2698
+ if (getSandboxTaskFeatureDriver(sandboxTaskConfig)?.driver) return { ...sandboxTaskConfig };
2507
2699
  const config = { ...sandboxTaskConfig };
2508
2700
  const hostedProvider = getSupportedHostingProvider(hosting, ["cloudflare", "vercel"]);
2509
2701
  if (hostedProvider) return {
2510
2702
  ...config,
2511
- provider: hostedProvider
2703
+ driver: hostedProvider
2512
2704
  };
2513
- const unsupportedHostedProvider = deploymentPresetFromNitro(hosting);
2514
- if (unsupportedHostedProvider) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0012({ message: "[vitehub] Sandbox hosting inference does not support " + unsupportedHostedProvider + ". An explicit `sandbox.provider` is required." });
2705
+ const unsupportedHostedProvider = hostFromNitroPreset(hosting);
2706
+ if (unsupportedHostedProvider) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0012({ message: "[vitehub] Sandbox hosting inference does not support " + unsupportedHostedProvider + ". An explicit `sandboxTask.driver` is required." });
2515
2707
  return config;
2516
2708
  }
2517
2709
  async function createSandboxTaskFeaturePlan(sandboxTaskConfig, definitions, paths, deps, hosting, discoveredDefinitionOptions = {}) {
@@ -2541,8 +2733,8 @@ async function createSandboxTaskFeaturePlan(sandboxTaskConfig, definitions, path
2541
2733
  ...definitionCompilerOptions,
2542
2734
  featureImports
2543
2735
  });
2544
- const defaultProvider = getSandboxTaskFeatureProvider(resolvedConfig);
2545
- const defaultProviderName = defaultProvider?.provider;
2736
+ const defaultProvider = getSandboxTaskFeatureDriver(resolvedConfig);
2737
+ const defaultProviderName = defaultProvider?.driver;
2546
2738
  const sandboxTaskArtifacts = sandboxTaskDefinitions.map((definition) => ({
2547
2739
  key: definition.definitionArtifactKey,
2548
2740
  filename: definition.definitionFilename,
@@ -2562,11 +2754,16 @@ async function createSandboxTaskFeaturePlan(sandboxTaskConfig, definitions, path
2562
2754
  }
2563
2755
  }));
2564
2756
  const providerLoaderTarget = resolveSandboxTaskProviderLoaderTarget(defaultProviderName, deps);
2565
- const cloudflareOptions = defaultProvider?.provider === "cloudflare" ? {
2757
+ if (defaultProvider?.driver === "cloudflare") resolveCloudflareSandboxTaskInstanceType(defaultProvider);
2758
+ else if (defaultProvider?.driver === "vercel") resolveVercelSandboxTaskVcpus(defaultProvider);
2759
+ const cloudflareOptions = defaultProvider?.driver === "cloudflare" ? {
2566
2760
  binding: typeof defaultProvider.binding === "string" ? defaultProvider.binding : defaultCloudflareSandboxBinding,
2567
2761
  className: typeof defaultProvider.className === "string" ? defaultProvider.className : defaultCloudflareSandboxClassName,
2568
2762
  migrationTag: typeof defaultProvider.migrationTag === "string" ? defaultProvider.migrationTag : "v1",
2569
- name: typeof defaultProvider.name === "string" ? defaultProvider.name : void 0
2763
+ name: typeof defaultProvider.name === "string" ? defaultProvider.name : void 0,
2764
+ cpu: defaultProvider.cpu,
2765
+ memory: defaultProvider.memory,
2766
+ maxInstances: defaultProvider.maxInstances
2570
2767
  } : void 0;
2571
2768
  return {
2572
2769
  manifest,
@@ -2583,7 +2780,7 @@ async function createSandboxTaskFeaturePlan(sandboxTaskConfig, definitions, path
2583
2780
  getContents(emitted, location) {
2584
2781
  return createSandboxTaskRegistryContents(location.dst, sandboxTaskDefinitions.map((definition) => {
2585
2782
  const artifact = emitted.get(definition.definitionArtifactKey);
2586
- if (!artifact) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0014({ message: `[vitehub] Missing generated sandbox definition module for "${definition.name}".` });
2783
+ invariant(artifact, `the Sandbox Task plan emits the Definition artifact of "${definition.name}" before the registry artifact`);
2587
2784
  return {
2588
2785
  name: definition.name,
2589
2786
  definitionModulePath: artifact.dst,
@@ -2594,7 +2791,7 @@ async function createSandboxTaskFeaturePlan(sandboxTaskConfig, definitions, path
2594
2791
  },
2595
2792
  ...providerLoaderTarget ? [{
2596
2793
  key: "sandbox-task-provider-loader",
2597
- filename: "runtime/sandbox-task-provider-loader.mjs",
2794
+ filename: "sandbox-task-provider-loader.mjs",
2598
2795
  contents: createSandboxTaskProviderLoaderContents(providerLoaderTarget)
2599
2796
  }] : []
2600
2797
  ],
@@ -2987,7 +3184,7 @@ async function withSandboxTaskRuntimeGenerationLock(generatedDir, operation, opt
2987
3184
  }
2988
3185
  if (cleanupErrors.length === 1) throw cleanupErrors[0];
2989
3186
  if (cleanupErrors.length > 1) throw new AggregateError(cleanupErrors, `[vitehub] Failed to clean up the Sandbox runtime generation lock in ${generatedDir}.`);
2990
- if (!operationResult) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0040({ message: `[vitehub] Sandbox runtime preparation completed without a result in ${generatedDir}.` });
3187
+ invariant(operationResult, "the Sandbox runtime preparation sets a result or a failure, and a failure returns earlier");
2991
3188
  return operationResult.value;
2992
3189
  }
2993
3190
  function markSandboxTaskRuntimeGeneration(contents, generationDir) {
@@ -3040,12 +3237,16 @@ function readNodeErrorCode(error) {
3040
3237
  }
3041
3238
  function normalizeSandboxTaskOptions(options) {
3042
3239
  if (options === false) return false;
3043
- if (!isPlainObject$1(options)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0042({ message: "[vitehub] `sandboxTask` must be a plain object." });
3240
+ if (!isRecord(options)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0042({ message: "[vitehub] `sandboxTask` must be a plain object." });
3241
+ if (options.driver === void 0 && Object.hasOwn(options, "provider")) {
3242
+ const provider = options.provider;
3243
+ throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_RENAMED_PROVIDER_KEY({ value: JSON.stringify(provider) ?? String(provider) });
3244
+ }
3044
3245
  return { ...options };
3045
3246
  }
3046
3247
  function createSandboxTaskRuntimeConfig(config, hosting) {
3047
- const provider = getSandboxTaskFeatureProvider(config);
3048
- const sandbox = provider?.provider === "vercel" ? {
3248
+ const provider = getSandboxTaskFeatureDriver(config);
3249
+ const sandbox = provider?.driver === "vercel" ? {
3049
3250
  ...config,
3050
3251
  token: provider.token ?? "",
3051
3252
  teamId: provider.teamId ?? "",
@@ -3064,15 +3265,11 @@ async function readSandboxTaskWorkspaceDeps(rootDir) {
3064
3265
  };
3065
3266
  }
3066
3267
  async function resolveSandboxTaskViteContext(integrationOptions, userConfig, env, hasDefinitions) {
3067
- const configOptions = userConfig.sandboxTask;
3268
+ const configOptions = getResolvedFeatureOptions(userConfig, "sandboxTask");
3068
3269
  const options = normalizeSandboxTaskOptions(typeof configOptions === "undefined" ? integrationOptions ?? {} : configOptions);
3069
- const nitro = isPlainObject$1(userConfig.nitro) ? userConfig.nitro : {};
3070
- const hosting = normalizeHosting(resolveHostPreset({
3071
- hosting: userConfig.preset,
3072
- nitro
3073
- })) || void 0;
3270
+ const hosting = normalizeHosting(resolveHostPreset({ nitro: isRecord(userConfig.nitro) ? userConfig.nitro : {} })) || void 0;
3074
3271
  const config = options === false ? false : hasDefinitions ? resolveSandboxTaskFeatureConfig(options, hosting) : { ...options };
3075
- const runtimeSandboxTaskConfig = config !== false && (hasDefinitions || getSandboxTaskFeatureProvider(config)?.provider) ? config : false;
3272
+ const runtimeSandboxTaskConfig = config !== false && (hasDefinitions || getSandboxTaskFeatureDriver(config)?.driver) ? config : false;
3076
3273
  const rootDir = resolve$1(process.cwd(), typeof userConfig.root === "string" ? userConfig.root : ".");
3077
3274
  return {
3078
3275
  rootDir,
@@ -3129,13 +3326,14 @@ function readResolveOptions(config) {
3129
3326
  const resolveOptions = config.resolve;
3130
3327
  return resolveOptions && typeof resolveOptions === "object" ? resolveOptions : {};
3131
3328
  }
3132
- function createSandboxTaskRuntimeFacadeContents(file, runtimeConfig, registryFile, providerLoaderFile) {
3329
+ function createSandboxTaskRuntimeFacadeContents(file, runtimeConfig, registryFile, development, providerLoaderImport) {
3133
3330
  return [
3134
3331
  `import sandboxTaskRegistry from ${JSON.stringify(createImportPath(file, registryFile))}`,
3135
- ...providerLoaderFile ? [`export { loadSandboxTaskRuntimeProvider } from ${JSON.stringify(createImportPath(file, providerLoaderFile))}`] : [],
3136
- `import { setSandboxTaskRuntimeConfig, setSandboxTaskRuntimeRegistry } from ${JSON.stringify(sandboxTaskRuntimeStateSpecifier)}`,
3332
+ ...providerLoaderImport ? [`export { loadSandboxTaskRuntimeProvider } from ${JSON.stringify(providerLoaderImport)}`] : [],
3333
+ `import { setSandboxTaskRuntimeConfig, setSandboxTaskRuntimeDevelopment, setSandboxTaskRuntimeRegistry } from ${JSON.stringify(sandboxTaskRuntimeStateSpecifier)}`,
3137
3334
  "",
3138
3335
  `setSandboxTaskRuntimeConfig(${JSON.stringify(runtimeConfig, null, 2)})`,
3336
+ `setSandboxTaskRuntimeDevelopment(${development})`,
3139
3337
  "setSandboxTaskRuntimeRegistry(sandboxTaskRegistry)",
3140
3338
  "",
3141
3339
  "export default sandboxTaskRegistry",
@@ -3160,6 +3358,17 @@ function createGeneratedAliasMap(rootDir, plan, platform = process.platform) {
3160
3358
  }
3161
3359
  return aliases;
3162
3360
  }
3361
+ async function writeStableSandboxTaskRuntimeFile(file, contents, lease) {
3362
+ if (await readFile(file, "utf8").catch(() => void 0) === contents) return;
3363
+ const staged = `${file}.${randomUUID()}.tmp`;
3364
+ await writeFile(staged, contents, "utf8");
3365
+ try {
3366
+ await lease.assertOwned();
3367
+ await rename(staged, file);
3368
+ } finally {
3369
+ await rm(staged, { force: true });
3370
+ }
3371
+ }
3163
3372
  async function writeSandboxTaskArtifacts(rootDir, plan, createFacadeContents, platform = process.platform) {
3164
3373
  const generatedDir = ensureGeneratedDir(rootDir, "sandbox-task");
3165
3374
  await mkdir(generatedDir, { recursive: true });
@@ -3180,13 +3389,12 @@ async function writeSandboxTaskArtifactsLocked(plan, createFacadeContents, gener
3180
3389
  try {
3181
3390
  for (const artifact of plan.artifacts || []) {
3182
3391
  const stableDst = resolve$1(generatedDir, artifact.filename);
3183
- const relativePath = stableDst.slice(runtimeDir.length + 1);
3184
- const dst = resolve$1(generationDir, relativePath);
3392
+ const dst = stableDst.startsWith(`${runtimeDir}/`) ? resolve$1(generationDir, stableDst.slice(runtimeDir.length + 1)) : stableDst;
3185
3393
  const contents = artifact.contents ?? await artifact.getContents?.(emitted, {
3186
3394
  dst,
3187
3395
  stableDst
3188
3396
  });
3189
- if (typeof contents !== "string") throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0043({ message: `[vitehub] Sandbox generated artifact "${artifact.key}" did not return contents.` });
3397
+ invariant(typeof contents === "string", `the Sandbox Task plan artifact "${artifact.key}" returns string contents`);
3190
3398
  emitted.set(artifact.key, {
3191
3399
  ...artifact,
3192
3400
  contents,
@@ -3195,13 +3403,15 @@ async function writeSandboxTaskArtifactsLocked(plan, createFacadeContents, gener
3195
3403
  });
3196
3404
  }
3197
3405
  if (typeTemplate) await writeFileIfChanged(resolve$1(generationDir, typeTemplate.filename.replace(/^runtime\//, "")), typeTemplate.contents);
3198
- for (const artifact of emitted.values()) await writeFileIfChanged(artifact.dst, artifact.contents);
3406
+ for (const artifact of emitted.values()) if (artifact.dst === artifact.stableDst) await writeStableSandboxTaskRuntimeFile(artifact.dst, artifact.contents, lease);
3407
+ else await writeFileIfChanged(artifact.dst, artifact.contents);
3199
3408
  const generationFacadeFile = resolve$1(generationDir, "sandbox-task.mjs");
3200
3409
  const activeFacadeFile = resolveSandboxTaskRuntimeFacadeImportBase(runtimeDir, generationFacadeFile, platform);
3201
3410
  const registryArtifact = emitted.get(plan.aliases?.find((alias) => alias.key === SANDBOX_REGISTRY_ID)?.artifactKey || "");
3202
- if (!registryArtifact) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0044({ message: "[vitehub] Sandbox runtime plan did not emit a registry artifact." });
3411
+ invariant(registryArtifact, "the Sandbox Task feature adds the registry artifact and its alias to the plan");
3203
3412
  const providerLoaderArtifact = emitted.get("sandbox-task-provider-loader");
3204
- await writeFileIfChanged(generationFacadeFile, markSandboxTaskRuntimeGeneration(createFacadeContents(activeFacadeFile, registryArtifact.dst, providerLoaderArtifact?.dst), generationDir));
3413
+ const providerLoaderImport = providerLoaderArtifact && (platform === "win32" ? createImportPath(activeFacadeFile, providerLoaderArtifact.dst) : providerLoaderArtifact.dst);
3414
+ await writeFileIfChanged(generationFacadeFile, markSandboxTaskRuntimeGeneration(createFacadeContents(activeFacadeFile, registryArtifact.dst, providerLoaderImport), generationDir));
3205
3415
  await lease.assertOwned();
3206
3416
  if (platform === "win32") await lease.publish(async () => {
3207
3417
  await lease.assertOwned();
@@ -3289,12 +3499,12 @@ async function prepareSandboxTaskRuntime(options) {
3289
3499
  const resolvedRoot = options.resolvedConfig?.root || resolve$1(process.cwd(), typeof options.userConfig.root === "string" ? options.userConfig.root : ".");
3290
3500
  const configuredProjectRoot = options.userConfig[VITEHUB_PROJECT_ROOT];
3291
3501
  const rootDir = typeof configuredProjectRoot === "string" ? resolve$1(configuredProjectRoot) : resolvedRoot;
3292
- const configOptions = options.userConfig.sandboxTask;
3502
+ const configOptions = getResolvedFeatureOptions(options.userConfig, "sandboxTask");
3293
3503
  const definitions = (typeof configOptions === "undefined" ? options.integrationOptions === false : configOptions === false) ? [] : discoverSandboxTaskDefinitions({ rootDir });
3294
3504
  const resolvedNitro = options.resolvedConfig?.nitro;
3295
3505
  const context = await resolveSandboxTaskViteContext(options.integrationOptions, {
3296
3506
  ...options.userConfig,
3297
- ...isPlainObject$1(resolvedNitro) ? { nitro: resolvedNitro } : {},
3507
+ ...isRecord(resolvedNitro) ? { nitro: resolvedNitro } : {},
3298
3508
  root: rootDir
3299
3509
  }, options.env, definitions.length > 0);
3300
3510
  const stateModule = createSandboxTaskStateModuleContents(context);
@@ -3322,12 +3532,12 @@ async function prepareSandboxTaskRuntime(options) {
3322
3532
  definitions,
3323
3533
  files: [],
3324
3534
  hosting: context.hosting,
3325
- provider: getSandboxTaskFeatureProvider(context.config)?.provider,
3535
+ provider: getSandboxTaskFeatureDriver(context.config)?.driver,
3326
3536
  rootDir,
3327
3537
  stateModule,
3328
3538
  watchFiles: plan.watchFiles || []
3329
3539
  };
3330
- const emitted = await writeSandboxTaskArtifacts(rootDir, plan, (file, registryFile, providerLoaderFile) => createSandboxTaskRuntimeFacadeContents(file, context.runtimeConfig.sandboxTask, registryFile, providerLoaderFile), options.platform);
3540
+ const emitted = await writeSandboxTaskArtifacts(rootDir, plan, (file, registryFile, providerLoaderImport) => createSandboxTaskRuntimeFacadeContents(file, context.runtimeConfig.sandboxTask, registryFile, context.command === "serve", providerLoaderImport), options.platform);
3331
3541
  return {
3332
3542
  aliases,
3333
3543
  cloudflare: plan.cloudflare,
@@ -3338,7 +3548,7 @@ async function prepareSandboxTaskRuntime(options) {
3338
3548
  ...(plan.artifacts || []).map((artifact) => resolve$1(ensureGeneratedDir(rootDir, "sandbox-task"), artifact.filename))
3339
3549
  ],
3340
3550
  hosting: context.hosting,
3341
- provider: getSandboxTaskFeatureProvider(context.config)?.provider,
3551
+ provider: getSandboxTaskFeatureDriver(context.config)?.driver,
3342
3552
  rootDir,
3343
3553
  stateModule,
3344
3554
  watchFiles: plan.watchFiles || []
@@ -3366,10 +3576,39 @@ function inspectSandboxTaskDefinitions(options) {
3366
3576
  source: definition.source
3367
3577
  }));
3368
3578
  }
3579
+ /** The Cloudflare instance type and instance limit, as the Container resource reports them. */
3580
+ function describeCloudflareSandboxTaskSize(options) {
3581
+ const instanceType = options.instanceType === void 0 ? void 0 : describeCloudflareInstanceType(options.instanceType)?.label ?? JSON.stringify(options.instanceType);
3582
+ return [instanceType ? `Instance type ${instanceType}` : "", options.maxInstances ? `at most ${options.maxInstances} instances` : ""].filter(Boolean).join(", ");
3583
+ }
3584
+ /** Lists the Cloudflare Durable Object and Container that run every Sandbox Task. Reads build options only. */
3585
+ function inspectSandboxTaskResources(options) {
3586
+ const binding = options.binding || "SANDBOX";
3587
+ const className = options.className || "Sandbox";
3588
+ const size = describeCloudflareSandboxTaskSize(options);
3589
+ return [{
3590
+ binding,
3591
+ definition: "Sandbox Tasks",
3592
+ host: "cloudflare",
3593
+ kind: "cloudflare-durable-object",
3594
+ name: className,
3595
+ note: "One Durable Object for each Sandbox ID. It starts the Container. Wrangler creates the class from the migration in the generated wrangler.json.",
3596
+ owner: "sandbox",
3597
+ source: "name"
3598
+ }, {
3599
+ definition: "Sandbox Tasks",
3600
+ host: "cloudflare",
3601
+ kind: "cloudflare-container",
3602
+ name: options.name || className,
3603
+ note: `Wrangler builds the image from the containers entry of class ${className} in the generated wrangler.json.${size ? ` ${size}.` : ""}`,
3604
+ owner: "sandbox",
3605
+ ...options.name ? { source: "name" } : {}
3606
+ }];
3607
+ }
3369
3608
  /** Console section that lists discovered Sandbox Task Definitions. `vitehub inspect definitions` reads the same data. */
3370
3609
  const sandboxTaskConsoleSection = {
3371
3610
  description: "Inspect discovered Sandbox Task Definitions without starting runtime resources.",
3372
- icon: "i-lucide-container",
3611
+ icon: "i-vitehub-sandbox",
3373
3612
  id: "sandbox-tasks",
3374
3613
  label: "Sandbox Tasks",
3375
3614
  read: inspectSandboxTaskDefinitions,
@@ -3379,12 +3618,51 @@ const sandboxTaskConsoleSection = {
3379
3618
  }
3380
3619
  };
3381
3620
  //#endregion
3621
+ //#region src/task/deployment-env.ts
3622
+ const owners = ["sandbox"];
3623
+ const vercelCredentialNames = {
3624
+ token: {
3625
+ names: ["VITE_SANDBOX_TOKEN", "VERCEL_TOKEN"],
3626
+ secret: true
3627
+ },
3628
+ teamId: {
3629
+ names: ["VITE_SANDBOX_TEAM_ID", "VERCEL_TEAM_ID"],
3630
+ secret: false
3631
+ },
3632
+ projectId: {
3633
+ names: ["VITE_SANDBOX_PROJECT_ID", "VERCEL_PROJECT_ID"],
3634
+ secret: false
3635
+ }
3636
+ };
3637
+ /**
3638
+ * The variables that Sandbox Tasks read on the deployed host. A Vercel Sandbox reads its token, team, and project from
3639
+ * env when the config leaves them out. On Vercel they are optional, since the Sandbox SDK then uses the OIDC token of
3640
+ * the deployment. A Cloudflare Sandbox uses its binding and reads none.
3641
+ */
3642
+ function sandboxDeploymentEnv(config, driver, context) {
3643
+ if (config === false || driver !== "vercel") return [];
3644
+ const configured = config?.driver === "vercel" ? config : void 0;
3645
+ const required = context.host !== "vercel";
3646
+ return [
3647
+ "token",
3648
+ "teamId",
3649
+ "projectId"
3650
+ ].flatMap((option) => configured?.[option]?.trim() ? [] : [{
3651
+ names: vercelCredentialNames[option].names,
3652
+ required,
3653
+ secret: vercelCredentialNames[option].secret,
3654
+ hasDefault: false,
3655
+ owners
3656
+ }]);
3657
+ }
3658
+ //#endregion
3382
3659
  //#region src/task/vite.ts
3383
3660
  const SANDBOX_PACKAGE_ID = "@vite-hub/sandbox/task";
3384
3661
  const SANDBOX_PACKAGE_NAME = "@vite-hub/sandbox";
3385
3662
  const SANDBOX_PROVIDER_LOADER_ID = "vitehub-sandbox-task-provider-loader";
3386
3663
  const SANDBOX_STATE_ID = "#vitehub/sandbox-task";
3387
3664
  const RESOLVED_SANDBOX_STATE_ID = "\0vitehub:sandbox-task:state";
3665
+ const SANDBOX_STATE_ID_PATTERN = /^(?:#vitehub\/sandbox-task|\0vitehub:sandbox-task:state)$/;
3388
3666
  function mergeSandboxTaskNitroProviderAliases(nitro, aliases) {
3389
3667
  const providerAliases = Object.fromEntries(sandboxTaskProviderLoaderSpecifiers.flatMap((specifier) => {
3390
3668
  const replacement = aliases[specifier];
@@ -3392,7 +3670,7 @@ function mergeSandboxTaskNitroProviderAliases(nitro, aliases) {
3392
3670
  }));
3393
3671
  if (!Object.keys(providerAliases).length) return;
3394
3672
  nitro.alias = {
3395
- ...isPlainObject$1(nitro.alias) ? nitro.alias : {},
3673
+ ...isRecord(nitro.alias) ? nitro.alias : {},
3396
3674
  ...providerAliases
3397
3675
  };
3398
3676
  }
@@ -3407,11 +3685,13 @@ function mergeSandboxTaskNitroNoExternals(nitro, provider) {
3407
3685
  function sandboxTaskProviderLoaderFallback() {
3408
3686
  return resolveFeatureRuntimePath(import.meta.url, "@vite-hub/sandbox/task", "./runtime/provider-loader", "runtime/provider-loader.js");
3409
3687
  }
3688
+ /** The path of the Sandbox Task runtime state module. Generated code of other owners imports it by path. */
3689
+ const sandboxTaskRuntimeStateModule = resolveFeatureRuntimePath(import.meta.url, SANDBOX_PACKAGE_ID, "./runtime/state", "runtime/state.js");
3410
3690
  const sandboxTaskRuntimePackageAliases = {
3411
3691
  [sandboxTaskRuntimeProviderSpecifiers.cloudflare]: resolveFeatureRuntimePath(import.meta.url, SANDBOX_PACKAGE_ID, "./runtime/providers/cloudflare", "runtime/providers/cloudflare.js"),
3412
3692
  [sandboxTaskRuntimeProviderSpecifiers.vercel]: resolveFeatureRuntimePath(import.meta.url, SANDBOX_PACKAGE_ID, "./runtime/providers/vercel", "runtime/providers/vercel.js"),
3413
3693
  [sandboxTaskRuntimeSpecifier]: resolveFeatureRuntimePath(import.meta.url, SANDBOX_PACKAGE_ID, "./index", "index.js"),
3414
- [sandboxTaskRuntimeStateSpecifier]: resolveFeatureRuntimePath(import.meta.url, SANDBOX_PACKAGE_ID, "./runtime/state", "runtime/state.js")
3694
+ [sandboxTaskRuntimeStateSpecifier]: sandboxTaskRuntimeStateModule
3415
3695
  };
3416
3696
  function toSandboxTaskAliasEntries(aliases) {
3417
3697
  return Object.entries(aliases).map(([find, replacement]) => ({
@@ -3458,6 +3738,24 @@ function invalidateGeneratedSandboxTaskModules(files, moduleGraph) {
3458
3738
  if (module) moduleGraph.invalidateModule(module);
3459
3739
  }
3460
3740
  }
3741
+ async function reloadStaleSandboxTaskGenerations(environments, rootDir, facadeFile) {
3742
+ const generationsDir = await realpath(resolve$1(ensureGeneratedDir(rootDir, "sandbox-task"), ".runtime-generations")).then(normalize).catch(() => void 0);
3743
+ const currentGeneration = generationsDir && await readSandboxTaskRuntimeGeneration(facadeFile, generationsDir);
3744
+ if (!generationsDir || !currentGeneration) return;
3745
+ for (const environment of Object.values(environments ?? {})) {
3746
+ if (environment.config.consumer !== "server") continue;
3747
+ for (const module of environment.moduleGraph.idToModuleMap.values()) {
3748
+ const id = module.id;
3749
+ if (!id?.startsWith(`${generationsDir}/`) || id.startsWith(`${currentGeneration}/`)) continue;
3750
+ environment.moduleGraph.invalidateModule(module);
3751
+ for (const importer of module.importers) environment.moduleGraph.invalidateModule(importer);
3752
+ environment.hot.send({
3753
+ type: "full-reload",
3754
+ triggeredBy: id
3755
+ });
3756
+ }
3757
+ }
3758
+ }
3461
3759
  async function resolveGeneratedSandboxTaskModuleIds(files) {
3462
3760
  return Promise.all(files.map(async (file) => normalize(await realpath(file).catch(() => file))));
3463
3761
  }
@@ -3488,6 +3786,7 @@ function hubSandboxTask(options) {
3488
3786
  let earlyNitroTarget;
3489
3787
  let earlyNitroSnapshot;
3490
3788
  let composedCloudflareEarly = false;
3789
+ let cloudflareSandbox;
3491
3790
  let sandboxTaskRuntimeRefresh = Promise.resolve();
3492
3791
  const sandboxTaskNitroModule = (nitro) => {
3493
3792
  const options = nitro.options;
@@ -3544,8 +3843,20 @@ function hubSandboxTask(options) {
3544
3843
  return await refresh;
3545
3844
  }
3546
3845
  async function composeCloudflareSandbox(config, prepared, finalizeWrangler = false) {
3547
- if (!prepared.cloudflare || !hasNitroConfigContext(config) || getHostingProvider(prepared.hosting) !== "cloudflare") return false;
3548
- config.nitro = await configureCloudflareSandboxNitro(mutableSandboxTaskNitroTarget(config.nitro), prepared.rootDir, prepared.cloudflare, finalizeWrangler);
3846
+ if (!prepared.cloudflare || !hasNitroConfigContext(config) || getHostingProvider(prepared.hosting) !== "cloudflare") {
3847
+ cloudflareSandbox = void 0;
3848
+ return false;
3849
+ }
3850
+ const nitro = await configureCloudflareSandboxNitro(mutableSandboxTaskNitroTarget(config.nitro), prepared.rootDir, prepared.cloudflare, finalizeWrangler);
3851
+ config.nitro = nitro;
3852
+ const className = prepared.cloudflare.className || "Sandbox";
3853
+ const container = nitro.cloudflare?.wrangler?.containers?.find((entry) => entry.class_name === className);
3854
+ cloudflareSandbox = {
3855
+ ...prepared.cloudflare,
3856
+ name: container?.name,
3857
+ instanceType: container?.instance_type,
3858
+ maxInstances: container?.max_instances
3859
+ };
3549
3860
  return true;
3550
3861
  }
3551
3862
  return {
@@ -3555,22 +3866,26 @@ function hubSandboxTask(options) {
3555
3866
  name: "@vite-hub/sandbox/task/provider-runtime",
3556
3867
  setup: sandboxTaskNitroModule
3557
3868
  },
3558
- vitehub: { inspect: () => sandboxTaskEnabled ? { definitions: [{
3559
- kind: "sandbox-task",
3560
- label: "Sandbox Tasks",
3561
- list: () => {
3562
- const sandboxTaskRoot = rootDir ?? resolvedConfig?.root ?? process.cwd();
3563
- return inspectSandboxTaskDefinitions({
3564
- projectRoot: resolveViteHubProjectRoot(sandboxTaskRoot),
3565
- rootDir: sandboxTaskRoot
3566
- });
3567
- }
3568
- }] } : void 0 },
3869
+ api: { deploymentEnv: (context) => sandboxTaskEnabled && definitions.length ? sandboxDeploymentEnv(integrationOptions, selectedProvider ?? (integrationOptions ? integrationOptions.driver : void 0), context) : [] },
3870
+ vitehub: { inspect: () => sandboxTaskEnabled ? {
3871
+ definitions: [{
3872
+ kind: "sandbox-task",
3873
+ label: "Sandbox Tasks",
3874
+ list: () => {
3875
+ const sandboxTaskRoot = rootDir ?? resolvedConfig?.root ?? process.cwd();
3876
+ return inspectSandboxTaskDefinitions({
3877
+ projectRoot: resolveViteHubProjectRoot(sandboxTaskRoot),
3878
+ rootDir: sandboxTaskRoot
3879
+ });
3880
+ }
3881
+ }],
3882
+ resources: () => cloudflareSandbox ? inspectSandboxTaskResources(cloudflareSandbox) : []
3883
+ } : void 0 },
3569
3884
  async config(config, env) {
3570
3885
  rawConfig = config;
3571
3886
  rawEnv = env;
3572
3887
  const prepared = await prepareCurrentSandboxTaskRuntime(false);
3573
- sandboxTaskEnabled = rawConfig.sandboxTask !== false && integrationOptions !== false;
3888
+ sandboxTaskEnabled = getResolvedFeatureOptions(rawConfig, "sandboxTask") !== false && integrationOptions !== false;
3574
3889
  generatedAliases = prepared.aliases;
3575
3890
  generatedFiles = prepared.files;
3576
3891
  watchFiles = prepared.watchFiles;
@@ -3578,7 +3893,7 @@ function hubSandboxTask(options) {
3578
3893
  rootDir = prepared.rootDir;
3579
3894
  selectedProvider = prepared.provider;
3580
3895
  const nitro = config.nitro;
3581
- if (isPlainObject$1(nitro)) {
3896
+ if (isRecord(nitro)) {
3582
3897
  earlyNitroTarget = nitro;
3583
3898
  earlyNitroSnapshot = cloneConfigValue(earlyNitroTarget);
3584
3899
  }
@@ -3588,18 +3903,24 @@ function hubSandboxTask(options) {
3588
3903
  ...withoutSandboxTaskPackageAlias(generatedAliases)
3589
3904
  }) } };
3590
3905
  },
3591
- resolveId(id) {
3592
- if (!sandboxTaskStateModule) return;
3593
- if (id === SANDBOX_STATE_ID) return RESOLVED_SANDBOX_STATE_ID;
3594
- if (id === RESOLVED_SANDBOX_STATE_ID) return id;
3906
+ resolveId: {
3907
+ filter: { id: SANDBOX_STATE_ID_PATTERN },
3908
+ handler(id) {
3909
+ if (!sandboxTaskStateModule) return;
3910
+ if (id === SANDBOX_STATE_ID) return RESOLVED_SANDBOX_STATE_ID;
3911
+ if (id === RESOLVED_SANDBOX_STATE_ID) return id;
3912
+ }
3595
3913
  },
3596
- load(id) {
3597
- if (id === SANDBOX_STATE_ID || id === RESOLVED_SANDBOX_STATE_ID) return sandboxTaskStateModule;
3914
+ load: {
3915
+ filter: { id: SANDBOX_STATE_ID_PATTERN },
3916
+ handler(id) {
3917
+ if (id === SANDBOX_STATE_ID || id === RESOLVED_SANDBOX_STATE_ID) return sandboxTaskStateModule;
3918
+ }
3598
3919
  },
3599
3920
  async configResolved(config) {
3600
3921
  resolvedConfig = config;
3601
3922
  const prepared = await refreshSandboxTaskRuntime();
3602
- sandboxTaskEnabled = rawConfig.sandboxTask !== false && integrationOptions !== false;
3923
+ sandboxTaskEnabled = getResolvedFeatureOptions(rawConfig, "sandboxTask") !== false && integrationOptions !== false;
3603
3924
  selectedProvider = prepared.provider;
3604
3925
  if (!await composeCloudflareSandbox(config, prepared, true) && composedCloudflareEarly && earlyNitroTarget && earlyNitroSnapshot) for (const key of ["cloudflare", "rollupConfig"]) if (key in earlyNitroSnapshot) earlyNitroTarget[key] = earlyNitroSnapshot[key];
3605
3926
  else delete earlyNitroTarget[key];
@@ -3620,6 +3941,8 @@ function hubSandboxTask(options) {
3620
3941
  ...currentFiles,
3621
3942
  ...currentResolvedFiles
3622
3943
  ], context.server.moduleGraph);
3944
+ const facadeFile = generatedAliases[SANDBOX_PACKAGE_ID];
3945
+ if (facadeFile) await reloadStaleSandboxTaskGenerations(context.server.environments, prepared.rootDir, facadeFile);
3623
3946
  return prepared;
3624
3947
  });
3625
3948
  },
@@ -3640,4 +3963,4 @@ function hubSandboxTask(options) {
3640
3963
  };
3641
3964
  }
3642
3965
  //#endregion
3643
- export { discoverSandboxTaskDefinitions, hubSandboxTask, inspectSandboxTaskDefinitions, sandboxTaskConsoleSection };
3966
+ export { discoverSandboxTaskDefinitions, hubSandboxTask, inspectSandboxTaskDefinitions, sandboxTaskConsoleSection, sandboxTaskRuntimeStateModule };