@vite-hub/queue 0.1.0 → 0.3.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.
Files changed (60) hide show
  1. package/README.md +141 -20
  2. package/dist/client-Cj50hQYp.js +180 -0
  3. package/dist/{cloudflare-client-COzQ8fHk.js → cloudflare-client-DYsAjM8B.js} +9 -16
  4. package/dist/{cloudflare-resource-name-CCuLDvSP.js → cloudflare-resource-name-BJHYRCMQ.js} +1 -1
  5. package/dist/config-BcTDeQIP.js +105 -0
  6. package/dist/durability.d.ts +13 -0
  7. package/dist/durability.js +47 -0
  8. package/dist/error-diagnostics-BRartC1z.js +181 -0
  9. package/dist/error-diagnostics-DSkCJC_L.js +266 -0
  10. package/dist/errors-DL3pcNO4.js +77 -0
  11. package/dist/{handler-response-CBwIkmTS.js → handler-response-By0Fpspv.js} +9 -4
  12. package/dist/index.d.ts +15 -31
  13. package/dist/index.js +23 -11
  14. package/dist/internal/runtime/cloudflare-client.d.ts +2 -2
  15. package/dist/internal/runtime/cloudflare-client.js +1 -1
  16. package/dist/internal/runtime/cloudflare-vite.d.ts +30 -2
  17. package/dist/internal/runtime/cloudflare-vite.js +111 -1
  18. package/dist/internal/runtime/local-client.d.ts +17 -0
  19. package/dist/internal/runtime/local-client.js +71 -0
  20. package/dist/internal/runtime/postgres-client.d.ts +46 -0
  21. package/dist/internal/runtime/postgres-client.js +560 -0
  22. package/dist/internal/runtime/state.d.ts +11 -4
  23. package/dist/internal/runtime/state.js +2 -2
  24. package/dist/internal/runtime/vercel-client.d.ts +2 -2
  25. package/dist/internal/runtime/vercel-client.js +52 -26
  26. package/dist/internal/runtime/worker-client.d.ts +6 -0
  27. package/dist/internal/runtime/worker-client.js +11 -0
  28. package/dist/invariant-D8_xBqmZ.js +22 -0
  29. package/dist/local-CGckW5nr.js +540 -0
  30. package/dist/local-CVVRVWeR.d.ts +22 -0
  31. package/dist/object-D8pRdprI.js +15 -0
  32. package/dist/{operations-tNUdj3G4.d.ts → operation-definition-8gOe-ubD.d.ts} +37 -15
  33. package/dist/operations-Crwjca91.js +124 -0
  34. package/dist/operations.d.ts +45 -8
  35. package/dist/operations.js +173 -24
  36. package/dist/runtime/hosted.d.ts +3 -5
  37. package/dist/runtime/hosted.js +21 -45
  38. package/dist/{state-G9s378-e.js → state-mVA2X_wa.js} +59 -47
  39. package/dist/types-BD-8U9zS.d.ts +420 -0
  40. package/dist/types-DS_rqu9l.d.ts +10 -0
  41. package/dist/vercel-region-D1CivgdA.js +26 -0
  42. package/dist/virtual.d.ts +4 -0
  43. package/dist/vite.d.ts +364 -49
  44. package/dist/vite.js +2071 -2
  45. package/package.json +39 -46
  46. package/dist/client-CIc3jsj2.js +0 -114
  47. package/dist/cloudflare-vite-BCuJOXcT.js +0 -111
  48. package/dist/cloudflare-vite-CjdP5yBN.d.ts +0 -29
  49. package/dist/config-BINujLv4.js +0 -74
  50. package/dist/enqueue-CnQ0QR3O.js +0 -22
  51. package/dist/error-diagnostics-A_8Kp-48.js +0 -116
  52. package/dist/error-diagnostics-qzRF6IVB.js +0 -109
  53. package/dist/errors-DIFaM9tW.js +0 -42
  54. package/dist/nuxt.d.ts +0 -39
  55. package/dist/nuxt.js +0 -34
  56. package/dist/object-B1NW521B.js +0 -7
  57. package/dist/operations-Cnjbz8kk.js +0 -63
  58. package/dist/types-1GRMYES1.d.ts +0 -180
  59. package/dist/vercel-region-cjskrOKl.js +0 -122
  60. package/dist/vite-ChWLzOVu.js +0 -1512
@@ -1,48 +1,21 @@
1
- import { t as queueErrorDiagnostics } from "../error-diagnostics-qzRF6IVB.js";
2
- import { n as isNonRetryableQueueError, r as reportQueueDeliveryError, t as checkQueueHandlerResponse } from "../handler-response-CBwIkmTS.js";
3
- import { n as dynamicQueue } from "../client-CIc3jsj2.js";
1
+ import { t as queueErrorDiagnostics } from "../error-diagnostics-BRartC1z.js";
2
+ import { n as dynamicQueue } from "../client-Cj50hQYp.js";
3
+ import { i as reportQueueDeliveryError, r as isNonRetryableQueueError, t as checkQueueHandlerResponse } from "../handler-response-By0Fpspv.js";
4
+ import { runInRunScopes } from "@vite-hub/runtime/internal/run-scope";
4
5
  import { waitUntil } from "@vercel/functions";
5
- import { Request as Request$1 } from "undici";
6
- import { getRequestHeaders, getRequestURL, readRawBody } from "h3";
7
6
  //#region src/runtime/hosted.ts
8
7
  const hostedVercelWaitUntil = waitUntil;
9
- function isRequestLike(value) {
10
- if (value === null || typeof value !== "object") return false;
11
- return [Object.getOwnPropertyDescriptor(Request.prototype, "url")?.get, Object.getOwnPropertyDescriptor(Request$1.prototype, "url")?.get].filter((getter) => typeof getter === "function").some((getter) => {
12
- try {
13
- getter.call(value);
14
- return true;
15
- } catch {
16
- return false;
17
- }
18
- });
19
- }
20
- async function toRequest(event) {
21
- let sameRealmRequest = false;
22
- try {
23
- sameRealmRequest = event.request instanceof Request;
24
- } catch {
25
- sameRealmRequest = false;
26
- }
27
- if (sameRealmRequest) return event.request;
28
- if (isRequestLike(event.request)) return event.request;
29
- const h3Event = event;
30
- const body = await readRawBody(h3Event);
31
- return new Request(getRequestURL(h3Event), {
32
- body: body || void 0,
33
- headers: getRequestHeaders(h3Event),
34
- method: event.method || "POST"
35
- });
36
- }
37
8
  function createVercelJobHandler(definition) {
38
9
  return async (payload, metadata) => {
39
10
  const meta = metadata;
40
- checkQueueHandlerResponse(await definition.handler({
41
- attempts: typeof meta?.deliveryCount === "number" ? meta.deliveryCount : 1,
42
- id: typeof meta?.messageId === "string" ? meta.messageId : "vercel-message",
43
- metadata,
44
- payload
45
- }));
11
+ await runInRunScopes(async () => {
12
+ checkQueueHandlerResponse(await definition.handler({
13
+ attempts: typeof meta?.deliveryCount === "number" ? meta.deliveryCount : 1,
14
+ id: typeof meta?.messageId === "string" ? meta.messageId : "vercel-message",
15
+ metadata,
16
+ payload
17
+ }));
18
+ });
46
19
  };
47
20
  }
48
21
  function createVercelCallbackOptions(name, options) {
@@ -63,13 +36,16 @@ function createVercelCallbackOptions(name, options) {
63
36
  }
64
37
  };
65
38
  }
66
- async function handleHostedVercelQueueCallback(event, name, definition) {
67
- const queue = await dynamicQueue.get(name);
68
- if (queue.provider !== "vercel") throw queueErrorDiagnostics.QUEUE_PROVIDER_MISMATCH({
69
- expected: "vercel",
70
- provider: queue.provider
39
+ /** Handle one Vercel Queue delivery. The generated consumer route is a Fetchable module that passes its Request here. */
40
+ async function handleHostedVercelQueueCallback(request, name, definition) {
41
+ const queue = await dynamicQueue.use(name);
42
+ if (queue.provider !== "vercel") throw queueErrorDiagnostics.QUEUE_DRIVER_MISMATCH({
43
+ driver: queue.provider,
44
+ expected: "vercel"
71
45
  });
72
- return await queue.callback(createVercelJobHandler(definition), createVercelCallbackOptions(name, definition.options?.callbackOptions))(await toRequest(event));
46
+ const result = await queue.callback(createVercelJobHandler(definition), createVercelCallbackOptions(name, definition.options?.callbackOptions))(request);
47
+ if (result instanceof Response) return result;
48
+ return result === void 0 ? new Response(null, { status: 204 }) : Response.json(result);
73
49
  }
74
50
  //#endregion
75
51
  export { handleHostedVercelQueueCallback, hostedVercelWaitUntil };
@@ -1,10 +1,48 @@
1
- import { t as isPlainObject } from "./object-B1NW521B.js";
2
- import { t as queueErrorDiagnostics } from "./error-diagnostics-qzRF6IVB.js";
1
+ import { t as queueErrorDiagnostics } from "./error-diagnostics-BRartC1z.js";
2
+ import { n as isRecord } from "./object-D8pRdprI.js";
3
3
  import { AsyncLocalStorage } from "node:async_hooks";
4
- import { hasRuntimeType } from "@vite-hub/runtime/internal/runtime-type";
5
- //#region ../internal/src/runtime/cloudflare-env.ts
6
- let activeEnv;
4
+ //#region ../internal/src/runtime/cloudflare-env-lookup.ts
5
+ /** The key of the AsyncLocalStorage store on `globalThis`. Every bundled copy of this module shares the store. */
7
6
  const activeEnvStorageKey = Symbol.for("vitehub.cloudflare.env-storage");
7
+ let activeEnv;
8
+ function setInstalledCloudflareEnv(env) {
9
+ activeEnv = env;
10
+ }
11
+ /** The store of the current `runWithActiveCloudflareEnv()` call, or undefined outside one. */
12
+ function getScopedCloudflareEnv() {
13
+ return globalThis[activeEnvStorageKey]?.getStore();
14
+ }
15
+ function getActiveCloudflareEnv() {
16
+ const scoped = getScopedCloudflareEnv();
17
+ if (scoped) return scoped.env;
18
+ const host = globalThis;
19
+ return Object.hasOwn(host, "__env__") && host.__env__ !== void 0 ? host.__env__ : activeEnv;
20
+ }
21
+ function ownValue(value, key) {
22
+ if (value === null || typeof value !== "object" && typeof value !== "function" || !Object.hasOwn(value, key)) return void 0;
23
+ return Reflect.get(value, key);
24
+ }
25
+ function ownObject(value) {
26
+ return value !== null && (typeof value === "object" || typeof value === "function") ? value : void 0;
27
+ }
28
+ /** The objects where H3 and Nitro hosts put Cloudflare `env` and `context`, in lookup order. */
29
+ function cloudflareOwners(target) {
30
+ const context = ownObject(ownValue(target, "context"));
31
+ const platform = ownObject(ownValue(context, "_platform"));
32
+ const req = ownObject(ownValue(target, "req"));
33
+ return [
34
+ ownObject(ownValue(context, "cloudflare")),
35
+ ownObject(ownValue(platform, "cloudflare")),
36
+ ownObject(ownValue(ownObject(ownValue(req, "runtime")), "cloudflare"))
37
+ ];
38
+ }
39
+ function getCloudflareEnv(event, options = {}) {
40
+ const target = ownObject(event);
41
+ for (const candidate of [ownValue(target, "env"), ...cloudflareOwners(target).map((owner) => ownValue(owner, "env"))]) if (candidate) return candidate;
42
+ return options.fallback === false ? void 0 : getActiveCloudflareEnv();
43
+ }
44
+ //#endregion
45
+ //#region ../internal/src/runtime/cloudflare-env.ts
8
46
  const runtimeGlobal = globalThis;
9
47
  const activeEnvStorage = runtimeGlobal[activeEnvStorageKey] ||= new AsyncLocalStorage();
10
48
  const globalEnvProbe = Symbol("vitehub.cloudflare.global-env-probe");
@@ -27,7 +65,7 @@ function readsGlobalEnv(env) {
27
65
  }
28
66
  }
29
67
  function setActiveCloudflareEnv(env) {
30
- activeEnv = env;
68
+ setInstalledCloudflareEnv(env);
31
69
  if (!env || !readsGlobalEnv(env)) globalThis.__env__ = env;
32
70
  try {
33
71
  activeEnvStorage.enterWith({ env });
@@ -36,37 +74,6 @@ function setActiveCloudflareEnv(env) {
36
74
  function runWithActiveCloudflareEnv(env, callback) {
37
75
  return activeEnvStorage.run({ env }, callback);
38
76
  }
39
- function getActiveCloudflareEnv() {
40
- const scoped = activeEnvStorage.getStore();
41
- if (scoped) return scoped.env;
42
- const host = globalThis;
43
- return Object.hasOwn(host, "__env__") && host.__env__ !== void 0 ? host.__env__ : activeEnv;
44
- }
45
- function ownValue(value, key) {
46
- if (value === null || typeof value !== "object" && typeof value !== "function" || !Object.hasOwn(value, key)) return void 0;
47
- return Reflect.get(value, key);
48
- }
49
- function ownObject(value) {
50
- return value !== null && (typeof value === "object" || typeof value === "function") ? value : void 0;
51
- }
52
- /** The objects where H3 1, H3 2, and Nitro hosts put Cloudflare `env` and `context`, in lookup order. */
53
- function cloudflareOwners(target) {
54
- const context = ownObject(ownValue(target, "context"));
55
- const platform = ownObject(ownValue(context, "_platform"));
56
- const req = ownObject(ownValue(target, "req"));
57
- const nodeReq = ownObject(ownValue(ownObject(ownValue(target, "node")), "req"));
58
- return [
59
- ownObject(ownValue(context, "cloudflare")),
60
- ownObject(ownValue(platform, "cloudflare")),
61
- ownObject(ownValue(ownObject(ownValue(req, "runtime")), "cloudflare")),
62
- ownObject(ownValue(ownObject(ownValue(nodeReq, "runtime")), "cloudflare"))
63
- ];
64
- }
65
- function getCloudflareEnv(event, options = {}) {
66
- const target = ownObject(event);
67
- for (const candidate of [ownValue(target, "env"), ...cloudflareOwners(target).map((owner) => ownValue(owner, "env"))]) if (candidate) return candidate;
68
- return options.fallback === false ? void 0 : getActiveCloudflareEnv();
69
- }
70
77
  function resolveWaitUntil(event, options = {}) {
71
78
  const target = ownObject(event);
72
79
  const context = ownObject(ownValue(target, "context"));
@@ -76,9 +83,6 @@ function resolveWaitUntil(event, options = {}) {
76
83
  const platformCloudflareContext = ownObject(ownValue(platformCloudflare, "context"));
77
84
  const req = ownObject(ownValue(target, "req"));
78
85
  const reqCloudflare = ownObject(ownValue(ownObject(ownValue(req, "runtime")), "cloudflare"));
79
- const reqCloudflareContext = ownObject(ownValue(reqCloudflare, "context"));
80
- const nodeReq = ownObject(ownValue(ownObject(ownValue(target, "node")), "req"));
81
- const nodeCloudflare = ownObject(ownValue(ownObject(ownValue(nodeReq, "runtime")), "cloudflare"));
82
86
  const hosts = [
83
87
  context,
84
88
  cloudflare,
@@ -87,10 +91,7 @@ function resolveWaitUntil(event, options = {}) {
87
91
  platformCloudflareContext,
88
92
  req,
89
93
  reqCloudflare,
90
- reqCloudflareContext,
91
- nodeReq,
92
- nodeCloudflare,
93
- ownObject(ownValue(nodeCloudflare, "context"))
94
+ ownObject(ownValue(reqCloudflare, "context"))
94
95
  ];
95
96
  const owners = options.preferHost ? [...hosts, target] : [target, ...hosts];
96
97
  for (const owner of owners) {
@@ -117,6 +118,7 @@ function createCloudflareRuntimeEvent(env, context) {
117
118
  let runtimeConfig;
118
119
  let runtimeClientFactory;
119
120
  let registryOverride;
121
+ let jobStore;
120
122
  const queueEventStorage = new AsyncLocalStorage();
121
123
  let queueEventDefaults;
122
124
  const queueClientCache = /* @__PURE__ */ new Map();
@@ -129,6 +131,16 @@ function setQueueRuntimeConfig(config, createClient) {
129
131
  if (typeof config === "undefined") queueEventDefaults = void 0;
130
132
  queueClientCache.clear();
131
133
  }
134
+ /**
135
+ * The stored jobs of a provider that does not keep them in this package's process state. The generated server sets it
136
+ * for the postgres provider, so the Queue operations read jobs without importing the Postgres driver.
137
+ */
138
+ function setQueueRuntimeJobStore(store) {
139
+ jobStore = store;
140
+ }
141
+ async function getQueueRuntimeJobStore() {
142
+ return await jobStore?.();
143
+ }
132
144
  function getQueueRuntimeConfig() {
133
145
  return runtimeConfig;
134
146
  }
@@ -169,7 +181,7 @@ function getOrCreateQueueClient(name, createClient) {
169
181
  return pending;
170
182
  }
171
183
  function isQueueDefinition(value) {
172
- return isPlainObject(value) && Object.hasOwn(value, "handler") && hasRuntimeType(value.handler, "function");
184
+ return isRecord(value) && Object.hasOwn(value, "handler") && typeof value.handler === "function";
173
185
  }
174
186
  async function loadQueueDefinition(name) {
175
187
  const registry = registryOverride;
@@ -178,7 +190,7 @@ async function loadQueueDefinition(name) {
178
190
  if (!entry) return;
179
191
  const loaded = await entry();
180
192
  if (isQueueDefinition(loaded)) return loaded;
181
- if (isPlainObject(loaded) && Object.hasOwn(loaded, "default") && isQueueDefinition(loaded.default)) return loaded.default;
193
+ if (isRecord(loaded) && Object.hasOwn(loaded, "default") && isQueueDefinition(loaded.default)) return loaded.default;
182
194
  }
183
195
  //#endregion
184
- export { getQueueRuntimeEvent as a, missingQueueDefinitionError as c, setQueueRuntimeEventDefaults as d, setQueueRuntimeRegistry as f, runWithActiveCloudflareEnv as g, resolveWaitUntil as h, getQueueRuntimeConfig as i, runWithQueueRuntimeEvent as l, getCloudflareEnv as m, getOrCreateQueueClient as n, listQueueDefinitionNames as o, createCloudflareRuntimeEvent as p, getQueueRuntimeClientFactory as r, loadQueueDefinition as s, enterQueueRuntimeEvent as t, setQueueRuntimeConfig as u };
196
+ export { runWithActiveCloudflareEnv as _, getQueueRuntimeEvent as a, loadQueueDefinition as c, setQueueRuntimeConfig as d, setQueueRuntimeEventDefaults as f, resolveWaitUntil as g, createCloudflareRuntimeEvent as h, getQueueRuntimeConfig as i, missingQueueDefinitionError as l, setQueueRuntimeRegistry as m, getOrCreateQueueClient as n, getQueueRuntimeJobStore as o, setQueueRuntimeJobStore as p, getQueueRuntimeClientFactory as r, listQueueDefinitionNames as s, enterQueueRuntimeEvent as t, runWithQueueRuntimeEvent as u, getCloudflareEnv as v };
@@ -0,0 +1,420 @@
1
+ import { Result } from "@vite-hub/runtime";
2
+ //#region src/types.d.ts
3
+ type QueueDriver = "cloudflare" | "local" | "postgres" | "vercel";
4
+ /** The Queue drivers that run jobs in a Node server process. */
5
+ type NodeQueueDriver = "local" | "postgres";
6
+ type CloudflareQueueContentType = "bytes" | "json" | "text" | "v8";
7
+ interface CloudflareQueueSendOptions {
8
+ contentType?: CloudflareQueueContentType;
9
+ delaySeconds?: number;
10
+ }
11
+ interface CloudflareQueueSendBatchOptions {
12
+ delaySeconds?: number;
13
+ }
14
+ interface CloudflareQueueSendBatchMessage<T = unknown> extends CloudflareQueueSendOptions {
15
+ body: T;
16
+ }
17
+ interface CloudflareQueueRetryOptions {
18
+ delaySeconds?: number;
19
+ }
20
+ interface CloudflareQueueBinding {
21
+ send: <T = unknown>(body: T, options?: CloudflareQueueSendOptions) => Promise<unknown>;
22
+ sendBatch: <T = unknown>(messages: Iterable<CloudflareQueueSendBatchMessage<T>>, options?: CloudflareQueueSendBatchOptions) => Promise<unknown>;
23
+ }
24
+ interface CloudflareQueueMessage<T = unknown> {
25
+ ack: () => void;
26
+ attempts: number;
27
+ body: T;
28
+ id: string;
29
+ retry: (options?: CloudflareQueueRetryOptions) => void;
30
+ timestamp?: Date;
31
+ }
32
+ interface CloudflareQueueMessageBatch<T = unknown> {
33
+ ackAll: () => void;
34
+ messages: CloudflareQueueMessage<T>[];
35
+ queue: string;
36
+ retryAll: (options?: CloudflareQueueRetryOptions) => void;
37
+ }
38
+ type CloudflareQueueBatchErrorAction = "ack" | "retry" | {
39
+ retry: CloudflareQueueRetryOptions;
40
+ };
41
+ interface CloudflareQueueBatchHandlerOptions<T = unknown> {
42
+ concurrency?: number;
43
+ onError?: (error: unknown, message: CloudflareQueueMessage<T>, batch: CloudflareQueueMessageBatch<T>) => CloudflareQueueBatchErrorAction | void | Promise<CloudflareQueueBatchErrorAction | void>;
44
+ onMessage: (message: CloudflareQueueMessage<T>, batch: CloudflareQueueMessageBatch<T>) => unknown | Promise<unknown>;
45
+ }
46
+ type VercelQueueRetryDirective = {
47
+ acknowledge: true;
48
+ } | {
49
+ afterSeconds: number;
50
+ };
51
+ type VercelQueueRetryHandler = (error: unknown, metadata: unknown) => VercelQueueRetryDirective | void;
52
+ interface VercelQueueCallbackOptions {
53
+ retry?: VercelQueueRetryHandler;
54
+ visibilityTimeoutSeconds?: number;
55
+ }
56
+ interface VercelQueueSendOptions {
57
+ delaySeconds?: number;
58
+ headers?: Record<string, string>;
59
+ idempotencyKey?: string;
60
+ region?: string;
61
+ retentionSeconds?: number;
62
+ }
63
+ interface VercelQueueSendResult {
64
+ messageId?: string | null;
65
+ }
66
+ interface VercelQueueBatchSendMessage extends Omit<VercelQueueSendOptions, "headers" | "region"> {
67
+ payload: unknown;
68
+ }
69
+ /** Result of one message in a `@vercel/queue` `sendBatch()` request, in input order. */
70
+ type VercelQueueBatchSendResult = {
71
+ messageId: string;
72
+ status: "sent";
73
+ } | {
74
+ messageId: null;
75
+ status: "deferred";
76
+ } | {
77
+ error: string;
78
+ retryable: boolean;
79
+ status: "failed";
80
+ statusCode: number;
81
+ };
82
+ /**
83
+ * One job in `sendBatch()` of a Vercel QueueClient. Omitted `idempotencyKey` values are generated anew on each call.
84
+ * Supply a stable key from the first attempt to deduplicate retries.
85
+ */
86
+ interface VercelQueueSendBatchMessage<T = unknown> {
87
+ body: T;
88
+ delaySeconds?: number;
89
+ idempotencyKey?: string;
90
+ retentionSeconds?: number;
91
+ }
92
+ /** Options that apply to every job of a Vercel `sendBatch()` unless the job sets its own. */
93
+ interface VercelQueueSendBatchOptions {
94
+ delaySeconds?: number;
95
+ retentionSeconds?: number;
96
+ }
97
+ type VercelQueueMessageHandler<T = unknown> = (payload: T, metadata?: unknown) => unknown | Promise<unknown>;
98
+ type VercelQueueCallbackReturn = (request: Request) => Promise<unknown> | unknown;
99
+ interface VercelQueueSDK {
100
+ handleCallback: <TPayload = unknown>(handler: VercelQueueMessageHandler<TPayload>, options?: VercelQueueCallbackOptions) => VercelQueueCallbackReturn;
101
+ send: (topic: string, payload: unknown, options?: VercelQueueSendOptions) => Promise<VercelQueueSendResult>;
102
+ /** `@vercel/queue` 0.10 and later. A custom client without it makes `sendBatch()` fail with `QUEUE_PROVIDER_FAILED`. */
103
+ sendBatch?: (topic: string, messages: readonly VercelQueueBatchSendMessage[]) => Promise<readonly VercelQueueBatchSendResult[]>;
104
+ }
105
+ interface QueueSharedOptions {
106
+ cache?: boolean;
107
+ }
108
+ interface CloudflareQueueDriverOptions extends QueueSharedOptions {
109
+ binding?: string | CloudflareQueueBinding;
110
+ driver: "cloudflare";
111
+ }
112
+ interface CloudflareQueueModuleDriverOptions extends QueueSharedOptions {
113
+ binding?: string;
114
+ namePrefix?: string;
115
+ driver: "cloudflare";
116
+ }
117
+ interface VercelQueueDriverOptions extends QueueSharedOptions {
118
+ client?: VercelQueueSDK;
119
+ driver: "vercel";
120
+ region?: string;
121
+ topic?: string;
122
+ }
123
+ interface VercelQueueModuleDriverOptions extends QueueSharedOptions {
124
+ driver: "vercel";
125
+ region?: string;
126
+ }
127
+ /**
128
+ * The local driver keeps jobs in files under `base` and runs the Queue Definitions in this process.
129
+ * The jobs survive a restart on the same host. They do not move to another host or container.
130
+ */
131
+ interface LocalQueueDriverOptions extends QueueSharedOptions {
132
+ /** Directory of the stored jobs, relative to the working directory. Defaults to `.vitehub/data/queue`. */
133
+ base?: string;
134
+ driver: "local";
135
+ /** Queue Definition that receives the jobs. `useQueue()` sets it. */
136
+ queue?: string;
137
+ /** The driver whose delivery rules the jobs follow. Defaults to `local`. `vite dev` sets the driver of the build. */
138
+ rules?: LocalQueueRules;
139
+ }
140
+ /**
141
+ * The driver whose documented delivery rules the local driver follows: attempts, retry delay, the largest delay,
142
+ * payload, and batch, and the enqueue options it accepts. In `vite dev`, a Cloudflare or Vercel app runs its jobs
143
+ * with the local driver and the rules of its hosted driver.
144
+ */
145
+ type LocalQueueRules = QueueDriver;
146
+ interface LocalQueueModuleDriverOptions extends QueueSharedOptions {
147
+ /** Directory of the stored jobs, relative to the working directory. Defaults to `.vitehub/data/queue`. */
148
+ base?: string;
149
+ driver: "local";
150
+ }
151
+ /**
152
+ * The postgres driver keeps jobs in the `vitehub_queue_jobs` table of a Postgres database. Every server process
153
+ * that runs the app takes jobs from the table, so the jobs survive a restart and spread over all instances.
154
+ * It uses the connection of the Default Database. `QUEUE_POSTGRES_URL` overrides it at runtime.
155
+ */
156
+ interface PostgresQueueDriverOptions extends QueueSharedOptions {
157
+ /** The Database whose Postgres connection Queue uses. The build sets `default` when the Default Database is on Postgres. */
158
+ database?: string;
159
+ driver: "postgres";
160
+ /** Queue Definition that receives the jobs. `getQueue()` sets it. */
161
+ queue?: string;
162
+ }
163
+ interface PostgresQueueModuleDriverOptions extends QueueSharedOptions {
164
+ driver: "postgres";
165
+ }
166
+ /** Postgres options after resolution. The build adds `database` when the Default Database is on Postgres. */
167
+ interface ResolvedPostgresQueueOptions extends PostgresQueueModuleDriverOptions {
168
+ database?: string;
169
+ }
170
+ type QueueDriverOptions = CloudflareQueueDriverOptions | LocalQueueDriverOptions | PostgresQueueDriverOptions | VercelQueueDriverOptions;
171
+ type QueueModuleDriverOptions = CloudflareQueueModuleDriverOptions | LocalQueueModuleDriverOptions | PostgresQueueModuleDriverOptions | VercelQueueModuleDriverOptions;
172
+ type QueueOptions = false | (QueueSharedOptions & {
173
+ base?: string;
174
+ namePrefix?: string;
175
+ driver?: undefined;
176
+ }) | QueueModuleDriverOptions;
177
+ /** Local options after resolution. `vite dev` adds `rules` for a Cloudflare or Vercel app. */
178
+ interface ResolvedLocalQueueOptions extends LocalQueueModuleDriverOptions {
179
+ rules?: LocalQueueRules;
180
+ }
181
+ type ResolvedQueueOptions = CloudflareQueueModuleDriverOptions | ResolvedLocalQueueOptions | ResolvedPostgresQueueOptions | VercelQueueModuleDriverOptions;
182
+ interface QueueJob<TPayload = unknown> {
183
+ attempts: number;
184
+ id: string;
185
+ metadata?: unknown;
186
+ payload: TPayload;
187
+ }
188
+ type QueueHandler<TPayload = unknown, TResult = unknown> = (job: QueueJob<TPayload>) => TResult;
189
+ interface QueueDefinitionOptions {
190
+ cache?: boolean;
191
+ callbackOptions?: VercelQueueCallbackOptions;
192
+ concurrency?: number;
193
+ onDispatchError?: (error: unknown, context: {
194
+ name: string;
195
+ }) => unknown | Promise<unknown>;
196
+ onError?: CloudflareQueueBatchHandlerOptions["onError"];
197
+ }
198
+ interface QueueDefinition<TPayload = unknown, TResult = unknown> {
199
+ handler: QueueHandler<TPayload, TResult>;
200
+ options?: QueueDefinitionOptions;
201
+ }
202
+ /**
203
+ * Options of `sendQueue()` and `send()`. ViteHub generates the message ID. To deduplicate sends, pass `idempotencyKey`
204
+ * on a provider that supports it.
205
+ */
206
+ interface QueueEnqueueOptions {
207
+ contentType?: CloudflareQueueContentType;
208
+ delaySeconds?: number;
209
+ idempotencyKey?: string;
210
+ region?: string;
211
+ retentionSeconds?: number;
212
+ }
213
+ type QueueSendResult = {
214
+ messageId?: string;
215
+ status: "queued";
216
+ };
217
+ /** Codes that Queue operations return in the `[error, data]` tuple. Config errors throw instead. */
218
+ type QueueErrorCode = "QUEUE_PROVIDER_FAILED" | "QUEUE_PROVIDER_INVALID_RESPONSE" | "QUEUE_UNSUPPORTED_OPTION";
219
+ /** Codes that `send()` and `sendBatch()` of a Cloudflare QueueClient return. */
220
+ type CloudflareQueueErrorCode = "QUEUE_PROVIDER_FAILED" | "QUEUE_UNSUPPORTED_OPTION";
221
+ /** Codes that `send()` and `sendBatch()` of a local QueueClient return. */
222
+ type LocalQueueErrorCode = "QUEUE_PROVIDER_FAILED" | "QUEUE_UNSUPPORTED_OPTION";
223
+ /** Codes that `send()` and `sendBatch()` of a postgres QueueClient return. */
224
+ type PostgresQueueErrorCode = "QUEUE_PROVIDER_FAILED" | "QUEUE_UNSUPPORTED_OPTION";
225
+ /** One job in `sendBatch()` of a local or postgres QueueClient. */
226
+ interface LocalQueueSendBatchMessage<T = unknown> {
227
+ body: T;
228
+ delaySeconds?: number;
229
+ idempotencyKey?: string;
230
+ }
231
+ /** Codes that `send()` and `sendBatch()` of a Vercel QueueClient return. */
232
+ type VercelQueueErrorCode = QueueErrorCode;
233
+ interface QueueClientBase<P extends QueueDriver = QueueDriver> {
234
+ readonly native: unknown;
235
+ readonly provider: P;
236
+ }
237
+ /**
238
+ * `send()` and `sendBatch()` return `[error, data]`. `error.code` is one of the codes in the method type.
239
+ */
240
+ interface CloudflareQueueClient<TPayload = unknown> extends QueueClientBase<"cloudflare"> {
241
+ readonly binding: CloudflareQueueBinding;
242
+ createBatchHandler: <TMessage = unknown>(options: CloudflareQueueBatchHandlerOptions<TMessage>) => (batch: CloudflareQueueMessageBatch<TMessage>) => Promise<void>;
243
+ send: (payload: TPayload, options?: QueueEnqueueOptions) => Promise<Result<QueueSendResult, CloudflareQueueErrorCode>>;
244
+ sendBatch: (items: CloudflareQueueSendBatchMessage<TPayload>[], options?: QueueEnqueueOptions) => Promise<Result<QueueSendResult[], CloudflareQueueErrorCode>>;
245
+ }
246
+ /**
247
+ * `send()` and `sendBatch()` return `[error, data]`. `error.code` is one of the codes in the method type.
248
+ */
249
+ interface VercelQueueClient<TPayload = unknown> extends QueueClientBase<"vercel"> {
250
+ readonly topic: string;
251
+ send: (payload: TPayload, options?: QueueEnqueueOptions) => Promise<Result<QueueSendResult, VercelQueueErrorCode>>;
252
+ /**
253
+ * Sends 1 to 100 jobs in one `@vercel/queue` request. When any job fails, it returns `QUEUE_PROVIDER_FAILED`
254
+ * with the per-job results in `error.cause.results`. Request-level failures can occur after jobs are accepted.
255
+ * To retry safely, supply the same caller-provided `idempotencyKey` on every job from the first attempt.
256
+ * Generated keys change on each call and do not deduplicate retries.
257
+ */
258
+ sendBatch: (items: VercelQueueSendBatchMessage<TPayload>[], options?: VercelQueueSendBatchOptions) => Promise<Result<QueueSendResult[], VercelQueueErrorCode>>;
259
+ callback: <TMessage = unknown>(handler: VercelQueueMessageHandler<TMessage>, options?: VercelQueueCallbackOptions) => VercelQueueCallbackReturn;
260
+ }
261
+ /**
262
+ * `send()` stores the job under `base` and returns when the file is written. This process then runs the
263
+ * Queue Definition. `send()` and `sendBatch()` return `[error, data]`.
264
+ */
265
+ interface LocalQueueClient<TPayload = unknown> extends QueueClientBase<"local"> {
266
+ readonly queue: string;
267
+ send: (payload: TPayload, options?: QueueEnqueueOptions) => Promise<Result<QueueSendResult, LocalQueueErrorCode>>;
268
+ sendBatch: (items: LocalQueueSendBatchMessage<TPayload>[], options?: {
269
+ delaySeconds?: number;
270
+ }) => Promise<Result<QueueSendResult[], LocalQueueErrorCode>>;
271
+ }
272
+ /**
273
+ * `send()` inserts the job in the Postgres table and returns when the insert commits. Any server process of the app
274
+ * then runs the Queue Definition. `send()` and `sendBatch()` return `[error, data]`.
275
+ */
276
+ interface PostgresQueueClient<TPayload = unknown> extends QueueClientBase<"postgres"> {
277
+ readonly queue: string;
278
+ send: (payload: TPayload, options?: QueueEnqueueOptions) => Promise<Result<QueueSendResult, PostgresQueueErrorCode>>;
279
+ /** Inserts all jobs in one transaction. When one insert fails, no job of the batch is stored. */
280
+ sendBatch: (items: LocalQueueSendBatchMessage<TPayload>[], options?: {
281
+ delaySeconds?: number;
282
+ }) => Promise<Result<QueueSendResult[], PostgresQueueErrorCode>>;
283
+ }
284
+ interface QueueClientMap<TPayload> {
285
+ cloudflare: CloudflareQueueClient<TPayload>;
286
+ local: LocalQueueClient<TPayload>;
287
+ postgres: PostgresQueueClient<TPayload>;
288
+ vercel: VercelQueueClient<TPayload>;
289
+ }
290
+ type QueueClient<P extends QueueDriver = QueueDriver, TPayload = unknown> = QueueClientMap<TPayload>[P];
291
+ /** Discovered Queue Definitions. Generated declarations extend this interface. */
292
+ interface QueueRegistry {}
293
+ type QueueName = Extract<keyof QueueRegistry, string>;
294
+ type QueuePayload<TName extends QueueName> = QueueRegistry[TName] extends {
295
+ handler: (job: infer TJob) => unknown;
296
+ } ? TJob extends QueueJob<infer TPayload> ? TPayload : never : never;
297
+ interface QueueDefinitionRegistry {
298
+ [name: string]: () => Promise<{
299
+ default?: QueueDefinition;
300
+ } | QueueDefinition>;
301
+ }
302
+ interface DiscoveredQueueDefinition {
303
+ /** Plugin that contributed this Definition through `vitehub.queues`, when it was not found in the app. */
304
+ contributor?: string;
305
+ handler: string;
306
+ name: string;
307
+ /** Why the contributing plugin adds this Definition. */
308
+ reason?: string;
309
+ source?: "server-queues" | "vite-plugin-contribution" | "vite-suffix";
310
+ }
311
+ /** The last delivery error of a stored job, as `vitehub queue jobs` shows it. */
312
+ interface QueueDeliveryErrorDetails {
313
+ code?: string;
314
+ details?: Readonly<Record<string, unknown>>;
315
+ docs?: string;
316
+ fix?: string;
317
+ message: string;
318
+ name: string;
319
+ stack?: string;
320
+ }
321
+ /** The delivery rules that the local engine applies. */
322
+ interface LocalQueueDeliveryRules {
323
+ /** Deliveries before a failing job becomes a dead job. `Infinity` retries until the job expires. */
324
+ maxAttempts: number;
325
+ /** Largest `delaySeconds` that a send accepts. */
326
+ maxDelaySeconds?: number;
327
+ /** Largest number of jobs in one `sendBatch()`. */
328
+ maxBatchJobs?: number;
329
+ /** Largest JSON size in bytes of all payloads of one `sendBatch()`. */
330
+ maxBatchBytes?: number;
331
+ /** Largest JSON size in bytes of one payload. */
332
+ maxPayloadBytes?: number;
333
+ /** Accepted `retentionSeconds`. A job expires at the end of its retention, whether it ran or not. */
334
+ retention?: {
335
+ defaultSeconds: number;
336
+ maxSeconds: number;
337
+ minSeconds: number;
338
+ };
339
+ /** Milliseconds before the next delivery after `attempts` failed deliveries. */
340
+ retryDelayMs: (attempts: number) => number;
341
+ /** The provider whose documented rules these are. */
342
+ rules: LocalQueueRules;
343
+ /** Enqueue options that fail with `QUEUE_UNSUPPORTED_OPTION`. */
344
+ unsupportedOptions: readonly ("contentType" | "idempotencyKey" | "region" | "retentionSeconds")[];
345
+ }
346
+ interface LocalQueueStatus {
347
+ /** Absolute directory of the local provider, or the Postgres table and database, without the password. */
348
+ base: string;
349
+ /** Dead jobs kept per Queue Definition. Older dead jobs are deleted. */
350
+ deadLimit: number;
351
+ /**
352
+ * `single-host`: the jobs survive a restart of this host. Another host or a new container does not see them.
353
+ * `shared`: the postgres provider keeps the jobs in Postgres, and every instance of the app takes jobs from it.
354
+ */
355
+ durability: "shared" | "single-host";
356
+ queues: Record<string, {
357
+ dead: number;
358
+ pending: number;
359
+ running: number;
360
+ }>;
361
+ }
362
+ /** One stored job, as `vitehub queue jobs list` shows it. Times are ISO strings. */
363
+ interface LocalQueueJob {
364
+ attempts: number;
365
+ /** When a pending job runs next. */
366
+ availableAt: string;
367
+ enqueuedAt: string;
368
+ /** The last delivery error. A pending job has one after a failed attempt. */
369
+ error?: QueueDeliveryErrorDetails;
370
+ /** When the job expires, for Vercel rules. */
371
+ expiresAt?: string;
372
+ /** When the job became dead. */
373
+ failedAt?: string;
374
+ /** The message ID that `runQueue()` returned. */
375
+ id: string;
376
+ queue: string;
377
+ state: "dead" | "pending" | "running";
378
+ }
379
+ /** One stored job with its payload, as `vitehub queue jobs show` shows it. */
380
+ interface LocalQueueJobDetail extends LocalQueueJob {
381
+ /** The local provider only: the file of the job. */
382
+ file?: string;
383
+ idempotencyKey?: string;
384
+ payload?: unknown;
385
+ }
386
+ /** Which jobs `jobs()` lists. */
387
+ interface QueueJobsFilter {
388
+ queue?: string;
389
+ state?: LocalQueueJob["state"];
390
+ }
391
+ /** Which jobs `clear()` removes. Running jobs always stay. */
392
+ interface LocalQueueClearFilter {
393
+ queue?: string;
394
+ state?: "dead" | "pending";
395
+ }
396
+ /**
397
+ * The stored jobs of a provider that ViteHub can read: the local and the postgres provider. The Queue operations,
398
+ * so `vitehub queue jobs` and the Console, read jobs through it.
399
+ */
400
+ interface QueueJobStore {
401
+ /** The directory of the local provider, or the Postgres table and database, without the password. */
402
+ readonly base: string;
403
+ /** Removes the stored jobs that match, except running jobs. Returns how many it removed. */
404
+ clear: (filter?: LocalQueueClearFilter) => Promise<number>;
405
+ /** The newest stored job with this message ID, with its payload. */
406
+ job: (id: string) => Promise<LocalQueueJobDetail | undefined>;
407
+ /** The stored jobs, newest first. The postgres provider applies `filter` and returns at most 1,000 jobs. */
408
+ jobs: (filter?: QueueJobsFilter) => Promise<LocalQueueJob[]>;
409
+ readonly provider: "local" | "postgres";
410
+ /**
411
+ * Runs the newest stored job with this message ID now. A dead job gets a new set of attempts. A pending job keeps
412
+ * its attempts and does not wait for its delay or retry delay. A running job is not changed. `duplicate`: a newer
413
+ * live job holds the `idempotencyKey` of the dead job.
414
+ */
415
+ retry: (id: string) => Promise<LocalQueueJob | "duplicate" | "missing" | "running">;
416
+ readonly rules: LocalQueueDeliveryRules;
417
+ status: () => Promise<LocalQueueStatus>;
418
+ }
419
+ //#endregion
420
+ export { QueueModuleDriverOptions as A, VercelQueueClient as B, QueueDriver as C, QueueHandler as D, QueueErrorCode as E, QueueSendResult as F, VercelQueueSendBatchOptions as G, VercelQueueRetryDirective as H, ResolvedLocalQueueOptions as I, VercelQueueSendResult as K, ResolvedQueueOptions as L, QueueOptions as M, QueuePayload as N, QueueJob as O, QueueRegistry as P, VercelQueueBatchSendResult as R, QueueDefinitionRegistry as S, QueueEnqueueOptions as T, VercelQueueRetryHandler as U, VercelQueueErrorCode as V, VercelQueueSendBatchMessage as W, PostgresQueueDriverOptions as _, CloudflareQueueMessageBatch as a, QueueDefinition as b, LocalQueueDriverOptions as c, LocalQueueJobDetail as d, LocalQueueRules as f, PostgresQueueClient as g, NodeQueueDriver as h, CloudflareQueueMessage as i, QueueName as j, QueueJobStore as k, LocalQueueErrorCode as l, LocalQueueStatus as m, CloudflareQueueClient as n, DiscoveredQueueDefinition as o, LocalQueueSendBatchMessage as p, CloudflareQueueErrorCode as r, LocalQueueClient as s, CloudflareQueueBatchHandlerOptions as t, LocalQueueJob as u, PostgresQueueErrorCode as v, QueueDriverOptions as w, QueueDefinitionOptions as x, QueueClient as y, VercelQueueCallbackOptions as z };