@vite-hub/queue 0.0.3 → 0.1.0

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 (52) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +110 -50
  3. package/dist/client-CIc3jsj2.js +114 -0
  4. package/dist/cloudflare-client-COzQ8fHk.js +147 -0
  5. package/dist/{cloudflare-resource-name-R8zYQiZb.js → cloudflare-resource-name-CCuLDvSP.js} +3 -2
  6. package/dist/{cloudflare-vite-bA1eLf46.js → cloudflare-vite-BCuJOXcT.js} +31 -12
  7. package/dist/{cloudflare-vite-nFPor46-.d.ts → cloudflare-vite-CjdP5yBN.d.ts} +9 -4
  8. package/dist/config-BINujLv4.js +74 -0
  9. package/dist/enqueue-CnQ0QR3O.js +22 -0
  10. package/dist/error-diagnostics-A_8Kp-48.js +116 -0
  11. package/dist/error-diagnostics-qzRF6IVB.js +109 -0
  12. package/dist/errors-DIFaM9tW.js +42 -0
  13. package/dist/handler-response-CBwIkmTS.js +56 -0
  14. package/dist/index.d.ts +32 -70
  15. package/dist/index.js +9 -8
  16. package/dist/inspect-PeuckaC3.js +30 -0
  17. package/dist/internal/runtime/cloudflare-client.d.ts +3 -5
  18. package/dist/internal/runtime/cloudflare-client.js +1 -1
  19. package/dist/internal/runtime/cloudflare-vite.d.ts +1 -1
  20. package/dist/internal/runtime/cloudflare-vite.js +1 -1
  21. package/dist/internal/runtime/state.d.ts +16 -15
  22. package/dist/internal/runtime/state.js +2 -2
  23. package/dist/internal/runtime/vercel-client.d.ts +3 -5
  24. package/dist/internal/runtime/vercel-client.js +93 -62
  25. package/dist/nuxt.d.ts +27 -7
  26. package/dist/nuxt.js +7 -2
  27. package/dist/object-B1NW521B.js +7 -0
  28. package/dist/operations-Cnjbz8kk.js +63 -0
  29. package/dist/operations-tNUdj3G4.d.ts +212 -0
  30. package/dist/operations.d.ts +32 -0
  31. package/dist/operations.js +1195 -0
  32. package/dist/runtime/hosted.d.ts +4 -7
  33. package/dist/runtime/hosted.js +30 -8
  34. package/dist/state-G9s378-e.js +184 -0
  35. package/dist/{types-CwvoMATy.d.ts → types-1GRMYES1.d.ts} +35 -24
  36. package/dist/vercel-region-cjskrOKl.js +122 -0
  37. package/dist/vite-ChWLzOVu.js +1512 -0
  38. package/dist/vite.d.ts +346 -33
  39. package/dist/vite.js +2 -2
  40. package/package.json +69 -23
  41. package/dist/_app-D29AwUdD.d.ts +0 -11
  42. package/dist/app-BZpq2cwC.js +0 -10
  43. package/dist/client-CPQ-iyXS.js +0 -93
  44. package/dist/cloudflare-client-w5vphoNn.js +0 -99
  45. package/dist/config-B7xkD1v0.js +0 -47
  46. package/dist/delivery-error-glgYWC9g.js +0 -45
  47. package/dist/errors-CjuG_qr-.js +0 -108
  48. package/dist/internal/runtime/vercel-vite.d.ts +0 -20
  49. package/dist/internal/runtime/vercel-vite.js +0 -49
  50. package/dist/state-Bo8CLZ_k.js +0 -105
  51. package/dist/vercel-runtime-package-copy-CKimoFJ5.js +0 -66
  52. package/dist/vite-BcMpQk_n.js +0 -1842
@@ -0,0 +1,147 @@
1
+ import { t as queueErrorDiagnostics } from "./error-diagnostics-qzRF6IVB.js";
2
+ import { n as normalizeQueueEnqueueInput } from "./enqueue-CnQ0QR3O.js";
3
+ import { a as queueProviderResult, n as formatQueueOptionNames, t as cloudflareUnsupportedEnqueueOptions } from "./errors-DIFaM9tW.js";
4
+ import { n as getCloudflareQueueDefinitionName } from "./cloudflare-GosJefIK.js";
5
+ import { n as isNonRetryableQueueError, r as reportQueueDeliveryError, t as checkQueueHandlerResponse } from "./handler-response-CBwIkmTS.js";
6
+ //#region src/providers/cloudflare.ts
7
+ const cloudflareBindingName = /^[A-Z_]\w{0,127}$/i;
8
+ function isCloudflareQueueBinding(binding) {
9
+ if (binding === null || typeof binding !== "object" || Array.isArray(binding)) return false;
10
+ const hasCallableMethod = (name) => {
11
+ let owner = binding;
12
+ while (owner && owner !== Object.prototype) {
13
+ let descriptor;
14
+ try {
15
+ descriptor = Object.getOwnPropertyDescriptor(owner, name);
16
+ } catch {
17
+ return false;
18
+ }
19
+ if (descriptor) {
20
+ if (owner !== binding) {
21
+ const constructor = Object.getOwnPropertyDescriptor(owner, "constructor");
22
+ if (!constructor || !("value" in constructor) || typeof constructor.value !== "function" || constructor.value.prototype !== owner) return false;
23
+ }
24
+ if ("value" in descriptor) return typeof descriptor.value === "function";
25
+ try {
26
+ return typeof Reflect.get(binding, name) === "function";
27
+ } catch {
28
+ return false;
29
+ }
30
+ }
31
+ try {
32
+ owner = Object.getPrototypeOf(owner);
33
+ } catch {
34
+ return false;
35
+ }
36
+ }
37
+ return false;
38
+ };
39
+ return hasCallableMethod("send") && hasCallableMethod("sendBatch");
40
+ }
41
+ function toSendOptions(options = {}) {
42
+ const unsupported = cloudflareUnsupportedEnqueueOptions.filter((option) => options[option] !== void 0);
43
+ if (unsupported.length) return [queueErrorDiagnostics.QUEUE_UNSUPPORTED_OPTION({
44
+ options: formatQueueOptionNames(unsupported),
45
+ provider: "cloudflare"
46
+ }), void 0];
47
+ return [void 0, {
48
+ contentType: options.contentType,
49
+ delaySeconds: options.delaySeconds
50
+ }];
51
+ }
52
+ function resolveAction(action, message, fallback) {
53
+ if (action && typeof action === "object" && !Array.isArray(action) && Object.hasOwn(action, "retry")) {
54
+ message.retry(action.retry);
55
+ return;
56
+ }
57
+ if ((action === "ack" || action === "retry" ? action : fallback) === "ack") message.ack();
58
+ else message.retry();
59
+ }
60
+ function createCloudflareQueueBatchHandler(options) {
61
+ const requested = Number(options.concurrency ?? 1);
62
+ const concurrency = Number.isFinite(requested) ? Math.max(1, Math.floor(requested)) : 1;
63
+ return async (batch) => {
64
+ const messages = Array.isArray(batch?.messages) ? batch.messages : [];
65
+ if (!messages.length) return;
66
+ let index = 0;
67
+ const worker = async () => {
68
+ while (index < messages.length) {
69
+ const message = messages[index++];
70
+ try {
71
+ checkQueueHandlerResponse(await options.onMessage(message, batch));
72
+ message.ack();
73
+ } catch (error) {
74
+ const reportContext = {
75
+ attempts: message.attempts,
76
+ id: message.id,
77
+ provider: "cloudflare",
78
+ queue: getCloudflareQueueDefinitionName(batch.queue)
79
+ };
80
+ reportQueueDeliveryError(error, reportContext);
81
+ let action = void 0;
82
+ if (options.onError) try {
83
+ action = await options.onError(error, message, batch);
84
+ } catch (hookError) {
85
+ reportQueueDeliveryError(hookError, reportContext);
86
+ }
87
+ resolveAction(action, message, isNonRetryableQueueError(error) ? "ack" : "retry");
88
+ }
89
+ }
90
+ };
91
+ await Promise.all(Array.from({ length: Math.min(concurrency, messages.length) }, () => worker()));
92
+ };
93
+ }
94
+ function createCloudflareQueueClient(provider) {
95
+ if (typeof provider.binding === "undefined" || typeof provider.binding === "string") {
96
+ const binding = typeof provider.binding === "string" && cloudflareBindingName.test(provider.binding) ? provider.binding : void 0;
97
+ throw queueErrorDiagnostics.QUEUE_BINDING_NOT_FOUND({ binding });
98
+ }
99
+ if (!isCloudflareQueueBinding(provider.binding)) throw queueErrorDiagnostics.QUEUE_INVALID_BINDING();
100
+ const binding = provider.binding;
101
+ return {
102
+ provider: "cloudflare",
103
+ native: binding,
104
+ binding,
105
+ async send(payload, options) {
106
+ const normalized = normalizeQueueEnqueueInput(payload, options);
107
+ const [optionsError, sendOptions] = toSendOptions(normalized.options);
108
+ if (optionsError) return [optionsError, void 0];
109
+ const [error] = await queueProviderResult("cloudflare", "send", () => binding.send(normalized.payload, sendOptions));
110
+ if (error) return [error, void 0];
111
+ return [void 0, {
112
+ status: "queued",
113
+ messageId: normalized.id
114
+ }];
115
+ },
116
+ async sendBatch(items, options) {
117
+ const messages = [];
118
+ for (const item of items) {
119
+ const [optionsError, sendOptions] = toSendOptions({
120
+ ...options,
121
+ contentType: item.contentType || options?.contentType,
122
+ delaySeconds: item.delaySeconds ?? options?.delaySeconds
123
+ });
124
+ if (optionsError) return [optionsError, void 0];
125
+ messages.push({
126
+ ...item,
127
+ ...sendOptions
128
+ });
129
+ }
130
+ const [error] = await queueProviderResult("cloudflare", "send-batch", () => binding.sendBatch(messages));
131
+ if (error) return [error, void 0];
132
+ return [void 0, messages.map(() => ({ status: "queued" }))];
133
+ },
134
+ createBatchHandler: createCloudflareQueueBatchHandler
135
+ };
136
+ }
137
+ //#endregion
138
+ //#region src/internal/runtime/cloudflare-client.ts
139
+ async function createCloudflareQueueRuntimeClient(options) {
140
+ if (options.provider !== "cloudflare") throw queueErrorDiagnostics.QUEUE_PROVIDER_MISMATCH({
141
+ expected: "cloudflare",
142
+ provider: options.provider
143
+ });
144
+ return createCloudflareQueueClient(options);
145
+ }
146
+ //#endregion
147
+ export { createCloudflareQueueBatchHandler as n, createCloudflareQueueRuntimeClient as t };
@@ -1,3 +1,4 @@
1
+ import { t as queueErrorDiagnostics } from "./error-diagnostics-qzRF6IVB.js";
1
2
  import { r as encodeNameHex } from "./cloudflare-GosJefIK.js";
2
3
  //#region src/internal/cloudflare-resource-name.ts
3
4
  const cloudflareQueueNamePrefix = "queue--";
@@ -8,7 +9,7 @@ const maxCloudflareQueueNameLength = 63;
8
9
  const digestLength = 32;
9
10
  function digestCloudflareQueueName(name, namePrefix) {
10
11
  const crypto = globalThis.process?.getBuiltinModule("node:crypto");
11
- if (!crypto) throw new Error("Cloudflare queue name derivation requires the Node.js crypto module.");
12
+ if (!crypto) throw queueErrorDiagnostics.QUEUE_CRYPTO_UNAVAILABLE();
12
13
  return crypto.hash("sha256", JSON.stringify([
13
14
  "vitehub",
14
15
  "cloudflare",
@@ -27,7 +28,7 @@ function createBoundedCloudflareQueueName(name, namePrefix) {
27
28
  }
28
29
  function getCloudflareQueueName(name, namePrefix = "") {
29
30
  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
+ if (!cloudflareQueueNamePattern.test(queueName)) throw queueErrorDiagnostics.QUEUE_INVALID_NAME({ name: queueName });
31
32
  return queueName.length <= maxCloudflareQueueNameLength ? queueName : createBoundedCloudflareQueueName(name, namePrefix);
32
33
  }
33
34
  //#endregion
@@ -1,14 +1,29 @@
1
- import { t as normalizeQueueOptions } from "./config-B7xkD1v0.js";
1
+ import { t as internalErrorDiagnostics } from "./error-diagnostics-A_8Kp-48.js";
2
+ import { t as normalizeQueueOptions } from "./config-BINujLv4.js";
3
+ import { t as queueErrorDiagnostics } from "./error-diagnostics-qzRF6IVB.js";
2
4
  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-Bo8CLZ_k.js";
6
- import { t as resolveAppFetch } from "./app-BZpq2cwC.js";
7
- import { H3, toWebHandler } from "h3/cloudflare";
5
+ import { n as createCloudflareQueueBatchHandler, t as createCloudflareQueueRuntimeClient } from "./cloudflare-client-COzQ8fHk.js";
6
+ import { t as getCloudflareQueueName } from "./cloudflare-resource-name-CCuLDvSP.js";
7
+ import { f as setQueueRuntimeRegistry, g as runWithActiveCloudflareEnv, l as runWithQueueRuntimeEvent, p as createCloudflareRuntimeEvent, s as loadQueueDefinition, u as setQueueRuntimeConfig } from "./state-G9s378-e.js";
8
+ //#region ../internal/src/runtime/app.ts
9
+ function resolveAppFetch(label, app) {
10
+ if (!app) return;
11
+ if (typeof app === "function") return app;
12
+ if (typeof app.request === "function") return (request, context) => app.request(request, void 0, context);
13
+ if (typeof app.fetch === "function") return app.fetch.bind(app);
14
+ throw internalErrorDiagnostics.INTERNAL_R0011({ message: `Invalid ${label} app. Expected an h3 app or a fetch-compatible handler.` });
15
+ }
16
+ //#endregion
8
17
  //#region ../internal/src/runtime/cloudflare-hosted.ts
9
18
  function createWebRequestHandler(appHandler) {
10
- const defaultHandler = toWebHandler(new H3());
11
- return async (request, context) => await Promise.resolve(appHandler ? appHandler(request, context) : defaultHandler(request, context));
19
+ return async (request, context) => await Promise.resolve(appHandler ? appHandler(request, context) : new Response(JSON.stringify({
20
+ status: 404,
21
+ message: `Cannot find any route matching [${request.method}] ${request.url}`
22
+ }), {
23
+ headers: { "content-type": "application/json;charset=UTF-8" },
24
+ status: 404,
25
+ statusText: "Not Found"
26
+ }));
12
27
  }
13
28
  function createCloudflareHostedWorker(adapter) {
14
29
  const requestHandler = createWebRequestHandler(resolveAppFetch(adapter.label, adapter.app));
@@ -42,7 +57,11 @@ function createRegistryDefinitionNames(registry, namePrefix) {
42
57
  const definitions = {};
43
58
  for (const name of Object.keys(registry)) {
44
59
  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.`);
60
+ if (definitions[physicalName]) throw queueErrorDiagnostics.QUEUE_NAME_COLLISION({
61
+ first: definitions[physicalName],
62
+ resolved: physicalName,
63
+ second: name
64
+ });
46
65
  definitions[physicalName] = name;
47
66
  }
48
67
  return definitions;
@@ -71,10 +90,10 @@ function createQueueCloudflareWorker(options = {}) {
71
90
  if (queueConfig === false || queueConfig?.provider !== "cloudflare") return;
72
91
  const runtimeEvent = createCloudflareRuntimeEvent(env, context);
73
92
  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.`);
93
+ const definitionName = definitions ? Object.hasOwn(definitions, batch.queue) ? definitions[batch.queue] : void 0 : 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));
94
+ if (!definitionName) throw queueErrorDiagnostics.QUEUE_DEFINITION_NOT_FOUND({ queue: batch.queue });
76
95
  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)}.`);
96
+ if (!definition) throw queueErrorDiagnostics.QUEUE_DEFINITION_NOT_FOUND({ queue: definitionName });
78
97
  await createCloudflareQueueBatchHandler({
79
98
  concurrency: definition.options?.concurrency,
80
99
  onError: definition.options?.onError,
@@ -1,14 +1,19 @@
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
-
1
+ import { C as ResolvedQueueOptions, a as CloudflareQueueMessageBatch, u as QueueDefinitionRegistry } from "./types-1GRMYES1.js";
4
2
  //#region ../internal/src/runtime/cloudflare-env.d.ts
5
3
  type CloudflareWorkerEnv = Record<string, unknown>;
6
4
  interface CloudflareWorkerExecutionContext {
7
5
  waitUntil?: (promise: Promise<unknown>) => void;
8
6
  }
9
7
  //#endregion
8
+ //#region ../internal/src/runtime/app.d.ts
9
+ type AppHandler = (request: Request, context?: Record<string, unknown>) => Response | Promise<Response>;
10
+ type VitehubApp = AppHandler | {
11
+ fetch?: AppHandler;
12
+ request?: (request: Request, options?: RequestInit, context?: Record<string, unknown>) => Response | Promise<Response>;
13
+ };
14
+ //#endregion
10
15
  //#region src/internal/runtime/cloudflare-vite.d.ts
11
- type CloudflareWorkerApp = QueueApp;
16
+ type CloudflareWorkerApp = VitehubApp;
12
17
  interface QueueCloudflareWorkerOptions {
13
18
  app?: CloudflareWorkerApp;
14
19
  definitions?: Record<string, string>;
@@ -0,0 +1,74 @@
1
+ import { t as isPlainObject } from "./object-B1NW521B.js";
2
+ import { t as queueErrorDiagnostics } from "./error-diagnostics-qzRF6IVB.js";
3
+ import { defu } from "defu";
4
+ function deploymentPresetFromNitro(value) {
5
+ const normalized = value?.trim().toLowerCase().replaceAll("_", "-");
6
+ if (!normalized) return;
7
+ if (normalized.startsWith("cloudflare")) return "cloudflare";
8
+ if (normalized.startsWith("deno")) return "deno";
9
+ if (normalized.startsWith("netlify")) return "netlify";
10
+ if (normalized === "node" || normalized.startsWith("node-")) return "node";
11
+ if (normalized.startsWith("vercel")) return "vercel";
12
+ }
13
+ //#endregion
14
+ //#region ../internal/src/hosting.ts
15
+ /**
16
+ * Returns the Nitro preset name that this build targets, as the developer wrote it.
17
+ * The order is `nitro.preset`, `hosting`, `NITRO_PRESET`, `SERVER_PRESET`, then `VITEHUB_HOSTING`.
18
+ * Empty values are skipped.
19
+ */
20
+ function resolveHostPreset(input = {}) {
21
+ const env = input.env ?? (typeof process === "undefined" ? {} : process.env);
22
+ const nitroPreset = input.nitro && typeof input.nitro === "object" ? Reflect.get(input.nitro, "preset") : void 0;
23
+ for (const value of [
24
+ nitroPreset,
25
+ input.hosting,
26
+ env.NITRO_PRESET,
27
+ env.SERVER_PRESET,
28
+ env.VITEHUB_HOSTING
29
+ ]) if (typeof value === "string" && value.trim()) return value.trim();
30
+ }
31
+ /** Returns the host that this build targets: `cloudflare`, `deno`, `netlify`, `node`, or `vercel`. */
32
+ function resolveHost(input = {}) {
33
+ return deploymentPresetFromNitro(resolveHostPreset(input));
34
+ }
35
+ function normalizeHosting(hosting) {
36
+ const normalized = hosting?.trim().toLowerCase().replaceAll("_", "-") || "";
37
+ if (normalized === "cloudflare") return "cloudflare-module";
38
+ return normalized;
39
+ }
40
+ /** Narrows a preset or host name to the hosts that have a native provider: Cloudflare, Netlify, or Vercel. */
41
+ function getHostingProvider(hosting) {
42
+ const preset = deploymentPresetFromNitro(hosting);
43
+ if (preset === "cloudflare" || preset === "netlify" || preset === "vercel") return preset;
44
+ }
45
+ //#endregion
46
+ //#region src/config.ts
47
+ const knownProviders = /* @__PURE__ */ new Set(["cloudflare", "vercel"]);
48
+ function readOwnOption(options, key) {
49
+ return Object.hasOwn(options, key) ? options[key] : void 0;
50
+ }
51
+ function resolveProvider(options, hosting) {
52
+ const cache = readOwnOption(options, "cache");
53
+ const shared = typeof cache === "boolean" ? { cache } : {};
54
+ const provider = readOwnOption(options, "provider");
55
+ if (typeof provider === "string" && !knownProviders.has(provider)) throw queueErrorDiagnostics.QUEUE_INVALID_PROVIDER({ provider });
56
+ if (typeof provider === "undefined" && hosting && !hosting.includes("cloudflare") && !hosting.includes("vercel")) throw queueErrorDiagnostics.QUEUE_MISSING_PROVIDER({ hosting });
57
+ if ((provider || (hosting.includes("cloudflare") ? "cloudflare" : "vercel")) === "cloudflare") {
58
+ const binding = readOwnOption(options, "binding");
59
+ const namePrefix = readOwnOption(options, "namePrefix");
60
+ return defu({
61
+ ...typeof binding === "string" ? { binding } : {},
62
+ ...typeof namePrefix === "string" ? { namePrefix } : {}
63
+ }, shared, { provider: "cloudflare" });
64
+ }
65
+ const region = readOwnOption(options, "region");
66
+ return defu(typeof region === "string" ? { region } : {}, shared, { provider: "vercel" });
67
+ }
68
+ function normalizeQueueOptions(options, input = {}) {
69
+ if (options === false) return void 0;
70
+ if (typeof options !== "undefined" && !isPlainObject(options)) throw queueErrorDiagnostics.QUEUE_INVALID_CONFIG();
71
+ return resolveProvider(options || {}, normalizeHosting(input.hosting));
72
+ }
73
+ //#endregion
74
+ export { resolveHostPreset as i, getHostingProvider as n, resolveHost as r, normalizeQueueOptions as t };
@@ -0,0 +1,22 @@
1
+ //#region src/enqueue.ts
2
+ let fallbackCounter = 0;
3
+ function createQueueMessageId(prefix = "queue") {
4
+ const uuid = globalThis.crypto?.randomUUID?.();
5
+ if (uuid) return `${prefix}_${uuid}`;
6
+ fallbackCounter = fallbackCounter + 1 >>> 0;
7
+ return `${prefix}_${Date.now().toString(36)}_${fallbackCounter.toString(36)}`;
8
+ }
9
+ /** Payload properties never select enqueue options. */
10
+ function normalizeQueueEnqueueInput(payload, options = {}) {
11
+ const hasOwnId = Object.hasOwn(options, "id");
12
+ const providerOptions = { ...options };
13
+ const id = hasOwnId ? Object.hasOwn(providerOptions, "id") ? providerOptions.id : options.id : void 0;
14
+ delete providerOptions.id;
15
+ return {
16
+ id: typeof id === "string" && id.length > 0 ? id : createQueueMessageId(),
17
+ options: providerOptions,
18
+ payload
19
+ };
20
+ }
21
+ //#endregion
22
+ export { normalizeQueueEnqueueInput as n, createQueueMessageId as t };
@@ -0,0 +1,116 @@
1
+ import { defineDiagnostics } from "nostics";
2
+ //#region ../internal/src/error-diagnostics.ts
3
+ const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
4
+ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
5
+ docsBase: () => "https://vitehub.dev/docs/reference/diagnostics",
6
+ codes: {
7
+ INTERNAL_R0012: dynamicError,
8
+ INTERNAL_R0013: dynamicError,
9
+ INTERNAL_R0014: {
10
+ why: ({ path }) => `Cannot read Provision State from "${path}".`,
11
+ fix: "Check file access and restore valid JSON while preserving existing resource IDs."
12
+ },
13
+ INTERNAL_R0020: {
14
+ fix: "Give the operation a name like `content.publish`, a description, a section, a kind, an input schema, and a run function.",
15
+ why: ({ message }) => message === void 0 ? "" : String(message)
16
+ },
17
+ INTERNAL_R0021: {
18
+ fix: "Run `vitehub inspect definitions --kind operation` to list the operations of this app.",
19
+ why: ({ message }) => message === void 0 ? "" : String(message)
20
+ },
21
+ INTERNAL_R0022: {
22
+ fix: "Send input that matches the schema of the operation. `vitehub <namespace> <command> --help` shows the fields.",
23
+ why: ({ message }) => message === void 0 ? "" : String(message)
24
+ },
25
+ INTERNAL_R0024: {
26
+ fix: "Start the dev server with `vite dev`, or pass `--url <origin>` of a deployed app with credentials in VITEHUB_CONSOLE_AUTHORIZATION, VITEHUB_CONSOLE_COOKIE, or CF_ACCESS_CLIENT_ID and CF_ACCESS_CLIENT_SECRET.",
27
+ why: ({ message }) => message === void 0 ? "" : String(message)
28
+ },
29
+ INTERNAL_R0023: {
30
+ fix: "Ask for access to the section of this operation.",
31
+ why: ({ message }) => message === void 0 ? "" : String(message)
32
+ },
33
+ INTERNAL_B0001: dynamicError,
34
+ INTERNAL_B0002: dynamicError,
35
+ INTERNAL_B0003: dynamicError,
36
+ INTERNAL_B0004: dynamicError,
37
+ INTERNAL_B0005: dynamicError,
38
+ INTERNAL_B0006: dynamicError,
39
+ INTERNAL_B0007: dynamicError,
40
+ INTERNAL_B0008: dynamicError,
41
+ INTERNAL_B0009: dynamicError,
42
+ INTERNAL_B0010: dynamicError,
43
+ INTERNAL_B0011: dynamicError,
44
+ INTERNAL_B0012: dynamicError,
45
+ INTERNAL_B0013: dynamicError,
46
+ INTERNAL_B0014: dynamicError,
47
+ INTERNAL_B0015: dynamicError,
48
+ INTERNAL_B0016: dynamicError,
49
+ INTERNAL_B0017: dynamicError,
50
+ INTERNAL_B0018: dynamicError,
51
+ INTERNAL_B0019: dynamicError,
52
+ INTERNAL_B0020: dynamicError,
53
+ INTERNAL_B0021: dynamicError,
54
+ INTERNAL_B0022: dynamicError,
55
+ INTERNAL_B0023: dynamicError,
56
+ INTERNAL_B0024: dynamicError,
57
+ INTERNAL_B0025: dynamicError,
58
+ INTERNAL_B0026: dynamicError,
59
+ INTERNAL_B0027: dynamicError,
60
+ INTERNAL_B0028: dynamicError,
61
+ INTERNAL_B0029: dynamicError,
62
+ INTERNAL_B0030: dynamicError,
63
+ INTERNAL_B0031: dynamicError,
64
+ INTERNAL_B0032: dynamicError,
65
+ INTERNAL_B0033: dynamicError,
66
+ INTERNAL_B0034: dynamicError,
67
+ INTERNAL_B0035: dynamicError,
68
+ INTERNAL_B0036: dynamicError,
69
+ INTERNAL_B0037: dynamicError,
70
+ INTERNAL_B0038: dynamicError,
71
+ INTERNAL_B0039: dynamicError,
72
+ INTERNAL_B0040: dynamicError,
73
+ INTERNAL_B0041: dynamicError,
74
+ INTERNAL_B0042: dynamicError,
75
+ INTERNAL_B0043: dynamicError,
76
+ INTERNAL_B0044: dynamicError,
77
+ INTERNAL_B0045: dynamicError,
78
+ INTERNAL_B0046: dynamicError,
79
+ INTERNAL_B0047: dynamicError,
80
+ INTERNAL_B0048: {
81
+ fix: "Rename one of the two operations. A name is `<section>.<verb>` and is unique in the app.",
82
+ why: ({ message }) => message === void 0 ? "" : String(message)
83
+ },
84
+ INTERNAL_B0049: {
85
+ fix: "Set `cli: { namespace, command }` on one of the two operations.",
86
+ why: ({ message }) => message === void 0 ? "" : String(message)
87
+ },
88
+ INTERNAL_B0050: {
89
+ fix: "Rename one of the two operations, or set `mcp: false` on it. MCP tool names replace every character outside letters, digits, `_`, and `-` with `_`.",
90
+ why: ({ message }) => message === void 0 ? "" : String(message)
91
+ },
92
+ INTERNAL_R0025: {
93
+ fix: "Start `vite dev` in the project that you run the command from, or pass `--url` of that server.",
94
+ why: ({ message }) => message === void 0 ? "" : String(message)
95
+ },
96
+ INTERNAL_R0026: {
97
+ why: "The server parsed a destructive operation that the CLI did not confirm.",
98
+ fix: "Review the operation, then run it again with --yes to confirm the change."
99
+ },
100
+ INTERNAL_C0001: dynamicError,
101
+ INTERNAL_C0002: dynamicError,
102
+ INTERNAL_R0001: dynamicError,
103
+ INTERNAL_R0002: dynamicError,
104
+ INTERNAL_R0003: dynamicError,
105
+ INTERNAL_R0004: dynamicError,
106
+ INTERNAL_R0005: dynamicError,
107
+ INTERNAL_R0006: dynamicError,
108
+ INTERNAL_R0007: dynamicError,
109
+ INTERNAL_R0008: dynamicError,
110
+ INTERNAL_R0009: dynamicError,
111
+ INTERNAL_R0010: dynamicError,
112
+ INTERNAL_R0011: dynamicError
113
+ }
114
+ });
115
+ //#endregion
116
+ export { internalErrorDiagnostics as t };
@@ -0,0 +1,109 @@
1
+ import { defineErrors } from "@vite-hub/runtime";
2
+ //#region src/error-diagnostics.ts
3
+ const queueErrorDiagnostics = /*#__PURE__*/ defineErrors({
4
+ docs: "https://vitehub.dev/docs/queue/limits-and-errors",
5
+ codes: {
6
+ QUEUE_PROVIDER_FAILED: {
7
+ why: ({ operation, provider }) => `The ${provider} queue provider failed during ${operation}.`,
8
+ fix: "Read `error.cause` for the provider error. Retry when the provider is available again. Pass `idempotencyKey` on Vercel so that a retry does not enqueue the job two times."
9
+ },
10
+ QUEUE_PROVIDER_INVALID_RESPONSE: {
11
+ why: "The Vercel queue provider accepted the job, but returned an invalid `messageId`.",
12
+ fix: "Do not send the job again without an `idempotencyKey`, because the provider can have it. Check the installed `@vercel/queue` version."
13
+ },
14
+ QUEUE_UNSUPPORTED_OPTION: {
15
+ why: ({ options, provider }) => `The ${provider} queue provider does not support the enqueue option ${options}.`,
16
+ fix: "Remove the option for this provider. The enqueue options table on the Queue Server API page shows which provider supports each option."
17
+ },
18
+ QUEUE_BINDING_NOT_FOUND: {
19
+ why: ({ binding }) => binding ? `The Cloudflare queue binding "${binding}" is not in the Worker env.` : "The Cloudflare queue client has no binding.",
20
+ fix: "The dev server has no local Queue delivery. Run the built Worker with `wrangler dev`, or deploy it. In a deployed Worker, add the binding to the Worker configuration."
21
+ },
22
+ QUEUE_DEFINITION_LOAD_FAILED: {
23
+ why: ({ queue }) => queue ? `The Queue Definition "${queue}" failed to load.` : "A Queue Definition failed to load.",
24
+ fix: "Read `error.cause` for the import error, and fix the Queue Definition module."
25
+ },
26
+ QUEUE_DEFINITION_NOT_FOUND: {
27
+ why: ({ queue }) => queue ? `No Queue Definition has the name "${queue}".` : "No Queue Definition has the requested name.",
28
+ fix: "Add `server/queues/<name>.ts` with a default `defineQueue()` export, and build again. The generated server output loads the Queue Definitions, so a script that runs outside of it finds none."
29
+ },
30
+ QUEUE_DISABLED: {
31
+ why: "Queue is disabled in this runtime.",
32
+ fix: "Add `hubQueue()` to the Vite config and do not set `queue: false`."
33
+ },
34
+ QUEUE_INVALID_BINDING: {
35
+ why: "The Cloudflare queue binding does not have `send()` and `sendBatch()`.",
36
+ fix: "Pass a Cloudflare Queue producer binding, for example `env.WELCOME_QUEUE`."
37
+ },
38
+ QUEUE_MISSING_REGION: {
39
+ why: "The installed `@vercel/queue` needs a region, and ViteHub cannot find one.",
40
+ fix: "Set `queue.region` in the Vite config, or set the `QUEUE_REGION` environment variable."
41
+ },
42
+ QUEUE_MISSING_TOPIC: {
43
+ why: "A direct Vercel queue client needs a `topic`.",
44
+ fix: "Pass `topic` to `createQueueClient()`, or use `getQueue()` for a discovered Queue Definition."
45
+ },
46
+ QUEUE_PROVIDER_MISMATCH: {
47
+ why: ({ expected, provider }) => `The ${expected} Queue runtime received the ${provider} provider.`,
48
+ fix: "Set `queue.provider` to the provider of the deployment preset, and build again."
49
+ },
50
+ QUEUE_RUNTIME_NOT_INSTALLED: {
51
+ why: "The Queue runtime has no client factory. The generated server output installs it.",
52
+ fix: "Add `hubQueue()` to the Vite config, build the app, and run the built server."
53
+ },
54
+ QUEUE_VERCEL_SDK_INVALID: {
55
+ why: "`@vercel/queue` does not have the client API that ViteHub uses.",
56
+ fix: "Install a supported `@vercel/queue` version, or pass a `client` that has `send()` and `handleCallback()`."
57
+ },
58
+ QUEUE_VERCEL_SDK_UNAVAILABLE: {
59
+ why: "`@vercel/queue` cannot be loaded.",
60
+ fix: "Add `@vercel/queue` to the app dependencies. Read `error.cause` for the import error."
61
+ },
62
+ QUEUE_BINDING_CONFLICT: {
63
+ why: "A custom `queue.binding` works with one Queue Definition only, and this app has more.",
64
+ fix: "Remove `queue.binding`, so that each Queue Definition gets its own generated binding."
65
+ },
66
+ QUEUE_CRYPTO_UNAVAILABLE: {
67
+ why: "Cloudflare queue names for long Queue Definition names need the `node:crypto` module, and this runtime does not have it.",
68
+ fix: "Enable the `nodejs_compat` compatibility flag, or use a shorter Queue Definition name."
69
+ },
70
+ QUEUE_DEFINITIONS_CHANGED: {
71
+ why: ({ context }) => `The ${context} Queue Definitions changed after Vite resolved the config.`,
72
+ fix: "Generate Queue Definition files before the Vite config resolves, then build again."
73
+ },
74
+ QUEUE_INVALID_CONFIG: {
75
+ why: "`queue` must be a plain object or `false`.",
76
+ fix: "Pass an object, for example `queue: { provider: 'cloudflare' }`."
77
+ },
78
+ QUEUE_INVALID_DEFINITION: {
79
+ why: "`defineQueue()` needs a handler function.",
80
+ fix: "Pass the handler as the first argument, for example `defineQueue(async (job) => { ... })`."
81
+ },
82
+ QUEUE_INVALID_NAME: {
83
+ why: ({ name }) => `The Cloudflare queue name "${name}" can contain only letters, numbers, and dashes, and must start and end with a letter or number.`,
84
+ fix: "Change `queue.namePrefix` so that it contains only letters, numbers, and dashes."
85
+ },
86
+ QUEUE_INVALID_PROVIDER: {
87
+ why: ({ provider }) => `\`queue.provider\` "${provider}" is not a Queue provider.`,
88
+ fix: "Set `queue.provider` to \"cloudflare\" or \"vercel\"."
89
+ },
90
+ QUEUE_MISSING_PROVIDER: {
91
+ why: ({ hosting }) => `ViteHub cannot select a Queue provider for ${hosting} hosting.`,
92
+ fix: "Set `queue.provider`, select the Cloudflare or Vercel deployment preset, or set `queue: false`."
93
+ },
94
+ QUEUE_NAME_COLLISION: {
95
+ why: ({ first, resolved, second }) => `The Queue Definitions "${first}" and "${second}" have the same provider name "${resolved}".`,
96
+ fix: "Rename one of the two Queue Definition files."
97
+ },
98
+ QUEUE_PLUGIN_INCOMPATIBLE: {
99
+ why: "The `hubQueue()` plugin in the Vite config does not expose the Queue Nitro config.",
100
+ fix: "Install one version of `@vite-hub/queue`, and use `hubQueue()` from it."
101
+ },
102
+ QUEUE_PROVISION_FAILED: {
103
+ why: "Cloudflare returned an invalid queue list during provisioning.",
104
+ fix: "Run `vitehub provision run --provider cloudflare --dry-run` again, and check the Cloudflare token permissions."
105
+ }
106
+ }
107
+ });
108
+ //#endregion
109
+ export { queueErrorDiagnostics as t };
@@ -0,0 +1,42 @@
1
+ import { t as queueErrorDiagnostics } from "./error-diagnostics-qzRF6IVB.js";
2
+ import { isRuntimeDiagnostic } from "@vite-hub/runtime";
3
+ //#region src/errors.ts
4
+ const cloudflareUnsupportedEnqueueOptions = [
5
+ "idempotencyKey",
6
+ "region",
7
+ "retentionSeconds"
8
+ ];
9
+ /** Returns `true` for an error from the Queue catalog. Pass `codes` to accept only some codes. */
10
+ function isQueueError(error, codes) {
11
+ if (!isRuntimeDiagnostic(error) || !Object.hasOwn(queueErrorDiagnostics, error.code)) return false;
12
+ return !codes || codes.some((code) => code === error.code);
13
+ }
14
+ /** Formats option names for an error `why`, for example `"region" and "retentionSeconds"`. */
15
+ function formatQueueOptionNames(names) {
16
+ const quoted = names.map((name) => `\`${name}\``);
17
+ return quoted.length > 1 ? `${quoted.slice(0, -1).join(", ")} and ${quoted.at(-1)}` : quoted.join("");
18
+ }
19
+ function normalizePublicQueueIdentifier(value) {
20
+ if (typeof value !== "string" || !value || value.length > 128 || value.trim() !== value) return;
21
+ if (!/^[a-z\d][a-z\d._/-]*$/i.test(value)) return;
22
+ if (/^[a-z][a-z\d+.-]*:\/\//i.test(value) || /^[a-z]:\//i.test(value)) return;
23
+ if (value.split("/").some((part) => part === "." || part === "..")) return;
24
+ return value;
25
+ }
26
+ /**
27
+ * Runs one provider call and returns `[error, data]`.
28
+ * Any failure becomes `QUEUE_PROVIDER_FAILED` with the failure in `cause`.
29
+ */
30
+ async function queueProviderResult(provider, operation, run) {
31
+ try {
32
+ return [void 0, await run()];
33
+ } catch (cause) {
34
+ return [queueErrorDiagnostics.QUEUE_PROVIDER_FAILED({
35
+ cause,
36
+ operation,
37
+ provider
38
+ }), void 0];
39
+ }
40
+ }
41
+ //#endregion
42
+ export { queueProviderResult as a, normalizePublicQueueIdentifier as i, formatQueueOptionNames as n, isQueueError as r, cloudflareUnsupportedEnqueueOptions as t };