@vite-hub/queue 0.6.0 → 0.7.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.
- package/README.md +17 -12
- package/dist/{client-CwoCdKct.js → client-B8QVg1mA.js} +46 -15
- package/dist/{cloudflare-client-xWteD-su.js → cloudflare-client-BoaOlFzD.js} +13 -8
- package/dist/{cloudflare-resource-name-Bv8Z7nDU.js → cloudflare-resource-name-Coz5CPmn.js} +1 -1
- package/dist/{config-Bzp1xmdh.js → config-ByKUipob.js} +4 -2
- package/dist/{definition-CIiFfst2.js → definition-Dorliu47.js} +9 -2
- package/dist/{duration-C5w_-Rf4.js → duration-CcLSF94z.js} +20 -5
- package/dist/{error-diagnostics-kKXseq8d.js → error-diagnostics-CsiNo_oI.js} +3 -3
- package/dist/{error-diagnostics-Dv6nKZQW.js → error-diagnostics-Yj8XCiya.js} +30 -6
- package/dist/{handler-response-CchTXVjm.js → handler-response-GFXYd6mF.js} +6 -2
- package/dist/index.d.ts +13 -8
- package/dist/index.js +4 -4
- package/dist/internal/runtime/cloudflare-client.d.ts +1 -1
- package/dist/internal/runtime/cloudflare-client.js +1 -1
- package/dist/internal/runtime/cloudflare-vite.d.ts +1 -1
- package/dist/internal/runtime/cloudflare-vite.js +9 -8
- package/dist/internal/runtime/local-client.d.ts +3 -3
- package/dist/internal/runtime/local-client.js +4 -4
- package/dist/internal/runtime/postgres-client.d.ts +9 -7
- package/dist/internal/runtime/postgres-client.js +174 -36
- package/dist/internal/runtime/state.d.ts +5 -3
- package/dist/internal/runtime/state.js +1 -1
- package/dist/internal/runtime/vercel-client.d.ts +1 -1
- package/dist/internal/runtime/vercel-client.js +24 -5
- package/dist/internal/runtime/worker-client.d.ts +2 -2
- package/dist/internal/runtime/worker-client.js +1 -1
- package/dist/{local-RX10a_Sq.js → local-BR4W57HU.js} +146 -97
- package/dist/{local-B72WRWkS.d.ts → local-DUh8sGn-.d.ts} +1 -1
- package/dist/{operations-CoEXxfUW.js → operations-COCpSoua.js} +11 -6
- package/dist/{operation-definition-CqZkx1Rm.d.ts → operations-DSslh_vK.d.ts} +169 -1
- package/dist/operations.d.ts +13 -4
- package/dist/operations.js +98 -37
- package/dist/retries-BSAZru9n.js +27 -0
- package/dist/run-handler-B_RVXMs5.js +61 -0
- package/dist/runtime/hosted.d.ts +1 -1
- package/dist/runtime/hosted.js +32 -20
- package/dist/{state-DqxeV11k.js → state-C-t99I4Q.js} +9 -3
- package/dist/{types-BevEYrUV.d.ts → types-BPs6OsRv.d.ts} +1 -1
- package/dist/{types-BzPGPV9z.d.ts → types-rZHAtkK0.d.ts} +74 -12
- package/dist/{vercel-region-DEsR1YJQ.js → vercel-region-Bp3hwRBr.js} +1 -1
- package/dist/vite.d.ts +3 -156
- package/dist/vite.js +460 -68
- package/package.json +3 -3
package/dist/vite.js
CHANGED
|
@@ -1,20 +1,21 @@
|
|
|
1
1
|
import { t as invariant } from "./invariant-CmdvZ3vp.js";
|
|
2
|
-
import { t as internalErrorDiagnostics } from "./error-diagnostics-
|
|
2
|
+
import { t as internalErrorDiagnostics } from "./error-diagnostics-CsiNo_oI.js";
|
|
3
3
|
import { n as isRecord, r as isRecordOrFunction, t as cloneRecord } from "./object-DRSmpe04.js";
|
|
4
|
-
import { a as
|
|
5
|
-
import { t as queueErrorDiagnostics } from "./error-diagnostics-
|
|
6
|
-
import { n as isQueueMaxBatchSize } from "./definition-
|
|
4
|
+
import { a as getHostingProvider, i as queueWorkersVariable, n as normalizeQueueOptions, o as resolveHost, r as postgresQueueUrlVariable, s as resolveHostPreset, t as defaultLocalQueueBase } from "./config-ByKUipob.js";
|
|
5
|
+
import { t as queueErrorDiagnostics } from "./error-diagnostics-Yj8XCiya.js";
|
|
6
|
+
import { n as isQueueMaxBatchSize } from "./definition-Dorliu47.js";
|
|
7
7
|
import { t as getCloudflareQueueBindingName } from "./cloudflare-BMc35cBD.js";
|
|
8
8
|
import { t as getVercelQueueTopicName } from "./vercel-sUJOxFBB.js";
|
|
9
|
-
import { t as getCloudflareQueueName } from "./cloudflare-resource-name-
|
|
9
|
+
import { t as getCloudflareQueueName } from "./cloudflare-resource-name-Coz5CPmn.js";
|
|
10
10
|
import { n as summarizeDefinitions } from "./inspect-CwdWUhPj.js";
|
|
11
11
|
import { createRequire } from "node:module";
|
|
12
12
|
import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
|
|
13
13
|
import { tmpdir } from "node:os";
|
|
14
14
|
import { basename, dirname, isAbsolute, parse, resolve } from "node:path";
|
|
15
15
|
import { fileURLToPath } from "node:url";
|
|
16
|
-
import { mkdir, rm, writeFile } from "node:fs/promises";
|
|
16
|
+
import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
|
|
17
17
|
import { basename as basename$1, dirname as dirname$1, isAbsolute as isAbsolute$1, relative, resolve as resolve$1 } from "pathe";
|
|
18
|
+
import { isDeepStrictEqual } from "node:util";
|
|
18
19
|
// ../internal/src/build/vite.ts
|
|
19
20
|
const projectRootDirectoryMarkers = [
|
|
20
21
|
["server", "agents"],
|
|
@@ -251,19 +252,312 @@ function mergeOwnedArrays(existing, value, arrays) {
|
|
|
251
252
|
const next = { ...value };
|
|
252
253
|
for (const [field, ownership] of Object.entries(arrays ?? {})) {
|
|
253
254
|
const incoming = Array.isArray(value[field]) ? value[field] : [];
|
|
254
|
-
const
|
|
255
|
+
const unowned = preserveUnownedKeyedArrayEntries(existing[field], ownership, incoming);
|
|
256
|
+
const merged = ownership.key !== void 0 && ownership.preserveOrder && Array.isArray(existing[field]) ? mergeOrderedEntries(existing[field], unowned, incoming, ownership.key) : [...unowned, ...incoming];
|
|
255
257
|
if (merged.length) next[field] = merged;
|
|
256
258
|
else delete next[field];
|
|
257
259
|
}
|
|
258
260
|
return next;
|
|
259
261
|
}
|
|
262
|
+
function mergeOrderedEntries(current, unowned, incoming, key) {
|
|
263
|
+
const preserved = new Set(unowned);
|
|
264
|
+
const replacements = new Map(incoming.flatMap((entry) => {
|
|
265
|
+
const identity = getKeyedArrayEntryValue(entry, key);
|
|
266
|
+
return identity === void 0 ? [] : [[identity, entry]];
|
|
267
|
+
}));
|
|
268
|
+
return [...current.flatMap((entry) => {
|
|
269
|
+
if (preserved.has(entry)) return [entry];
|
|
270
|
+
const identity = getKeyedArrayEntryValue(entry, key);
|
|
271
|
+
if (identity === void 0) return [];
|
|
272
|
+
const replacement = replacements.get(identity);
|
|
273
|
+
if (replacement === void 0) return [];
|
|
274
|
+
replacements.delete(identity);
|
|
275
|
+
return [replacement];
|
|
276
|
+
}), ...incoming.filter((entry) => {
|
|
277
|
+
const identity = getKeyedArrayEntryValue(entry, key);
|
|
278
|
+
return identity === void 0 || replacements.has(identity);
|
|
279
|
+
})];
|
|
280
|
+
}
|
|
260
281
|
function mergeProviderOutputConfig(existing, value, ownership = {}) {
|
|
261
282
|
assertProviderJsonRecord(existing);
|
|
262
283
|
assertProviderJsonRecord(value);
|
|
263
|
-
|
|
284
|
+
const next = {
|
|
264
285
|
...deleteOwnedFields(existing, ownership),
|
|
265
286
|
...mergeOwnedArrays(existing, value, ownership.arrays)
|
|
266
287
|
};
|
|
288
|
+
for (const [field, childOwnership] of Object.entries(ownership.objects ?? {})) {
|
|
289
|
+
const current = existing[field];
|
|
290
|
+
const incoming = value[field];
|
|
291
|
+
const merged = mergeProviderOutputConfig(isProviderJsonRecord(current) ? current : {}, isProviderJsonRecord(incoming) ? incoming : {}, childOwnership);
|
|
292
|
+
if (Object.keys(merged).length) next[field] = merged;
|
|
293
|
+
else delete next[field];
|
|
294
|
+
}
|
|
295
|
+
return next;
|
|
296
|
+
}
|
|
297
|
+
// ../internal/src/build/wrangler-bindings.ts
|
|
298
|
+
/**
|
|
299
|
+
* Named-entry arrays that ViteHub writes, other than `d1_databases`, which the Database package collapses with its
|
|
300
|
+
* own rules and error.
|
|
301
|
+
*/
|
|
302
|
+
const wranglerEntrySpecs = [
|
|
303
|
+
{
|
|
304
|
+
path: ["kv_namespaces"],
|
|
305
|
+
identity: "binding",
|
|
306
|
+
resource: ["id", "preview_id"],
|
|
307
|
+
ids: ["id", "preview_id"],
|
|
308
|
+
preservePlaceholderIds: ["preview_id"]
|
|
309
|
+
},
|
|
310
|
+
{
|
|
311
|
+
path: ["r2_buckets"],
|
|
312
|
+
identity: "binding",
|
|
313
|
+
resource: [
|
|
314
|
+
"bucket_name",
|
|
315
|
+
"jurisdiction",
|
|
316
|
+
"preview_bucket_name"
|
|
317
|
+
]
|
|
318
|
+
},
|
|
319
|
+
{
|
|
320
|
+
path: ["ratelimits"],
|
|
321
|
+
identity: "name",
|
|
322
|
+
resource: ["namespace_id", "simple"]
|
|
323
|
+
},
|
|
324
|
+
{
|
|
325
|
+
path: ["hyperdrive"],
|
|
326
|
+
identity: "binding",
|
|
327
|
+
resource: ["id"],
|
|
328
|
+
ids: ["id"],
|
|
329
|
+
preservePlaceholderIds: true
|
|
330
|
+
},
|
|
331
|
+
{
|
|
332
|
+
path: ["containers"],
|
|
333
|
+
identity: ["class_name", "name"],
|
|
334
|
+
resource: [
|
|
335
|
+
"scheduling_policy",
|
|
336
|
+
"image",
|
|
337
|
+
"images",
|
|
338
|
+
"image_build_context",
|
|
339
|
+
"image_vars",
|
|
340
|
+
"class_name",
|
|
341
|
+
"name",
|
|
342
|
+
"instance_type",
|
|
343
|
+
"max_instances"
|
|
344
|
+
],
|
|
345
|
+
defaults: { scheduling_policy: "default" },
|
|
346
|
+
exclusive: [["image", "images"]]
|
|
347
|
+
},
|
|
348
|
+
{
|
|
349
|
+
path: ["durable_objects", "bindings"],
|
|
350
|
+
identity: "name",
|
|
351
|
+
resource: [
|
|
352
|
+
"class_name",
|
|
353
|
+
"script_name",
|
|
354
|
+
"environment"
|
|
355
|
+
]
|
|
356
|
+
},
|
|
357
|
+
{
|
|
358
|
+
path: ["migrations"],
|
|
359
|
+
identity: "tag",
|
|
360
|
+
resource: [
|
|
361
|
+
"new_classes",
|
|
362
|
+
"new_sqlite_classes",
|
|
363
|
+
"renamed_classes",
|
|
364
|
+
"deleted_classes",
|
|
365
|
+
"transferred_classes"
|
|
366
|
+
]
|
|
367
|
+
},
|
|
368
|
+
{
|
|
369
|
+
path: ["queues", "producers"],
|
|
370
|
+
identity: "binding",
|
|
371
|
+
resource: ["queue"]
|
|
372
|
+
},
|
|
373
|
+
{
|
|
374
|
+
path: ["queues", "consumers"],
|
|
375
|
+
identity: "queue",
|
|
376
|
+
resource: ["max_retries"]
|
|
377
|
+
},
|
|
378
|
+
{
|
|
379
|
+
path: ["workflows"],
|
|
380
|
+
identity: "binding",
|
|
381
|
+
resource: [
|
|
382
|
+
"name",
|
|
383
|
+
"class_name",
|
|
384
|
+
"script_name",
|
|
385
|
+
"jurisdiction"
|
|
386
|
+
],
|
|
387
|
+
exclusive: [["script_name", "jurisdiction"]]
|
|
388
|
+
},
|
|
389
|
+
{
|
|
390
|
+
path: ["services"],
|
|
391
|
+
identity: "binding",
|
|
392
|
+
resource: [
|
|
393
|
+
"service",
|
|
394
|
+
"entrypoint",
|
|
395
|
+
"environment"
|
|
396
|
+
]
|
|
397
|
+
},
|
|
398
|
+
{
|
|
399
|
+
path: ["send_email"],
|
|
400
|
+
identity: "name",
|
|
401
|
+
resource: [
|
|
402
|
+
"destination_address",
|
|
403
|
+
"allowed_destination_addresses",
|
|
404
|
+
"allowed_sender_addresses"
|
|
405
|
+
],
|
|
406
|
+
exclusive: [["destination_address", "allowed_destination_addresses"]]
|
|
407
|
+
},
|
|
408
|
+
{
|
|
409
|
+
path: ["analytics_engine_datasets"],
|
|
410
|
+
identity: "binding",
|
|
411
|
+
resource: ["dataset"]
|
|
412
|
+
}
|
|
413
|
+
];
|
|
414
|
+
const placeholderId = /^(?:0+|0{8}-0{4}-[0-8]000-[089ab]000-0{12})$/;
|
|
415
|
+
/**
|
|
416
|
+
* Whether `value` is an all-zero id, such as `00000000000000000000000000000000` or
|
|
417
|
+
* `00000000-0000-4000-8000-000000000000`. Templates such as a Deploy to Cloudflare repository put one where Cloudflare
|
|
418
|
+
* writes the real id. It never names a resource.
|
|
419
|
+
*/
|
|
420
|
+
function isPlaceholderCloudflareId(value) {
|
|
421
|
+
return typeof value === "string" && placeholderId.test(value);
|
|
422
|
+
}
|
|
423
|
+
function defaultConflict({ field, generated, name, path, project, scope }) {
|
|
424
|
+
return internalErrorDiagnostics.INTERNAL_B0051({
|
|
425
|
+
field,
|
|
426
|
+
generated: JSON.stringify(generated),
|
|
427
|
+
name,
|
|
428
|
+
path,
|
|
429
|
+
project: JSON.stringify(project),
|
|
430
|
+
scope
|
|
431
|
+
});
|
|
432
|
+
}
|
|
433
|
+
function collapseEntries(entries, spec, scope, conflict) {
|
|
434
|
+
const collapsed = [];
|
|
435
|
+
const byName = /* @__PURE__ */ new Map();
|
|
436
|
+
const identities = typeof spec.identity === "string" ? [spec.identity] : spec.identity;
|
|
437
|
+
const aliases = /* @__PURE__ */ new Map();
|
|
438
|
+
function canonical(key) {
|
|
439
|
+
const parent = aliases.get(key);
|
|
440
|
+
if (parent === void 0) return key;
|
|
441
|
+
const root = canonical(parent);
|
|
442
|
+
aliases.set(key, root);
|
|
443
|
+
return root;
|
|
444
|
+
}
|
|
445
|
+
if (identities.length > 1) for (const entry of entries) {
|
|
446
|
+
if (!isRecord(entry)) continue;
|
|
447
|
+
const keys = identities.filter((field) => typeof entry[field] === "string").map((field) => `${field}:${entry[field]}`);
|
|
448
|
+
for (const key of keys.slice(1)) {
|
|
449
|
+
const root = canonical(keys[0]);
|
|
450
|
+
const alias = canonical(key);
|
|
451
|
+
if (root !== alias) aliases.set(alias, root);
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
for (const entry of entries) {
|
|
455
|
+
const identity = isRecord(entry) ? identities.find((field) => typeof entry[field] === "string") : void 0;
|
|
456
|
+
if (!isRecord(entry) || identity === void 0) {
|
|
457
|
+
collapsed.push(entry);
|
|
458
|
+
continue;
|
|
459
|
+
}
|
|
460
|
+
const name = entry[identity];
|
|
461
|
+
const key = canonical(`${identity}:${name}`);
|
|
462
|
+
const first = byName.get(key);
|
|
463
|
+
if (!first) {
|
|
464
|
+
const copy = { ...entry };
|
|
465
|
+
byName.set(key, copy);
|
|
466
|
+
collapsed.push(copy);
|
|
467
|
+
continue;
|
|
468
|
+
}
|
|
469
|
+
for (const field of spec.resource) {
|
|
470
|
+
const generated = first[field] === void 0 ? spec.defaults?.[field] : first[field];
|
|
471
|
+
const project = entry[field] === void 0 ? spec.defaults?.[field] : entry[field];
|
|
472
|
+
if (generated === void 0 || project === void 0 || isDeepStrictEqual(generated, project)) continue;
|
|
473
|
+
const isId = spec.ids?.includes(field) === true;
|
|
474
|
+
if (isId && isPlaceholderCloudflareId(project)) continue;
|
|
475
|
+
if (isId && isPlaceholderCloudflareId(generated)) {
|
|
476
|
+
first[field] = project;
|
|
477
|
+
continue;
|
|
478
|
+
}
|
|
479
|
+
throw conflict({
|
|
480
|
+
field,
|
|
481
|
+
generated,
|
|
482
|
+
name,
|
|
483
|
+
path: spec.path.join("."),
|
|
484
|
+
project,
|
|
485
|
+
scope
|
|
486
|
+
});
|
|
487
|
+
}
|
|
488
|
+
for (const group of spec.exclusive ?? []) {
|
|
489
|
+
const generatedField = group.find((field) => first[field] !== void 0);
|
|
490
|
+
const projectField = group.find((field) => entry[field] !== void 0);
|
|
491
|
+
if (generatedField && projectField && generatedField !== projectField) throw conflict({
|
|
492
|
+
field: group.join(" / "),
|
|
493
|
+
generated: { [generatedField]: first[generatedField] },
|
|
494
|
+
name,
|
|
495
|
+
path: spec.path.join("."),
|
|
496
|
+
project: { [projectField]: entry[projectField] },
|
|
497
|
+
scope
|
|
498
|
+
});
|
|
499
|
+
}
|
|
500
|
+
const kept = new Set((spec.groups ?? []).filter((group) => group.some((field) => first[field] !== void 0)).flat());
|
|
501
|
+
for (const [key, value] of Object.entries(entry)) if (!kept.has(key) && first[key] === void 0) first[key] = value;
|
|
502
|
+
}
|
|
503
|
+
const preservedIds = spec.preservePlaceholderIds === true ? spec.ids : spec.preservePlaceholderIds || [];
|
|
504
|
+
for (const entry of byName.values()) for (const field of spec.ids ?? []) if (!preservedIds?.includes(field) && isPlaceholderCloudflareId(entry[field])) delete entry[field];
|
|
505
|
+
return collapsed;
|
|
506
|
+
}
|
|
507
|
+
function unique(values) {
|
|
508
|
+
return Array.isArray(values) ? [...new Set(values)] : values;
|
|
509
|
+
}
|
|
510
|
+
function collapseTarget(target, specs, scope, conflict) {
|
|
511
|
+
const result = { ...target };
|
|
512
|
+
for (const spec of specs) {
|
|
513
|
+
const parents = spec.path.slice(0, -1);
|
|
514
|
+
const key = spec.path.at(-1);
|
|
515
|
+
let parent = result;
|
|
516
|
+
let found = true;
|
|
517
|
+
for (const segment of parents) {
|
|
518
|
+
const next = parent[segment];
|
|
519
|
+
if (!isRecord(next)) {
|
|
520
|
+
found = false;
|
|
521
|
+
break;
|
|
522
|
+
}
|
|
523
|
+
parent = parent[segment] = { ...next };
|
|
524
|
+
}
|
|
525
|
+
if (found && Array.isArray(parent[key])) parent[key] = collapseEntries(parent[key], spec, scope, conflict);
|
|
526
|
+
}
|
|
527
|
+
if (Array.isArray(result.compatibility_flags)) result.compatibility_flags = unique(result.compatibility_flags);
|
|
528
|
+
if (isRecord(result.secrets) && Array.isArray(result.secrets.required)) result.secrets = {
|
|
529
|
+
...result.secrets,
|
|
530
|
+
required: unique(result.secrets.required)
|
|
531
|
+
};
|
|
532
|
+
return result;
|
|
533
|
+
}
|
|
534
|
+
/**
|
|
535
|
+
* The Wrangler config with one entry per name in each array of `specs`, and without repeated compatibility flags or
|
|
536
|
+
* required secrets, at the top level and in each `env`.
|
|
537
|
+
*/
|
|
538
|
+
function collapseWranglerConfig(wrangler, options = {}) {
|
|
539
|
+
const specs = options.specs ?? wranglerEntrySpecs;
|
|
540
|
+
const conflict = options.conflict ?? defaultConflict;
|
|
541
|
+
const result = collapseTarget(wrangler, specs, "", conflict);
|
|
542
|
+
if (isRecord(wrangler.env)) result.env = Object.fromEntries(Object.entries(wrangler.env).map(([name, config]) => [name, isRecord(config) ? collapseTarget(config, specs, ` in env.${name}`, conflict) : config]));
|
|
543
|
+
return result;
|
|
544
|
+
}
|
|
545
|
+
/**
|
|
546
|
+
* Collapses the `wrangler.json` in `serverDir` that Nitro's Cloudflare preset wrote. Run it in a `compiled` hook. It
|
|
547
|
+
* does nothing when the file is missing, and writes only when something changed.
|
|
548
|
+
*/
|
|
549
|
+
async function collapseWranglerConfigFile(serverDir, options = {}) {
|
|
550
|
+
const file = resolve(serverDir, "wrangler.json");
|
|
551
|
+
const text = await readFile(file, "utf8").catch((error) => {
|
|
552
|
+
if (error.code === "ENOENT") return void 0;
|
|
553
|
+
throw error;
|
|
554
|
+
});
|
|
555
|
+
if (text === void 0) return;
|
|
556
|
+
const wrangler = JSON.parse(text);
|
|
557
|
+
if (!isRecord(wrangler)) return;
|
|
558
|
+
options.validate?.(wrangler);
|
|
559
|
+
const collapsed = collapseWranglerConfig(wrangler, options);
|
|
560
|
+
if (!isDeepStrictEqual(collapsed, wrangler)) await writeFile(file, `${JSON.stringify(collapsed, null, 2)}\n`);
|
|
267
561
|
}
|
|
268
562
|
// ../internal/src/build/bundle-options.ts
|
|
269
563
|
/** Select the runtime constants from one resolved Vite configuration. */
|
|
@@ -280,16 +574,16 @@ function resolveViteHubBundleDefines(config) {
|
|
|
280
574
|
return defines;
|
|
281
575
|
}
|
|
282
576
|
// ../internal/src/build/cloudflare-provider-output.ts
|
|
283
|
-
function isDeepStrictEqual(left, right) {
|
|
577
|
+
function isDeepStrictEqual$1(left, right) {
|
|
284
578
|
if (Object.is(left, right)) return true;
|
|
285
579
|
if (!left || !right || typeof left !== "object" || typeof right !== "object") return false;
|
|
286
580
|
if (Array.isArray(left) !== Array.isArray(right)) return false;
|
|
287
|
-
if (Array.isArray(left)) return left.length === right.length && left.every((value, index) => isDeepStrictEqual(value, right[index]));
|
|
581
|
+
if (Array.isArray(left)) return left.length === right.length && left.every((value, index) => isDeepStrictEqual$1(value, right[index]));
|
|
288
582
|
const leftRecord = left;
|
|
289
583
|
const rightRecord = right;
|
|
290
584
|
const leftKeys = Object.keys(leftRecord);
|
|
291
585
|
const rightKeys = Object.keys(rightRecord);
|
|
292
|
-
return leftKeys.length === rightKeys.length && leftKeys.every((key) => Object.hasOwn(rightRecord, key) && isDeepStrictEqual(leftRecord[key], rightRecord[key]));
|
|
586
|
+
return leftKeys.length === rightKeys.length && leftKeys.every((key) => Object.hasOwn(rightRecord, key) && isDeepStrictEqual$1(leftRecord[key], rightRecord[key]));
|
|
293
587
|
}
|
|
294
588
|
const providerOutputCatalogRegistry$1 = globalThis;
|
|
295
589
|
const providerOutputCatalogByNitroValue = providerOutputCatalogRegistry$1.__vitehubProviderOutputCatalogsByNitroValue ??= /* @__PURE__ */ new WeakMap();
|
|
@@ -302,10 +596,6 @@ function cloneProviderValue(value) {
|
|
|
302
596
|
if (value && typeof value === "object") return cloneProviderRecord(value);
|
|
303
597
|
return value;
|
|
304
598
|
}
|
|
305
|
-
/**
|
|
306
|
-
* The incoming entries that the app config does not have yet. An entry that the app already has must agree on
|
|
307
|
-
* `conflictKeys`, and on each of `setKeys` that the incoming entry sets, because the app's entry is the one that stays.
|
|
308
|
-
*/
|
|
309
599
|
function compatibleEntries(existing, incoming, identityKey, conflictKeys, owner, setKeys = []) {
|
|
310
600
|
const current = Array.isArray(existing) ? existing.map(cloneProviderRecord) : [];
|
|
311
601
|
return (incoming ?? []).filter((entry) => {
|
|
@@ -315,15 +605,33 @@ function compatibleEntries(existing, incoming, identityKey, conflictKeys, owner,
|
|
|
315
605
|
current.push(entry);
|
|
316
606
|
return true;
|
|
317
607
|
}
|
|
318
|
-
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.` });
|
|
319
|
-
const differentKey = setKeys.find((key) => entry[key] !== void 0 && !isDeepStrictEqual(match[key], entry[key]));
|
|
608
|
+
if (conflictKeys.some((key) => !isDeepStrictEqual$1(match[key], entry[key]))) throw internalErrorDiagnostics.INTERNAL_B0001({ message: `[vitehub] Cloudflare ${identityKey} ${JSON.stringify(identity)} from ${owner} is already assigned to an incompatible resource.` });
|
|
609
|
+
const differentKey = setKeys.find((key) => entry[key] !== void 0 && !isDeepStrictEqual$1(match[key], entry[key]));
|
|
320
610
|
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.` });
|
|
321
611
|
return false;
|
|
322
612
|
});
|
|
323
613
|
}
|
|
614
|
+
async function finalizeCloudflareQueueConsumers(serverDir, consumers) {
|
|
615
|
+
const expected = new Map(consumers.filter((consumer) => consumer.max_retries !== void 0).map((consumer) => [consumer.queue, consumer]));
|
|
616
|
+
await collapseWranglerConfigFile(serverDir, {
|
|
617
|
+
specs: wranglerEntrySpecs.filter((spec) => spec.path[0] === "queues" && spec.path[1] === "consumers"),
|
|
618
|
+
validate(wrangler) {
|
|
619
|
+
const environments = cloneRecord(wrangler.env);
|
|
620
|
+
for (const config of [wrangler, ...Object.values(environments).map(cloneRecord)]) {
|
|
621
|
+
const queues = cloneRecord(config.queues);
|
|
622
|
+
if (!Array.isArray(queues.consumers)) continue;
|
|
623
|
+
for (const entry of queues.consumers) {
|
|
624
|
+
const consumer = cloneRecord(entry);
|
|
625
|
+
const definition = typeof consumer.queue === "string" ? expected.get(consumer.queue) : void 0;
|
|
626
|
+
if (definition) compatibleEntries([consumer], [definition], "queue", [], "queue", ["max_retries"]);
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
});
|
|
631
|
+
}
|
|
324
632
|
function removeEntries(existing, entries) {
|
|
325
633
|
if (!Array.isArray(existing) || !entries?.length) return Array.isArray(existing) ? existing : [];
|
|
326
|
-
return existing.filter((entry) => !entries.some((previous) => isDeepStrictEqual(entry, previous)));
|
|
634
|
+
return existing.filter((entry) => !entries.some((previous) => isDeepStrictEqual$1(entry, previous)));
|
|
327
635
|
}
|
|
328
636
|
function removeContribution(wrangler, contribution) {
|
|
329
637
|
const queues = cloneProviderRecord(wrangler.queues);
|
|
@@ -374,7 +682,7 @@ function mergeContribution(wrangler, owner, contribution) {
|
|
|
374
682
|
const queues = cloneProviderRecord(wrangler.queues);
|
|
375
683
|
const secrets = cloneProviderRecord(wrangler.secrets);
|
|
376
684
|
const environments = cloneProviderRecord(wrangler.env);
|
|
377
|
-
const consumers = compatibleEntries(queues.consumers, contribution.queues?.consumers, "queue", [], owner, ["max_batch_size"]);
|
|
685
|
+
const consumers = compatibleEntries(queues.consumers, contribution.queues?.consumers, "queue", [], owner, ["max_batch_size", "max_retries"]);
|
|
378
686
|
const producers = compatibleEntries(queues.producers, contribution.queues?.producers, "binding", ["queue"], owner);
|
|
379
687
|
const r2Buckets = compatibleEntries(wrangler.r2_buckets, contribution.r2Buckets, "binding", ["bucket_name", "jurisdiction"], owner);
|
|
380
688
|
const rateLimits = compatibleEntries(wrangler.ratelimits, contribution.rateLimits, "name", ["namespace_id", "simple"], owner);
|
|
@@ -537,17 +845,17 @@ var ProviderOutputCatalog = class {
|
|
|
537
845
|
}
|
|
538
846
|
this.#restoreDeploymentContribution(entry);
|
|
539
847
|
}
|
|
540
|
-
resetDeploymentContributions(generation) {
|
|
848
|
+
resetDeploymentContributions(generation, failure) {
|
|
541
849
|
if (!generation) {
|
|
542
850
|
for (const reference of this.#deploymentGenerations) {
|
|
543
851
|
const current = reference.deref();
|
|
544
852
|
if (current) current.valid = false;
|
|
545
853
|
}
|
|
546
854
|
this.#deploymentGenerations.clear();
|
|
547
|
-
for (const entries of this.#deploymentContributions.values()) for (const entry of entries) this.#queueDeploymentDiscard(entry);
|
|
855
|
+
for (const entries of this.#deploymentContributions.values()) for (const entry of entries) this.#queueDeploymentDiscard(entry, failure);
|
|
548
856
|
for (const taken of this.#takenDeploymentContributions.values()) {
|
|
549
|
-
if (!taken.entryDiscarded) this.#queueDeploymentDiscard(taken.entry);
|
|
550
|
-
for (const fallback of taken.fallbacks) this.#queueDeploymentDiscard(fallback);
|
|
857
|
+
if (!taken.entryDiscarded) this.#queueDeploymentDiscard(taken.entry, failure);
|
|
858
|
+
for (const fallback of taken.fallbacks) this.#queueDeploymentDiscard(fallback, failure);
|
|
551
859
|
}
|
|
552
860
|
this.#deploymentContributions.clear();
|
|
553
861
|
this.#takenDeploymentContributions.clear();
|
|
@@ -556,7 +864,7 @@ var ProviderOutputCatalog = class {
|
|
|
556
864
|
generation.valid = false;
|
|
557
865
|
this.#deleteDeploymentGeneration(generation);
|
|
558
866
|
for (const [owner, entries] of this.#deploymentContributions) {
|
|
559
|
-
for (const entry of entries) if (entry.generation === generation) this.#queueDeploymentDiscard(entry);
|
|
867
|
+
for (const entry of entries) if (entry.generation === generation) this.#queueDeploymentDiscard(entry, failure);
|
|
560
868
|
const remaining = entries.filter((entry) => entry.generation !== generation);
|
|
561
869
|
if (remaining.length) this.#deploymentContributions.set(owner, remaining);
|
|
562
870
|
else this.#deploymentContributions.delete(owner);
|
|
@@ -564,10 +872,10 @@ var ProviderOutputCatalog = class {
|
|
|
564
872
|
for (const [contribution, taken] of this.#takenDeploymentContributions) {
|
|
565
873
|
const invalidatedFallbacks = taken.fallbacks.filter((entry) => entry.generation === generation);
|
|
566
874
|
taken.fallbacks = taken.fallbacks.filter((entry) => entry.generation !== generation);
|
|
567
|
-
for (const fallback of invalidatedFallbacks) this.#queueDeploymentDiscard(fallback);
|
|
875
|
+
for (const fallback of invalidatedFallbacks) this.#queueDeploymentDiscard(fallback, failure);
|
|
568
876
|
if (taken.entry.generation !== generation) continue;
|
|
569
877
|
this.#takenDeploymentContributions.delete(contribution);
|
|
570
|
-
if (!taken.entryDiscarded) this.#queueDeploymentDiscard(taken.entry);
|
|
878
|
+
if (!taken.entryDiscarded) this.#queueDeploymentDiscard(taken.entry, failure);
|
|
571
879
|
for (const fallback of taken.fallbacks) if (taken.committed) this.#queueDeploymentDiscard(fallback);
|
|
572
880
|
else this.#restoreDeploymentContribution(fallback);
|
|
573
881
|
}
|
|
@@ -610,7 +918,7 @@ var ProviderOutputCatalog = class {
|
|
|
610
918
|
const failure = (await Promise.allSettled(discarded)).find((result) => result.status === "rejected");
|
|
611
919
|
if (failure) throw failure.reason;
|
|
612
920
|
}
|
|
613
|
-
async completeDeploymentContributions(contributions) {
|
|
921
|
+
async completeDeploymentContributions(contributions, buildFailure) {
|
|
614
922
|
const discarded = this.#pendingDeploymentDiscards.splice(0);
|
|
615
923
|
const completedGenerations = /* @__PURE__ */ new Set();
|
|
616
924
|
for (const contribution of contributions) {
|
|
@@ -620,7 +928,7 @@ var ProviderOutputCatalog = class {
|
|
|
620
928
|
const entries = taken.entryDiscarded ? taken.fallbacks : [...taken.fallbacks, taken.entry];
|
|
621
929
|
for (const entry of entries) {
|
|
622
930
|
if (entry.generation) completedGenerations.add(entry.generation);
|
|
623
|
-
if (entry.contribution.discard) discarded.push(entry.contribution.discard());
|
|
931
|
+
if (entry.contribution.discard) discarded.push(entry.contribution.discard(entry === taken.entry ? buildFailure : void 0));
|
|
624
932
|
}
|
|
625
933
|
}
|
|
626
934
|
for (const generation of completedGenerations) this.#retireDeploymentGeneration(generation);
|
|
@@ -664,9 +972,9 @@ var ProviderOutputCatalog = class {
|
|
|
664
972
|
if (reference) this.#deploymentGenerations.delete(reference);
|
|
665
973
|
this.#deploymentGenerationRefs.delete(generation);
|
|
666
974
|
}
|
|
667
|
-
#queueDeploymentDiscard(entry) {
|
|
975
|
+
#queueDeploymentDiscard(entry, failure) {
|
|
668
976
|
if (!entry.contribution.discard) return;
|
|
669
|
-
const discard = Promise.resolve().then(entry.contribution.discard);
|
|
977
|
+
const discard = Promise.resolve().then(async () => await entry.contribution.discard?.(failure));
|
|
670
978
|
discard.catch(() => {});
|
|
671
979
|
this.#pendingDeploymentDiscards.push(discard);
|
|
672
980
|
}
|
|
@@ -690,7 +998,12 @@ function contributeCloudflareProviderOutput(catalog, contribution) {
|
|
|
690
998
|
const { owner, ...value } = contribution;
|
|
691
999
|
catalog.replaceCloudflareContribution(owner, value);
|
|
692
1000
|
}
|
|
693
|
-
|
|
1001
|
+
// ../internal/src/nitro-kit.ts
|
|
1002
|
+
/**
|
|
1003
|
+
* The route meta of a ViteHub handler that Auth access routes leave alone, such as the Console RPC. The handler takes
|
|
1004
|
+
* only its own signed requests and signed Site access tokens, so app access rules do not apply to it.
|
|
1005
|
+
*/
|
|
1006
|
+
const ownAccessHandlerMeta = Object.freeze({ vitehubAuthAccess: "handler" });
|
|
694
1007
|
Object.freeze({ vitehubOwnAccess: true });
|
|
695
1008
|
function cloneArray(value) {
|
|
696
1009
|
return Array.isArray(value) ? [...value] : [];
|
|
@@ -863,8 +1176,8 @@ async function collectQueueContributions(plugins, context) {
|
|
|
863
1176
|
const owners = ["queue"];
|
|
864
1177
|
/**
|
|
865
1178
|
* The variables that Queue reads on the deployed host. The `postgres` provider reads `QUEUE_POSTGRES_URL`, which is
|
|
866
|
-
* required unless the build found a Postgres Default Database to borrow
|
|
867
|
-
* `QUEUE_REGION`. Cloudflare Queues and the `local` provider read none.
|
|
1179
|
+
* required unless the build found a Postgres Default Database to borrow, and the optional `QUEUE_WORKERS`. The `vercel`
|
|
1180
|
+
* provider reads the optional `QUEUE_REGION`. Cloudflare Queues and the `local` provider read none.
|
|
868
1181
|
*/
|
|
869
1182
|
function queueDeploymentEnv(queue) {
|
|
870
1183
|
if (!queue) return [];
|
|
@@ -874,6 +1187,12 @@ function queueDeploymentEnv(queue) {
|
|
|
874
1187
|
secret: true,
|
|
875
1188
|
hasDefault: Boolean(queue.database),
|
|
876
1189
|
owners
|
|
1190
|
+
}, {
|
|
1191
|
+
names: [queueWorkersVariable],
|
|
1192
|
+
required: false,
|
|
1193
|
+
secret: false,
|
|
1194
|
+
hasDefault: true,
|
|
1195
|
+
owners
|
|
877
1196
|
}];
|
|
878
1197
|
if (queue.driver === "vercel") return [{
|
|
879
1198
|
names: ["QUEUE_REGION"],
|
|
@@ -1034,6 +1353,12 @@ function createRuntimeRegistryContents(registryFile, definitions) {
|
|
|
1034
1353
|
""
|
|
1035
1354
|
].join("\n");
|
|
1036
1355
|
}
|
|
1356
|
+
/** `writeFileIfChangedSync` for async callers. */
|
|
1357
|
+
async function writeFileIfChanged(file, contents) {
|
|
1358
|
+
if (await readFile(file, "utf8").catch(() => void 0) === contents) return;
|
|
1359
|
+
await mkdir(resolve$1(file, ".."), { recursive: true });
|
|
1360
|
+
await writeFile(file, contents, "utf8");
|
|
1361
|
+
}
|
|
1037
1362
|
// src/discovery.ts
|
|
1038
1363
|
const queueSuffixPattern = /\.queue\.(?:c|m)?[jt]s$/i;
|
|
1039
1364
|
/** Discovery source of Queue Definitions that Vite plugins contribute through `vitehub.queues`. */
|
|
@@ -1083,8 +1408,7 @@ function createQueueTypes(file, definitions, importBase = "@vite-hub/queue") {
|
|
|
1083
1408
|
}
|
|
1084
1409
|
async function writeQueueTypes(root, definitions, importBase = "@vite-hub/queue") {
|
|
1085
1410
|
const file = resolve$1(root, ".vitehub/queue.d.ts");
|
|
1086
|
-
await
|
|
1087
|
-
await writeFile(file, createQueueTypes(file, definitions, importBase), "utf8");
|
|
1411
|
+
await writeFileIfChanged(file, createQueueTypes(file, definitions, importBase));
|
|
1088
1412
|
}
|
|
1089
1413
|
// src/internal/vite-build.ts
|
|
1090
1414
|
const queuePackageName = "@vite-hub/queue";
|
|
@@ -1094,6 +1418,7 @@ const generatedQueueTestSetup = ".vitehub/queue/test-setup.mjs";
|
|
|
1094
1418
|
const generatedQueueNitroPlugin = ".vitehub/nitro/queue/plugin.ts";
|
|
1095
1419
|
const generatedQueueNitroMiddleware = ".vitehub/nitro/queue/middleware.ts";
|
|
1096
1420
|
const generatedQueueNitroVercelConsumerDir = ".vitehub/nitro/queue/vercel";
|
|
1421
|
+
const vercelQueueFunctionEnv = "VITEHUB_VERCEL_QUEUE_FUNCTION";
|
|
1097
1422
|
const vercelQueueConsumerRoutePrefix = "/api/vitehub/queues/vercel";
|
|
1098
1423
|
const packageDir = computePackageDir(import.meta.url);
|
|
1099
1424
|
const packageRequire = createRequire(resolve(packageDir, "package.json"));
|
|
@@ -1140,29 +1465,60 @@ function createCloudflareQueueDefinitionNames(definitions, namePrefix = "") {
|
|
|
1140
1465
|
}
|
|
1141
1466
|
return Object.fromEntries([...names].map(([physicalName, definition]) => [physicalName, definition.name]));
|
|
1142
1467
|
}
|
|
1468
|
+
function readLiteral(properties, key, valid, exported, invalid) {
|
|
1469
|
+
const property = properties.findLast((candidate) => candidate.key === key);
|
|
1470
|
+
if (!property) return void 0;
|
|
1471
|
+
if (!exported || property.node.type !== "Property" || property.node.kind !== "init" || property.node.method || property.value?.type !== "Literal" || !valid(property.value.value)) return invalid();
|
|
1472
|
+
return property.value.value;
|
|
1473
|
+
}
|
|
1474
|
+
function isQueueRetriesLimit(value) {
|
|
1475
|
+
return typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 100;
|
|
1476
|
+
}
|
|
1143
1477
|
/**
|
|
1144
|
-
* Reads `maxBatchSize`
|
|
1145
|
-
* so the build fails when it cannot prove
|
|
1146
|
-
* number literal, or the option on a `defineQueue()` call that is not the default export.
|
|
1478
|
+
* Reads `maxBatchSize` and `retries.limit` from a default-exported Queue Definition. The Cloudflare consumer is
|
|
1479
|
+
* configured at build time, so the build fails when it cannot prove a value: a spread or computed key in those options,
|
|
1480
|
+
* a value that is not a number literal, or the option on a `defineQueue()` call that is not the default export.
|
|
1147
1481
|
*/
|
|
1148
|
-
function
|
|
1482
|
+
function readQueueConsumerOptions(file, { argumentExpression, defaultExportExpression, findCalls, objectProperties, scanModule }) {
|
|
1149
1483
|
const module = scanModule(readFileSync(file, "utf8"), file);
|
|
1150
|
-
const
|
|
1484
|
+
const invalidBatchSize = () => {
|
|
1151
1485
|
throw queueErrorDiagnostics.QUEUE_MAX_BATCH_SIZE_INVALID({ where: file });
|
|
1152
1486
|
};
|
|
1487
|
+
const invalidRetries = () => {
|
|
1488
|
+
throw queueErrorDiagnostics.QUEUE_RETRIES_LIMIT_INVALID({ where: file });
|
|
1489
|
+
};
|
|
1153
1490
|
const exported = defaultExportExpression(module);
|
|
1154
|
-
|
|
1155
|
-
for (const
|
|
1156
|
-
|
|
1157
|
-
if (
|
|
1491
|
+
const names = /* @__PURE__ */ new Set(["defineQueue"]);
|
|
1492
|
+
for (const statement of module.program.body) {
|
|
1493
|
+
if (statement.type !== "ImportDeclaration") continue;
|
|
1494
|
+
for (const specifier of statement.specifiers) if (specifier.type === "ImportSpecifier" && specifier.imported.type === "Identifier" && specifier.imported.name === "defineQueue") names.add(specifier.local.name);
|
|
1495
|
+
}
|
|
1496
|
+
const consumer = {};
|
|
1497
|
+
const definitions = findCalls(module, names).map((call) => ({
|
|
1498
|
+
options: argumentExpression(call.arguments[0]),
|
|
1499
|
+
exported: call === exported
|
|
1500
|
+
}));
|
|
1501
|
+
if (exported?.type === "ObjectExpression") definitions.push({
|
|
1502
|
+
options: exported,
|
|
1503
|
+
exported: true
|
|
1504
|
+
});
|
|
1505
|
+
for (const definition of definitions) {
|
|
1506
|
+
const { options } = definition;
|
|
1507
|
+
if (options?.type !== "ObjectExpression") return invalidBatchSize();
|
|
1158
1508
|
const properties = objectProperties(options);
|
|
1159
|
-
if (properties.some((property) => property.key === void 0 || property.computed)) return
|
|
1160
|
-
const
|
|
1161
|
-
if (
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1509
|
+
if (properties.some((property) => property.key === void 0 || property.computed)) return invalidBatchSize();
|
|
1510
|
+
const maxBatchSize = readLiteral(properties, "maxBatchSize", isQueueMaxBatchSize, definition.exported, invalidBatchSize);
|
|
1511
|
+
if (maxBatchSize !== void 0) consumer.max_batch_size = maxBatchSize;
|
|
1512
|
+
const retries = properties.findLast((candidate) => candidate.key === "retries");
|
|
1513
|
+
if (!retries) continue;
|
|
1514
|
+
if (retries.node.type !== "Property" || retries.node.kind !== "init" || retries.node.method || retries.value?.type !== "ObjectExpression") return invalidRetries();
|
|
1515
|
+
const retryProperties = objectProperties(retries.value);
|
|
1516
|
+
if (retryProperties.some((property) => property.key === void 0 || property.computed)) return invalidRetries();
|
|
1517
|
+
const limit = readLiteral(retryProperties, "limit", isQueueRetriesLimit, definition.exported, invalidRetries);
|
|
1518
|
+
if (limit !== void 0) consumer.max_retries = limit;
|
|
1519
|
+
}
|
|
1520
|
+
if (!definitions.some((definition) => definition.exported)) return invalidRetries();
|
|
1521
|
+
return consumer;
|
|
1166
1522
|
}
|
|
1167
1523
|
async function createCloudflareQueueBindings(definitions, namePrefix = "") {
|
|
1168
1524
|
if (!definitions.length) return;
|
|
@@ -1170,9 +1526,8 @@ async function createCloudflareQueueBindings(definitions, namePrefix = "") {
|
|
|
1170
1526
|
const scanner = await import("./scan-module-BaqBao0J.js");
|
|
1171
1527
|
return {
|
|
1172
1528
|
consumers: definitions.map((definition) => {
|
|
1173
|
-
const maxBatchSize = readQueueMaxBatchSize(definition.handler, scanner);
|
|
1174
1529
|
return {
|
|
1175
|
-
...
|
|
1530
|
+
...readQueueConsumerOptions(definition.handler, scanner),
|
|
1176
1531
|
queue: getCloudflareQueueName(definition.name, namePrefix)
|
|
1177
1532
|
};
|
|
1178
1533
|
}),
|
|
@@ -1198,7 +1553,7 @@ function renderNitroPlugin(pluginFile, registryFile, queueConfig, cloudflareQueu
|
|
|
1198
1553
|
...cloudflare ? [`import { createQueueCloudflareWorker } from ${JSON.stringify(createImportPath(pluginFile, resolveRuntimeModule("internal/runtime/cloudflare-vite")))}`] : [],
|
|
1199
1554
|
...cloudflareRuntime ? [`import { createCloudflareQueueRuntimeClient } from ${JSON.stringify(createImportPath(pluginFile, resolveRuntimeModule("internal/runtime/cloudflare-client")))}`] : [],
|
|
1200
1555
|
...localRuntime ? [`import { closeLocalQueues, createLocalQueueRuntimeClient, startLocalQueue } from ${JSON.stringify(createImportPath(pluginFile, resolveRuntimeModule("internal/runtime/local-client")))}`] : [],
|
|
1201
|
-
...postgresRuntime ? [`import { closePostgresQueues, createPostgresQueueRuntimeClient, startPostgresQueue } from ${JSON.stringify(createImportPath(pluginFile, resolveRuntimeModule("internal/runtime/postgres-client")))}`] : [],
|
|
1556
|
+
...postgresRuntime ? [`import { closePostgresQueues, createPostgresQueueRuntimeClient, readQueueWorkers, startPostgresQueue } from ${JSON.stringify(createImportPath(pluginFile, resolveRuntimeModule("internal/runtime/postgres-client")))}`] : [],
|
|
1202
1557
|
...vercelRuntime ? [`import { createVercelQueueRuntimeClient } from ${JSON.stringify(createImportPath(pluginFile, resolveRuntimeModule("internal/runtime/vercel-client")))}`] : [],
|
|
1203
1558
|
`import { setQueueRuntimeConfig, setQueueRuntimeEventDefaults, setQueueRuntimeRegistry } from ${JSON.stringify(createImportPath(pluginFile, resolveRuntimeModule("internal/runtime/state")))}`,
|
|
1204
1559
|
`import queueRegistry from ${JSON.stringify(createImportPath(pluginFile, registryFile))}`,
|
|
@@ -1206,6 +1561,7 @@ function renderNitroPlugin(pluginFile, registryFile, queueConfig, cloudflareQueu
|
|
|
1206
1561
|
...cloudflareGlobals ? ["const { env: vitehubEnv, waitUntil: vitehubWaitUntil } = vitehubCloudflareWorkers as unknown as { env: Record<string, unknown>, waitUntil(promise: Promise<unknown>): void }", ""] : [],
|
|
1207
1562
|
...vercelRuntime ? ["globalThis.__vitehubVercelQueue = __vitehubVercelQueue", ""] : [],
|
|
1208
1563
|
`const queueConfig = ${JSON.stringify(queueConfig, null, 2)}`,
|
|
1564
|
+
...postgresRuntime ? ["const queueWorkers = readQueueWorkers()"] : [],
|
|
1209
1565
|
...cloudflare ? [`const queueDefinitions = ${JSON.stringify(queueDefinitions, null, 2)}`, "const queueWorker = createQueueCloudflareWorker({ definitions: queueDefinitions, queue: queueConfig, registry: queueRegistry })"] : [],
|
|
1210
1566
|
"",
|
|
1211
1567
|
`export default definePlugin((${cloudflare || localRuntime || postgresRuntime ? "nitro" : ""}) => {`,
|
|
@@ -1214,7 +1570,7 @@ function renderNitroPlugin(pluginFile, registryFile, queueConfig, cloudflareQueu
|
|
|
1214
1570
|
...cloudflareGlobals ? [" setQueueRuntimeEventDefaults({ env: vitehubEnv, waitUntil: vitehubWaitUntil })"] : [],
|
|
1215
1571
|
...cloudflare ? [" nitro.hooks.hook('cloudflare:queue', ({ batch, context, env }) => queueWorker.queue(batch, env, context))"] : [],
|
|
1216
1572
|
...localRuntime ? [" startLocalQueue(queueConfig)", " nitro.hooks.hook('close', closeLocalQueues)"] : [],
|
|
1217
|
-
...postgresRuntime ? [postgresDatabase ? ` startPostgresQueue(queueConfig, () => import(${JSON.stringify(databaseImport)}).then(module => module.databases))` : " startPostgresQueue(queueConfig)", " nitro.hooks.hook('close', closePostgresQueues)"] : [],
|
|
1573
|
+
...postgresRuntime ? [postgresDatabase ? ` startPostgresQueue(queueConfig, () => import(${JSON.stringify(databaseImport)}).then(module => module.databases), queueWorkers)` : " startPostgresQueue(queueConfig, undefined, queueWorkers)", " nitro.hooks.hook('close', closePostgresQueues)"] : [],
|
|
1218
1574
|
"})",
|
|
1219
1575
|
""
|
|
1220
1576
|
].join("\n");
|
|
@@ -1252,26 +1608,27 @@ async function writeQueueNitroIntegration(rootDir, queue, hosting, cloudflareQue
|
|
|
1252
1608
|
await Promise.all([mkdir(dirname(pluginFile), { recursive: true }), mkdir(generatedDir, { recursive: true })]);
|
|
1253
1609
|
const vercelConsumerDir = resolve(rootDir, generatedQueueNitroVercelConsumerDir);
|
|
1254
1610
|
const vercelConsumers = queueConfig !== false && queueConfig.driver === "vercel" ? createVercelQueueConsumerRoutes(definitions) : [];
|
|
1255
|
-
|
|
1611
|
+
const vercelConsumerFiles = new Set(vercelConsumers.map((consumer) => resolve(rootDir, consumer.handler)));
|
|
1612
|
+
const staleVercelConsumerFiles = (await readdir(vercelConsumerDir).catch(() => [])).map((name) => resolve(vercelConsumerDir, name)).filter((file) => !vercelConsumerFiles.has(file));
|
|
1613
|
+
await Promise.all(staleVercelConsumerFiles.map((file) => rm(file, {
|
|
1256
1614
|
force: true,
|
|
1257
1615
|
recursive: true
|
|
1258
|
-
});
|
|
1259
|
-
if (vercelConsumers.length) await mkdir(vercelConsumerDir, { recursive: true });
|
|
1616
|
+
})));
|
|
1260
1617
|
await Promise.all([
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1618
|
+
writeFileIfChanged(registryFile, createRuntimeRegistryContents(registryFile, definitions)),
|
|
1619
|
+
writeFileIfChanged(pluginFile, renderNitroPlugin(pluginFile, registryFile, runtimeConfig, cloudflareQueues, queueDefinitions, development, database.import ?? "@vite-hub/database/runtime/registry")),
|
|
1620
|
+
writeFileIfChanged(middlewareFile, renderNitroMiddleware(middlewareFile, runtimeConfig, definitions.length > 0, development)),
|
|
1264
1621
|
...vercelConsumers.map(async (consumer) => {
|
|
1265
1622
|
const file = resolve(rootDir, consumer.handler);
|
|
1266
|
-
await
|
|
1623
|
+
await writeFileIfChanged(file, renderVercelQueueConsumerHandler(file, consumer));
|
|
1267
1624
|
}),
|
|
1268
|
-
...process.env.VITEST ? [
|
|
1625
|
+
...process.env.VITEST ? [writeFileIfChanged(resolve(rootDir, generatedQueueTestSetup), [
|
|
1269
1626
|
`import { setQueueRuntimeConfig, setQueueRuntimeRegistry } from ${JSON.stringify(createImportPath(resolve(rootDir, generatedQueueTestSetup), resolveRuntimeModule("internal/runtime/state")))}`,
|
|
1270
1627
|
`import registry from "./${generatedRegistryFileName}"`,
|
|
1271
1628
|
`setQueueRuntimeConfig(${JSON.stringify(queueConfig)})`,
|
|
1272
1629
|
"setQueueRuntimeRegistry(registry)",
|
|
1273
1630
|
""
|
|
1274
|
-
].join("\n")
|
|
1631
|
+
].join("\n"))] : []
|
|
1275
1632
|
]);
|
|
1276
1633
|
return queueConfig;
|
|
1277
1634
|
}
|
|
@@ -1310,15 +1667,17 @@ function createVercelQueueConsumerRoutes(definitions) {
|
|
|
1310
1667
|
};
|
|
1311
1668
|
});
|
|
1312
1669
|
}
|
|
1313
|
-
function renderVercelQueueConsumerHandler(file, name) {
|
|
1670
|
+
function renderVercelQueueConsumerHandler(file, { consumer, name }) {
|
|
1314
1671
|
return [
|
|
1315
1672
|
`import { handleHostedVercelQueueCallback } from ${JSON.stringify(createImportPath(file, resolveRuntimeModule("runtime/hosted")))}`,
|
|
1316
1673
|
`import { loadQueueDefinition, missingQueueDefinitionError } from ${JSON.stringify(createImportPath(file, resolveRuntimeModule("internal/runtime/state")))}`,
|
|
1317
1674
|
"",
|
|
1318
1675
|
`const name = ${JSON.stringify(name)}`,
|
|
1676
|
+
`const isConsumerFunction = process.env.${vercelQueueFunctionEnv} === ${JSON.stringify(consumer)}`,
|
|
1319
1677
|
"",
|
|
1320
1678
|
"export default {",
|
|
1321
1679
|
" async fetch(request) {",
|
|
1680
|
+
" if (!isConsumerFunction) return new Response(null, { status: 404 })",
|
|
1322
1681
|
" const definition = await loadQueueDefinition(name)",
|
|
1323
1682
|
" if (!definition) throw missingQueueDefinitionError(name)",
|
|
1324
1683
|
" return await handleHostedVercelQueueCallback(request, name, definition)",
|
|
@@ -1513,6 +1872,13 @@ function readProviderErrorCodes(body) {
|
|
|
1513
1872
|
function isShellSafeProvisionValue(value) {
|
|
1514
1873
|
return /^[A-Za-z0-9][\w.-]*$/.test(value);
|
|
1515
1874
|
}
|
|
1875
|
+
/**
|
|
1876
|
+
* The warning of a Cloudflare Provision Step that skips without credentials. `vitehub provision` and `vitehub deploy`
|
|
1877
|
+
* read a `wrangler login` of the Wrangler installed in the project, so the warning names it.
|
|
1878
|
+
*/
|
|
1879
|
+
function cloudflareProvisionSkipWarning(skipping) {
|
|
1880
|
+
return `${skipping}, missing CLOUDFLARE_ACCOUNT_ID/CLOUDFLARE_API_TOKEN. Install Wrangler in the project and run \`npx wrangler login\`, or set both variables. With more than one Cloudflare account, also set CLOUDFLARE_ACCOUNT_ID.`;
|
|
1881
|
+
}
|
|
1516
1882
|
function resolveCloudflareProvisionConfig(env) {
|
|
1517
1883
|
const credentials = readHostCredentialsFromEnv("cloudflare", env);
|
|
1518
1884
|
if (!credentials?.accountId) return;
|
|
@@ -1646,7 +2012,7 @@ function createQueueProvisionStep(resolveDefinitions, resolveNamePrefix = () =>
|
|
|
1646
2012
|
async plan(context) {
|
|
1647
2013
|
const config = resolveCloudflareProvisionConfig(context.env);
|
|
1648
2014
|
if (!config) {
|
|
1649
|
-
context.logger.warn("queue: skipping Cloudflare queues
|
|
2015
|
+
context.logger.warn(cloudflareProvisionSkipWarning("queue: skipping Cloudflare queues"));
|
|
1650
2016
|
context.markPlanUnchecked?.();
|
|
1651
2017
|
return [];
|
|
1652
2018
|
}
|
|
@@ -1741,12 +2107,19 @@ function addVercelQueueConsumers(kit, definitions, root) {
|
|
|
1741
2107
|
const vercel = cloneRecord(kit.config.vercel);
|
|
1742
2108
|
const functionRules = cloneRecord(vercel.functionRules);
|
|
1743
2109
|
for (const consumer of createVercelQueueConsumerRoutes(definitions)) {
|
|
2110
|
+
const rule = cloneRecord(functionRules[consumer.route]);
|
|
1744
2111
|
kit.addHandler({
|
|
1745
2112
|
handler: root ? resolve$1(root, consumer.handler) : consumer.handler,
|
|
2113
|
+
lazy: false,
|
|
2114
|
+
meta: { ...ownAccessHandlerMeta },
|
|
1746
2115
|
route: consumer.route
|
|
1747
2116
|
});
|
|
1748
2117
|
functionRules[consumer.route] = {
|
|
1749
|
-
...
|
|
2118
|
+
...rule,
|
|
2119
|
+
environment: {
|
|
2120
|
+
...cloneRecord(rule.environment),
|
|
2121
|
+
[vercelQueueFunctionEnv]: consumer.consumer
|
|
2122
|
+
},
|
|
1750
2123
|
experimentalTriggers: [{
|
|
1751
2124
|
consumer: consumer.consumer,
|
|
1752
2125
|
topic: consumer.topic,
|
|
@@ -1759,9 +2132,21 @@ function addVercelQueueConsumers(kit, definitions, root) {
|
|
|
1759
2132
|
functionRules
|
|
1760
2133
|
};
|
|
1761
2134
|
}
|
|
2135
|
+
const queueWranglerModules = /* @__PURE__ */ new WeakSet();
|
|
2136
|
+
function queueWranglerModule(consumers) {
|
|
2137
|
+
const module = (nitro) => {
|
|
2138
|
+
nitro.hooks.hook("compiled", async () => {
|
|
2139
|
+
if (nitro.options.cloudflare?.deployConfig === false) return;
|
|
2140
|
+
await finalizeCloudflareQueueConsumers(nitro.options.output.serverDir, consumers);
|
|
2141
|
+
});
|
|
2142
|
+
};
|
|
2143
|
+
queueWranglerModules.add(module);
|
|
2144
|
+
return module;
|
|
2145
|
+
}
|
|
1762
2146
|
async function mergeNitroConfig(config, value, queue, root, definitions) {
|
|
1763
2147
|
const providerOutput = useProviderOutputCatalog(config);
|
|
1764
2148
|
const nitro = cloneRecord(value);
|
|
2149
|
+
if (Array.isArray(nitro.modules)) nitro.modules = nitro.modules.filter((module) => !queueWranglerModules.has(module));
|
|
1765
2150
|
const nitroHosting = getHostingProvider(resolveHost({ nitro }));
|
|
1766
2151
|
const normalizedQueue = normalizeQueueForHosting(queue, nitroHosting);
|
|
1767
2152
|
const runtimeEnabled = queue !== false && !(queue !== false && nitroHosting && queue && normalizedQueue === void 0);
|
|
@@ -1829,7 +2214,14 @@ async function mergeNitroConfig(config, value, queue, root, definitions) {
|
|
|
1829
2214
|
producers: generatedProducers
|
|
1830
2215
|
}
|
|
1831
2216
|
});
|
|
1832
|
-
|
|
2217
|
+
if (cloudflareQueues && generated.consumers.some((consumer) => consumer.max_retries !== void 0)) {
|
|
2218
|
+
const modules = Array.isArray(nitro.modules) ? nitro.modules : [];
|
|
2219
|
+
nitro.modules = [queueWranglerModule(generated.consumers), ...modules];
|
|
2220
|
+
}
|
|
2221
|
+
return composeNitroCloudflareProviderOutput(providerOutput, {
|
|
2222
|
+
...baseNitro,
|
|
2223
|
+
modules: nitro.modules
|
|
2224
|
+
}, value);
|
|
1833
2225
|
}
|
|
1834
2226
|
function hubQueue(options, internalOptions = {}) {
|
|
1835
2227
|
let resolved;
|