@vite-hub/queue 0.0.0 → 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 (37) hide show
  1. package/README.md +89 -1
  2. package/dist/_app-D29AwUdD.d.ts +11 -0
  3. package/dist/app-BZpq2cwC.js +10 -0
  4. package/dist/client-CBDT9GL9.js +93 -0
  5. package/dist/cloudflare-GosJefIK.js +26 -0
  6. package/dist/cloudflare-client-w5vphoNn.js +99 -0
  7. package/dist/cloudflare-resource-name-R8zYQiZb.js +34 -0
  8. package/dist/cloudflare-vite-BNBVtEwG.js +92 -0
  9. package/dist/cloudflare-vite-krY8T3zM.d.ts +24 -0
  10. package/dist/config-B7xkD1v0.js +47 -0
  11. package/dist/delivery-error-glgYWC9g.js +45 -0
  12. package/dist/errors-CjuG_qr-.js +108 -0
  13. package/dist/index.d.ts +91 -0
  14. package/dist/index.js +28 -0
  15. package/dist/internal/runtime/cloudflare-client.d.ts +6 -0
  16. package/dist/internal/runtime/cloudflare-client.js +2 -0
  17. package/dist/internal/runtime/vercel-client.d.ts +6 -0
  18. package/dist/internal/runtime/vercel-client.js +114 -0
  19. package/dist/nuxt.d.ts +19 -0
  20. package/dist/nuxt.js +29 -0
  21. package/dist/runtime/cloudflare-vite.d.ts +2 -0
  22. package/dist/runtime/cloudflare-vite.js +2 -0
  23. package/dist/runtime/hosted.d.ts +11 -0
  24. package/dist/runtime/hosted.js +53 -0
  25. package/dist/runtime/state.d.ts +16 -0
  26. package/dist/runtime/state.js +2 -0
  27. package/dist/runtime/vercel-vite.d.ts +20 -0
  28. package/dist/runtime/vercel-vite.js +49 -0
  29. package/dist/state-BfUFGeC2.js +105 -0
  30. package/dist/types-CwvoMATy.d.ts +169 -0
  31. package/dist/vercel-C_4vqxcl.js +8 -0
  32. package/dist/vercel-runtime-package-copy-B8AEFWXT.js +66 -0
  33. package/dist/virtual.d.ts +4 -0
  34. package/dist/vite-C6yK76Sw.js +1823 -0
  35. package/dist/vite.d.ts +129 -0
  36. package/dist/vite.js +2 -0
  37. package/package.json +73 -5
package/README.md CHANGED
@@ -1,3 +1,91 @@
1
1
  # @vite-hub/queue
2
2
 
3
- Reserved package name for ViteHub.
3
+ <p>
4
+ <a href="https://vitehub.dev"><img alt="ViteHub" src="https://img.shields.io/badge/ViteHub-vitehub.dev-646cff?style=flat-square"></a>
5
+ <img alt="TypeScript" src="https://img.shields.io/badge/TypeScript-ready-3178c6?style=flat-square">
6
+ <img alt="Vite" src="https://img.shields.io/badge/Vite-discovery-646cff?style=flat-square">
7
+ <img alt="Queue" src="https://img.shields.io/badge/Queue-background%20jobs-9333ea?style=flat-square">
8
+ </p>
9
+
10
+ `@vite-hub/queue` defines background job handlers by file path and keeps producers on one `runQueue()` API.
11
+
12
+ ## Install
13
+
14
+ ```sh
15
+ pnpm add @vite-hub/queue
16
+ ```
17
+
18
+ Add `@vercel/queue` when you use the Vercel provider.
19
+
20
+ Vercel Queue projects that typecheck the generated path need Node and ws ambient types:
21
+
22
+ ```sh
23
+ pnpm add -D @types/node @types/ws
24
+ ```
25
+
26
+ ## Minimal API
27
+
28
+ ```ts
29
+ // server/queues/welcome-email.ts
30
+ import { defineQueue } from "@vite-hub/queue"
31
+
32
+ export default defineQueue<{ email: string }>(async (job) => {
33
+ console.log(`Send welcome email to ${job.payload.email}`)
34
+ })
35
+ ```
36
+
37
+ ```ts
38
+ // server/api/signup.post.ts
39
+ import { runQueue } from "@vite-hub/queue"
40
+ import { defineEventHandler, readBody } from "h3"
41
+
42
+ export default defineEventHandler(async (event) => {
43
+ return runQueue("welcome-email", await readBody<{ email: string }>(event))
44
+ })
45
+ ```
46
+
47
+ ```ts
48
+ // vite.config.ts
49
+ import { hubQueue } from "@vite-hub/queue/vite"
50
+ import { defineConfig } from "vite"
51
+
52
+ export default defineConfig({
53
+ plugins: [hubQueue()],
54
+ queue: { provider: "cloudflare" },
55
+ })
56
+ ```
57
+
58
+ Throw `ViteHubError` when a Queue Definition needs a stable application error code. Queue retry policy belongs to Queue Delivery and provider callbacks, not the error object.
59
+
60
+ ```ts
61
+ import { ViteHubError } from "@vite-hub/runtime"
62
+ import { defineQueue } from "@vite-hub/queue"
63
+
64
+ export default defineQueue<{ email?: string }>(async ({ payload }) => {
65
+ if (!payload.email) {
66
+ throw new ViteHubError("WELCOME_EMAIL_INVALID_PAYLOAD", "Welcome email payload requires an email address.", {
67
+ details: { field: "email" },
68
+ })
69
+ }
70
+
71
+ await sendWelcomeEmail(payload.email)
72
+ })
73
+ ```
74
+
75
+ ViteHub's built-in codes remain available as `QueueErrorCode`. ViteHub reports each failed delivery with safe Queue and message identifiers, attempt count, code, details, and the Queue-owned retry decision before choosing the provider action. Cloudflare `onError` and Vercel `callbackOptions.retry` directives override the default action when they return an explicit directive.
76
+
77
+ ## Vite Integration
78
+
79
+ Use `hubQueue()` in Vite to discover `server/queues/<name>.ts` and `src/<name>.queue.ts`. The handler name comes from the file path, while provider output maps it to [Cloudflare Queues](https://developers.cloudflare.com/queues/) or [Vercel Queues](https://vercel.com/docs/queues).
80
+
81
+ In Nuxt, install the Queue module instead. It installs the same Vite integration and merges the generated runtime files and provider bindings into Nitro configuration:
82
+
83
+ ```ts
84
+ export default defineNuxtConfig({
85
+ modules: [["@vite-hub/queue/nuxt", { provider: "cloudflare" }]],
86
+ })
87
+ ```
88
+
89
+ Run `vite build` to emit Queue Provider Output. Cloudflare output is written under `dist/**/wrangler.json`; Vercel output is written under `.vercel/output/functions/api/vitehub/queues/vercel/**`.
90
+
91
+ Learn more at [vitehub.dev](https://vitehub.dev).
@@ -0,0 +1,11 @@
1
+ //#region ../internal/src/runtime/app.d.ts
2
+ type AppHandler = (request: Request, context?: Record<string, unknown>) => Response | Promise<Response>;
3
+ type VitehubApp = AppHandler | {
4
+ fetch?: AppHandler;
5
+ request?: (request: Request, options?: RequestInit, context?: Record<string, unknown>) => Response | Promise<Response>;
6
+ };
7
+ //#endregion
8
+ //#region src/runtime/_app.d.ts
9
+ type QueueApp = VitehubApp;
10
+ //#endregion
11
+ export { QueueApp as t };
@@ -0,0 +1,10 @@
1
+ //#region ../internal/src/runtime/app.ts
2
+ function resolveAppFetch(label, app) {
3
+ if (!app) return;
4
+ if (typeof app === "function") return app;
5
+ if (typeof app.request === "function") return (request, context) => app.request(request, void 0, context);
6
+ if (typeof app.fetch === "function") return app.fetch.bind(app);
7
+ throw new TypeError(`Invalid ${label} app. Expected an h3 app or a fetch-compatible handler.`);
8
+ }
9
+ //#endregion
10
+ export { resolveAppFetch as t };
@@ -0,0 +1,93 @@
1
+ import { t as normalizeQueueOptions } from "./config-B7xkD1v0.js";
2
+ import { i as isQueueBoundaryIdentity, l as normalizeQueueEnqueueInput, n as createQueueError, o as normalizePublicQueueIdentifier, s as runQueueProviderOperation } from "./errors-CjuG_qr-.js";
3
+ import { t as getCloudflareQueueBindingName } from "./cloudflare-GosJefIK.js";
4
+ import { t as getVercelQueueTopicName } from "./vercel-C_4vqxcl.js";
5
+ import { a as getQueueRuntimeEvent, f as getCloudflareEnv, i as getQueueRuntimeConfig, n as getQueueClientCache, o as loadQueueDefinition, p as resolveWaitUntil, r as getQueueRuntimeClientFactory, s as runWithQueueRuntimeEvent } from "./state-BfUFGeC2.js";
6
+ //#region src/runtime/client.ts
7
+ function createQueueDefinitionNotFoundError(name) {
8
+ const queue = normalizePublicQueueIdentifier(name);
9
+ return createQueueError("QUEUE_DEFINITION_NOT_FOUND", { details: queue ? { queue } : void 0 });
10
+ }
11
+ async function loadNamedQueueDefinition(name) {
12
+ try {
13
+ return await loadQueueDefinition(name);
14
+ } catch (cause) {
15
+ if (isQueueBoundaryIdentity(cause)) throw cause;
16
+ const queue = normalizePublicQueueIdentifier(name);
17
+ throw createQueueError("QUEUE_DEFINITION_LOAD_FAILED", {
18
+ cause,
19
+ details: queue ? { queue } : void 0
20
+ });
21
+ }
22
+ }
23
+ function resolveCloudflareBinding(binding, name) {
24
+ if (binding && typeof binding !== "string") return binding;
25
+ const bindingName = binding || getCloudflareQueueBindingName(name);
26
+ return getCloudflareEnv(getQueueRuntimeEvent())?.[bindingName] || bindingName;
27
+ }
28
+ function toProviderOptions(name, config) {
29
+ if (config.provider === "cloudflare") return {
30
+ ...config,
31
+ binding: resolveCloudflareBinding(config.binding, name)
32
+ };
33
+ return {
34
+ ...config,
35
+ topic: getVercelQueueTopicName(name)
36
+ };
37
+ }
38
+ function getActiveQueueConfig() {
39
+ const config = getQueueRuntimeConfig();
40
+ if (config === false) return false;
41
+ return config || normalizeQueueOptions(void 0, { hosting: "vercel" });
42
+ }
43
+ function hasRequestScopedVercelRegion(config) {
44
+ return config.provider === "vercel" && !config.region && !process.env.QUEUE_REGION && !process.env.VERCEL_REGION && typeof getQueueRuntimeEvent() !== "undefined";
45
+ }
46
+ async function createNamedQueueClient(name) {
47
+ const config = getActiveQueueConfig();
48
+ if (config === false) throw createQueueError("QUEUE_DISABLED");
49
+ const provider = toProviderOptions(name, config);
50
+ const createClient = getQueueRuntimeClientFactory();
51
+ if (!createClient) throw new Error("[vitehub] Queue Client is installed by generated Provider Output.");
52
+ return await runQueueProviderOperation(provider.provider, "create-client", () => createClient(provider));
53
+ }
54
+ async function getQueue(name) {
55
+ const definition = await loadNamedQueueDefinition(name);
56
+ if (!definition) throw createQueueDefinitionNotFoundError(name);
57
+ const config = getActiveQueueConfig();
58
+ if (definition.options?.cache === false || config === false || config.cache === false || config.provider === "cloudflare" || hasRequestScopedVercelRegion(config)) return await createNamedQueueClient(name);
59
+ const cache = getQueueClientCache();
60
+ const existing = cache.get(name);
61
+ if (existing) return await existing;
62
+ const pending = createNamedQueueClient(name).catch((error) => {
63
+ cache.delete(name);
64
+ throw error;
65
+ });
66
+ cache.set(name, pending);
67
+ return await pending;
68
+ }
69
+ async function runQueue(name, input) {
70
+ const normalized = normalizeQueueEnqueueInput(input);
71
+ return await (await getQueue(name)).send({
72
+ ...normalized.options,
73
+ id: normalized.id,
74
+ payload: normalized.payload
75
+ });
76
+ }
77
+ function deferQueue(name, input) {
78
+ const request = getQueueRuntimeEvent();
79
+ const task = () => runWithQueueRuntimeEvent(request, () => runQueue(name, input));
80
+ const handleError = async (error) => {
81
+ console.error(`[vitehub] Deferred queue dispatch failed for "${name}"`, error);
82
+ try {
83
+ await (await loadNamedQueueDefinition(name))?.options?.onDispatchError?.(error, { name });
84
+ } catch (hookError) {
85
+ console.error(`[vitehub] onDispatchError hook failed for "${name}"`, hookError);
86
+ }
87
+ };
88
+ const promise = task().catch(handleError);
89
+ const waitUntil = resolveWaitUntil(request);
90
+ if (typeof waitUntil === "function") waitUntil(promise);
91
+ }
92
+ //#endregion
93
+ export { getQueue as n, runQueue as r, deferQueue as t };
@@ -0,0 +1,26 @@
1
+ //#region ../internal/src/integrations/hex.ts
2
+ const textEncoder = new TextEncoder();
3
+ const textDecoder = new TextDecoder();
4
+ function encodeNameHex(name) {
5
+ return [...textEncoder.encode(name)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
6
+ }
7
+ function decodeNameHex(hex) {
8
+ const bytes = hex.match(/.{2}/g)?.map((byte) => Number.parseInt(byte, 16)) ?? [];
9
+ if (!bytes.length || bytes.some((byte) => !Number.isFinite(byte))) return;
10
+ return textDecoder.decode(new Uint8Array(bytes));
11
+ }
12
+ //#endregion
13
+ //#region src/integrations/cloudflare.ts
14
+ const defaultCloudflareQueueBindingPrefix = "QUEUE";
15
+ const encodedCloudflareQueueNamePattern = /^queue--([0-9a-f]{2})+$/i;
16
+ function getCloudflareQueueBindingName(name) {
17
+ const encoded = encodeNameHex(name).toUpperCase();
18
+ return encoded ? `${defaultCloudflareQueueBindingPrefix}_${encoded}` : defaultCloudflareQueueBindingPrefix;
19
+ }
20
+ function getCloudflareQueueDefinitionName(name, namePrefix = "") {
21
+ const encodedName = namePrefix && name.startsWith(namePrefix) ? name.slice(namePrefix.length) : name;
22
+ if (!encodedCloudflareQueueNamePattern.test(encodedName)) return encodedName;
23
+ return decodeNameHex(encodedName.slice(7)) || name;
24
+ }
25
+ //#endregion
26
+ export { getCloudflareQueueDefinitionName as n, encodeNameHex as r, getCloudflareQueueBindingName as t };
@@ -0,0 +1,99 @@
1
+ import { l as normalizeQueueEnqueueInput, n as createQueueError, s as runQueueProviderOperation, t as cloudflareUnsupportedEnqueueOptions } from "./errors-CjuG_qr-.js";
2
+ import { n as getCloudflareQueueDefinitionName } from "./cloudflare-GosJefIK.js";
3
+ import { n as reportQueueDeliveryError, t as isNonRetryableQueueError } from "./delivery-error-glgYWC9g.js";
4
+ //#region src/providers/cloudflare.ts
5
+ function isCloudflareQueueBinding(binding) {
6
+ return Boolean(binding) && typeof binding === "object" && typeof binding.send === "function" && typeof binding.sendBatch === "function";
7
+ }
8
+ function toSendOptions(options = {}) {
9
+ const unsupported = cloudflareUnsupportedEnqueueOptions.filter((option) => options[option] !== void 0);
10
+ if (unsupported.length) throw createQueueError("CLOUDFLARE_UNSUPPORTED_ENQUEUE_OPTIONS", { details: {
11
+ provider: "cloudflare",
12
+ unsupported
13
+ } });
14
+ return {
15
+ contentType: options.contentType,
16
+ delaySeconds: options.delaySeconds
17
+ };
18
+ }
19
+ function resolveAction(action, message, fallback) {
20
+ if (action === "ack") {
21
+ message.ack();
22
+ return;
23
+ }
24
+ if (action === "retry") {
25
+ message.retry();
26
+ return;
27
+ }
28
+ if (action && typeof action === "object" && "retry" in action) {
29
+ message.retry(action.retry);
30
+ return;
31
+ }
32
+ if (fallback === "ack") message.ack();
33
+ else message.retry();
34
+ }
35
+ function createCloudflareQueueBatchHandler(options) {
36
+ const requested = Number(options.concurrency ?? 1);
37
+ const concurrency = Number.isFinite(requested) ? Math.max(1, Math.floor(requested)) : 1;
38
+ return async (batch) => {
39
+ const messages = Array.isArray(batch?.messages) ? batch.messages : [];
40
+ if (!messages.length) return;
41
+ let index = 0;
42
+ const worker = async () => {
43
+ while (index < messages.length) {
44
+ const message = messages[index++];
45
+ try {
46
+ await options.onMessage(message, batch);
47
+ message.ack();
48
+ } catch (error) {
49
+ reportQueueDeliveryError(error, {
50
+ attempts: message.attempts,
51
+ id: message.id,
52
+ provider: "cloudflare",
53
+ queue: getCloudflareQueueDefinitionName(batch.queue)
54
+ });
55
+ resolveAction(options.onError ? await options.onError(error, message, batch) : void 0, message, isNonRetryableQueueError(error) ? "ack" : "retry");
56
+ }
57
+ }
58
+ };
59
+ await Promise.all(Array.from({ length: Math.min(concurrency, messages.length) }, () => worker()));
60
+ };
61
+ }
62
+ function createCloudflareQueueClient(provider) {
63
+ if (typeof provider.binding === "undefined" || typeof provider.binding === "string") throw createQueueError("CLOUDFLARE_BINDING_RESOLUTION_REQUIRED", { details: { provider: "cloudflare" } });
64
+ if (!isCloudflareQueueBinding(provider.binding)) throw createQueueError("CLOUDFLARE_BINDING_INVALID", { details: { provider: "cloudflare" } });
65
+ const binding = provider.binding;
66
+ return {
67
+ provider: "cloudflare",
68
+ native: binding,
69
+ binding,
70
+ async send(input) {
71
+ const normalized = normalizeQueueEnqueueInput(input);
72
+ await runQueueProviderOperation("cloudflare", "send", () => binding.send(normalized.payload, toSendOptions(normalized.options)));
73
+ return {
74
+ status: "queued",
75
+ messageId: normalized.id
76
+ };
77
+ },
78
+ async sendBatch(items, options) {
79
+ await runQueueProviderOperation("cloudflare", "send-batch", () => binding.sendBatch(items.map((item) => ({
80
+ ...item,
81
+ ...toSendOptions({
82
+ ...options,
83
+ contentType: item.contentType || options?.contentType,
84
+ delaySeconds: item.delaySeconds ?? options?.delaySeconds
85
+ })
86
+ }))));
87
+ return items.map(() => ({ status: "queued" }));
88
+ },
89
+ createBatchHandler: createCloudflareQueueBatchHandler
90
+ };
91
+ }
92
+ //#endregion
93
+ //#region src/internal/runtime/cloudflare-client.ts
94
+ async function createCloudflareQueueRuntimeClient(options) {
95
+ if (options.provider !== "cloudflare") throw new TypeError("[vitehub] Cloudflare Queue runtime received a non-Cloudflare provider.");
96
+ return createCloudflareQueueClient(options);
97
+ }
98
+ //#endregion
99
+ export { createCloudflareQueueBatchHandler as n, createCloudflareQueueRuntimeClient as t };
@@ -0,0 +1,34 @@
1
+ import { r as encodeNameHex } from "./cloudflare-GosJefIK.js";
2
+ //#region src/internal/cloudflare-resource-name.ts
3
+ const cloudflareQueueNamePrefix = "queue--";
4
+ const cloudflareQueueNamePattern = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i;
5
+ const cloudflareLegacyQueueDefinitionNamePattern = /^[a-z0-9]+-[a-z0-9]+$/;
6
+ const cloudflareQueueDigestSuffixPattern = /-[0-9a-f]{32}$/;
7
+ const maxCloudflareQueueNameLength = 63;
8
+ const digestLength = 32;
9
+ function digestCloudflareQueueName(name, namePrefix) {
10
+ const crypto = globalThis.process?.getBuiltinModule("node:crypto");
11
+ if (!crypto) throw new Error("Cloudflare queue name derivation requires the Node.js crypto module.");
12
+ return crypto.hash("sha256", JSON.stringify([
13
+ "vitehub",
14
+ "cloudflare",
15
+ "queue",
16
+ 1,
17
+ namePrefix,
18
+ name
19
+ ]), "hex").slice(0, digestLength);
20
+ }
21
+ function createBoundedCloudflareQueueName(name, namePrefix) {
22
+ const legacyName = `${namePrefix}${name}`;
23
+ if (namePrefix.endsWith("-") && cloudflareLegacyQueueDefinitionNamePattern.test(name) && !cloudflareQueueDigestSuffixPattern.test(name) && legacyName.length <= maxCloudflareQueueNameLength) return legacyName;
24
+ const digest = digestCloudflareQueueName(name, namePrefix);
25
+ const readableLength = maxCloudflareQueueNameLength - digest.length - 1;
26
+ return `${legacyName.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, readableLength).replace(/-+$/g, "") || "queue"}-${digest}`;
27
+ }
28
+ function getCloudflareQueueName(name, namePrefix = "") {
29
+ const queueName = `${namePrefix}${cloudflareQueueNamePrefix}${encodeNameHex(name)}`;
30
+ if (!cloudflareQueueNamePattern.test(queueName)) throw new TypeError(`Cloudflare queue name ${JSON.stringify(queueName)} must contain only letters, numbers, and dashes, and must start and end with a letter or number.`);
31
+ return queueName.length <= maxCloudflareQueueNameLength ? queueName : createBoundedCloudflareQueueName(name, namePrefix);
32
+ }
33
+ //#endregion
34
+ export { getCloudflareQueueName as t };
@@ -0,0 +1,92 @@
1
+ import { t as normalizeQueueOptions } from "./config-B7xkD1v0.js";
2
+ import { n as getCloudflareQueueDefinitionName } from "./cloudflare-GosJefIK.js";
3
+ import { n as createCloudflareQueueBatchHandler, t as createCloudflareQueueRuntimeClient } from "./cloudflare-client-w5vphoNn.js";
4
+ import { t as getCloudflareQueueName } from "./cloudflare-resource-name-R8zYQiZb.js";
5
+ import { c as setQueueRuntimeConfig, d as createCloudflareRuntimeEvent, m as runWithActiveCloudflareEnv, o as loadQueueDefinition, s as runWithQueueRuntimeEvent, u as setQueueRuntimeRegistry } from "./state-BfUFGeC2.js";
6
+ import { t as resolveAppFetch } from "./app-BZpq2cwC.js";
7
+ import { H3, toWebHandler } from "h3/cloudflare";
8
+ //#region ../internal/src/runtime/cloudflare-hosted.ts
9
+ function createWebRequestHandler(appHandler) {
10
+ const defaultHandler = toWebHandler(new H3());
11
+ return async (request, context) => await Promise.resolve(appHandler ? appHandler(request, context) : defaultHandler(request, context));
12
+ }
13
+ function createCloudflareHostedWorker(adapter) {
14
+ const requestHandler = createWebRequestHandler(resolveAppFetch(adapter.label, adapter.app));
15
+ return { async fetch(request, env, context) {
16
+ const handle = async (handlerContext) => await Promise.resolve(requestHandler(request, handlerContext));
17
+ if (adapter.onRequest) return await adapter.onRequest({
18
+ env,
19
+ executionContext: context,
20
+ handle
21
+ });
22
+ return await handle();
23
+ } };
24
+ }
25
+ //#endregion
26
+ //#region src/runtime/cloudflare-shared.ts
27
+ function createQueueJob(message, batch) {
28
+ return {
29
+ attempts: typeof message.attempts === "number" ? message.attempts : 1,
30
+ id: message.id,
31
+ metadata: {
32
+ batch,
33
+ message
34
+ },
35
+ payload: message.body
36
+ };
37
+ }
38
+ //#endregion
39
+ //#region src/runtime/cloudflare-vite.ts
40
+ function createRegistryDefinitionNames(registry, namePrefix) {
41
+ if (!registry) return void 0;
42
+ const definitions = {};
43
+ for (const name of Object.keys(registry)) {
44
+ const physicalName = getCloudflareQueueName(name, namePrefix);
45
+ if (definitions[physicalName]) throw new Error(`Queue names ${JSON.stringify(definitions[physicalName])} and ${JSON.stringify(name)} collide after Cloudflare resource name derivation.`);
46
+ definitions[physicalName] = name;
47
+ }
48
+ return definitions;
49
+ }
50
+ function createQueueCloudflareWorker(options = {}) {
51
+ const queueConfig = options.queue === false ? false : normalizeQueueOptions(options.queue, { hosting: "cloudflare" });
52
+ const registry = options.registry;
53
+ const definitions = options.definitions;
54
+ const registryDefinitions = !definitions && queueConfig !== false && queueConfig.provider === "cloudflare" ? createRegistryDefinitionNames(registry, queueConfig.namePrefix ?? "") : void 0;
55
+ const applyRuntimeState = () => {
56
+ setQueueRuntimeConfig(queueConfig, createCloudflareQueueRuntimeClient);
57
+ setQueueRuntimeRegistry(registry);
58
+ };
59
+ return {
60
+ ...createCloudflareHostedWorker({
61
+ app: options.app,
62
+ label: "queue",
63
+ async onRequest({ env, executionContext, handle }) {
64
+ applyRuntimeState();
65
+ const runtimeEvent = createCloudflareRuntimeEvent(env, executionContext);
66
+ return await runWithActiveCloudflareEnv(env, () => runWithQueueRuntimeEvent(runtimeEvent, () => handle(runtimeEvent.context)));
67
+ }
68
+ }),
69
+ async queue(batch, env, context) {
70
+ applyRuntimeState();
71
+ if (queueConfig === false || queueConfig?.provider !== "cloudflare") return;
72
+ const runtimeEvent = createCloudflareRuntimeEvent(env, context);
73
+ await runWithActiveCloudflareEnv(env, async () => {
74
+ const definitionName = definitions ? definitions[batch.queue] : registryDefinitions?.[batch.queue] ?? (/-[0-9a-f]{32}$/.test(batch.queue) && !/(?:^|-)queue--(?:[0-9a-f]{2})+$/i.test(batch.queue) || queueConfig.namePrefix && !batch.queue.startsWith(queueConfig.namePrefix) ? void 0 : getCloudflareQueueDefinitionName(batch.queue, queueConfig.namePrefix));
75
+ if (!definitionName) throw new Error(`[vitehub] Cloudflare queue ${JSON.stringify(batch.queue)} is not mapped to a Queue Definition.`);
76
+ const definition = await loadQueueDefinition(definitionName);
77
+ if (!definition) throw new Error(`[vitehub] Cloudflare queue ${JSON.stringify(batch.queue)} maps to unknown Queue Definition ${JSON.stringify(definitionName)}.`);
78
+ await createCloudflareQueueBatchHandler({
79
+ concurrency: definition.options?.concurrency,
80
+ onError: definition.options?.onError,
81
+ onMessage: async (message, currentBatch) => {
82
+ await runWithQueueRuntimeEvent(runtimeEvent, async () => {
83
+ await definition.handler(createQueueJob(message, currentBatch));
84
+ });
85
+ }
86
+ })(batch);
87
+ });
88
+ }
89
+ };
90
+ }
91
+ //#endregion
92
+ export { createQueueCloudflareWorker as t };
@@ -0,0 +1,24 @@
1
+ import { i as CloudflareQueueMessageBatch, l as QueueDefinitionRegistry, y as ResolvedQueueOptions } from "./types-CwvoMATy.js";
2
+ import { t as QueueApp } from "./_app-D29AwUdD.js";
3
+
4
+ //#region ../internal/src/runtime/cloudflare-env.d.ts
5
+ type CloudflareWorkerEnv = Record<string, unknown>;
6
+ interface CloudflareWorkerExecutionContext {
7
+ waitUntil?: (promise: Promise<unknown>) => void;
8
+ }
9
+ //#endregion
10
+ //#region src/runtime/cloudflare-vite.d.ts
11
+ type CloudflareWorkerApp = QueueApp;
12
+ interface QueueCloudflareWorkerOptions {
13
+ app?: CloudflareWorkerApp;
14
+ definitions?: Record<string, string>;
15
+ queue?: false | ResolvedQueueOptions;
16
+ registry?: QueueDefinitionRegistry;
17
+ }
18
+ interface QueueCloudflareWorker {
19
+ fetch: (request: Request, env: CloudflareWorkerEnv, context: CloudflareWorkerExecutionContext) => Promise<Response>;
20
+ queue: (batch: CloudflareQueueMessageBatch, env: CloudflareWorkerEnv, context: CloudflareWorkerExecutionContext) => Promise<void>;
21
+ }
22
+ declare function createQueueCloudflareWorker(options?: QueueCloudflareWorkerOptions): QueueCloudflareWorker;
23
+ //#endregion
24
+ export { createQueueCloudflareWorker as i, QueueCloudflareWorker as n, QueueCloudflareWorkerOptions as r, CloudflareWorkerApp as t };
@@ -0,0 +1,47 @@
1
+ import { defu } from "defu";
2
+ function deploymentPresetFromNitro(value) {
3
+ const normalized = value?.trim().toLowerCase().replaceAll("_", "-");
4
+ if (!normalized) return;
5
+ if (normalized.startsWith("cloudflare")) return "cloudflare";
6
+ if (normalized.startsWith("deno")) return "deno";
7
+ if (normalized.startsWith("netlify")) return "netlify";
8
+ if (normalized === "node" || normalized.startsWith("node-")) return "node";
9
+ if (normalized.startsWith("vercel")) return "vercel";
10
+ }
11
+ //#endregion
12
+ //#region ../internal/src/hosting.ts
13
+ function normalizeHosting(hosting) {
14
+ const normalized = hosting?.trim().toLowerCase().replaceAll("_", "-") || "";
15
+ if (normalized === "cloudflare") return "cloudflare-module";
16
+ return normalized;
17
+ }
18
+ function getHostingProvider(hosting) {
19
+ const preset = deploymentPresetFromNitro(hosting);
20
+ if (preset === "cloudflare" || preset === "netlify" || preset === "vercel") return preset;
21
+ }
22
+ //#endregion
23
+ //#region ../internal/src/object.ts
24
+ function isPlainObject(value) {
25
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
26
+ }
27
+ //#endregion
28
+ //#region src/config.ts
29
+ const knownProviders = new Set(["cloudflare", "vercel"]);
30
+ function resolveProvider(options, hosting) {
31
+ const shared = typeof options.cache === "boolean" ? { cache: options.cache } : {};
32
+ const provider = options.provider;
33
+ if (typeof provider === "string" && !knownProviders.has(provider)) throw new TypeError(`Unknown \`queue.provider\`: ${JSON.stringify(provider)}. Expected "cloudflare" or "vercel".`);
34
+ if (typeof provider === "undefined" && hosting && !hosting.includes("cloudflare") && !hosting.includes("vercel")) throw new TypeError("`queue.provider` cannot be inferred for " + hosting + " hosting. Disable `queue` or select the Cloudflare or Vercel deployment preset.");
35
+ if ((provider || (hosting.includes("cloudflare") ? "cloudflare" : "vercel")) === "cloudflare") return defu({
36
+ ...typeof options.binding === "string" ? { binding: options.binding } : {},
37
+ ...typeof options.namePrefix === "string" ? { namePrefix: options.namePrefix } : {}
38
+ }, shared, { provider: "cloudflare" });
39
+ return defu(typeof options.region === "string" ? { region: options.region } : {}, shared, { provider: "vercel" });
40
+ }
41
+ function normalizeQueueOptions(options, input = {}) {
42
+ if (options === false) return void 0;
43
+ if (typeof options !== "undefined" && !isPlainObject(options)) throw new TypeError("`queue` must be a plain object.");
44
+ return resolveProvider(options || {}, normalizeHosting(input.hosting));
45
+ }
46
+ //#endregion
47
+ export { getHostingProvider as n, normalizeQueueOptions as t };
@@ -0,0 +1,45 @@
1
+ import { a as isQueueOwnedError, o as normalizePublicQueueIdentifier, r as getQueueErrorPublicShape } from "./errors-CjuG_qr-.js";
2
+ //#region src/internal/delivery-error.ts
3
+ const nonRetryableBuiltInCodes = new Set([
4
+ "CLOUDFLARE_BINDING_INVALID",
5
+ "CLOUDFLARE_BINDING_RESOLUTION_REQUIRED",
6
+ "CLOUDFLARE_UNSUPPORTED_ENQUEUE_OPTIONS",
7
+ "QUEUE_DEFINITION_LOAD_FAILED",
8
+ "QUEUE_DEFINITION_NOT_FOUND",
9
+ "QUEUE_DISABLED",
10
+ "VERCEL_PROVIDER_EXPECTED",
11
+ "VERCEL_QUEUE_REGION_REQUIRED",
12
+ "VERCEL_QUEUE_SDK_INVALID",
13
+ "VERCEL_QUEUE_SDK_LOAD_FAILED",
14
+ "VERCEL_TOPIC_RESOLUTION_REQUIRED",
15
+ "VERCEL_UNSUPPORTED_ENQUEUE_OPTIONS"
16
+ ]);
17
+ function isNonRetryableQueueError(error) {
18
+ const shape = getQueueErrorPublicShape(error);
19
+ return isQueueOwnedError(error) && shape !== void 0 && nonRetryableBuiltInCodes.has(shape.code);
20
+ }
21
+ function createQueueDeliveryErrorReport(error, context) {
22
+ const queueError = getQueueErrorPublicShape(error);
23
+ const id = normalizePublicQueueIdentifier(context.id);
24
+ const queue = normalizePublicQueueIdentifier(context.queue);
25
+ return {
26
+ attempts: context.attempts,
27
+ provider: context.provider,
28
+ ...id ? { id } : {},
29
+ ...queue ? { queue } : {},
30
+ error: {
31
+ ...queueError ? {
32
+ code: queueError.code,
33
+ details: queueError.details
34
+ } : {},
35
+ message: queueError?.message ?? "[vitehub] Queue Delivery failed.",
36
+ name: queueError ? "ViteHubError" : "Error"
37
+ },
38
+ retryable: !isNonRetryableQueueError(error)
39
+ };
40
+ }
41
+ function reportQueueDeliveryError(error, context) {
42
+ console.error("[vitehub:queue] Queue Delivery failed.", createQueueDeliveryErrorReport(error, context));
43
+ }
44
+ //#endregion
45
+ export { reportQueueDeliveryError as n, isNonRetryableQueueError as t };