@vite-hub/queue 0.4.1 → 0.5.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 (42) hide show
  1. package/README.md +2 -2
  2. package/dist/{client-B53_G4ky.js → client-DYE_ZV8c.js} +5 -6
  3. package/dist/{cloudflare-client-CoISDpIx.js → cloudflare-client-BasaJ68s.js} +4 -5
  4. package/dist/{cloudflare-resource-name-BIfBglC2.js → cloudflare-resource-name-BUNNqgkg.js} +1 -1
  5. package/dist/{config-B2eaXaT5.js → config-YEuaeQVq.js} +1 -3
  6. package/dist/definition-BL_3WHNu.js +27 -0
  7. package/dist/{duration-tujyhAKt.js → duration-CshzgSSx.js} +11 -3
  8. package/dist/{error-diagnostics-CQ4BUqRe.js → error-diagnostics-C0KyI408.js} +5 -1
  9. package/dist/{error-diagnostics-mJXBjmQx.js → error-diagnostics-DukggGP6.js} +8 -4
  10. package/dist/{handler-response-B6lz9nCn.js → handler-response-ChtAjPNo.js} +8 -3
  11. package/dist/index.d.ts +1 -1
  12. package/dist/index.js +4 -22
  13. package/dist/internal/runtime/cloudflare-client.d.ts +1 -1
  14. package/dist/internal/runtime/cloudflare-client.js +1 -1
  15. package/dist/internal/runtime/cloudflare-vite.d.ts +1 -1
  16. package/dist/internal/runtime/cloudflare-vite.js +8 -7
  17. package/dist/internal/runtime/local-client.d.ts +3 -3
  18. package/dist/internal/runtime/local-client.js +4 -4
  19. package/dist/internal/runtime/postgres-client.d.ts +5 -4
  20. package/dist/internal/runtime/postgres-client.js +16 -9
  21. package/dist/internal/runtime/state.d.ts +2 -2
  22. package/dist/internal/runtime/state.js +1 -1
  23. package/dist/internal/runtime/vercel-client.d.ts +1 -1
  24. package/dist/internal/runtime/vercel-client.js +3 -4
  25. package/dist/internal/runtime/worker-client.d.ts +2 -2
  26. package/dist/internal/runtime/worker-client.js +1 -1
  27. package/dist/{local-Di0FrVUw.js → local-CnBd5jdm.js} +26 -20
  28. package/dist/{local-CUaWoRUx.d.ts → local-DAL5ZgDg.d.ts} +1 -1
  29. package/dist/{operation-definition-nmRu_O3V.d.ts → operation-definition-CI2PJGqu.d.ts} +8 -2
  30. package/dist/{operations-BVV-9Q0N.js → operations-BL0b9pte.js} +5 -11
  31. package/dist/operations.d.ts +3 -3
  32. package/dist/operations.js +3 -3
  33. package/dist/runtime/hosted.d.ts +1 -1
  34. package/dist/runtime/hosted.js +3 -3
  35. package/dist/scan-module-BbqyaLl6.js +311 -0
  36. package/dist/{state-DLqTqF6V.js → state-ER1YdCBF.js} +1 -1
  37. package/dist/{types-Dsbb_Pvp.d.ts → types-D6hDNcMY.d.ts} +1 -2
  38. package/dist/{types-CiuSIPR0.d.ts → types-klaR79hV.d.ts} +8 -2
  39. package/dist/{vercel-region-B95MAMXN.js → vercel-region-DOciq2kx.js} +1 -1
  40. package/dist/vite.d.ts +8 -4
  41. package/dist/vite.js +123 -94
  42. package/package.json +3 -3
@@ -52,6 +52,8 @@ interface CloudflareQueueBatchHandlerOptions<T = unknown> {
52
52
  concurrency?: number;
53
53
  onError?: (error: unknown, message: CloudflareQueueMessage<T>, batch: CloudflareQueueMessageBatch<T>) => CloudflareQueueBatchErrorAction | void | Promise<CloudflareQueueBatchErrorAction | void>;
54
54
  onMessage: (message: CloudflareQueueMessage<T>, batch: CloudflareQueueMessageBatch<T>) => unknown | Promise<unknown>;
55
+ /** The Queue Definition name in delivery error reports. Defaults to the name that `batch.queue` encodes. */
56
+ queue?: string;
55
57
  }
56
58
  type VercelQueueRetryDirective = {
57
59
  acknowledge: true;
@@ -156,7 +158,6 @@ interface LocalQueueDriverOptions extends QueueSharedOptions {
156
158
  */
157
159
  type LocalQueueRules = QueueDriver;
158
160
  interface LocalQueueModuleDriverOptions extends QueueSharedOptions {
159
- /** Directory of the stored jobs, relative to the working directory. Defaults to `.vitehub/data/queue`. */
160
161
  base?: string;
161
162
  driver: "local";
162
163
  }
@@ -207,6 +208,11 @@ interface QueueDefinitionOptions {
207
208
  cache?: boolean;
208
209
  callbackOptions?: VercelQueueCallbackOptions;
209
210
  concurrency?: number;
211
+ /**
212
+ * Cloudflare: the most messages in one batch, from 1 to 100. Cloudflare's default is 10. Write it as a number literal,
213
+ * because the build reads it from the file to configure the consumer.
214
+ */
215
+ maxBatchSize?: number;
210
216
  onDispatchError?: (error: unknown, context: {
211
217
  name: string;
212
218
  }) => unknown | Promise<unknown>;
@@ -396,7 +402,7 @@ interface LocalQueueJob {
396
402
  queue: string;
397
403
  state: "dead" | "pending" | "running";
398
404
  }
399
- /** One stored job with its payload, as `vitehub queue jobs show` shows it. */
405
+ /** One stored job with its payload, as `vitehub queue jobs get` shows it. */
400
406
  interface LocalQueueJobDetail extends LocalQueueJob {
401
407
  /** The local provider only: the file of the job. */
402
408
  file?: string;
@@ -1,4 +1,4 @@
1
- import { a as getQueueRuntimeEvent } from "./state-DLqTqF6V.js";
1
+ import { a as getQueueRuntimeEvent } from "./state-ER1YdCBF.js";
2
2
  //#region src/internal/vercel-region.ts
3
3
  function readHeader(headers, name) {
4
4
  const get = headers?.get;
package/dist/vite.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { N as QueueOptions, s as DiscoveredQueueDefinition } from "./types-CiuSIPR0.js";
2
- import { n as OperationContributionEntry } from "./operation-definition-nmRu_O3V.js";
1
+ import { N as QueueOptions, s as DiscoveredQueueDefinition } from "./types-klaR79hV.js";
2
+ import { n as OperationContributionEntry } from "./operation-definition-CI2PJGqu.js";
3
3
  import "nostics";
4
4
  import { Plugin, UserConfig } from "vite";
5
5
  //#region ../internal/src/deployment.d.ts
@@ -56,6 +56,8 @@ interface ViteHubResourceSummary {
56
56
  owner: string;
57
57
  /** Absent when no id is known yet. */
58
58
  source?: ViteHubResourceIdSource;
59
+ /** The resource is in the Wrangler config of a standalone Provider Output Worker, not in Nitro's. */
60
+ standalone?: boolean;
59
61
  }
60
62
  interface ViteHubInspectionContributor {
61
63
  definitions?: readonly ViteHubDefinitionInspector[];
@@ -122,6 +124,7 @@ interface DurabilityPluginMetadata {
122
124
  interface HostCliRunResult {
123
125
  exitCode: number | null;
124
126
  stdout: string;
127
+ stderr?: string;
125
128
  }
126
129
  /** Runs a host CLI with an argument array and no shell, and returns its stdout. */
127
130
  type HostCliRun = (command: string, args: readonly string[], options: {
@@ -305,6 +308,8 @@ interface ContributionContext {
305
308
  projectRoot: string;
306
309
  /** Server directories that the host forwards, for example Nuxt's `serverDir` and the server directories of layers. */
307
310
  serverDirs?: readonly string[];
311
+ /** The flat list of Vite plugins, so a factory can read what sibling plugins declare. */
312
+ plugins?: readonly unknown[];
308
313
  }
309
314
  /**
310
315
  * Returns the contributions of a plugin. It runs once per discovery pass, so it must be idempotent and must not depend
@@ -356,7 +361,6 @@ export declare function collectQueueContributions(plugins: readonly unknown[] |
356
361
  /** Discovery source of Queue Definitions that Vite plugins contribute through `vitehub.queues`. */
357
362
  export declare const contributedQueueSource = "vite-plugin-contribution";
358
363
  interface QueueContributionOptions {
359
- /** Queue Definitions that Vite plugins contribute. See `collectQueueContributions()`. */
360
364
  contributions?: readonly CollectedQueueContribution[];
361
365
  }
362
366
  export declare function discoverQueueDefinitions(options: QueueContributionOptions & {
@@ -712,7 +716,7 @@ interface QueueInspectionOptions {
712
716
  serverDirs?: string[];
713
717
  }
714
718
  /** Summarizes discovered Queue Definitions for the CLI and Console. */
715
- export declare function inspectQueueDefinitions(options: QueueInspectionOptions): ViteHubDefinitionSummary[];
719
+ export declare function inspectQueueDefinitions(options: QueueInspectionOptions, definitions?: readonly DiscoveredQueueDefinition[]): ViteHubDefinitionSummary[];
716
720
  /** Console section that lists discovered Queue Definitions. `vitehub inspect definitions` reads the same data. */
717
721
  export declare const queueConsoleSection: ViteHubConsoleSectionContribution<QueueInspectionOptions>;
718
722
  //#endregion
package/dist/vite.js CHANGED
@@ -1,14 +1,15 @@
1
1
  import { n as isRecord, r as isRecordOrFunction, t as cloneRecord } from "./object-D8pRdprI.js";
2
- import { t as queueErrorDiagnostics } from "./error-diagnostics-mJXBjmQx.js";
3
- import { t as internalErrorDiagnostics } from "./error-diagnostics-CQ4BUqRe.js";
4
- import { a as resolveHost, i as getHostingProvider, n as normalizeQueueOptions, o as resolveHostPreset, r as postgresQueueUrlVariable, t as defaultLocalQueueBase } from "./config-B2eaXaT5.js";
2
+ import { t as queueErrorDiagnostics } from "./error-diagnostics-DukggGP6.js";
3
+ import { n as isQueueMaxBatchSize } from "./definition-BL_3WHNu.js";
4
+ import { t as internalErrorDiagnostics } from "./error-diagnostics-C0KyI408.js";
5
+ import { a as resolveHost, i as getHostingProvider, n as normalizeQueueOptions, o as resolveHostPreset, r as postgresQueueUrlVariable, t as defaultLocalQueueBase } from "./config-YEuaeQVq.js";
5
6
  import { t as getCloudflareQueueBindingName } from "./cloudflare-GosJefIK.js";
6
7
  import { t as getVercelQueueTopicName } from "./vercel-C_4vqxcl.js";
7
8
  import { n as summarizeDefinitions } from "./inspect-PeuckaC3.js";
8
9
  import { t as invariant } from "./invariant-D8_xBqmZ.js";
9
- import { t as getCloudflareQueueName } from "./cloudflare-resource-name-BIfBglC2.js";
10
+ import { t as getCloudflareQueueName } from "./cloudflare-resource-name-BUNNqgkg.js";
10
11
  import { createRequire } from "node:module";
11
- import { existsSync, readdirSync, realpathSync, statSync } from "node:fs";
12
+ import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
12
13
  import { tmpdir } from "node:os";
13
14
  import { basename, dirname, isAbsolute, parse, resolve } from "node:path";
14
15
  import { fileURLToPath } from "node:url";
@@ -42,6 +43,7 @@ function createNoExternalAddition(...packageNames) {
42
43
  function isServerEnvironment(name, config) {
43
44
  return name === "ssr" || config.consumer === "server";
44
45
  }
46
+ const VITEHUB_PROJECT_ROOT = "__vitehubProjectRoot";
45
47
  /** The deployment host that `vitehub()` selected, such as `"cloudflare"`. */
46
48
  const VITEHUB_DEPLOYMENT_HOST = "__vitehubDeploymentHost";
47
49
  /**
@@ -98,7 +100,7 @@ function hasProjectRootDirectoryMarker(root) {
98
100
  for (const marker of projectRootDirectoryMarkers) try {
99
101
  if (statSync(resolve(root, ...marker)).isDirectory()) return true;
100
102
  } catch (error) {
101
- if (error.code !== "ENOENT") throw error;
103
+ if (!isMissingProjectMarker(error)) throw error;
102
104
  }
103
105
  return false;
104
106
  }
@@ -112,11 +114,15 @@ function hasProjectRootFileMarker(root, markers) {
112
114
  try {
113
115
  if (statSync(resolve(root, ...path)).isFile()) return true;
114
116
  } catch (error) {
115
- if (error.code !== "ENOENT") throw error;
117
+ if (!isMissingProjectMarker(error)) throw error;
116
118
  }
117
119
  }
118
120
  return false;
119
121
  }
122
+ function isMissingProjectMarker(error) {
123
+ const code = error.code;
124
+ return code === "ENOENT" || code === "ENOTDIR";
125
+ }
120
126
  //#endregion
121
127
  //#region ../internal/src/durability.ts
122
128
  /** The `durability` module next to the Vite plugin module at `importMetaUrl`, in source and in `dist`. */
@@ -297,7 +303,11 @@ function cloneProviderValue(value) {
297
303
  if (value && typeof value === "object") return cloneProviderRecord(value);
298
304
  return value;
299
305
  }
300
- function compatibleEntries(existing, incoming, identityKey, conflictKeys, owner) {
306
+ /**
307
+ * The incoming entries that the app config does not have yet. An entry that the app already has must agree on
308
+ * `conflictKeys`, and on each of `setKeys` that the incoming entry sets, because the app's entry is the one that stays.
309
+ */
310
+ function compatibleEntries(existing, incoming, identityKey, conflictKeys, owner, setKeys = []) {
301
311
  const current = Array.isArray(existing) ? existing.map(cloneProviderRecord) : [];
302
312
  return (incoming ?? []).filter((entry) => {
303
313
  const identity = entry[identityKey];
@@ -307,6 +317,8 @@ function compatibleEntries(existing, incoming, identityKey, conflictKeys, owner)
307
317
  return true;
308
318
  }
309
319
  if (conflictKeys.some((key) => !isDeepStrictEqual(match[key], entry[key]))) throw internalErrorDiagnostics.INTERNAL_B0001({ message: `[vitehub] Cloudflare ${identityKey} ${JSON.stringify(identity)} from ${owner} is already assigned to an incompatible resource.` });
320
+ const differentKey = setKeys.find((key) => entry[key] !== void 0 && !isDeepStrictEqual(match[key], entry[key]));
321
+ if (differentKey) throw internalErrorDiagnostics.INTERNAL_B0001({ message: `[vitehub] The Cloudflare ${identityKey} ${JSON.stringify(identity)} in the app's Wrangler config has ${differentKey} ${JSON.stringify(match[differentKey]) ?? "unset"}, but ${owner} sets ${JSON.stringify(entry[differentKey])}. Remove the entry from the Wrangler config, because ViteHub writes it, or give it the same value.` });
310
322
  return false;
311
323
  });
312
324
  }
@@ -363,7 +375,7 @@ function mergeContribution(wrangler, owner, contribution) {
363
375
  const queues = cloneProviderRecord(wrangler.queues);
364
376
  const secrets = cloneProviderRecord(wrangler.secrets);
365
377
  const environments = cloneProviderRecord(wrangler.env);
366
- const consumers = compatibleEntries(queues.consumers, contribution.queues?.consumers, "queue", [], owner);
378
+ const consumers = compatibleEntries(queues.consumers, contribution.queues?.consumers, "queue", [], owner, ["max_batch_size"]);
367
379
  const producers = compatibleEntries(queues.producers, contribution.queues?.producers, "binding", ["queue"], owner);
368
380
  const r2Buckets = compatibleEntries(wrangler.r2_buckets, contribution.r2Buckets, "binding", ["bucket_name", "jurisdiction"], owner);
369
381
  const rateLimits = compatibleEntries(wrangler.ratelimits, contribution.rateLimits, "name", ["namespace_id", "simple"], owner);
@@ -680,8 +692,8 @@ function contributeCloudflareProviderOutput(catalog, contribution) {
680
692
  const { owner, ...value } = contribution;
681
693
  catalog.replaceCloudflareContribution(owner, value);
682
694
  }
683
- //#endregion
684
- //#region ../internal/src/nitro-kit.ts
695
+ Object.freeze({ vitehubAuthAccess: "handler" });
696
+ Object.freeze({ vitehubOwnAccess: true });
685
697
  function cloneArray(value) {
686
698
  return Array.isArray(value) ? [...value] : [];
687
699
  }
@@ -756,6 +768,10 @@ async function collectContributions(plugins, options) {
756
768
  const candidates = [];
757
769
  await flattenPlugins(plugins ?? [], candidates, /* @__PURE__ */ new Set());
758
770
  const collected = /* @__PURE__ */ new Map();
771
+ const context = {
772
+ ...options.context,
773
+ plugins: candidates
774
+ };
759
775
  for (const plugin of candidates) {
760
776
  if (!Object.hasOwn(plugin, "vitehub")) continue;
761
777
  const metadata = Reflect.get(plugin, "vitehub");
@@ -767,7 +783,7 @@ async function collectContributions(plugins, options) {
767
783
  throw options.invalid(`[vitehub] Plugin ${JSON.stringify(contributor)} contributed an invalid ${options.kind}: ${reason}`);
768
784
  };
769
785
  const callable = typeof source === "function";
770
- const entries = callable ? await Reflect.apply(source, void 0, [options.context]) : source;
786
+ const entries = callable ? await Reflect.apply(source, void 0, [context]) : source;
771
787
  if (entries === void 0 && callable) continue;
772
788
  if (!Array.isArray(entries)) fail(`\`vitehub.${options.key}\` must be an array or a function that returns one.`);
773
789
  const list = entries;
@@ -1052,7 +1068,7 @@ function mergeContributedQueueDefinitions(discovered, contributions) {
1052
1068
  function discoverQueueDefinitions(options) {
1053
1069
  if (options.mode === "server-queues") return mergeContributedQueueDefinitions(discoverDefinitions("queue", [createDirectoryDefinitionSource("server-queues", options.scanDirs, "queues")]), options.contributions);
1054
1070
  const roots = resolveDefinitionScanRoots(options.rootDir, options.scanDirs);
1055
- const serverScanDirs = options.serverDirs || [...new Set(options.serverRootDirs || roots)].map((root) => resolve$1(root, "server"));
1071
+ const serverScanDirs = [...new Set(options.serverDirs?.map((dir) => resolve$1(dir)) ?? (options.serverRootDirs ?? roots).map((root) => resolve$1(root, "server")))];
1056
1072
  return mergeContributedQueueDefinitions(discoverDefinitions("queue", [createSuffixDefinitionSource("vite-suffix", roots, queueSuffixPattern, normalizeSuffixQueueName), createDirectoryDefinitionSource("server-queues", serverScanDirs, "queues")]), options.contributions);
1057
1073
  }
1058
1074
  //#endregion
@@ -1090,7 +1106,6 @@ const generatedQueueNitroVercelConsumerDir = ".vitehub/nitro/queue/vercel";
1090
1106
  const vercelQueueConsumerRoutePrefix = "/api/vitehub/queues/vercel";
1091
1107
  const packageDir = computePackageDir(import.meta.url);
1092
1108
  const packageRequire = createRequire(resolve(packageDir, "package.json"));
1093
- /** `@vercel/queue` and `@vercel/functions` are optional peers. A Vercel build needs both in the app. */
1094
1109
  function resolveVercelDependency(specifier) {
1095
1110
  try {
1096
1111
  return packageRequire.resolve(specifier);
@@ -1106,11 +1121,6 @@ function resolveOutputQueueConfig(queue, hosting, postgresDatabase) {
1106
1121
  postgresDatabase
1107
1122
  }) || false;
1108
1123
  }
1109
- /**
1110
- * The Queue configuration that the generated server installs. `vite dev` runs in Node, where Cloudflare and Vercel
1111
- * cannot deliver jobs, so it runs them with the local driver and the delivery rules of the driver of the build.
1112
- * A build keeps the configured driver.
1113
- */
1114
1124
  function resolveRuntimeQueueConfig(queueConfig, development, rootDir) {
1115
1125
  if (!development || queueConfig === false) return queueConfig;
1116
1126
  if (queueConfig.driver === "local") return {
@@ -1139,11 +1149,42 @@ function createCloudflareQueueDefinitionNames(definitions, namePrefix = "") {
1139
1149
  }
1140
1150
  return Object.fromEntries([...names].map(([physicalName, definition]) => [physicalName, definition.name]));
1141
1151
  }
1142
- function createCloudflareQueueBindings(definitions, namePrefix = "") {
1152
+ /**
1153
+ * Reads `maxBatchSize` from `export default defineQueue({ ... })`. The Cloudflare consumer is configured at build time,
1154
+ * so the build fails when it cannot prove the value: a spread or computed key in those options, a value that is not a
1155
+ * number literal, or the option on a `defineQueue()` call that is not the default export.
1156
+ */
1157
+ function readQueueMaxBatchSize(file, { argumentExpression, defaultExportExpression, findCalls, objectProperties, scanModule }) {
1158
+ const module = scanModule(readFileSync(file, "utf8"), file);
1159
+ const invalid = () => {
1160
+ throw queueErrorDiagnostics.QUEUE_MAX_BATCH_SIZE_INVALID({ where: file });
1161
+ };
1162
+ const exported = defaultExportExpression(module);
1163
+ let maxBatchSize;
1164
+ for (const call of findCalls(module, ["defineQueue"])) {
1165
+ const options = argumentExpression(call.arguments[0]);
1166
+ if (options?.type !== "ObjectExpression") return invalid();
1167
+ const properties = objectProperties(options);
1168
+ if (properties.some((property) => property.key === void 0 || property.computed)) return invalid();
1169
+ const property = properties.findLast((candidate) => candidate.key === "maxBatchSize");
1170
+ if (!property) continue;
1171
+ if (call !== exported || property.node.type !== "Property" || property.node.kind !== "init" || property.node.method || property.value?.type !== "Literal" || !isQueueMaxBatchSize(property.value.value)) return invalid();
1172
+ maxBatchSize = property.value.value;
1173
+ }
1174
+ return maxBatchSize;
1175
+ }
1176
+ async function createCloudflareQueueBindings(definitions, namePrefix = "") {
1143
1177
  if (!definitions.length) return;
1144
- const names = createCloudflareQueueDefinitionNames(definitions, namePrefix);
1178
+ createCloudflareQueueDefinitionNames(definitions, namePrefix);
1179
+ const scanner = await import("./scan-module-BbqyaLl6.js");
1145
1180
  return {
1146
- consumers: Object.keys(names).map((queue) => ({ queue })),
1181
+ consumers: definitions.map((definition) => {
1182
+ const maxBatchSize = readQueueMaxBatchSize(definition.handler, scanner);
1183
+ return {
1184
+ ...maxBatchSize === void 0 ? {} : { max_batch_size: maxBatchSize },
1185
+ queue: getCloudflareQueueName(definition.name, namePrefix)
1186
+ };
1187
+ }),
1147
1188
  producers: definitions.map((definition) => ({
1148
1189
  binding: getCloudflareQueueBindingName(definition.name),
1149
1190
  queue: getCloudflareQueueName(definition.name, namePrefix)
@@ -1298,12 +1339,7 @@ function renderVercelQueueConsumerHandler(file, name) {
1298
1339
  //#endregion
1299
1340
  //#region src/inspect.ts
1300
1341
  /** Summarizes discovered Queue Definitions for the CLI and Console. */
1301
- function inspectQueueDefinitions(options) {
1302
- const definitions = discoverQueueDefinitions({
1303
- contributions: options.contributions,
1304
- rootDir: options.rootDir,
1305
- serverDirs: options.serverDirs
1306
- });
1342
+ function inspectQueueDefinitions(options, definitions = discoverQueueDefinitions(options)) {
1307
1343
  return summarizeDefinitions(options.projectRoot, definitions, "queue").map((summary, index) => {
1308
1344
  const { contributor, reason } = definitions[index];
1309
1345
  if (!contributor) return summary;
@@ -1320,12 +1356,8 @@ function inspectQueueDefinitions(options) {
1320
1356
  });
1321
1357
  }
1322
1358
  /** Lists the Cloudflare Queues that Queue Definitions bind by name. Reads local files only. */
1323
- function inspectQueueResources(options) {
1324
- return discoverQueueDefinitions({
1325
- contributions: options.contributions,
1326
- rootDir: options.rootDir,
1327
- serverDirs: options.serverDirs
1328
- }).map((definition) => ({
1359
+ function inspectQueueResources(options, definitions = discoverQueueDefinitions(options)) {
1360
+ return definitions.map((definition) => ({
1329
1361
  binding: options.binding ?? getCloudflareQueueBindingName(definition.name),
1330
1362
  definition: definition.name,
1331
1363
  host: "cloudflare",
@@ -1606,22 +1638,18 @@ async function listCloudflarePages(request, path, options) {
1606
1638
  }
1607
1639
  //#endregion
1608
1640
  //#region src/provision.ts
1609
- /** Provision State category for Cloudflare Queue names, keyed by Queue Definition name. Config never reads it, because Queue names come from Definitions. */
1610
1641
  const QUEUE_CLOUDFLARE_PROVISION_CATEGORY = "queue";
1611
1642
  function parseQueues(value) {
1612
1643
  if (!Array.isArray(value) || Array.from(value).some((queue, index) => !(index in value) || queue === null || typeof queue !== "object" || Array.isArray(queue))) throw queueErrorDiagnostics.QUEUE_PROVISION_FAILED();
1613
1644
  return value;
1614
1645
  }
1615
- function createQueueProvisionStep(resolveRootDir, resolveNamePrefix = () => void 0, resolveContributions = () => []) {
1646
+ function createQueueProvisionStep(resolveDefinitions, resolveNamePrefix = () => void 0) {
1616
1647
  return {
1617
1648
  id: "queue:cloudflare-queues",
1618
1649
  provider: "cloudflare",
1619
1650
  recordedState() {
1620
1651
  const namePrefix = resolveNamePrefix();
1621
- const queues = new Map(discoverQueueDefinitions({
1622
- contributions: resolveContributions(),
1623
- rootDir: resolveRootDir()
1624
- }).map((definition) => [definition.name, getCloudflareQueueName(definition.name, namePrefix)]));
1652
+ const queues = new Map(resolveDefinitions().map((definition) => [definition.name, getCloudflareQueueName(definition.name, namePrefix)]));
1625
1653
  return [{
1626
1654
  category: QUEUE_CLOUDFLARE_PROVISION_CATEGORY,
1627
1655
  declared: [...queues.keys()],
@@ -1638,10 +1666,7 @@ function createQueueProvisionStep(resolveRootDir, resolveNamePrefix = () => void
1638
1666
  }
1639
1667
  const request = createCloudflareProvisionClient(config, context.fetch);
1640
1668
  const namePrefix = resolveNamePrefix();
1641
- const queues = discoverQueueDefinitions({
1642
- contributions: resolveContributions(),
1643
- rootDir: resolveRootDir()
1644
- }).map((definition) => ({
1669
+ const queues = resolveDefinitions().map((definition) => ({
1645
1670
  definition: definition.name,
1646
1671
  name: getCloudflareQueueName(definition.name, namePrefix)
1647
1672
  }));
@@ -1674,10 +1699,6 @@ function findDatabasePlugin(plugins) {
1674
1699
  if (found) return found;
1675
1700
  } else if (plugin && typeof plugin === "object" && "name" in plugin && plugin.name === databaseVitePluginName) return plugin;
1676
1701
  }
1677
- /**
1678
- * Whether the Database integration resolved the Default Database on Postgres, with its layers, contributions, and
1679
- * server directories. A Node server then infers the postgres provider on the connection of that Database.
1680
- */
1681
1702
  function hasPostgresDefaultDatabase(plugin) {
1682
1703
  return plugin?.api?.getConfig?.()?.databases.default?.dialect === "postgresql";
1683
1704
  }
@@ -1699,10 +1720,10 @@ function normalizeQueueForHosting(queue, hosting) {
1699
1720
  }
1700
1721
  return normalizeQueueOptions(queue, { hosting });
1701
1722
  }
1702
- /**
1703
- * The host of this build: the Nitro preset, else the host that `vitehub()` selected. `vite dev` has no Nitro preset, so
1704
- * a Node app in dev reads its host from `vitehub()`.
1705
- */
1723
+ function frameworkProjectRoot(config) {
1724
+ const configured = Reflect.get(config, VITEHUB_PROJECT_ROOT);
1725
+ return typeof configured === "string" && configured ? resolve$1(configured) : void 0;
1726
+ }
1706
1727
  function resolveQueueHost(config, nitro) {
1707
1728
  return resolveHost({
1708
1729
  nitro,
@@ -1727,7 +1748,6 @@ function isGeneratedNitroRegistration(value, generatedPath) {
1727
1748
  function isGeneratedVercelConsumer(value) {
1728
1749
  return typeof value === "string" && value.replaceAll("\\", "/").includes(`.vitehub/nitro/queue/vercel/`);
1729
1750
  }
1730
- /** Vercel delivers Queue messages to Nitro routes that have a queue trigger in `vercel.functionRules`. */
1731
1751
  function hostsVercelQueueConsumers(nitro) {
1732
1752
  const hosting = getHostingProvider(resolveHost({ nitro }));
1733
1753
  return hosting === "vercel" || hosting === void 0 && Boolean(process.env.VERCEL);
@@ -1754,7 +1774,7 @@ function addVercelQueueConsumers(kit, definitions, root) {
1754
1774
  functionRules
1755
1775
  };
1756
1776
  }
1757
- function mergeNitroConfig(config, value, queue, root, definitions) {
1777
+ async function mergeNitroConfig(config, value, queue, root, definitions) {
1758
1778
  const providerOutput = useProviderOutputCatalog(config);
1759
1779
  const nitro = cloneRecord(value);
1760
1780
  const nitroHosting = getHostingProvider(resolveHost({ nitro }));
@@ -1790,7 +1810,7 @@ function mergeNitroConfig(config, value, queue, root, definitions) {
1790
1810
  const cloudflareQueues = supportsCloudflareQueues(nitro);
1791
1811
  const rollupConfig = cloneRecord(nitro.rollupConfig);
1792
1812
  const resolvedQueue = normalizeQueueOptions(queue, { hosting: queueHosting });
1793
- const generated = createCloudflareQueueBindings(definitions, resolvedQueue?.driver === "cloudflare" ? resolvedQueue.namePrefix : void 0);
1813
+ const generated = await createCloudflareQueueBindings(definitions, resolvedQueue?.driver === "cloudflare" ? resolvedQueue.namePrefix : void 0);
1794
1814
  const baseNitro = {
1795
1815
  ...nitro,
1796
1816
  ...cloudflareQueues ? { rollupConfig: {
@@ -1854,6 +1874,22 @@ function hubQueue(options, internalOptions = {}) {
1854
1874
  serverDirs: dirs
1855
1875
  });
1856
1876
  }
1877
+ function discoverViteQueueDefinitions(viteRoot, outputRoot, found) {
1878
+ return resolve$1(viteRoot) === outputRoot ? discoverQueueDefinitions({
1879
+ contributions: found,
1880
+ rootDir: viteRoot
1881
+ }) : discoverQueueDefinitions({
1882
+ contributions: found,
1883
+ rootDir: outputRoot,
1884
+ serverDirs
1885
+ });
1886
+ }
1887
+ function discoverCurrentQueueDefinitions() {
1888
+ return resolveNuxtDefinitions?.() ?? (resolved && buildStates.get(resolved)?.resolveDefinitions()) ?? discoverQueueDefinitions({
1889
+ contributions,
1890
+ rootDir: resolved?.root ?? process.cwd()
1891
+ });
1892
+ }
1857
1893
  let databasePlugin;
1858
1894
  let postgresDatabase = false;
1859
1895
  const database = () => ({
@@ -1904,34 +1940,31 @@ function hubQueue(options, internalOptions = {}) {
1904
1940
  const resolvedQueue = normalizeQueueOptions(queue, { hosting });
1905
1941
  if (!resolvedQueue?.driver) return;
1906
1942
  const rootDir = resolved?.root ?? process.cwd();
1943
+ const projectRoot = nuxtProjectRoot ?? (resolved && frameworkProjectRoot(resolved)) ?? resolveViteHubProjectRoot(rootDir);
1907
1944
  return {
1908
1945
  definitions: [{
1909
1946
  kind: "queue",
1910
1947
  label: "Queues",
1911
1948
  list: () => inspectQueueDefinitions({
1912
- contributions,
1913
- projectRoot: resolveViteHubProjectRoot(rootDir),
1914
- rootDir,
1915
- serverDirs
1916
- })
1949
+ projectRoot,
1950
+ rootDir
1951
+ }, discoverCurrentQueueDefinitions())
1917
1952
  }],
1918
1953
  resources: () => resolvedQueue.driver === "cloudflare" ? inspectQueueResources({
1919
1954
  binding: resolvedQueue.binding,
1920
- contributions,
1921
1955
  namePrefix: resolvedQueue.namePrefix,
1922
- projectRoot: resolveViteHubProjectRoot(rootDir),
1923
- rootDir,
1924
- serverDirs
1925
- }) : []
1956
+ projectRoot,
1957
+ rootDir
1958
+ }, discoverCurrentQueueDefinitions()) : []
1926
1959
  };
1927
1960
  },
1928
1961
  cli: async () => {
1929
1962
  return {
1930
1963
  namespaces: [],
1931
- provision: [createQueueProvisionStep(() => resolved?.root ?? process.cwd(), () => {
1964
+ provision: [createQueueProvisionStep(discoverCurrentQueueDefinitions, () => {
1932
1965
  const resolvedQueue = normalizeQueueOptions(queue, { hosting: "cloudflare" });
1933
1966
  return resolvedQueue?.driver === "cloudflare" ? resolvedQueue.namePrefix : void 0;
1934
- }, () => contributions)]
1967
+ })]
1935
1968
  };
1936
1969
  },
1937
1970
  queue: { async createNitroConfig({ development = false, nitro, projectRoot, root, serverDirs, viteConfig }) {
@@ -1954,7 +1987,7 @@ function hubQueue(options, internalOptions = {}) {
1954
1987
  });
1955
1988
  const definitions = resolveNuxtDefinitions();
1956
1989
  nuxtConfiguredDefinitions = definitions;
1957
- const configuredNitro = mergeNitroConfig(config, nitro, projectQueue, projectRoot, definitions);
1990
+ const configuredNitro = await mergeNitroConfig(config, nitro, projectQueue, projectRoot, definitions);
1958
1991
  databasePlugin = findDatabasePlugin(viteConfig?.plugins) ?? databasePlugin;
1959
1992
  const host = resolveQueueHost(config, configuredNitro);
1960
1993
  postgresDatabase = host === "node" && hasPostgresDefaultDatabase(databasePlugin);
@@ -1982,30 +2015,30 @@ function hubQueue(options, internalOptions = {}) {
1982
2015
  queueOptions.set(resolve$1(config.root || process.cwd()), queue);
1983
2016
  serverDirs = config["__vitehubServerDirs"] ?? serverDirs;
1984
2017
  const root = config.root || process.cwd();
1985
- contributions = await collectPluginQueueContributions(config.plugins, root);
2018
+ const configuredRoot = frameworkProjectRoot(config);
2019
+ const outputRoot = configuredRoot ?? resolve$1(root);
2020
+ contributions = await collectPluginQueueContributions(config.plugins, root, configuredRoot);
1986
2021
  const nitro = config.nitro;
1987
- config.nitro = mergeNitroConfig(config, nitro, queue, root, discoverQueueDefinitions({
1988
- contributions,
1989
- rootDir: root
1990
- }));
1991
- if (process.env.VITEST) return { test: { setupFiles: [resolve$1(root, generatedQueueTestSetup)] } };
2022
+ config.nitro = await mergeNitroConfig(config, nitro, queue, outputRoot, discoverViteQueueDefinitions(root, outputRoot, contributions));
2023
+ if (process.env.VITEST) return { test: { setupFiles: [resolve$1(outputRoot, generatedQueueTestSetup)] } };
1992
2024
  },
1993
2025
  async configResolved(config) {
1994
2026
  resolved = config;
1995
- resolvedConfigs.set(config.root, config);
1996
- const nuxtState = nuxtStates.get(config.root);
2027
+ const configuredRoot = frameworkProjectRoot(config);
2028
+ const nuxtState = nuxtStates.get(config.root) ?? (configuredRoot ? nuxtStates.get(configuredRoot) : void 0);
1997
2029
  nuxtConfiguredDefinitions = nuxtState?.nuxtConfiguredDefinitions;
1998
2030
  nuxtProjectRoot = nuxtState?.nuxtProjectRoot;
1999
2031
  resolveNuxtDefinitions = nuxtState?.resolveNuxtDefinitions;
2032
+ const outputRoot = nuxtProjectRoot ?? configuredRoot ?? resolve$1(config.root);
2033
+ for (const root of /* @__PURE__ */ new Set([config.root, outputRoot])) resolvedConfigs.set(root, config);
2000
2034
  queue = getResolvedFeatureOptions(config, "queue") ?? options;
2001
- queueOptions.set(config.root, queue);
2035
+ for (const root of /* @__PURE__ */ new Set([config.root, outputRoot])) queueOptions.set(root, queue);
2002
2036
  const configuredNitro = config.nitro;
2003
- contributions = await collectPluginQueueContributions(config.plugins, config.root);
2004
- configuredDefinitions = discoverQueueDefinitions({
2005
- contributions,
2006
- rootDir: config.root
2007
- });
2008
- const nitro = mergeNitroConfig(config, configuredNitro, queue, config.root, configuredDefinitions);
2037
+ contributions = await collectPluginQueueContributions(config.plugins, config.root, nuxtProjectRoot ?? configuredRoot);
2038
+ const resolveContributions = contributions;
2039
+ const resolveDefinitions = resolveNuxtDefinitions ?? (() => discoverViteQueueDefinitions(config.root, outputRoot, resolveContributions));
2040
+ configuredDefinitions = resolveDefinitions();
2041
+ const nitro = await mergeNitroConfig(config, configuredNitro, queue, outputRoot, configuredDefinitions);
2009
2042
  config.nitro = nitro;
2010
2043
  databasePlugin = findDatabasePlugin(config.plugins) ?? databasePlugin;
2011
2044
  const host = resolveQueueHost(config, nitro);
@@ -2017,13 +2050,14 @@ function hubQueue(options, internalOptions = {}) {
2017
2050
  nitroQueue = resolvedQueue?.driver && nitroHosting && resolvedQueue.driver !== nitroHosting ? false : queue;
2018
2051
  validatesNitroDefinitions = hasNitroConfigContext(config) && nitroQueue !== false;
2019
2052
  localDevelopment = config.command === "serve" && !preview;
2020
- writtenQueue = await writeQueueNitroIntegration(config.root, nitroQueue, hosting, cloudflareQueues, configuredDefinitions, localDevelopment, internalOptions.importBase, database());
2021
- recordNodeWrite(config.root, queue, host, configuredDefinitions);
2053
+ writtenQueue = await writeQueueNitroIntegration(outputRoot, nitroQueue, hosting, cloudflareQueues, configuredDefinitions, localDevelopment, internalOptions.importBase, database());
2054
+ recordNodeWrite(outputRoot, queue, host, configuredDefinitions);
2022
2055
  buildStates.set(config, {
2023
2056
  configuredDefinitions,
2024
2057
  contributions,
2025
2058
  nuxtConfiguredDefinitions,
2026
2059
  queue,
2060
+ resolveDefinitions,
2027
2061
  resolveNuxtDefinitions,
2028
2062
  resolved: config,
2029
2063
  validatesNitroDefinitions
@@ -2038,11 +2072,9 @@ function hubQueue(options, internalOptions = {}) {
2038
2072
  const isDirectoryDefinition = /\.(?:c|m)?[jt]s$/i.test(file) && (/\/server\/queues\//.test(file) || nuxtServerQueueDirs.some((dir) => file.startsWith(dir)));
2039
2073
  if (!/\.queue\.(?:c|m)?[jt]s$/i.test(file) && !isDirectoryDefinition) return;
2040
2074
  resolved = context.server.config;
2041
- const definitions = resolveNuxtDefinitions?.() ?? discoverQueueDefinitions({
2042
- contributions,
2043
- rootDir: resolved.root
2044
- });
2045
- writtenQueue = await writeQueueNitroIntegration(nuxtProjectRoot || resolved.root, nitroQueue, hosting, cloudflareQueues, definitions, localDevelopment, internalOptions.importBase, database());
2075
+ const outputRoot = nuxtProjectRoot || frameworkProjectRoot(resolved) || resolve$1(resolved.root);
2076
+ const definitions = resolveNuxtDefinitions?.() ?? discoverViteQueueDefinitions(resolved.root, outputRoot, contributions);
2077
+ writtenQueue = await writeQueueNitroIntegration(outputRoot, nitroQueue, hosting, cloudflareQueues, definitions, localDevelopment, internalOptions.importBase, database());
2046
2078
  },
2047
2079
  async buildStart() {
2048
2080
  const databaseConfig = databasePlugin?.api?.getConfig?.();
@@ -2060,10 +2092,7 @@ function hubQueue(options, internalOptions = {}) {
2060
2092
  const state = config ? buildStates.get(config) : void 0;
2061
2093
  if (error || !state || shouldSkipViteProviderBuild(state.resolved.command)) return;
2062
2094
  if (state.resolveNuxtDefinitions && state.nuxtConfiguredDefinitions) resolveStableQueueDefinitions(state.resolveNuxtDefinitions, state.nuxtConfiguredDefinitions, "Nuxt");
2063
- else if (state.validatesNitroDefinitions) resolveStableQueueDefinitions(() => discoverQueueDefinitions({
2064
- contributions: state.contributions,
2065
- rootDir: state.resolved.root
2066
- }), state.configuredDefinitions, "Nitro");
2095
+ else if (state.validatesNitroDefinitions) resolveStableQueueDefinitions(state.resolveDefinitions, state.configuredDefinitions, "Nitro");
2067
2096
  }
2068
2097
  };
2069
2098
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vite-hub/queue",
3
- "version": "0.4.1",
3
+ "version": "0.5.0",
4
4
  "description": "Queue primitives and Vite deployment integration for ViteHub.",
5
5
  "keywords": [
6
6
  "background-jobs",
@@ -64,7 +64,7 @@
64
64
  "./package.json": "./package.json"
65
65
  },
66
66
  "dependencies": {
67
- "@vite-hub/runtime": "0.4.1",
67
+ "@vite-hub/runtime": "0.5.0",
68
68
  "defu": "^6.1.7",
69
69
  "nostics": "1.4.0",
70
70
  "pathe": "^2.0.3"
@@ -73,7 +73,7 @@
73
73
  "@types/node": "^24.19.1",
74
74
  "@vercel/functions": "^3.9.11",
75
75
  "@vercel/queue": "^0.11.0",
76
- "@vite-hub/database": "0.4.1",
76
+ "@vite-hub/database": "0.5.0",
77
77
  "@vite-hub/internal": "0.0.1",
78
78
  "postgres": "^3.4.9",
79
79
  "publint": "^0.3.25",