@vite-hub/queue 0.0.0 → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,55 @@
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
+ ## Minimal API
21
+
22
+ ```ts
23
+ // server/queues/welcome-email.ts
24
+ import { defineQueue } from "@vite-hub/queue"
25
+
26
+ export default defineQueue<{ email: string }>(async (job) => {
27
+ console.log(`Send welcome email to ${job.payload.email}`)
28
+ })
29
+ ```
30
+
31
+ ```ts
32
+ // server/api/signup.post.ts
33
+ import { runQueue } from "@vite-hub/queue"
34
+ import { defineEventHandler, readBody } from "h3"
35
+
36
+ export default defineEventHandler(async (event) => {
37
+ return runQueue("welcome-email", await readBody<{ email: string }>(event))
38
+ })
39
+ ```
40
+
41
+ ```ts
42
+ // nitro.config.ts
43
+ import { defineNitroConfig } from "nitro/config"
44
+
45
+ export default defineNitroConfig({
46
+ modules: ["@vite-hub/queue/nitro"],
47
+ queue: { provider: "cloudflare" },
48
+ })
49
+ ```
50
+
51
+ ## Vite and Nitro
52
+
53
+ Nitro discovers `server/queues/<name>.ts`; Vite also supports `src/<name>.queue.ts` through `hubQueue()`. 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).
54
+
55
+ 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,107 @@
1
+ import { r as normalizeQueueEnqueueInput, t as QueueError } from "./errors-xRt0BFZK.js";
2
+ //#region \0rolldown/runtime.js
3
+ var __defProp = Object.defineProperty;
4
+ var __exportAll = (all, no_symbols) => {
5
+ let target = {};
6
+ for (var name in all) __defProp(target, name, {
7
+ get: all[name],
8
+ enumerable: true
9
+ });
10
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
11
+ return target;
12
+ };
13
+ //#endregion
14
+ //#region src/providers/cloudflare.ts
15
+ var cloudflare_exports = /* @__PURE__ */ __exportAll({
16
+ createCloudflareQueueBatchHandler: () => createCloudflareQueueBatchHandler,
17
+ createCloudflareQueueClient: () => createCloudflareQueueClient
18
+ });
19
+ function isCloudflareQueueBinding(binding) {
20
+ return Boolean(binding) && typeof binding === "object" && typeof binding.send === "function" && typeof binding.sendBatch === "function";
21
+ }
22
+ function toSendOptions(options = {}) {
23
+ const unsupported = [options.idempotencyKey !== void 0 ? "idempotencyKey" : void 0, options.retentionSeconds !== void 0 ? "retentionSeconds" : void 0].filter(Boolean);
24
+ if (unsupported.length) throw new QueueError(`Cloudflare queue does not support enqueue options: ${unsupported.join(", ")}.`, {
25
+ code: "CLOUDFLARE_UNSUPPORTED_ENQUEUE_OPTIONS",
26
+ details: { unsupported },
27
+ httpStatus: 400,
28
+ method: "send",
29
+ provider: "cloudflare"
30
+ });
31
+ return {
32
+ contentType: options.contentType,
33
+ delaySeconds: options.delaySeconds
34
+ };
35
+ }
36
+ function resolveAction(action, message) {
37
+ if (action === "ack") {
38
+ message.ack();
39
+ return;
40
+ }
41
+ if (action && typeof action === "object" && "retry" in action) {
42
+ message.retry(action.retry);
43
+ return;
44
+ }
45
+ message.retry();
46
+ }
47
+ function createCloudflareQueueBatchHandler(options) {
48
+ const requested = Number(options.concurrency ?? 1);
49
+ const concurrency = Number.isFinite(requested) ? Math.max(1, Math.floor(requested)) : 1;
50
+ return async (batch) => {
51
+ const messages = Array.isArray(batch?.messages) ? batch.messages : [];
52
+ if (!messages.length) return;
53
+ let index = 0;
54
+ const worker = async () => {
55
+ while (index < messages.length) {
56
+ const message = messages[index++];
57
+ try {
58
+ await options.onMessage(message, batch);
59
+ message.ack();
60
+ } catch (error) {
61
+ resolveAction(options.onError ? await options.onError(error, message, batch) : void 0, message);
62
+ }
63
+ }
64
+ };
65
+ await Promise.all(Array.from({ length: Math.min(concurrency, messages.length) }, () => worker()));
66
+ };
67
+ }
68
+ function createCloudflareQueueClient(provider) {
69
+ if (typeof provider.binding === "undefined" || typeof provider.binding === "string") throw new QueueError(typeof provider.binding === "string" ? "Cloudflare queue binding names require request-scoped runtime resolution." : "Cloudflare queue direct clients require a binding.", {
70
+ code: "CLOUDFLARE_BINDING_RESOLUTION_REQUIRED",
71
+ httpStatus: 400,
72
+ provider: "cloudflare"
73
+ });
74
+ if (!isCloudflareQueueBinding(provider.binding)) throw new QueueError("Invalid Cloudflare queue binding. Expected an object with send() and sendBatch().", {
75
+ code: "CLOUDFLARE_BINDING_INVALID",
76
+ httpStatus: 400,
77
+ provider: "cloudflare"
78
+ });
79
+ const binding = provider.binding;
80
+ return {
81
+ provider: "cloudflare",
82
+ native: binding,
83
+ binding,
84
+ async send(input) {
85
+ const normalized = normalizeQueueEnqueueInput(input);
86
+ await binding.send(normalized.payload, toSendOptions(normalized.options));
87
+ return {
88
+ status: "queued",
89
+ messageId: normalized.id
90
+ };
91
+ },
92
+ async sendBatch(items, options) {
93
+ await binding.sendBatch(items.map((item) => ({
94
+ ...item,
95
+ ...toSendOptions({
96
+ ...options,
97
+ contentType: item.contentType || options?.contentType,
98
+ delaySeconds: item.delaySeconds ?? options?.delaySeconds
99
+ })
100
+ })));
101
+ return items.map(() => ({ status: "queued" }));
102
+ },
103
+ createBatchHandler: createCloudflareQueueBatchHandler
104
+ };
105
+ }
106
+ //#endregion
107
+ export { createCloudflareQueueBatchHandler as n, cloudflare_exports as t };
@@ -0,0 +1,29 @@
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 cloudflareQueueNamePrefix = "queue--";
15
+ const defaultCloudflareQueueBindingPrefix = "QUEUE";
16
+ const encodedCloudflareQueueNamePattern = /^queue--([0-9a-f]{2})+$/i;
17
+ function getCloudflareQueueName(name) {
18
+ return `${cloudflareQueueNamePrefix}${encodeNameHex(name)}`;
19
+ }
20
+ function getCloudflareQueueBindingName(name) {
21
+ const encoded = encodeNameHex(name).toUpperCase();
22
+ return encoded ? `${defaultCloudflareQueueBindingPrefix}_${encoded}` : defaultCloudflareQueueBindingPrefix;
23
+ }
24
+ function getCloudflareQueueDefinitionName(name) {
25
+ if (!encodedCloudflareQueueNamePattern.test(name)) return name;
26
+ return decodeNameHex(name.slice(7)) || name;
27
+ }
28
+ //#endregion
29
+ export { encodeNameHex as i, getCloudflareQueueDefinitionName as n, getCloudflareQueueName as r, getCloudflareQueueBindingName as t };
@@ -0,0 +1,49 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ //#region ../internal/src/runtime/cloudflare-env.ts
3
+ let activeEnv;
4
+ const activeEnvStorage = new AsyncLocalStorage();
5
+ function setActiveCloudflareEnv(env) {
6
+ activeEnv = env;
7
+ globalThis.__env__ = env;
8
+ try {
9
+ activeEnvStorage.enterWith(env);
10
+ } catch {}
11
+ }
12
+ function getActiveCloudflareEnv() {
13
+ return activeEnvStorage.getStore() ?? activeEnv ?? globalThis.__env__;
14
+ }
15
+ function getCloudflareEnv(event) {
16
+ const target = event;
17
+ return target?.env || target?.context?.cloudflare?.env || target?.context?._platform?.cloudflare?.env || target?.req?.runtime?.cloudflare?.env || getActiveCloudflareEnv();
18
+ }
19
+ function resolveWaitUntil(event) {
20
+ const target = event;
21
+ const owners = [
22
+ target,
23
+ target?.context,
24
+ target?.context?.cloudflare,
25
+ target?.context?.cloudflare?.context,
26
+ target?.context?._platform?.cloudflare,
27
+ target?.context?._platform?.cloudflare?.context,
28
+ target?.req,
29
+ target?.req?.runtime?.cloudflare,
30
+ target?.req?.runtime?.cloudflare?.context
31
+ ];
32
+ for (const owner of owners) if (typeof owner?.waitUntil === "function") return owner.waitUntil.bind(owner);
33
+ }
34
+ function createCloudflareRuntimeEvent(env, context) {
35
+ const waitUntil = typeof context?.waitUntil === "function" ? context.waitUntil.bind(context) : void 0;
36
+ return {
37
+ context: {
38
+ cloudflare: {
39
+ env,
40
+ context
41
+ },
42
+ waitUntil
43
+ },
44
+ env,
45
+ waitUntil
46
+ };
47
+ }
48
+ //#endregion
49
+ export { setActiveCloudflareEnv as i, getCloudflareEnv as n, resolveWaitUntil as r, createCloudflareRuntimeEvent as t };
@@ -0,0 +1,14 @@
1
+ //#region src/runtime/cloudflare-shared.ts
2
+ function createQueueJob(message, batch) {
3
+ return {
4
+ attempts: typeof message.attempts === "number" ? message.attempts : 1,
5
+ id: message.id,
6
+ metadata: {
7
+ batch,
8
+ message
9
+ },
10
+ payload: message.body
11
+ };
12
+ }
13
+ //#endregion
14
+ export { createQueueJob as t };
@@ -0,0 +1,66 @@
1
+ import { n as createCloudflareQueueBatchHandler } from "./cloudflare-CTdH2u_E.js";
2
+ import { t as normalizeQueueOptions } from "./config-CIDUZkmH.js";
3
+ import { n as getCloudflareQueueDefinitionName } from "./cloudflare-D5dVqiNw.js";
4
+ import { i as setActiveCloudflareEnv, t as createCloudflareRuntimeEvent } from "./cloudflare-env-CJ6g1-Qb.js";
5
+ import { loadQueueDefinition, runWithQueueRuntimeEvent, setQueueRuntimeConfig, setQueueRuntimeRegistry } from "./runtime/state.js";
6
+ import { t as resolveAppFetch } from "./app-BFpA3j89.js";
7
+ import { t as createQueueJob } from "./cloudflare-shared-Ce61GXcn.js";
8
+ import { H3, toWebHandler } from "h3/cloudflare";
9
+ //#region ../internal/src/runtime/cloudflare-hosted.ts
10
+ function createWebRequestHandler(appHandler) {
11
+ const defaultHandler = toWebHandler(new H3());
12
+ return async (request, context) => await Promise.resolve(appHandler ? appHandler(request, context) : defaultHandler(request, context));
13
+ }
14
+ function createCloudflareHostedWorker(adapter) {
15
+ const requestHandler = createWebRequestHandler(resolveAppFetch(adapter.label, adapter.app));
16
+ return { async fetch(request, env, context) {
17
+ const handle = async (handlerContext) => await Promise.resolve(requestHandler(request, handlerContext));
18
+ if (adapter.onRequest) return await adapter.onRequest({
19
+ env,
20
+ executionContext: context,
21
+ handle
22
+ });
23
+ return await handle();
24
+ } };
25
+ }
26
+ //#endregion
27
+ //#region src/runtime/cloudflare-vite.ts
28
+ function createQueueCloudflareWorker(options = {}) {
29
+ const queueConfig = options.queue === false ? false : normalizeQueueOptions(options.queue, { hosting: "cloudflare" });
30
+ const registry = options.registry;
31
+ const applyRuntimeState = () => {
32
+ setQueueRuntimeConfig(queueConfig);
33
+ setQueueRuntimeRegistry(registry);
34
+ };
35
+ return {
36
+ ...createCloudflareHostedWorker({
37
+ app: options.app,
38
+ label: "queue",
39
+ async onRequest({ env, executionContext, handle }) {
40
+ applyRuntimeState();
41
+ setActiveCloudflareEnv(env);
42
+ const runtimeEvent = createCloudflareRuntimeEvent(env, executionContext);
43
+ return await runWithQueueRuntimeEvent(runtimeEvent, () => handle(runtimeEvent.context));
44
+ }
45
+ }),
46
+ async queue(batch, env, context) {
47
+ applyRuntimeState();
48
+ setActiveCloudflareEnv(env);
49
+ if (queueConfig === false || queueConfig?.provider !== "cloudflare") return;
50
+ const definition = await loadQueueDefinition(getCloudflareQueueDefinitionName(batch.queue));
51
+ if (!definition) return;
52
+ const runtimeEvent = createCloudflareRuntimeEvent(env, context);
53
+ await createCloudflareQueueBatchHandler({
54
+ concurrency: definition.options?.concurrency,
55
+ onError: definition.options?.onError,
56
+ onMessage: async (message, currentBatch) => {
57
+ await runWithQueueRuntimeEvent(runtimeEvent, async () => {
58
+ await definition.handler(createQueueJob(message, currentBatch));
59
+ });
60
+ }
61
+ })(batch);
62
+ }
63
+ };
64
+ }
65
+ //#endregion
66
+ export { createQueueCloudflareWorker as t };
@@ -0,0 +1,23 @@
1
+ import { i as CloudflareQueueMessageBatch, l as QueueDefinitionRegistry, y as ResolvedQueueOptions } from "./types-CBsyjWye.js";
2
+ import { t as QueueApp } from "./_app-Bx4e5L33.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
+ queue?: false | ResolvedQueueOptions;
15
+ registry?: QueueDefinitionRegistry;
16
+ }
17
+ interface QueueCloudflareWorker {
18
+ fetch: (request: Request, env: CloudflareWorkerEnv, context: CloudflareWorkerExecutionContext) => Promise<Response>;
19
+ queue: (batch: CloudflareQueueMessageBatch, env: CloudflareWorkerEnv, context: CloudflareWorkerExecutionContext) => Promise<void>;
20
+ }
21
+ declare function createQueueCloudflareWorker(options?: QueueCloudflareWorkerOptions): QueueCloudflareWorker;
22
+ //#endregion
23
+ export { createQueueCloudflareWorker as i, QueueCloudflareWorker as n, QueueCloudflareWorkerOptions as r, CloudflareWorkerApp as t };
@@ -0,0 +1,29 @@
1
+ import { defu } from "defu";
2
+ //#region ../internal/src/feature-bridge/hosting.ts
3
+ function normalizeHosting(hosting) {
4
+ const normalized = hosting?.trim().toLowerCase().replaceAll("_", "-") || "";
5
+ if (normalized === "cloudflare") return "cloudflare-module";
6
+ return normalized;
7
+ }
8
+ //#endregion
9
+ //#region ../internal/src/object.ts
10
+ function isPlainObject(value) {
11
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
12
+ }
13
+ //#endregion
14
+ //#region src/config.ts
15
+ const knownProviders = new Set(["cloudflare", "vercel"]);
16
+ function resolveProvider(options, hosting) {
17
+ const shared = typeof options.cache === "boolean" ? { cache: options.cache } : {};
18
+ const provider = options.provider;
19
+ if (typeof provider === "string" && !knownProviders.has(provider)) throw new TypeError(`Unknown \`queue.provider\`: ${JSON.stringify(provider)}. Expected "cloudflare" or "vercel".`);
20
+ if ((provider || (hosting.includes("cloudflare") ? "cloudflare" : "vercel")) === "cloudflare") return defu(typeof options.binding === "string" ? { binding: options.binding } : {}, shared, { provider: "cloudflare" });
21
+ return defu(typeof options.region === "string" ? { region: options.region } : {}, shared, { provider: "vercel" });
22
+ }
23
+ function normalizeQueueOptions(options, input = {}) {
24
+ if (options === false) return void 0;
25
+ if (typeof options !== "undefined" && !isPlainObject(options)) throw new TypeError("`queue` must be a plain object.");
26
+ return resolveProvider(options || {}, normalizeHosting(input.hosting));
27
+ }
28
+ //#endregion
29
+ export { normalizeQueueOptions as t };
@@ -0,0 +1,57 @@
1
+ //#region src/enqueue.ts
2
+ const envelopeKeys = new Set([
3
+ "contentType",
4
+ "delaySeconds",
5
+ "id",
6
+ "idempotencyKey",
7
+ "region",
8
+ "retentionSeconds"
9
+ ]);
10
+ let fallbackCounter = 0;
11
+ function createQueueMessageId(prefix = "queue") {
12
+ const uuid = globalThis.crypto?.randomUUID?.();
13
+ if (uuid) return `${prefix}_${uuid}`;
14
+ fallbackCounter = fallbackCounter + 1 >>> 0;
15
+ return `${prefix}_${Date.now().toString(36)}_${fallbackCounter.toString(36)}`;
16
+ }
17
+ function isQueueEnvelope(input) {
18
+ if (typeof input !== "object" || input === null || Array.isArray(input) || !("payload" in input)) return false;
19
+ return Object.keys(input).every((key) => key === "payload" || envelopeKeys.has(key));
20
+ }
21
+ function normalizeQueueEnqueueInput(input) {
22
+ if (!isQueueEnvelope(input)) return {
23
+ id: createQueueMessageId(),
24
+ options: {},
25
+ payload: input
26
+ };
27
+ const { contentType, delaySeconds, id, idempotencyKey, payload, region, retentionSeconds } = input;
28
+ const options = {
29
+ ...contentType !== void 0 ? { contentType } : {},
30
+ ...delaySeconds !== void 0 ? { delaySeconds } : {},
31
+ ...idempotencyKey !== void 0 ? { idempotencyKey } : {},
32
+ ...region !== void 0 ? { region } : {},
33
+ ...retentionSeconds !== void 0 ? { retentionSeconds } : {}
34
+ };
35
+ return {
36
+ id: typeof id === "string" && id.length > 0 ? id : createQueueMessageId(),
37
+ options,
38
+ payload
39
+ };
40
+ }
41
+ //#endregion
42
+ //#region src/errors.ts
43
+ var QueueError = class extends Error {
44
+ code;
45
+ details;
46
+ httpStatus;
47
+ method;
48
+ provider;
49
+ cause;
50
+ constructor(message, metadata = {}) {
51
+ super(message);
52
+ this.name = "QueueError";
53
+ Object.assign(this, metadata);
54
+ }
55
+ };
56
+ //#endregion
57
+ export { createQueueMessageId as n, normalizeQueueEnqueueInput as r, QueueError as t };
@@ -0,0 +1,136 @@
1
+ import { t as normalizeQueueOptions } from "./config-CIDUZkmH.js";
2
+ import { r as normalizeQueueEnqueueInput, t as QueueError } from "./errors-xRt0BFZK.js";
3
+ import { t as getCloudflareQueueBindingName } from "./cloudflare-D5dVqiNw.js";
4
+ import { t as getVercelQueueTopicName } from "./vercel-BGm0G00p.js";
5
+ import { n as getCloudflareEnv, r as resolveWaitUntil } from "./cloudflare-env-CJ6g1-Qb.js";
6
+ import { getQueueClientCache, getQueueRuntimeConfig, getQueueRuntimeEvent, loadQueueDefinition, runWithQueueRuntimeEvent } from "./runtime/state.js";
7
+ import { waitUntil } from "@vercel/functions";
8
+ import { getRequestHeaders, getRequestURL, readRawBody } from "h3";
9
+ //#region src/runtime/client.ts
10
+ function resolveCloudflareBinding(binding, name) {
11
+ if (binding && typeof binding !== "string") return binding;
12
+ const bindingName = binding || getCloudflareQueueBindingName(name);
13
+ return getCloudflareEnv(getQueueRuntimeEvent())?.[bindingName] || bindingName;
14
+ }
15
+ function toProviderOptions(name, config) {
16
+ if (config.provider === "cloudflare") return {
17
+ ...config,
18
+ binding: resolveCloudflareBinding(config.binding, name)
19
+ };
20
+ return {
21
+ ...config,
22
+ topic: getVercelQueueTopicName(name)
23
+ };
24
+ }
25
+ async function createQueueClient(options) {
26
+ if (options.provider === "cloudflare") {
27
+ const { createCloudflareQueueClient } = await import("./cloudflare-CTdH2u_E.js").then((n) => n.t);
28
+ return createCloudflareQueueClient(options);
29
+ }
30
+ const { createVercelQueueClient } = await import("./vercel-D31zfxiW.js");
31
+ return await createVercelQueueClient(options);
32
+ }
33
+ function getActiveQueueConfig() {
34
+ const config = getQueueRuntimeConfig();
35
+ if (config === false) return false;
36
+ return config || normalizeQueueOptions(void 0, { hosting: "vercel" });
37
+ }
38
+ async function createNamedQueueClient(name) {
39
+ const config = getActiveQueueConfig();
40
+ if (config === false) throw new QueueError("Queue is disabled.", {
41
+ code: "QUEUE_DISABLED",
42
+ httpStatus: 400
43
+ });
44
+ const provider = toProviderOptions(name, config);
45
+ try {
46
+ return await createQueueClient(provider);
47
+ } catch (error) {
48
+ if (error instanceof QueueError) throw error;
49
+ throw new QueueError(error instanceof Error ? error.message : String(error), {
50
+ cause: error,
51
+ provider: provider.provider
52
+ });
53
+ }
54
+ }
55
+ async function getQueue(name) {
56
+ const definition = await loadQueueDefinition(name);
57
+ if (!definition) throw new QueueError(`Unknown queue definition: ${name}`, {
58
+ code: "QUEUE_DEFINITION_NOT_FOUND",
59
+ details: { name },
60
+ httpStatus: 404
61
+ });
62
+ const config = getActiveQueueConfig();
63
+ if (definition.options?.cache === false || config === false || config.cache === false || config.provider === "cloudflare") return await createNamedQueueClient(name);
64
+ const cache = getQueueClientCache();
65
+ const existing = cache.get(name);
66
+ if (existing) return await existing;
67
+ const pending = createNamedQueueClient(name).catch((error) => {
68
+ cache.delete(name);
69
+ throw error;
70
+ });
71
+ cache.set(name, pending);
72
+ return await pending;
73
+ }
74
+ async function runQueue(name, input) {
75
+ if (!await loadQueueDefinition(name)) throw new QueueError(`Unknown queue definition: ${name}`, {
76
+ code: "QUEUE_DEFINITION_NOT_FOUND",
77
+ details: { name },
78
+ httpStatus: 404
79
+ });
80
+ const normalized = normalizeQueueEnqueueInput(input);
81
+ return await (await getQueue(name)).send({
82
+ ...normalized.options,
83
+ id: normalized.id,
84
+ payload: normalized.payload
85
+ });
86
+ }
87
+ function deferQueue(name, input) {
88
+ const request = getQueueRuntimeEvent();
89
+ const task = () => runWithQueueRuntimeEvent(request, () => runQueue(name, input));
90
+ const handleError = async (error) => {
91
+ console.error(`[vitehub] Deferred queue dispatch failed for "${name}"`, error);
92
+ try {
93
+ await (await loadQueueDefinition(name))?.options?.onDispatchError?.(error, { name });
94
+ } catch (hookError) {
95
+ console.error(`[vitehub] onDispatchError hook failed for "${name}"`, hookError);
96
+ }
97
+ };
98
+ const promise = task().catch(handleError);
99
+ const waitUntil = resolveWaitUntil(request);
100
+ if (typeof waitUntil === "function") waitUntil(promise);
101
+ }
102
+ //#endregion
103
+ //#region src/runtime/hosted.ts
104
+ const hostedVercelWaitUntil = waitUntil;
105
+ async function toRequest(event) {
106
+ if (event.request instanceof Request) return event.request;
107
+ const h3Event = event;
108
+ const body = await readRawBody(h3Event);
109
+ return new Request(getRequestURL(h3Event), {
110
+ body: body || void 0,
111
+ headers: getRequestHeaders(h3Event),
112
+ method: event.method || "POST"
113
+ });
114
+ }
115
+ function createVercelJobHandler(definition) {
116
+ return async (payload, metadata) => {
117
+ const meta = metadata;
118
+ await definition.handler({
119
+ attempts: typeof meta?.deliveryCount === "number" ? meta.deliveryCount : 1,
120
+ id: typeof meta?.messageId === "string" ? meta.messageId : "vercel-message",
121
+ metadata,
122
+ payload
123
+ });
124
+ };
125
+ }
126
+ async function handleHostedVercelQueueCallback(event, name, definition) {
127
+ const queue = await getQueue(name);
128
+ if (queue.provider !== "vercel") throw new QueueError(`Queue "${name}" resolved to provider "${queue.provider}", expected "vercel".`, {
129
+ code: "VERCEL_PROVIDER_EXPECTED",
130
+ httpStatus: 400,
131
+ provider: queue.provider
132
+ });
133
+ return await queue.callback(createVercelJobHandler(definition), definition.options?.callbackOptions)(await toRequest(event));
134
+ }
135
+ //#endregion
136
+ export { getQueue as a, deferQueue as i, hostedVercelWaitUntil as n, runQueue as o, createQueueClient as r, handleHostedVercelQueueCallback as t };
@@ -0,0 +1,53 @@
1
+ import { C as VercelQueueRetryHandler, S as VercelQueueRetryDirective, _ as QueueProviderOptions, a as DiscoveredQueueDefinition, b as VercelQueueCallbackOptions, c as QueueDefinitionOptions, d as QueueEnqueueOptions, f as QueueHandler, g as QueueProvider, h as QueueModuleProviderOptions, i as CloudflareQueueMessageBatch, l as QueueDefinitionRegistry, m as QueueModuleOptions, n as CloudflareQueueClient, o as QueueClient, p as QueueJob, r as CloudflareQueueMessage, s as QueueDefinition, t as CloudflareQueueBatchHandlerOptions, u as QueueEnqueueInput, v as QueueSendResult, w as VercelQueueSendResult, x as VercelQueueClient, y as ResolvedQueueOptions } from "./types-CBsyjWye.js";
2
+ import { handleHostedVercelQueueCallback } from "./runtime/hosted.js";
3
+ import { i as createQueueCloudflareWorker } from "./cloudflare-vite-CRx2CsH9.js";
4
+
5
+ //#region src/config.d.ts
6
+ interface QueueResolutionInput {
7
+ hosting?: string;
8
+ }
9
+ declare function normalizeQueueOptions(options: QueueModuleOptions | undefined, input?: QueueResolutionInput): ResolvedQueueOptions | undefined;
10
+ //#endregion
11
+ //#region src/definition.d.ts
12
+ declare function defineQueue<TPayload = unknown, TResult = unknown>(handler: QueueHandler<TPayload, TResult>, options?: QueueDefinitionOptions): QueueDefinition<TPayload, TResult>;
13
+ //#endregion
14
+ //#region src/enqueue.d.ts
15
+ declare function createQueueMessageId(prefix?: string): string;
16
+ //#endregion
17
+ //#region src/errors.d.ts
18
+ interface QueueErrorMetadata {
19
+ cause?: unknown;
20
+ code?: string;
21
+ details?: Record<string, unknown>;
22
+ httpStatus?: number;
23
+ method?: string;
24
+ provider?: string;
25
+ }
26
+ declare class QueueError extends Error {
27
+ readonly code?: string;
28
+ readonly details?: Record<string, unknown>;
29
+ readonly httpStatus?: number;
30
+ readonly method?: string;
31
+ readonly provider?: string;
32
+ override readonly cause?: unknown;
33
+ constructor(message: string, metadata?: QueueErrorMetadata);
34
+ }
35
+ //#endregion
36
+ //#region src/providers/cloudflare.d.ts
37
+ declare function createCloudflareQueueBatchHandler<TPayload = unknown>(options: CloudflareQueueBatchHandlerOptions<TPayload>): (batch: CloudflareQueueMessageBatch<TPayload>) => Promise<void>;
38
+ //#endregion
39
+ //#region src/integrations/cloudflare.d.ts
40
+ declare function getCloudflareQueueName(name: string): string;
41
+ declare function getCloudflareQueueBindingName(name: string): string;
42
+ declare function getCloudflareQueueDefinitionName(name: string): string;
43
+ //#endregion
44
+ //#region src/integrations/vercel.d.ts
45
+ declare function getVercelQueueTopicName(name: string): string;
46
+ //#endregion
47
+ //#region src/runtime/client.d.ts
48
+ declare function createQueueClient(options: QueueProviderOptions): Promise<QueueClient>;
49
+ declare function getQueue(name: string): Promise<QueueClient>;
50
+ declare function runQueue<TPayload = unknown>(name: string, input: QueueEnqueueInput<TPayload>): Promise<QueueSendResult>;
51
+ declare function deferQueue<TPayload = unknown>(name: string, input: QueueEnqueueInput<TPayload>): void;
52
+ //#endregion
53
+ export { type CloudflareQueueBatchHandlerOptions, type CloudflareQueueClient, type CloudflareQueueMessage, type CloudflareQueueMessageBatch, type DiscoveredQueueDefinition, type QueueClient, type QueueDefinition, type QueueDefinitionOptions, type QueueDefinitionRegistry, type QueueEnqueueInput, type QueueEnqueueOptions, QueueError, type QueueHandler, type QueueJob, type QueueModuleOptions, type QueueModuleProviderOptions, type QueueProvider, type QueueProviderOptions, type QueueSendResult, type ResolvedQueueOptions, type VercelQueueCallbackOptions, type VercelQueueClient, type VercelQueueRetryDirective, type VercelQueueRetryHandler, type VercelQueueSendResult, createCloudflareQueueBatchHandler, createQueueClient, createQueueCloudflareWorker, createQueueMessageId, deferQueue, defineQueue, getCloudflareQueueBindingName, getCloudflareQueueDefinitionName, getCloudflareQueueName, getQueue, getVercelQueueTopicName, handleHostedVercelQueueCallback, normalizeQueueOptions, runQueue };
package/dist/index.js ADDED
@@ -0,0 +1,17 @@
1
+ import { n as createCloudflareQueueBatchHandler } from "./cloudflare-CTdH2u_E.js";
2
+ import { t as normalizeQueueOptions } from "./config-CIDUZkmH.js";
3
+ import { n as createQueueMessageId, t as QueueError } from "./errors-xRt0BFZK.js";
4
+ import { n as getCloudflareQueueDefinitionName, r as getCloudflareQueueName, t as getCloudflareQueueBindingName } from "./cloudflare-D5dVqiNw.js";
5
+ import { t as getVercelQueueTopicName } from "./vercel-BGm0G00p.js";
6
+ import { a as getQueue, i as deferQueue, o as runQueue, r as createQueueClient, t as handleHostedVercelQueueCallback } from "./hosted-Dw9WiPNH.js";
7
+ import { t as createQueueCloudflareWorker } from "./cloudflare-vite-Bs67_E_Y.js";
8
+ //#region src/definition.ts
9
+ function defineQueue(handler, options) {
10
+ if (typeof handler !== "function") throw new TypeError("`defineQueue()` requires a queue handler.");
11
+ return {
12
+ handler,
13
+ options
14
+ };
15
+ }
16
+ //#endregion
17
+ export { QueueError, createCloudflareQueueBatchHandler, createQueueClient, createQueueCloudflareWorker, createQueueMessageId, deferQueue, defineQueue, getCloudflareQueueBindingName, getCloudflareQueueDefinitionName, getCloudflareQueueName, getQueue, getVercelQueueTopicName, handleHostedVercelQueueCallback, normalizeQueueOptions, runQueue };