vite-hub 0.0.2 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,1122 +1,2 @@
1
- import { builtinModules, createRequire } from "node:module";
2
- import { existsSync, readFileSync, statSync } from "node:fs";
3
- import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
4
- import { fileURLToPath } from "node:url";
5
- import { hubAgent } from "@vite-hub/agent/vite";
6
- import { hubAuth } from "@vite-hub/auth/vite";
7
- import { hubBlob } from "@vite-hub/blob/vite";
8
- import { hubBrowser } from "@vite-hub/browser/vite";
9
- import { hubDb } from "@vite-hub/database/vite";
10
- import { hubEmail } from "@vite-hub/email/vite";
11
- import { hubEnv } from "@vite-hub/env/vite";
12
- import { hubKv, hubKvOptionalPeerResolver, resolveKVViteConfig } from "@vite-hub/kv/vite";
13
- import { hubMarkdownTemplate } from "@vite-hub/markdown-template/vite";
14
- import { hubQueue } from "@vite-hub/queue/vite";
15
- import { hubRateLimit } from "@vite-hub/rate-limit/vite";
16
- import { hubSandbox } from "@vite-hub/sandbox/vite";
17
- import { hubSchedule } from "@vite-hub/schedule/vite";
18
- import { hubWorkflow } from "@vite-hub/workflow/vite";
19
- import { hubWorkspace } from "@vite-hub/workspace/vite";
20
- import { access, cp, mkdir, readFile, readdir, realpath, rm, writeFile } from "node:fs/promises";
21
- //#region package.json
22
- var exports = {
23
- ".": "./dist/index.js",
24
- "./_internal/agent": "./dist/_internal/agent.js",
25
- "./_internal/agent/cloudflare": "./dist/_internal/agent/cloudflare.js",
26
- "./_internal/agent/cloudflare/state": "./dist/_internal/agent/cloudflare/state.js",
27
- "./_internal/agent/runtime/workflow": "./dist/_internal/agent/runtime/workflow.js",
28
- "./_internal/agent/server": "./dist/_internal/agent/server.js",
29
- "./_internal/agent/server/internal": "./dist/_internal/agent/server/internal.js",
30
- "./_internal/agent/server/workspace": "./dist/_internal/agent/server/workspace.js",
31
- "./_internal/agent/state/sqlite": "./dist/_internal/agent/state/sqlite.js",
32
- "./_internal/blob": "./dist/_internal/blob.js",
33
- "./_internal/blob/runtime/state": "./dist/_internal/blob/runtime/state.js",
34
- "./_internal/kv": "./dist/_internal/kv.js",
35
- "./_internal/kv/runtime/disabled-upstash": "./dist/_internal/kv/runtime/disabled-upstash.js",
36
- "./_internal/markdown-template": "./dist/_internal/markdown-template.js",
37
- "./_internal/rate-limit/runtime": "./dist/_internal/rate-limit/runtime.js",
38
- "./_internal/sandbox/runtime/state": "./dist/_internal/sandbox/runtime/state.js",
39
- "./_internal/schedule": "./dist/_internal/schedule.js",
40
- "./_internal/schedule/runtime": "./dist/_internal/schedule/runtime.js",
41
- "./_internal/schedule/runtime/driver": "./dist/_internal/schedule/runtime/driver.js",
42
- "./_internal/schedule/runtime/process": "./dist/_internal/schedule/runtime/process.js",
43
- "./_internal/schedule/runtime/static": "./dist/_internal/schedule/runtime/static.js",
44
- "./_internal/workflow": "./dist/_internal/workflow.js",
45
- "./_internal/workflow/runtime/execute": "./dist/_internal/workflow/runtime/execute.js",
46
- "./_internal/workflow/runtime/state": "./dist/_internal/workflow/runtime/state.js",
47
- "./_internal/workspace": "./dist/_internal/workspace.js",
48
- "./_internal/workspace/internal/runtime/hosted": "./dist/_internal/workspace/internal/runtime/hosted.js",
49
- "./_internal/workspace/internal/runtime/hosted-vercel-blob": "./dist/_internal/workspace/internal/runtime/hosted-vercel-blob.js",
50
- "./_internal/workspace/internal/runtime/state": "./dist/_internal/workspace/internal/runtime/state.js",
51
- "./_internal/workspace/runtime": "./dist/_internal/workspace/runtime.js",
52
- "./agent": "./dist/agent.js",
53
- "./agent/capabilities": "./dist/agent/capabilities.js",
54
- "./agent/channels": "./dist/agent/channels.js",
55
- "./agent/cloudflare": "./dist/agent/cloudflare.js",
56
- "./agent/eval": "./dist/agent/eval.js",
57
- "./agent/harness/claude-code": "./dist/agent/harness/claude-code.js",
58
- "./agent/harness/codex": "./dist/agent/harness/codex.js",
59
- "./agent/harness/local-sandbox": "./dist/agent/harness/local-sandbox.js",
60
- "./agent/server": "./dist/agent/server.js",
61
- "./agent/state/sqlite": "./dist/agent/state/sqlite.js",
62
- "./auth": "./dist/auth.js",
63
- "./auth/agent": "./dist/auth/agent.js",
64
- "./auth/server": "./dist/auth/server.js",
65
- "./blob": "./dist/blob.js",
66
- "./blob/content-type": "./dist/blob/content-type.js",
67
- "./box": "./dist/box.js",
68
- "./box/cloudflare": "./dist/box/cloudflare.js",
69
- "./box/crabbox": "./dist/box/crabbox.js",
70
- "./box/vercel": "./dist/box/vercel.js",
71
- "./browser": "./dist/browser.js",
72
- "./browser/controllers/cdp": "./dist/browser/controllers/cdp.js",
73
- "./browser/controllers/playwright": "./dist/browser/controllers/playwright.js",
74
- "./browser/providers/cloudflare": "./dist/browser/providers/cloudflare.js",
75
- "./browser/providers/local": "./dist/browser/providers/local.js",
76
- "./database": "./dist/database.js",
77
- "./database/drizzle": "./dist/database/drizzle.js",
78
- "./email": "./dist/email.js",
79
- "./email/drivers/smtp": "./dist/email/drivers/smtp.js",
80
- "./email/markdown": "./dist/email/markdown.js",
81
- "./email/server": "./dist/email/server.js",
82
- "./env": "./dist/env.js",
83
- "./env/presets": "./dist/env/presets.js",
84
- "./env/schema": "./dist/env/schema.js",
85
- "./env/secret": "./dist/env/secret.js",
86
- "./env/server": "./dist/env/server.js",
87
- "./kv": "./dist/kv.js",
88
- "./markdown-template": "./dist/markdown-template.js",
89
- "./queue": "./dist/queue.js",
90
- "./rate-limit": "./dist/rate-limit.js",
91
- "./runtime": "./dist/runtime.js",
92
- "./sandbox": "./dist/sandbox.js",
93
- "./schedule": "./dist/schedule.js",
94
- "./schedule/runtime": "./dist/schedule/runtime.js",
95
- "./schedule/runtime/driver": "./dist/schedule/runtime/driver.js",
96
- "./schedule/runtime/process": "./dist/schedule/runtime/process.js",
97
- "./shell": "./dist/shell.js",
98
- "./shell/providers/cloudflare": "./dist/shell/providers/cloudflare.js",
99
- "./shell/providers/just-bash": "./dist/shell/providers/just-bash.js",
100
- "./shell/workspace": "./dist/shell/workspace.js",
101
- "./source": "./dist/source.js",
102
- "./workflow": "./dist/workflow.js",
103
- "./workspace": "./dist/workspace.js",
104
- "./workspace/cloudflare": "./dist/workspace/cloudflare.js",
105
- "./workspace/collections": "./dist/workspace/collections.js",
106
- "./workspace/collections/client": "./dist/workspace/collections/client.js",
107
- "./workspace/loader": "./dist/workspace/loader.js",
108
- "./workspace/publish": "./dist/workspace/publish.js",
109
- "./workspace/runtime": "./dist/workspace/runtime.js",
110
- "./workspace/server": "./dist/workspace/server.js",
111
- "./package.json": "./package.json",
112
- "./tsconfig": "./tsconfig.json"
113
- };
114
- //#endregion
115
- //#region ../internal/src/build/deployment-plan-output.ts
116
- async function finalizeDeploymentPlanOutput(options) {
117
- const nitroOutputRoot = resolve(options.rootDir, options.outputDir ?? options.plan.output.directory);
118
- const outputRoot = options.plan.preset === "netlify" && basename(nitroOutputRoot) === "functions-internal" ? dirname(nitroOutputRoot) : nitroOutputRoot;
119
- const entry = options.plan.output.entry ? resolve(outputRoot, options.plan.output.entry) : void 0;
120
- if (entry) try {
121
- await access(entry);
122
- } catch (error) {
123
- if (error.code !== "ENOENT") throw error;
124
- throw new Error("[vitehub] The " + JSON.stringify(options.plan.preset) + " preset did not emit its required entry: " + entry + ".");
125
- }
126
- const manifest = {
127
- host: options.plan.host,
128
- ...options.identity ? { identity: options.identity } : {},
129
- output: {
130
- ...options.plan.output,
131
- directory: relative(options.rootDir, outputRoot).replaceAll("\\", "/") || "."
132
- },
133
- preset: options.plan.preset,
134
- runtime: options.plan.runtime,
135
- services: options.services ?? options.plan.services
136
- };
137
- const manifestPath = resolve(outputRoot, "deployment.json");
138
- await mkdir(dirname(manifestPath), { recursive: true });
139
- await writeFile(manifestPath, JSON.stringify(manifest, null, 2) + "\n", "utf8");
140
- }
141
- //#endregion
142
- //#region ../internal/src/build/deno-runtime-packages.ts
143
- const builtinModuleNames = new Set([...builtinModules, ...builtinModules.map((name) => `node:${name}`)]);
144
- const runtimeExtensions = new Set([
145
- ".cjs",
146
- ".js",
147
- ".mjs",
148
- ".ts"
149
- ]);
150
- const denoRuntimeTargets = [{
151
- cpu: "arm64",
152
- libc: "glibc",
153
- os: "linux"
154
- }, {
155
- cpu: "x64",
156
- libc: "glibc",
157
- os: "linux"
158
- }];
159
- function packageNameFromSpecifier(specifier) {
160
- if (!specifier || specifier.startsWith(".") || specifier.startsWith("/") || specifier.startsWith("#")) return;
161
- if (builtinModuleNames.has(specifier) || specifier.includes(":")) return;
162
- const parts = specifier.split("/");
163
- return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
164
- }
165
- function collectBundledPackages(source) {
166
- const packages = /* @__PURE__ */ new Map();
167
- for (const match of source.matchAll(/(?:^|[\s"'`(])((?:[A-Za-z]:)?[^\s"'`()]*?node_modules[/\\](?:\.pnpm[/\\][^/\\]+[/\\]node_modules[/\\])?((?:@[^/\\]+[/\\])?[^/\\\s"'`()]+))/gm)) {
168
- const name = packageNameFromSpecifier(match[2].replaceAll("\\", "/"));
169
- if (name) packages.set(name, match[1]);
170
- }
171
- return packages;
172
- }
173
- function collectImportedPackageNames(source) {
174
- const names = /* @__PURE__ */ new Set();
175
- const executableSource = maskInertImportText(source);
176
- for (const pattern of [
177
- /(?:^|;)\s*(?:import|export)\s*["']([^"']+)["']/gm,
178
- /(?:^|;)\s*(?:import|export)[^;\n]*?\bfrom\s*["']([^"']+)["']/gm,
179
- /\brequire\s*\(\s*["']([^"']+)["']\s*\)/g,
180
- /\bimport\s*\(\s*["']([^"']+)["']\s*\)/g
181
- ]) for (const match of executableSource.matchAll(pattern)) {
182
- const name = packageNameFromSpecifier(match[1]);
183
- if (name) names.add(name);
184
- }
185
- return names;
186
- }
187
- function maskInertImportText(source) {
188
- let output = "";
189
- for (let index = 0; index < source.length;) {
190
- const character = source[index];
191
- const next = source[index + 1];
192
- if (character === "/" && next === "/") {
193
- const end = source.indexOf("\n", index);
194
- const length = (end === -1 ? source.length : end) - index;
195
- output += " ".repeat(length);
196
- index += length;
197
- continue;
198
- }
199
- if (character === "/" && next === "*") {
200
- const closing = source.indexOf("*/", index + 2);
201
- const length = (closing === -1 ? source.length : closing + 2) - index;
202
- output += source.slice(index, index + length).replace(/[^\n]/g, " ");
203
- index += length;
204
- continue;
205
- }
206
- if (character === "\"" || character === "'" || character === "`") {
207
- const prefix = output.slice(Math.max(0, output.length - 120));
208
- const keep = character !== "`" && /(?:\b(?:from|import|export)|\b(?:import|require)\s*\()\s*$/.test(prefix);
209
- let end = index + 1;
210
- while (end < source.length) if (source[end] === "\\") end += 2;
211
- else if (source[end++] === character) break;
212
- const literal = source.slice(index, end);
213
- output += keep ? literal : literal.replace(/[^\n]/g, " ");
214
- index = end;
215
- continue;
216
- }
217
- output += character;
218
- index++;
219
- }
220
- return output;
221
- }
222
- async function copyRuntimePackagesToNodeModules(options) {
223
- const copied = /* @__PURE__ */ new Set();
224
- const staged = /* @__PURE__ */ new Set();
225
- const resolver = createRequire(join(options.rootDir, "package.json"));
226
- for (const runtimePackage of options.packages) await copyPackageToNodeModules(runtimePackage.name, resolver, options.rootDir, options.outputNodeModules, copied, staged, runtimePackage);
227
- }
228
- async function copyPackageToNodeModules(name, resolver, fromDir, outputNodeModules, copied, staged, options) {
229
- let packageJsonPath = options.packageJsonPath;
230
- if (packageJsonPath) try {
231
- await access(packageJsonPath);
232
- } catch (error) {
233
- if (error.code !== "ENOENT") throw error;
234
- packageJsonPath = void 0;
235
- }
236
- packageJsonPath ??= await resolvePackageJson(name, resolver, fromDir);
237
- if (!packageJsonPath) {
238
- if (options.optional) return;
239
- throw new Error("Could not resolve package.json for " + name + ".");
240
- }
241
- const resolvedPackageJsonPath = await realpath(packageJsonPath);
242
- const packageDir = dirname(resolvedPackageJsonPath);
243
- const packageJson = JSON.parse(await readFile(resolvedPackageJsonPath, "utf8"));
244
- if (options.onlyIfOptionalDependencies && !Object.keys(packageJson.optionalDependencies || {}).length) return;
245
- const packageKey = name + "\0" + resolvedPackageJsonPath;
246
- if (copied.has(packageKey)) return;
247
- const targetDir = join(outputNodeModules, ...name.split("/"));
248
- const stagedKey = packageKey + "\0" + targetDir;
249
- if (staged.has(stagedKey)) return;
250
- copied.add(packageKey);
251
- await rm(targetDir, {
252
- force: true,
253
- recursive: true
254
- });
255
- await cp(packageDir, targetDir, {
256
- dereference: true,
257
- filter: (source) => relative(packageDir, source).split(sep)[0] !== "node_modules",
258
- recursive: true
259
- });
260
- staged.add(stagedKey);
261
- const packageRequire = createRequire(resolvedPackageJsonPath);
262
- const optionalDependencyNames = new Set(Object.keys(packageJson.optionalDependencies || {}));
263
- const dependencyNames = new Set(Object.keys(packageJson.dependencies || {}).filter((dependencyName) => !optionalDependencyNames.has(dependencyName)));
264
- if (options.includeOptionalDependencies) for (const dependencyName of Object.keys(packageJson.optionalDependencies || {})) {
265
- const dependencyPackageJsonPath = await resolvePackageJson(dependencyName, packageRequire, packageDir);
266
- if (!dependencyPackageJsonPath) continue;
267
- if (supportsDenoRuntime(JSON.parse(await readFile(dependencyPackageJsonPath, "utf8")))) dependencyNames.add(dependencyName);
268
- }
269
- if (options.includePeerDependencies) {
270
- for (const dependencyName of Object.keys(packageJson.peerDependencies || {})) if (!packageJson.peerDependenciesMeta?.[dependencyName]?.optional) dependencyNames.add(dependencyName);
271
- }
272
- for (const dependencyName of dependencyNames) await copyPackageToNodeModules(dependencyName, packageRequire, packageDir, options.hoistOptionalDependencies && packageJson.optionalDependencies?.[dependencyName] ? outputNodeModules : join(targetDir, "node_modules"), copied, staged, {
273
- hoistOptionalDependencies: options.hoistOptionalDependencies && Boolean(packageJson.optionalDependencies?.[dependencyName]),
274
- includeOptionalDependencies: options.includeOptionalDependencies,
275
- includePeerDependencies: options.includePeerDependencies,
276
- name: dependencyName,
277
- optional: Boolean(packageJson.optionalDependencies?.[dependencyName])
278
- });
279
- copied.delete(packageKey);
280
- }
281
- function supportsDenoRuntime(packageJson) {
282
- return denoRuntimeTargets.some((target) => supportsConstraint(packageJson.os, target.os) && supportsConstraint(packageJson.cpu, target.cpu) && supportsConstraint(packageJson.libc, target.libc));
283
- }
284
- function supportsConstraint(values, target) {
285
- if (!values?.length) return true;
286
- if (values.length === 1 && values[0] === "any") return true;
287
- if (values.includes(`!${target}`)) return false;
288
- const included = values.filter((value) => !value.startsWith("!"));
289
- return included.length === 0 || included.includes(target);
290
- }
291
- async function resolvePackageJson(name, resolver, fromDir) {
292
- try {
293
- return resolver.resolve(name + "/package.json");
294
- } catch (error) {
295
- if (!isPackageResolutionMiss(error)) throw error;
296
- }
297
- try {
298
- let current = dirname(resolver.resolve(name));
299
- while (current !== dirname(current)) {
300
- const candidate = join(current, "package.json");
301
- try {
302
- await access(candidate);
303
- if (JSON.parse(await readFile(candidate, "utf8")).name === name) return candidate;
304
- } catch (error) {
305
- if (error.code !== "ENOENT") throw error;
306
- }
307
- current = dirname(current);
308
- }
309
- } catch (error) {
310
- if (!isPackageResolutionMiss(error)) throw error;
311
- }
312
- let current = fromDir;
313
- while (current !== dirname(current)) {
314
- const candidate = join(current, "node_modules", ...name.split("/"), "package.json");
315
- try {
316
- await access(candidate);
317
- return candidate;
318
- } catch (error) {
319
- if (error.code !== "ENOENT") throw error;
320
- }
321
- current = dirname(current);
322
- }
323
- }
324
- function isPackageResolutionMiss(error) {
325
- const code = error?.code;
326
- return code === "MODULE_NOT_FOUND" || code === "ERR_MODULE_NOT_FOUND" || code === "ERR_PACKAGE_PATH_NOT_EXPORTED";
327
- }
328
- async function runtimeSourceFiles(serverDir) {
329
- return (await readdir(serverDir, {
330
- recursive: true,
331
- withFileTypes: true
332
- })).filter((entry) => entry.isFile() && runtimeExtensions.has(extname(entry.name))).map((entry) => resolve(entry.parentPath, entry.name));
333
- }
334
- async function readRuntimePackages(serverDir, rootDir) {
335
- const packages = /* @__PURE__ */ new Map();
336
- for (const file of await runtimeSourceFiles(serverDir)) {
337
- const source = await readFile(file, "utf8");
338
- for (const [name, packagePath] of collectBundledPackages(source)) {
339
- const existing = packages.get(name);
340
- packages.set(name, {
341
- ...existing,
342
- hoistOptionalDependencies: true,
343
- includeOptionalDependencies: true,
344
- includePeerDependencies: true,
345
- name,
346
- onlyIfOptionalDependencies: existing?.onlyIfOptionalDependencies ?? true,
347
- optional: existing?.optional ?? true,
348
- packageJsonPath: resolve(isAbsolute(packagePath) ? packagePath : resolve(rootDir, packagePath), "package.json")
349
- });
350
- }
351
- for (const name of collectImportedPackageNames(source)) packages.set(name, {
352
- ...packages.get(name),
353
- includeOptionalDependencies: true,
354
- includePeerDependencies: true,
355
- name,
356
- onlyIfOptionalDependencies: false,
357
- optional: false
358
- });
359
- }
360
- return [...packages.values()].sort((a, b) => a.name.localeCompare(b.name));
361
- }
362
- function denoDeployRunnerSource(deploymentName) {
363
- return `import { spawn } from "node:child_process"
364
- import { access, cp, mkdtemp, realpath, rm } from "node:fs/promises"
365
- import { tmpdir } from "node:os"
366
- import { dirname, isAbsolute, join, relative, resolve } from "node:path"
367
- import { fileURLToPath } from "node:url"
368
-
369
- const organization = process.env.DENO_DEPLOY_ORG
370
- const app = process.env.DENO_DEPLOY_APP || process.env.VITEHUB_DEPLOYMENT_NAME || ${JSON.stringify(deploymentName)}
371
- const region = process.env.DENO_DEPLOY_REGION || "global"
372
-
373
- if (!organization || !app) {
374
- throw new Error("DENO_DEPLOY_ORG and DENO_DEPLOY_APP (or VITEHUB_DEPLOYMENT_NAME) are required.")
375
- }
376
-
377
- let activeChild
378
-
379
- function run(args, cwd) {
380
- return new Promise((resolve, reject) => {
381
- const child = spawn("deno", args, { cwd, stdio: "inherit" })
382
- activeChild = child
383
- child.on("error", reject)
384
- child.on("exit", (code, signal) => {
385
- activeChild = undefined
386
- resolve({ code, signal })
387
- })
388
- })
389
- }
390
-
391
- async function enclosingGitRoot(path) {
392
- let current = resolve(path)
393
- while (true) {
394
- try {
395
- await access(join(current, ".git"))
396
- return current
397
- } catch (error) {
398
- if (error?.code !== "ENOENT") throw error
399
- }
400
- const parent = dirname(current)
401
- if (parent === current) return
402
- current = parent
403
- }
404
- }
405
-
406
- function contains(parent, child) {
407
- const path = relative(parent, child)
408
- return path === "" || (!path.startsWith("..") && !isAbsolute(path))
409
- }
410
-
411
- const sourceRoot = await realpath(fileURLToPath(new URL(".", import.meta.url)))
412
- const uploadRoot = await realpath(await mkdtemp(join(tmpdir(), "vitehub-deno-deploy-")))
413
- const signals = ["SIGINT", "SIGTERM"]
414
- const handleSignal = (signal) => {
415
- activeChild?.kill(signal)
416
- void rm(uploadRoot, { force: true, recursive: true }).finally(() => {
417
- process.kill(process.pid, signal)
418
- })
419
- }
420
- for (const signal of signals) process.once(signal, handleSignal)
421
-
422
- try {
423
- if (contains(sourceRoot, uploadRoot) || await enclosingGitRoot(uploadRoot)) {
424
- throw new Error("Deno deployment staging must be outside the generated output and any enclosing Git repository. Set TMPDIR to an external directory.")
425
- }
426
- await cp(sourceRoot, uploadRoot, { recursive: true })
427
-
428
- const common = ["--allow-node-modules", "--org", organization, "--app", app]
429
- const creation = await run(["deploy", "create", ".", "--source", "local", "--do-not-use-detected-build-config", "--runtime-mode", "dynamic", "--entrypoint", "server/index.mjs", "--working-directory", ".", "--region", region, ...common], uploadRoot)
430
- if (creation.code !== 0) {
431
- const deployment = await run(["deploy", ".", "--prod", ...common], uploadRoot)
432
- if (deployment.code !== 0) {
433
- throw new Error("deno deploy exited with " + (deployment.signal || "code " + deployment.code))
434
- }
435
- }
436
- } finally {
437
- for (const signal of signals) process.off(signal, handleSignal)
438
- await rm(uploadRoot, { force: true, recursive: true })
439
- }
440
- `;
441
- }
442
- async function finalizeDenoDeploymentOutput(options) {
443
- const outputDir = resolve(options.rootDir, options.outputDir ?? ".output");
444
- const serverDir = join(outputDir, "server");
445
- const packages = await readRuntimePackages(serverDir, options.rootDir);
446
- await copyRuntimePackagesToNodeModules({
447
- outputNodeModules: join(outputDir, "node_modules"),
448
- packages,
449
- rootDir: options.rootDir
450
- });
451
- const denoConfig = {
452
- nodeModulesDir: "manual",
453
- tasks: { start: "deno run -A ./server/index.mjs" }
454
- };
455
- await writeFile(join(serverDir, "index.ts"), "await import(\"./index.\" + \"mjs\")\n", "utf8");
456
- await writeFile(join(outputDir, "deno.json"), `${JSON.stringify(denoConfig, null, 2)}\n`, "utf8");
457
- await writeFile(join(outputDir, "deploy.mjs"), denoDeployRunnerSource(options.deploymentName), "utf8");
458
- }
459
- //#endregion
460
- //#region ../internal/src/deployment.ts
461
- const unsupported = (reason) => ({
462
- reason,
463
- supported: false
464
- });
465
- const plans = {
466
- cloudflare: {
467
- host: "cloudflare",
468
- nitroPreset: "cloudflare-module",
469
- output: {
470
- directory: ".output",
471
- entry: "server/index.mjs",
472
- packaging: "none"
473
- },
474
- preset: "cloudflare",
475
- runtime: "workerd",
476
- services: {
477
- blob: {
478
- adapter: "cloudflare-r2",
479
- guarantee: "native",
480
- supported: true
481
- },
482
- queue: {
483
- adapter: "cloudflare",
484
- guarantee: "native",
485
- supported: true
486
- },
487
- rateLimit: {
488
- adapter: "cloudflare",
489
- guarantee: "native",
490
- supported: true
491
- },
492
- sandbox: {
493
- adapter: "cloudflare",
494
- guarantee: "native",
495
- supported: true
496
- }
497
- }
498
- },
499
- deno: {
500
- host: "deno-deploy",
501
- nitroPreset: "deno-deploy",
502
- output: {
503
- directory: ".output",
504
- entry: "server/index.mjs",
505
- packaging: "deno-node-modules"
506
- },
507
- preset: "deno",
508
- runtime: "deno",
509
- services: {
510
- blob: unsupported("Deno Deploy has no built-in durable Blob Store with ViteHub's object-storage contract."),
511
- queue: unsupported("Deno Deploy has no built-in Queue Provider with ViteHub's delivery contract."),
512
- rateLimit: unsupported("Deno Deploy has no built-in distributed Rate Limit driver."),
513
- sandbox: unsupported("Deno Deploy has no built-in isolated Sandbox Provider.")
514
- }
515
- },
516
- netlify: {
517
- host: "netlify",
518
- nitroPreset: "netlify",
519
- output: {
520
- directory: ".netlify",
521
- entry: "functions-internal/server/server.mjs",
522
- packaging: "none"
523
- },
524
- preset: "netlify",
525
- runtime: "node",
526
- services: {
527
- blob: {
528
- adapter: "netlify-blobs",
529
- guarantee: "native",
530
- supported: true
531
- },
532
- queue: unsupported("Netlify has no built-in Queue Provider with ViteHub's delivery contract."),
533
- rateLimit: unsupported("Netlify has no built-in distributed Rate Limit driver."),
534
- sandbox: unsupported("Netlify has no built-in isolated Sandbox Provider.")
535
- }
536
- },
537
- node: {
538
- host: "self-hosted",
539
- nitroPreset: "node-server",
540
- output: {
541
- directory: ".output",
542
- entry: "server/index.mjs",
543
- packaging: "none"
544
- },
545
- preset: "node",
546
- runtime: "node",
547
- services: {
548
- blob: {
549
- adapter: "fs",
550
- guarantee: "single-host",
551
- supported: true
552
- },
553
- queue: unsupported("The Node preset has no built-in durable Queue Provider."),
554
- rateLimit: {
555
- adapter: "memory",
556
- guarantee: "process-local",
557
- supported: true
558
- },
559
- sandbox: unsupported("The Node preset has no built-in isolated Sandbox Provider.")
560
- }
561
- },
562
- vercel: {
563
- host: "vercel",
564
- nitroPreset: "vercel",
565
- output: {
566
- directory: ".vercel/output",
567
- entry: "functions/__server.func/index.mjs",
568
- packaging: "none"
569
- },
570
- preset: "vercel",
571
- runtime: "node",
572
- services: {
573
- blob: {
574
- adapter: "vercel-blob",
575
- guarantee: "native",
576
- supported: true
577
- },
578
- queue: {
579
- adapter: "vercel",
580
- guarantee: "native",
581
- supported: true
582
- },
583
- rateLimit: unsupported("Vercel has no built-in distributed Rate Limit driver."),
584
- sandbox: {
585
- adapter: "vercel",
586
- guarantee: "native",
587
- supported: true
588
- }
589
- }
590
- }
591
- };
592
- function resolveDeploymentPlan(preset) {
593
- const plan = plans[preset];
594
- if (!plan) throw new TypeError(`Unknown ViteHub deployment preset: ${JSON.stringify(preset)}.`);
595
- return plan;
596
- }
597
- function assertDeploymentService(plan, service) {
598
- const policy = plan.services[service];
599
- if (policy.supported) return;
600
- throw new Error(`[vitehub] The ${JSON.stringify(plan.preset)} preset cannot provide ${service}. ${policy.reason} Configure an explicit portable implementation through the owner package or disable this capability.`);
601
- }
602
- function deploymentPresetFromNitro(value) {
603
- const normalized = value?.trim().toLowerCase().replaceAll("_", "-");
604
- if (!normalized) return;
605
- if (normalized.startsWith("cloudflare")) return "cloudflare";
606
- if (normalized.startsWith("deno")) return "deno";
607
- if (normalized.startsWith("netlify")) return "netlify";
608
- if (normalized === "node" || normalized.startsWith("node-")) return "node";
609
- if (normalized.startsWith("vercel")) return "vercel";
610
- }
611
- //#endregion
612
- //#region ../internal/src/build/vite.ts
613
- const projectRootDirectoryMarkers = [
614
- ["server", "agents"],
615
- ["server", "schedules"],
616
- ["server", "templates"],
617
- ["server", "workspaces"]
618
- ];
619
- const projectRootDefinitionFileMarkers = [
620
- ".ts",
621
- ".mts",
622
- ".cts",
623
- ".js",
624
- ".mjs",
625
- ".cjs"
626
- ].flatMap((extension) => [["server", `email${extension}`], [`server.email${extension}`]]);
627
- const projectRootFileMarkers = [["package.json"]];
628
- function resolveViteHubProjectRoot(root, options = {}) {
629
- const resolvedRoot = resolve(root);
630
- if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
631
- if (basename(resolvedRoot) === "app") {
632
- const parent = dirname(resolvedRoot);
633
- if (hasProjectRootDirectoryMarker(parent) || hasProjectRootDefinitionFileMarker(parent)) return parent;
634
- }
635
- let current = resolvedRoot;
636
- while (true) {
637
- if (hasProjectRootMarker(current)) return current;
638
- const parent = dirname(current);
639
- if (parent === current) return resolvedRoot;
640
- current = parent;
641
- }
642
- }
643
- function hasProjectRootDirectoryMarker(root) {
644
- for (const marker of projectRootDirectoryMarkers) try {
645
- if (statSync(resolve(root, ...marker)).isDirectory()) return true;
646
- } catch (error) {
647
- if (error.code !== "ENOENT") throw error;
648
- }
649
- return false;
650
- }
651
- function hasProjectRootMarker(root) {
652
- if (hasProjectRootDirectoryMarker(root)) return true;
653
- if (hasProjectRootDefinitionFileMarker(root)) return true;
654
- for (const marker of projectRootFileMarkers) try {
655
- if (statSync(resolve(root, ...marker)).isFile()) return true;
656
- } catch (error) {
657
- if (error.code !== "ENOENT") throw error;
658
- }
659
- return false;
660
- }
661
- function hasProjectRootDefinitionFileMarker(root) {
662
- for (const marker of projectRootDefinitionFileMarkers) try {
663
- if (statSync(resolve(root, ...marker)).isFile()) return true;
664
- } catch (error) {
665
- if (error.code !== "ENOENT") throw error;
666
- }
667
- return false;
668
- }
669
- //#endregion
670
- //#region src/internal/types.ts
671
- const viteHubTypesEntry = ".vitehub/types.d.ts";
672
- async function collectGeneratedTypeFiles(directory, root = directory) {
673
- let entries;
674
- try {
675
- entries = await readdir(directory, { withFileTypes: true });
676
- } catch (error) {
677
- if (error.code === "ENOENT") return [];
678
- throw error;
679
- }
680
- const files = [];
681
- for (const entry of entries) {
682
- const path = join(directory, entry.name);
683
- if (entry.isDirectory()) files.push(...await collectGeneratedTypeFiles(path, root));
684
- else if (entry.isFile() && entry.name.endsWith(".d.ts")) {
685
- const generatedPath = relative(root, path).replaceAll("\\", "/");
686
- if (generatedPath !== "types.d.ts") files.push(generatedPath);
687
- }
688
- }
689
- return files;
690
- }
691
- async function writeFileIfChanged(path, contents) {
692
- let current;
693
- try {
694
- current = await readFile(path, "utf8");
695
- } catch (error) {
696
- if (error.code !== "ENOENT") throw error;
697
- }
698
- if (current === contents) return;
699
- await mkdir(dirname(path), { recursive: true });
700
- await writeFile(path, contents, "utf8");
701
- }
702
- async function writeViteHubTypes(root) {
703
- const references = (await collectGeneratedTypeFiles(resolve(root, ".vitehub"))).sort().map((file) => `/// <reference path="./${file}" />`).join("\n");
704
- await writeFileIfChanged(resolve(root, viteHubTypesEntry), `${references}${references ? "\n\n" : ""}export {}\n`);
705
- }
706
- function viteHubTypesPlugin() {
707
- let projectRoot;
708
- const refreshGeneratedTypes = async () => {
709
- if (projectRoot) await writeViteHubTypes(projectRoot);
710
- };
711
- return {
712
- name: "vite-hub/types",
713
- enforce: "post",
714
- async configResolved(config) {
715
- projectRoot = resolveViteHubProjectRoot(config.root);
716
- await refreshGeneratedTypes();
717
- },
718
- buildStart: refreshGeneratedTypes,
719
- buildEnd: refreshGeneratedTypes,
720
- vitehub: { cli: { namespaces: [{
721
- description: "Generate ViteHub TypeScript declarations.",
722
- features: [{
723
- description: "Prepare generated declarations for editors and type checking.",
724
- name: "prepare",
725
- async run(_args, context) {
726
- await writeViteHubTypes(projectRoot || resolveViteHubProjectRoot(context.rootDir));
727
- context.stdout.write(`types: prepared ${viteHubTypesEntry}\n`);
728
- },
729
- usage: "vitehub types prepare"
730
- }],
731
- name: "types"
732
- }] } }
733
- };
734
- }
735
- //#endregion
736
- //#region src/index.ts
737
- const generatedOwnerPackageNames = Object.entries({
738
- "@vite-hub/agent": true,
739
- "@vite-hub/auth": true,
740
- "@vite-hub/blob": true,
741
- "@vite-hub/browser": true,
742
- "@vite-hub/box": true,
743
- "@vite-hub/cli": false,
744
- "@vite-hub/database": true,
745
- "@vite-hub/email": true,
746
- "@vite-hub/env": true,
747
- "@vite-hub/kv": true,
748
- "@vite-hub/markdown-template": true,
749
- "@vite-hub/queue": true,
750
- "@vite-hub/rate-limit": true,
751
- "@vite-hub/runtime": true,
752
- "@vite-hub/sandbox": true,
753
- "@vite-hub/schedule": true,
754
- "@vite-hub/shell": true,
755
- "@vite-hub/source": true,
756
- "@vite-hub/workflow": true,
757
- "@vite-hub/workspace": true
758
- }).filter(([, allowed]) => allowed).map(([name]) => name);
759
- const frameworkVirtualImporters = new Set([
760
- "\0#vitehub/auth/server",
761
- "\0#vitehub/env/server",
762
- "\0#vitehub/schedule/registry",
763
- "\0#vitehub/templates",
764
- "\0virtual:vitehub-agent-cloudflare-state-exports"
765
- ]);
766
- const frameworkPackageName = "vite-hub";
767
- const generatedImportBase = "vite-hub/_internal";
768
- const upstashDriverSpecifier = "@vite-hub/kv/runtime/upstash-driver";
769
- const disabledUpstashDriver = fileURLToPath(import.meta.resolve(`${generatedImportBase}/kv/runtime/disabled-upstash`));
770
- function frameworkWorkspaceDependencyRuntimeImports(sandbox) {
771
- return {
772
- ...sandbox ? {
773
- sandbox: "vite-hub/sandbox",
774
- sandboxRuntimeState: `${generatedImportBase}/sandbox/runtime/state`
775
- } : {},
776
- shellWorkspace: "vite-hub/shell/workspace"
777
- };
778
- }
779
- const frameworkProviderImportAliases = Object.fromEntries(Object.entries(exports).filter(([subpath, target]) => subpath.startsWith("./") && target.endsWith(".js")).map(([subpath]) => {
780
- const specifier = `${frameworkPackageName}/${subpath.slice(2)}`;
781
- return [specifier, fileURLToPath(import.meta.resolve(specifier))];
782
- }).sort(([left], [right]) => right.length - left.length));
783
- function isGeneratedImporter(importer) {
784
- const normalized = importer?.replace(/\\/g, "/");
785
- return Boolean(normalized && (/(?:^|\/)\.vitehub(?:\/|$)/.test(normalized) || frameworkVirtualImporters.has(normalized)));
786
- }
787
- function hasUpstashStore(kv) {
788
- if (!kv) return false;
789
- return Object.values(kv.stores || { default: kv.store }).some((store) => store.driver === "upstash");
790
- }
791
- function configureProviderOptionalImportAliases(aliases, options, configuredKV) {
792
- if (hasUpstashStore(options.kv ? resolveKVViteConfig(configuredKV ?? (options.kv === true ? void 0 : options.kv)).kv : false)) delete aliases[upstashDriverSpecifier];
793
- else aliases[upstashDriverSpecifier] = disabledUpstashDriver;
794
- }
795
- function frameworkDependencyResolver(options, providerImportAliases, blobEnabled, presetKVOptions) {
796
- return {
797
- name: "vite-hub/dependencies",
798
- enforce: "pre",
799
- config() {
800
- const aliases = { ...frameworkProviderImportAliases };
801
- if (!blobEnabled) delete aliases["vite-hub/blob"];
802
- return { resolve: { alias: aliases } };
803
- },
804
- configResolved(config) {
805
- configureProviderOptionalImportAliases(providerImportAliases, options, config.kv ?? presetKVOptions);
806
- },
807
- resolveId(id, importer) {
808
- if (!blobEnabled && id === "@vite-hub/blob") throw new Error("[vitehub] Blob is unavailable for this deployment preset. Configure an explicit Blob store before using Blob APIs or Agent Capabilities.");
809
- for (const specifier in providerImportAliases) {
810
- const frameworkFacade = frameworkProviderImportAliases[specifier];
811
- if (!frameworkFacade) continue;
812
- const providerFacade = providerImportAliases[specifier];
813
- if (id === frameworkFacade || providerImportAliases[id] === providerFacade) return providerFacade;
814
- }
815
- if (!isGeneratedImporter(importer)) return;
816
- const isFrameworkPackageImport = id === frameworkPackageName || id.startsWith(`${frameworkPackageName}/`);
817
- const isOwnerPackageImport = generatedOwnerPackageNames.some((name) => id === name || id.startsWith(`${name}/`));
818
- if (!isFrameworkPackageImport && !isOwnerPackageImport) return;
819
- return fileURLToPath(import.meta.resolve(id));
820
- }
821
- };
822
- }
823
- function normalizeDeploymentName(value) {
824
- return value?.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || void 0;
825
- }
826
- function cloudflareResourceScope(name) {
827
- return name.slice(0, 48).replace(/-+$/g, "");
828
- }
829
- function cloudflareR2BucketName(name) {
830
- const scoped = cloudflareResourceScope(name);
831
- return scoped.length >= 3 ? scoped : `${scoped || "app"}-blob`;
832
- }
833
- function packageName(root) {
834
- let directory = resolve(process.cwd(), root || ".");
835
- while (true) {
836
- const manifestPath = join(directory, "package.json");
837
- if (existsSync(manifestPath)) {
838
- const name = JSON.parse(readFileSync(manifestPath, "utf8")).name;
839
- if (typeof name === "string" && name.trim()) return name;
840
- }
841
- const parent = dirname(directory);
842
- if (parent === directory) return;
843
- directory = parent;
844
- }
845
- }
846
- function resolveDeploymentIdentity(root, configuredName) {
847
- const configured = normalizeDeploymentName(configuredName);
848
- if (configuredName !== void 0 && !configured) throw new Error("[vitehub] vitehub name must contain at least one letter or number.");
849
- const environmentName = process.env.VITEHUB_DEPLOYMENT_NAME;
850
- const environment = normalizeDeploymentName(environmentName);
851
- if (environmentName?.trim() && !environment) throw new Error("[vitehub] VITEHUB_DEPLOYMENT_NAME must contain at least one letter or number.");
852
- if (configured && environment && configured !== environment) throw new Error(`[vitehub] vitehub name ${JSON.stringify(configuredName)} conflicts with VITEHUB_DEPLOYMENT_NAME=${JSON.stringify(environmentName)}.`);
853
- if (configured) return {
854
- name: configured,
855
- source: "vitehub.name"
856
- };
857
- if (environment) return {
858
- name: environment,
859
- source: "VITEHUB_DEPLOYMENT_NAME"
860
- };
861
- const manifestName = normalizeDeploymentName(packageName(root));
862
- if (manifestName) return {
863
- name: manifestName,
864
- source: "package.json"
865
- };
866
- return {
867
- name: normalizeDeploymentName(basename(resolve(process.cwd(), root || "."))) || "vitehub",
868
- source: "root"
869
- };
870
- }
871
- function cloneRecord(value) {
872
- return value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
873
- }
874
- function normalizeNitroPreset(value) {
875
- return value.trim().toLowerCase().replaceAll("_", "-");
876
- }
877
- function deploymentNitroModule(plan, services, identity) {
878
- return (nitro) => {
879
- nitro.hooks.hook("compiled", async () => {
880
- const outputDir = nitro.options.output.dir;
881
- const rootDir = nitro.options.rootDir;
882
- if (plan.output.packaging === "deno-node-modules") await finalizeDenoDeploymentOutput({
883
- deploymentName: identity.name,
884
- outputDir,
885
- rootDir
886
- });
887
- await finalizeDeploymentPlanOutput({
888
- identity,
889
- outputDir,
890
- plan,
891
- rootDir,
892
- services
893
- });
894
- });
895
- };
896
- }
897
- function deploymentPlugins(plan, requestedServices, blobEnabled, services, options) {
898
- return [{
899
- name: "vite-hub/deployment-preset",
900
- enforce: "pre",
901
- resolveId(source) {
902
- if (!blobEnabled && (source === "vite-hub/blob" || source === frameworkProviderImportAliases["vite-hub/blob"])) {
903
- if (!plan.services.blob.supported) assertDeploymentService(plan, "blob");
904
- throw new Error("[vitehub] Blob is disabled but the application imports " + JSON.stringify(source) + ".");
905
- }
906
- },
907
- config(config) {
908
- for (const service of requestedServices) assertDeploymentService(plan, service);
909
- const identity = resolveDeploymentIdentity(typeof config.root === "string" ? config.root : void 0, options.name);
910
- const name = identity.name;
911
- if (requestedServices.includes("queue") && plan.services.queue.supported) config.queue = {
912
- ...cloneRecord(config.queue),
913
- provider: plan.services.queue.adapter,
914
- ...plan.services.queue.adapter === "cloudflare" ? { namePrefix: `${name}-` } : {}
915
- };
916
- if (requestedServices.includes("rateLimit") && plan.services.rateLimit.supported) config.rateLimit = {
917
- ...cloneRecord(config.rateLimit),
918
- namespace: name,
919
- provider: plan.services.rateLimit.adapter
920
- };
921
- if (requestedServices.includes("sandbox") && plan.services.sandbox.supported) config.sandbox = {
922
- ...cloneRecord(config.sandbox),
923
- ...plan.services.sandbox.adapter === "cloudflare" ? { name: cloudflareResourceScope(name) + "-sandbox" } : {},
924
- provider: plan.services.sandbox.adapter
925
- };
926
- const nitro = cloneRecord(config.nitro);
927
- if (blobEnabled && plan.services.blob.supported && plan.services.blob.adapter === "cloudflare-r2") {
928
- const optionBlob = options.blob === true ? void 0 : options.blob;
929
- const configuredBlob = config.blob;
930
- if (!hasExplicitBlobStore(optionBlob) && !hasExplicitBlobStore(configuredBlob)) config.blob = presetBlobOptions(plan, {
931
- ...cloneRecord(optionBlob),
932
- ...cloneRecord(configuredBlob)
933
- }, cloudflareR2BucketName(name));
934
- }
935
- if (plan.preset === "cloudflare") {
936
- const cloudflare = cloneRecord(nitro.cloudflare);
937
- const wrangler = cloneRecord(cloudflare.wrangler);
938
- if (typeof wrangler.name !== "string") wrangler.name = cloudflareResourceScope(name);
939
- cloudflare.wrangler = wrangler;
940
- nitro.cloudflare = cloudflare;
941
- }
942
- const configuredPreset = typeof nitro.preset === "string" ? nitro.preset : void 0;
943
- if (configuredPreset && normalizeNitroPreset(configuredPreset) !== plan.nitroPreset) throw new Error("[vitehub] vitehub preset " + JSON.stringify(plan.preset) + " conflicts with nitro.preset " + JSON.stringify(configuredPreset) + ".");
944
- for (const name of ["NITRO_PRESET", "SERVER_PRESET"]) {
945
- const value = process.env[name];
946
- if (value && normalizeNitroPreset(value) !== plan.nitroPreset) throw new Error("[vitehub] vitehub preset " + JSON.stringify(plan.preset) + " conflicts with " + name + "=" + JSON.stringify(value) + ".");
947
- }
948
- const configuredHosting = process.env.VITEHUB_HOSTING;
949
- if (configuredHosting && deploymentPresetFromNitro(configuredHosting) !== plan.preset) throw new Error("[vitehub] vitehub preset " + JSON.stringify(plan.preset) + " conflicts with VITEHUB_HOSTING=" + JSON.stringify(configuredHosting) + ".");
950
- nitro.modules = [...Array.isArray(nitro.modules) ? nitro.modules : [], deploymentNitroModule(plan, services, identity)];
951
- if (plan.output.packaging === "deno-node-modules") {
952
- nitro.commands = {
953
- ...cloneRecord(nitro.commands),
954
- deploy: "node ./deploy.mjs"
955
- };
956
- const rollupConfig = cloneRecord(nitro.rollupConfig);
957
- const output = Array.isArray(rollupConfig.output) ? rollupConfig.output.map((options) => ({
958
- ...cloneRecord(options),
959
- entryFileNames: "index.mjs"
960
- })) : {
961
- ...cloneRecord(rollupConfig.output),
962
- entryFileNames: "index.mjs"
963
- };
964
- nitro.rollupConfig = {
965
- ...rollupConfig,
966
- output
967
- };
968
- }
969
- config.nitro = {
970
- ...nitro,
971
- preset: plan.nitroPreset
972
- };
973
- }
974
- }, {
975
- name: "vite-hub/deployment-output",
976
- enforce: "post",
977
- configResolved(config) {
978
- if (cloneRecord(config.nitro).preset !== plan.nitroPreset) throw new Error("[vitehub] The " + JSON.stringify(plan.preset) + " deployment plan requires Nitro preset " + JSON.stringify(plan.nitroPreset) + ".");
979
- }
980
- }];
981
- }
982
- function hasExplicitBlobStore(options) {
983
- return Boolean(options && typeof options === "object" && ("driver" in options || "stores" in options));
984
- }
985
- function presetBlobOptions(plan, options, deploymentName = "vitehub-blob") {
986
- if (hasExplicitBlobStore(options)) return options;
987
- const configured = options && typeof options === "object" ? options : {};
988
- switch (plan.services.blob.supported && plan.services.blob.adapter) {
989
- case "cloudflare-r2": return {
990
- bucketName: process.env.BLOB_BUCKET_NAME || process.env.CLOUDFLARE_R2_BUCKET_NAME || process.env.R2_BUCKET_NAME || deploymentName,
991
- ...configured,
992
- driver: "cloudflare-r2"
993
- };
994
- case "fs": return {
995
- ...configured,
996
- driver: "fs"
997
- };
998
- case "netlify-blobs": return {
999
- name: "vitehub-blob",
1000
- ...configured,
1001
- driver: "netlify-blobs"
1002
- };
1003
- case "vercel-blob": return {
1004
- ...configured,
1005
- driver: "vercel-blob"
1006
- };
1007
- default: throw new Error("[vitehub] Missing Blob adapter for deployment preset " + JSON.stringify(plan.preset) + ".");
1008
- }
1009
- }
1010
- function vitehub(options) {
1011
- if (!options || typeof options !== "object") throw new TypeError("vitehub() requires a built-in deployment preset.");
1012
- const plan = resolveDeploymentPlan(options.preset);
1013
- if (options.schedule && plan.preset === "deno") throw new Error("[vitehub] The \"deno\" preset cannot provide Schedule because its generated cron output is not part of the deployed Nitro entrypoint. Disable Schedule or compose an explicit Deno scheduling integration.");
1014
- if (options.agent && options.agent !== true && options.agent.runtime === "deno" && plan.preset === "deno") throw new Error("[vitehub] The \"deno\" preset cannot deploy the Agent Deno runtime because its generated server is outside the deployed Nitro entrypoint. Use the preset's Nitro runtime or compose an explicit Deno Agent deployment.");
1015
- if (options.browser && plan.preset !== "cloudflare") throw new Error("[vitehub] Browser currently requires the Cloudflare deployment preset.");
1016
- const sandboxEnabled = options.sandbox === true && plan.services.sandbox.supported;
1017
- const blobEnabled = Boolean(options.blob) && (plan.services.blob.supported || hasExplicitBlobStore(options.blob));
1018
- const plugins = [];
1019
- const requestedServices = [];
1020
- if (options.blob !== void 0 && options.blob !== false && !hasExplicitBlobStore(options.blob)) requestedServices.push("blob");
1021
- if (options.queue) requestedServices.push("queue");
1022
- if (options.rateLimit) requestedServices.push("rateLimit");
1023
- if (options.sandbox) requestedServices.push("sandbox");
1024
- const manifestServices = hasExplicitBlobStore(options.blob) ? {
1025
- ...plan.services,
1026
- blob: {
1027
- configured: true,
1028
- supported: true
1029
- }
1030
- } : plan.services;
1031
- plugins.push(...deploymentPlugins(plan, requestedServices, blobEnabled, manifestServices, options));
1032
- const providerImportAliases = {};
1033
- const configuredKV = options.kv && options.kv !== true ? options.kv : void 0;
1034
- const presetKV = options.kv ? resolveKVViteConfig(configuredKV, { hosting: plan.nitroPreset }).kv : false;
1035
- const presetKVOptions = presetKV && (presetKV.stores ? { stores: presetKV.stores } : presetKV.store);
1036
- configureProviderOptionalImportAliases(providerImportAliases, options, presetKVOptions || void 0);
1037
- const workspaceDependencyRuntimeImports = frameworkWorkspaceDependencyRuntimeImports(sandboxEnabled);
1038
- plugins.push(frameworkDependencyResolver(options, providerImportAliases, blobEnabled, presetKVOptions || void 0));
1039
- plugins.push(hubMarkdownTemplate({ runtimeImport: `${generatedImportBase}/markdown-template` }));
1040
- if (options.env !== false) {
1041
- const envOptions = options.env ?? {};
1042
- plugins.push(hubEnv({
1043
- ...envOptions,
1044
- runtimeImports: {
1045
- secret: "vite-hub/env/secret",
1046
- server: "vite-hub/env/server",
1047
- ...envOptions.runtimeImports
1048
- }
1049
- }));
1050
- }
1051
- if (options.auth) plugins.push(hubAuth({
1052
- ...options.auth === true ? {} : options.auth,
1053
- importBase: "vite-hub/auth"
1054
- }));
1055
- if (sandboxEnabled) {
1056
- const sandboxPolicy = plan.services.sandbox;
1057
- plugins.push(hubSandbox({
1058
- ...sandboxPolicy.supported ? { provider: sandboxPolicy.adapter } : {},
1059
- providerImportAliases,
1060
- providerImportSpecifier: "vite-hub/sandbox"
1061
- }));
1062
- }
1063
- if (options.agent) plugins.push(hubAgent({
1064
- ...options.agent === true ? {} : options.agent,
1065
- cloudflareStateImport: `${generatedImportBase}/agent/cloudflare/state`,
1066
- importBase: `${generatedImportBase}/agent`,
1067
- providerImportAliases,
1068
- runtimeCapabilityImports: {
1069
- blob: blobEnabled ? `${generatedImportBase}/blob` : false,
1070
- email: "vite-hub/email/server",
1071
- kv: `${generatedImportBase}/kv`
1072
- },
1073
- scheduleRuntimeImport: `${generatedImportBase}/schedule/runtime`,
1074
- workflowImportBase: `${generatedImportBase}/workflow`,
1075
- workspaceDependencyRuntimeImports,
1076
- workspaceImportBase: `${generatedImportBase}/workspace`
1077
- }));
1078
- if (options.browser) plugins.push(hubBrowser(options.browser === true ? void 0 : options.browser));
1079
- if (options.database) plugins.push(hubDb(options.database === true ? void 0 : options.database));
1080
- if (blobEnabled) plugins.push(hubBlob({
1081
- ...presetBlobOptions(plan, options.blob),
1082
- importBase: `${generatedImportBase}/blob`,
1083
- nitroOwned: true
1084
- }));
1085
- if (options.email) plugins.push(hubEmail(options.email === true ? void 0 : options.email));
1086
- if (options.kv) plugins.push(hubKv(presetKVOptions || void 0));
1087
- else plugins.push(hubKvOptionalPeerResolver());
1088
- if (options.queue && plan.services.queue.supported) plugins.push(hubQueue({
1089
- provider: plan.services.queue.adapter,
1090
- providerImportAliases
1091
- }));
1092
- if (options.rateLimit) {
1093
- const rateLimitPolicy = plan.services.rateLimit;
1094
- plugins.push(hubRateLimit({
1095
- provider: rateLimitPolicy.supported ? rateLimitPolicy.adapter : "memory",
1096
- importBase: `${generatedImportBase}/rate-limit`
1097
- }));
1098
- }
1099
- if (options.schedule) plugins.push(hubSchedule({
1100
- ...options.schedule === true ? {} : options.schedule,
1101
- importBase: `${generatedImportBase}/schedule`,
1102
- providerImportAliases,
1103
- runtimeImport: `${generatedImportBase}/schedule/runtime/static`
1104
- }));
1105
- if (options.workflow) plugins.push(hubWorkflow({
1106
- ...options.workflow === true ? {} : options.workflow,
1107
- agentImportBase: `${generatedImportBase}/agent`,
1108
- importBase: `${generatedImportBase}/workflow`,
1109
- providerImportAliases,
1110
- workspaceDependencyRuntimeImports,
1111
- workspaceImportBase: `${generatedImportBase}/workspace`
1112
- }));
1113
- if (options.workspace) plugins.push(hubWorkspace({
1114
- ...options.workspace === true ? {} : options.workspace,
1115
- hosting: plan.nitroPreset,
1116
- importBase: `${generatedImportBase}/workspace`
1117
- }));
1118
- plugins.push(viteHubTypesPlugin());
1119
- return plugins;
1120
- }
1121
- //#endregion
1
+ import { t as vitehub } from "./src-o6zB-soj.js";
1122
2
  export { vitehub };