@vite-hub/queue 0.0.1 → 0.0.2

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 (46) hide show
  1. package/README.md +42 -6
  2. package/dist/client-CBDT9GL9.js +93 -0
  3. package/dist/{cloudflare-D5dVqiNw.js → cloudflare-GosJefIK.js} +5 -8
  4. package/dist/{cloudflare-CTdH2u_E.js → cloudflare-client-w5vphoNn.js} +34 -42
  5. package/dist/cloudflare-resource-name-R8zYQiZb.js +34 -0
  6. package/dist/cloudflare-vite-BNBVtEwG.js +92 -0
  7. package/dist/{cloudflare-vite-CRx2CsH9.d.ts → cloudflare-vite-krY8T3zM.d.ts} +3 -2
  8. package/dist/{config-CIDUZkmH.js → config-B7xkD1v0.js} +21 -3
  9. package/dist/delivery-error-glgYWC9g.js +45 -0
  10. package/dist/errors-CjuG_qr-.js +108 -0
  11. package/dist/index.d.ts +62 -24
  12. package/dist/index.js +19 -8
  13. package/dist/internal/runtime/cloudflare-client.d.ts +6 -0
  14. package/dist/internal/runtime/cloudflare-client.js +2 -0
  15. package/dist/internal/runtime/vercel-client.d.ts +6 -0
  16. package/dist/{vercel-D31zfxiW.js → internal/runtime/vercel-client.js} +46 -30
  17. package/dist/nuxt.d.ts +19 -0
  18. package/dist/nuxt.js +29 -0
  19. package/dist/runtime/cloudflare-vite.d.ts +1 -1
  20. package/dist/runtime/cloudflare-vite.js +1 -1
  21. package/dist/runtime/hosted.d.ts +1 -1
  22. package/dist/runtime/hosted.js +52 -1
  23. package/dist/runtime/state.d.ts +6 -3
  24. package/dist/runtime/state.js +2 -41
  25. package/dist/runtime/vercel-vite.d.ts +12 -5
  26. package/dist/runtime/vercel-vite.js +5 -4
  27. package/dist/state-BfUFGeC2.js +105 -0
  28. package/dist/{types-CBsyjWye.d.ts → types-CwvoMATy.d.ts} +3 -1
  29. package/dist/{vercel-BGm0G00p.js → vercel-C_4vqxcl.js} +1 -1
  30. package/dist/vercel-runtime-package-copy-B8AEFWXT.js +66 -0
  31. package/dist/vite-C6yK76Sw.js +1823 -0
  32. package/dist/vite.d.ts +90 -6
  33. package/dist/vite.js +2 -492
  34. package/package.json +42 -46
  35. package/dist/cloudflare-env-CJ6g1-Qb.js +0 -49
  36. package/dist/cloudflare-shared-Ce61GXcn.js +0 -14
  37. package/dist/cloudflare-vite-Bs67_E_Y.js +0 -66
  38. package/dist/errors-xRt0BFZK.js +0 -57
  39. package/dist/hosted-Dw9WiPNH.js +0 -136
  40. package/dist/module-Cr8pH2J_.js +0 -610
  41. package/dist/nitro.d.ts +0 -32
  42. package/dist/nitro.js +0 -2
  43. package/dist/runtime/nitro-plugin.d.ts +0 -6
  44. package/dist/runtime/nitro-plugin.js +0 -40
  45. /package/dist/{_app-Bx4e5L33.d.ts → _app-D29AwUdD.d.ts} +0 -0
  46. /package/dist/{app-BFpA3j89.js → app-BZpq2cwC.js} +0 -0
package/dist/vite.d.ts CHANGED
@@ -1,7 +1,78 @@
1
- import { m as QueueModuleOptions } from "./types-CBsyjWye.js";
2
- import { NitroModule } from "nitro/types";
1
+ import { m as QueueModuleOptions } from "./types-CwvoMATy.js";
3
2
  import { Plugin } from "vite";
4
3
 
4
+ //#region ../internal/src/provision.d.ts
5
+ type ProvisionProvider = "cloudflare" | "vercel";
6
+ interface ProvisionLogger {
7
+ log: (message: string) => void;
8
+ warn: (message: string) => void;
9
+ }
10
+ interface ProvisionContext {
11
+ env: Record<string, string | undefined>;
12
+ fetch: typeof globalThis.fetch;
13
+ logger: ProvisionLogger;
14
+ }
15
+ interface ProvisionState {
16
+ cloudflare?: Record<string, Record<string, string>>;
17
+ vercel?: Record<string, Record<string, string>>;
18
+ }
19
+ interface ProvisionResult {
20
+ ids?: ProvisionState;
21
+ }
22
+ interface ProvisionAction {
23
+ kind: string;
24
+ name: string;
25
+ exists: boolean;
26
+ apply: () => Promise<ProvisionResult>;
27
+ }
28
+ interface ProvisionStep {
29
+ id: string;
30
+ provider: ProvisionProvider;
31
+ plan: (context: ProvisionContext) => Promise<ProvisionAction[]>;
32
+ }
33
+ //#endregion
34
+ //#region ../internal/src/cli.d.ts
35
+ interface ViteHubCliStreams {
36
+ stderr: {
37
+ write: (chunk: string | Uint8Array) => unknown;
38
+ };
39
+ stdout: {
40
+ write: (chunk: string | Uint8Array) => unknown;
41
+ };
42
+ }
43
+ interface ViteHubCliSpawnResult {
44
+ exitCode: number | null;
45
+ signal?: NodeJS.Signals | null;
46
+ }
47
+ interface ViteHubCliSpawnOptions {
48
+ cwd?: string;
49
+ env?: NodeJS.ProcessEnv;
50
+ stderr?: "inherit" | "pipe";
51
+ stdout?: "inherit" | "pipe";
52
+ }
53
+ type ViteHubCliSpawn = (command: string, args: string[], options?: ViteHubCliSpawnOptions) => Promise<ViteHubCliSpawnResult>;
54
+ interface ViteHubCliContext extends ViteHubCliStreams {
55
+ cwd: string;
56
+ env: NodeJS.ProcessEnv;
57
+ rootDir: string;
58
+ spawn: ViteHubCliSpawn;
59
+ }
60
+ interface ViteHubCliFeature {
61
+ description?: string;
62
+ name: string;
63
+ run: (args: string[], context: ViteHubCliContext) => Promise<number | void> | number | void;
64
+ usage?: string;
65
+ }
66
+ interface ViteHubCliCommandNamespace {
67
+ description?: string;
68
+ features: ViteHubCliFeature[];
69
+ name: string;
70
+ }
71
+ interface ViteHubCliContributor {
72
+ namespaces: ViteHubCliCommandNamespace[];
73
+ provision?: ProvisionStep[];
74
+ }
75
+ //#endregion
5
76
  //#region src/internal/vite-build.d.ts
6
77
  interface CloudflareQueueConfigOptions {
7
78
  compatibilityDate?: string;
@@ -32,9 +103,22 @@ interface CloudflareQueueConfig {
32
103
  declare function createCloudflareQueueConfig(options?: CloudflareQueueConfigOptions): Promise<CloudflareQueueConfig>;
33
104
  //#endregion
34
105
  //#region src/vite.d.ts
35
- type QueueVitePlugin = Plugin & {
36
- nitro: NitroModule;
37
- };
106
+ interface QueueProvisionContributingPlugin {
107
+ vitehub?: {
108
+ cli?: () => Promise<ViteHubCliContributor>;
109
+ queue?: {
110
+ createNitroConfig: (options: QueueNitroConfigOptions) => Promise<Record<string, unknown>>;
111
+ };
112
+ };
113
+ }
114
+ type QueueVitePlugin = Plugin & QueueProvisionContributingPlugin;
115
+ interface QueueNitroConfigOptions {
116
+ nitro: Record<string, unknown>;
117
+ projectRoot: string;
118
+ root: string;
119
+ serverDirs?: string[];
120
+ }
121
+ declare function createQueueNitroConfig(plugin: QueueVitePlugin, options: QueueNitroConfigOptions): Promise<Record<string, unknown>>;
38
122
  declare function hubQueue(options?: QueueModuleOptions): QueueVitePlugin;
39
123
  declare module "vite" {
40
124
  interface UserConfig {
@@ -42,4 +126,4 @@ declare module "vite" {
42
126
  }
43
127
  }
44
128
  //#endregion
45
- export { type CloudflareQueueConfig, type CloudflareQueueConfigOptions, QueueVitePlugin, createCloudflareQueueConfig, hubQueue };
129
+ export { type CloudflareQueueConfig, type CloudflareQueueConfigOptions, QueueNitroConfigOptions, QueueVitePlugin, createCloudflareQueueConfig, createQueueNitroConfig, hubQueue };
package/dist/vite.js CHANGED
@@ -1,492 +1,2 @@
1
- import { t as normalizeQueueOptions } from "./config-CIDUZkmH.js";
2
- import { r as getCloudflareQueueName, t as getCloudflareQueueBindingName } from "./cloudflare-D5dVqiNw.js";
3
- import { t as getVercelQueueTopicName } from "./vercel-BGm0G00p.js";
4
- import { a as createRuntimeRegistryContents, c as ensureGeneratedDir, i as discoverQueueDefinitions, l as resolveRuntimeModule$1, n as createNodeFunctionConfig, o as computePackageDir, r as createVercelConfigJson, s as createImportPath, t as queueNitroModule, u as toGeneratedPath } from "./module-Cr8pH2J_.js";
5
- import { existsSync } from "node:fs";
6
- import { dirname, relative, resolve } from "pathe";
7
- import { cp, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
8
- import { basename as basename$1, relative as relative$1, resolve as resolve$1 } from "node:path";
9
- import { build } from "esbuild";
10
- const VITEHUB_MODES = {
11
- e2e: "e2e",
12
- blob: "blob",
13
- chat: "chat",
14
- db: "db",
15
- env: "env",
16
- kv: "kv",
17
- queue: "queue",
18
- schedule: "schedule",
19
- sandbox: "sandbox",
20
- workspace: "workspace",
21
- workflow: "workflow"
22
- };
23
- function isViteCli(argv) {
24
- return argv.some((arg) => /(?:^|[/\\])vite(?:\.[cm]?js)?$/.test(arg) || arg === "vite");
25
- }
26
- function getViteCliMode(argv = process.argv) {
27
- if (!isViteCli(argv)) return;
28
- const modes = new Set(Object.values(VITEHUB_MODES));
29
- for (let index = 0; index < argv.length; index += 1) {
30
- const arg = argv[index];
31
- const mode = arg === "--mode" || arg === "-m" ? argv[index + 1] : arg.startsWith("--mode=") ? arg.slice(7) : void 0;
32
- if (mode && modes.has(mode)) return mode;
33
- }
34
- }
35
- function getViteMode(env = process.env) {
36
- return env["VITEHUB_VITE_MODE"] ?? getViteCliMode();
37
- }
38
- //#endregion
39
- //#region ../internal/src/build/client-output.ts
40
- function hasStaticIndex(clientDir) {
41
- return existsSync(resolve(clientDir, "index.html"));
42
- }
43
- async function copyClientOutput(clientDir, targetDir) {
44
- const resolvedClientDir = resolve(clientDir);
45
- const resolvedTargetDir = resolve(targetDir);
46
- if (resolvedClientDir === resolvedTargetDir) return;
47
- await rm(resolvedTargetDir, {
48
- force: true,
49
- recursive: true
50
- });
51
- await mkdir(dirname(resolvedTargetDir), { recursive: true });
52
- const targetRelativePath = relative(resolvedClientDir, resolvedTargetDir);
53
- if (targetRelativePath && !targetRelativePath.startsWith("../")) {
54
- const [targetRootEntry] = targetRelativePath.split("/", 1);
55
- await mkdir(resolvedTargetDir, { recursive: true });
56
- await Promise.all((await readdir(resolvedClientDir)).filter((entry) => entry !== targetRootEntry).map((entry) => cp(resolve(resolvedClientDir, entry), resolve(resolvedTargetDir, entry), { recursive: true })));
57
- return;
58
- }
59
- await cp(resolvedClientDir, resolvedTargetDir, { recursive: true });
60
- }
61
- //#endregion
62
- //#region ../internal/src/build/esbuild.ts
63
- async function bundleEsmEntry(entryFile, outfile, options = {}) {
64
- const format = options.format || "esm";
65
- const platform = options.platform || "neutral";
66
- await build({
67
- alias: options.alias,
68
- banner: format === "esm" && platform === "node" ? { js: "import { createRequire as __createRequire } from \"node:module\";\nvar require = __createRequire(import.meta.url);\n" } : void 0,
69
- bundle: true,
70
- conditions: options.conditions,
71
- entryPoints: [entryFile],
72
- external: options.external,
73
- format,
74
- logLevel: "silent",
75
- outfile,
76
- platform,
77
- sourcemap: false,
78
- target: "es2022",
79
- write: true
80
- });
81
- }
82
- //#endregion
83
- //#region ../internal/src/build/user-entry.ts
84
- function toSafeAppName(rootDir) {
85
- return basename$1(rootDir).replace(/[^a-z0-9-]+/gi, "-").replace(/-+/g, "-").replace(/^-|-$/g, "").toLowerCase();
86
- }
87
- const DEFAULT_ENTRY_NAMES = [
88
- "server.ts",
89
- "server.mts",
90
- "server.js",
91
- "server.mjs",
92
- "worker.ts",
93
- "worker.mts",
94
- "worker.js",
95
- "worker.mjs"
96
- ];
97
- function resolveUserAppEntry(rootDir, options = {}) {
98
- const names = options.names ?? DEFAULT_ENTRY_NAMES;
99
- const srcSubdir = options.srcSubdir ?? "src";
100
- return names.map((name) => resolve$1(rootDir, srcSubdir, name)).find(existsSync);
101
- }
102
- //#endregion
103
- //#region ../internal/src/build/deployment-output.ts
104
- function resolveClientOutput(rootDir, clientOutDir) {
105
- const clientDir = resolve$1(rootDir, clientOutDir);
106
- return {
107
- clientDir,
108
- staticIndex: hasStaticIndex(clientDir)
109
- };
110
- }
111
- function isJsonObject(value) {
112
- return typeof value === "object" && value !== null && !Array.isArray(value);
113
- }
114
- async function readJsonObject(file) {
115
- try {
116
- const parsed = JSON.parse(await readFile(file, "utf8"));
117
- return isJsonObject(parsed) ? parsed : {};
118
- } catch (error) {
119
- if (error.code === "ENOENT") return {};
120
- throw error;
121
- }
122
- }
123
- function deleteJsonObjectKeys(value, keys) {
124
- if (!keys?.length) return value;
125
- const next = { ...value };
126
- for (const key of keys) delete next[key];
127
- return next;
128
- }
129
- async function writeMergedJsonObject(file, value, ownedKeys) {
130
- const existing = await readJsonObject(file);
131
- await writeFile(file, `${JSON.stringify({
132
- ...deleteJsonObjectKeys(existing, ownedKeys),
133
- ...value
134
- }, null, 2)}\n`, "utf8");
135
- }
136
- async function deleteJsonObjectKeysFromFile(file, keys) {
137
- if (!keys?.length) return;
138
- let existing;
139
- try {
140
- const parsed = JSON.parse(await readFile(file, "utf8"));
141
- existing = isJsonObject(parsed) ? parsed : {};
142
- } catch (error) {
143
- if (error.code === "ENOENT") return;
144
- throw error;
145
- }
146
- const next = { ...existing };
147
- let changed = false;
148
- for (const key of keys) if (key in next) {
149
- delete next[key];
150
- changed = true;
151
- }
152
- if (!changed) return;
153
- await writeFile(file, `${JSON.stringify(next, null, 2)}\n`, "utf8");
154
- }
155
- function shouldSkipViteProviderBuild(command, mode) {
156
- return command === "serve" || mode === "e2e";
157
- }
158
- function createDefaultCloudflareOutputRoot(rootDir) {
159
- return resolve$1(rootDir, "dist", toSafeAppName(rootDir));
160
- }
161
- function createDefaultCloudflareStaticOutputDir(rootDir) {
162
- return resolve$1(rootDir, "dist", "client");
163
- }
164
- function createDefaultVercelOutputRoot(rootDir) {
165
- return resolve$1(rootDir, ".vercel", "output");
166
- }
167
- async function writeCloudflareDeploymentOutput(options) {
168
- const { clientDir, staticIndex } = resolveClientOutput(options.rootDir, options.clientOutDir);
169
- const outputRoot = options.outputRoot ?? createDefaultCloudflareOutputRoot(options.rootDir);
170
- const workerOutfile = resolve$1(outputRoot, options.bundleOutfileName ?? "index.js");
171
- await mkdir(outputRoot, { recursive: true });
172
- await rm(workerOutfile, {
173
- force: true,
174
- recursive: true
175
- });
176
- await Promise.all([
177
- bundleEsmEntry(options.bundleEntry, workerOutfile, options.bundleOptions),
178
- writeMergedJsonObject(resolve$1(outputRoot, "wrangler.json"), options.wranglerConfig, options.wranglerConfigKeys),
179
- staticIndex ? copyClientOutput(clientDir, options.staticOutputDir ?? createDefaultCloudflareStaticOutputDir(options.rootDir)) : Promise.resolve()
180
- ]);
181
- }
182
- async function writeVercelDeploymentOutput(options) {
183
- const { clientDir, staticIndex } = resolveClientOutput(options.rootDir, options.clientOutDir);
184
- const outputRoot = options.outputRoot ?? createDefaultVercelOutputRoot(options.rootDir);
185
- const serverDir = resolve$1(outputRoot, "functions", options.serverFunctionName ?? "__server.func");
186
- const serverEntry = resolve$1(serverDir, "index.mjs");
187
- await rm(serverDir, {
188
- force: true,
189
- recursive: true
190
- });
191
- await mkdir(serverDir, { recursive: true });
192
- await Promise.all([
193
- bundleEsmEntry(options.bundleEntry, serverEntry, options.bundleOptions),
194
- writeFile(resolve$1(serverDir, ".vc-config.json"), `${JSON.stringify(options.functionConfig ?? createNodeFunctionConfig(), null, 2)}\n`, "utf8"),
195
- writeMergedJsonObject(resolve$1(outputRoot, "config.json"), options.config ?? createVercelConfigJson(), options.configKeys),
196
- staticIndex ? copyClientOutput(clientDir, options.staticOutputDir ?? resolve$1(outputRoot, "static")) : Promise.resolve()
197
- ]);
198
- }
199
- async function cleanupCloudflareDeploymentOutput(rootDir, cleanup) {
200
- const outputRoot = cleanup.outputRoot ?? createDefaultCloudflareOutputRoot(rootDir);
201
- const writes = [];
202
- if (cleanup.bundleOutfileName) writes.push(rm(resolve$1(outputRoot, cleanup.bundleOutfileName), {
203
- force: true,
204
- recursive: true
205
- }));
206
- writes.push(deleteJsonObjectKeysFromFile(resolve$1(outputRoot, "wrangler.json"), cleanup.wranglerConfigKeys));
207
- await Promise.all(writes);
208
- }
209
- async function cleanupVercelDeploymentOutput(rootDir, cleanup) {
210
- const outputRoot = cleanup.outputRoot ?? createDefaultVercelOutputRoot(rootDir);
211
- const writes = [];
212
- if (cleanup.serverFunctionName) writes.push(rm(resolve$1(outputRoot, "functions", cleanup.serverFunctionName), {
213
- force: true,
214
- recursive: true
215
- }));
216
- writes.push(deleteJsonObjectKeysFromFile(resolve$1(outputRoot, "config.json"), cleanup.configKeys));
217
- await Promise.all(writes);
218
- }
219
- async function writeProviderDeploymentOutputs(options) {
220
- const writes = [];
221
- if (options.cloudflare) writes.push(writeCloudflareDeploymentOutput({
222
- ...options.cloudflare,
223
- clientOutDir: options.clientOutDir,
224
- rootDir: options.rootDir
225
- }));
226
- else if (options.cleanup?.cloudflare) writes.push(cleanupCloudflareDeploymentOutput(options.rootDir, options.cleanup.cloudflare));
227
- if (options.vercel) writes.push(writeVercelDeploymentOutput({
228
- ...options.vercel,
229
- clientOutDir: options.clientOutDir,
230
- rootDir: options.rootDir
231
- }));
232
- else if (options.cleanup?.vercel) writes.push(cleanupVercelDeploymentOutput(options.rootDir, options.cleanup.vercel));
233
- await Promise.all(writes);
234
- }
235
- //#endregion
236
- //#region ../internal/src/build/vite.ts
237
- function createNoExternalMerger(packageName) {
238
- return (current) => {
239
- if (current === true) return true;
240
- if (!current) return [packageName];
241
- const values = Array.isArray(current) ? current : [current];
242
- return values.includes(packageName) ? values : [...values, packageName];
243
- };
244
- }
245
- function isServerEnvironment(name, config) {
246
- return name === "ssr" || config.consumer === "server";
247
- }
248
- //#endregion
249
- //#region ../internal/src/build/cloudflare.ts
250
- const defaultCloudflareCompatibilityDate = "2026-04-20";
251
- //#endregion
252
- //#region src/internal/vite-build.ts
253
- const queuePackageName = "@vite-hub/queue";
254
- const productName = "queue";
255
- const generatedRegistryFileName = "registry.mjs";
256
- const packageDir = computePackageDir(import.meta.url);
257
- const resolveRuntimeModule = (modulePath) => resolveRuntimeModule$1(packageDir, modulePath);
258
- const providerEntrySpecs = [{
259
- name: "cloudflare",
260
- entryFile: "cloudflare-worker.mjs",
261
- runtimeModule: "runtime/cloudflare-vite",
262
- factory: "createQueueCloudflareWorker",
263
- hosting: "cloudflare"
264
- }, {
265
- name: "vercel",
266
- entryFile: "vercel-server.mjs",
267
- runtimeModule: "runtime/vercel-vite",
268
- factory: "createQueueVercelServer",
269
- hosting: "vercel"
270
- }];
271
- function renderProviderEntry(spec, entryFile, registryFile, userAppEntry, queueConfig) {
272
- const imports = [`import { ${spec.factory} } from ${JSON.stringify(createImportPath(entryFile, resolveRuntimeModule(spec.runtimeModule)))}`, `import queueRegistry from ${JSON.stringify(`./${generatedRegistryFileName}`)}`];
273
- if (spec.name === "vercel") imports.unshift("import * as __vitehubVercelQueue from '@vercel/queue'");
274
- if (userAppEntry) imports.push(`import queueApp from ${JSON.stringify(createImportPath(entryFile, userAppEntry))}`);
275
- return [
276
- ...imports,
277
- "",
278
- spec.name === "vercel" ? "globalThis.__vitehubVercelQueue = __vitehubVercelQueue" : "",
279
- `const queueConfig = ${JSON.stringify(queueConfig, null, 2)}`,
280
- "",
281
- `export default ${spec.factory}({`,
282
- userAppEntry ? " app: queueApp," : "",
283
- " queue: queueConfig,",
284
- " registry: queueRegistry,",
285
- "})",
286
- ""
287
- ].filter(Boolean).join("\n");
288
- }
289
- async function writeProviderEntries(rootDir, queue) {
290
- const generatedDir = ensureGeneratedDir(rootDir, productName);
291
- await mkdir(generatedDir, { recursive: true });
292
- const registryFile = resolve$1(generatedDir, generatedRegistryFileName);
293
- const definitions = discoverQueueDefinitions({ rootDir });
294
- const userAppEntry = resolveUserAppEntry(rootDir);
295
- await writeFile(registryFile, createRuntimeRegistryContents(registryFile, definitions), "utf8");
296
- const entryFiles = {
297
- cloudflare: "",
298
- vercel: ""
299
- };
300
- for (const spec of providerEntrySpecs) {
301
- const entryFile = resolve$1(generatedDir, spec.entryFile);
302
- await writeFile(entryFile, renderProviderEntry(spec, entryFile, registryFile, userAppEntry, normalizeQueueOptions(queue, { hosting: spec.hosting }) || false), "utf8");
303
- entryFiles[spec.name] = entryFile;
304
- }
305
- return {
306
- cloudflareWorkerFile: entryFiles.cloudflare,
307
- definitions,
308
- generatedDir,
309
- registryFile,
310
- vercelServerFile: entryFiles.vercel
311
- };
312
- }
313
- function createCloudflareQueueBindings(definitions) {
314
- if (!definitions.length) return;
315
- return {
316
- consumers: definitions.map((definition) => ({ queue: getCloudflareQueueName(definition.name) })),
317
- producers: definitions.map((definition) => ({
318
- binding: getCloudflareQueueBindingName(definition.name),
319
- queue: getCloudflareQueueName(definition.name)
320
- }))
321
- };
322
- }
323
- async function createCloudflareQueueConfig(options = {}) {
324
- const rootDir = resolve$1(process.cwd(), options.rootDir || ".");
325
- const queues = createCloudflareQueueBindings((await writeProviderEntries(rootDir, void 0)).definitions);
326
- return {
327
- assets: { run_worker_first: ["/api/*"] },
328
- compatibility_date: options.compatibilityDate || "2026-04-20",
329
- compatibility_flags: ["nodejs_compat"],
330
- main: toGeneratedPath(rootDir, productName, providerEntrySpecs[0].entryFile),
331
- observability: { enabled: true },
332
- ...queues ? { queues } : {}
333
- };
334
- }
335
- function createCloudflareOutput(artifacts) {
336
- const queues = createCloudflareQueueBindings(artifacts.definitions);
337
- const wranglerConfig = {
338
- compatibility_date: defaultCloudflareCompatibilityDate,
339
- compatibility_flags: ["nodejs_compat"],
340
- main: "index.js",
341
- observability: { enabled: true },
342
- ...queues ? { queues } : {}
343
- };
344
- return {
345
- bundleEntry: artifacts.cloudflareWorkerFile,
346
- bundleOptions: {
347
- conditions: [
348
- "workerd",
349
- "worker",
350
- "browser",
351
- "default"
352
- ],
353
- external: [
354
- "@vercel/queue",
355
- "node:async_hooks",
356
- "node:fs",
357
- "node:fs/promises",
358
- "node:path",
359
- "node:url"
360
- ],
361
- format: "esm",
362
- platform: "neutral"
363
- },
364
- wranglerConfigKeys: ["queues"],
365
- wranglerConfig
366
- };
367
- }
368
- function sanitizeVercelConsumerName(functionPath) {
369
- let result = "";
370
- for (const char of functionPath) if (char === "_") result += "__";
371
- else if (char === "/") result += "_S";
372
- else if (char === ".") result += "_D";
373
- else if (/[A-Za-z0-9-]/.test(char)) result += char;
374
- else result += `_${char.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`;
375
- return result;
376
- }
377
- function createVercelQueueWrapperContents(file, registryFile, name, queueConfig) {
378
- return [
379
- "import * as __vitehubVercelQueue from '@vercel/queue'",
380
- "import { H3 } from 'h3'",
381
- "import { toNodeHandler } from 'h3/node'",
382
- `import { handleHostedVercelQueueCallback, hostedVercelWaitUntil } from ${JSON.stringify(createImportPath(file, resolveRuntimeModule("runtime/hosted")))}`,
383
- `import { loadQueueDefinition, runWithQueueRuntimeEvent, setQueueRuntimeConfig, setQueueRuntimeRegistry } from ${JSON.stringify(createImportPath(file, resolveRuntimeModule("runtime/state")))}`,
384
- `import queueRegistry from ${JSON.stringify(createImportPath(file, registryFile))}`,
385
- "",
386
- "globalThis.__vitehubVercelQueue = __vitehubVercelQueue",
387
- "",
388
- `setQueueRuntimeConfig(${JSON.stringify(queueConfig, null, 2)})`,
389
- "setQueueRuntimeRegistry(queueRegistry)",
390
- "",
391
- "const app = new H3()",
392
- "app.use(async (event) => {",
393
- ` const definition = await loadQueueDefinition(${JSON.stringify(name)})`,
394
- " if (!definition) {",
395
- " throw new Error('Missing queue definition.')",
396
- " }",
397
- ` return await handleHostedVercelQueueCallback(event, ${JSON.stringify(name)}, definition)`,
398
- "})",
399
- "",
400
- "const handler = toNodeHandler(app)",
401
- "export default function queueHandler(req, res) {",
402
- " return runWithQueueRuntimeEvent({ req, res, waitUntil: hostedVercelWaitUntil }, () => handler(req, res))",
403
- "}",
404
- ""
405
- ].join("\n");
406
- }
407
- function createVercelOutput(artifacts) {
408
- return {
409
- bundleEntry: artifacts.vercelServerFile,
410
- bundleOptions: {
411
- format: "esm",
412
- platform: "node"
413
- }
414
- };
415
- }
416
- async function writeVercelQueueFunctions(rootDir, queue, artifacts) {
417
- const outputRoot = createDefaultVercelOutputRoot(rootDir);
418
- const queueRoot = resolve$1(outputRoot, "functions", "api", "vitehub", "queues", "vercel");
419
- const queueConfig = normalizeQueueOptions(queue, { hosting: "vercel" }) || false;
420
- await rm(queueRoot, {
421
- force: true,
422
- recursive: true
423
- });
424
- if (queueConfig === false) return;
425
- const functionDirs = /* @__PURE__ */ new Map();
426
- for (const definition of artifacts.definitions) {
427
- const segments = definition.name.replace(/[^a-z0-9/_-]+/gi, "_").split("/");
428
- const functionDirKey = [...segments, `${segments.at(-1)}.func`].join("/");
429
- const existing = functionDirs.get(functionDirKey);
430
- if (existing) throw new Error(`Queue names "${existing.name}" and "${definition.name}" collide after Vercel output sanitization:\n - ${existing.handler}\n - ${definition.handler}\nResolved output path: ${functionDirKey}`);
431
- functionDirs.set(functionDirKey, definition);
432
- const functionDir = resolve$1(queueRoot, ...segments, `${segments.at(-1)}.func`);
433
- const functionFile = resolve$1(functionDir, "index.mjs");
434
- const wrapperFile = resolve$1(functionDir, "index.source.mjs");
435
- const consumer = sanitizeVercelConsumerName(relative$1(resolve$1(outputRoot, "functions"), functionDir).replace(/\\/g, "/"));
436
- await mkdir(functionDir, { recursive: true });
437
- await writeFile(wrapperFile, createVercelQueueWrapperContents(wrapperFile, artifacts.registryFile, definition.name, queueConfig), "utf8");
438
- await bundleEsmEntry(wrapperFile, functionFile, {
439
- format: "esm",
440
- platform: "node"
441
- });
442
- await rm(wrapperFile, { force: true });
443
- await writeFile(resolve$1(functionDir, ".vc-config.json"), `${JSON.stringify(createNodeFunctionConfig({ experimentalTriggers: [{
444
- consumer,
445
- topic: getVercelQueueTopicName(definition.name),
446
- type: "queue/v2beta"
447
- }] }), null, 2)}\n`, "utf8");
448
- }
449
- }
450
- async function generateProviderOutputs(options) {
451
- const artifacts = await writeProviderEntries(options.rootDir, options.queue);
452
- await writeProviderDeploymentOutputs({
453
- clientOutDir: options.clientOutDir,
454
- cloudflare: createCloudflareOutput(artifacts),
455
- rootDir: options.rootDir,
456
- vercel: createVercelOutput(artifacts)
457
- });
458
- await writeVercelQueueFunctions(options.rootDir, options.queue, artifacts);
459
- return artifacts;
460
- }
461
- //#endregion
462
- //#region src/vite.ts
463
- const mergeNoExternal = createNoExternalMerger(queuePackageName);
464
- function hubQueue(options) {
465
- let resolved;
466
- let queue = options;
467
- return {
468
- name: "@vite-hub/queue/vite",
469
- nitro: queueNitroModule,
470
- config(config) {
471
- queue = config.queue ?? queue;
472
- },
473
- configResolved(config) {
474
- resolved = config;
475
- queue = config.queue ?? queue;
476
- },
477
- configEnvironment(name, config) {
478
- if (!isServerEnvironment(name, config)) return;
479
- return { resolve: { noExternal: mergeNoExternal(config.resolve?.noExternal) } };
480
- },
481
- async closeBundle() {
482
- if (!resolved || shouldSkipViteProviderBuild(resolved.command, getViteMode())) return;
483
- await generateProviderOutputs({
484
- clientOutDir: resolved.build.outDir,
485
- queue,
486
- rootDir: resolved.root
487
- });
488
- }
489
- };
490
- }
491
- //#endregion
492
- export { createCloudflareQueueConfig, hubQueue };
1
+ import { n as hubQueue, r as createCloudflareQueueConfig, t as createQueueNitroConfig } from "./vite-C6yK76Sw.js";
2
+ export { createCloudflareQueueConfig, createQueueNitroConfig, hubQueue };