@cloudflare/deploy-helpers 0.10.2 → 0.11.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/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import { fetchResult, fetchPagedListResult, logger, confirm, fetchListResult, prompt, select } from './chunk-Z4LB73IF.mjs';
2
2
  export { initDeployHelpersContext } from './chunk-Z4LB73IF.mjs';
3
- import { createWorkerUploadForm, moduleTypeMimeType } from './chunk-PXVCTRCA.mjs';
4
- export { createWorkerUploadForm, fromMimeType, handleUnsafeCapnp, moduleTypeMimeType } from './chunk-PXVCTRCA.mjs';
3
+ import { createWorkerUploadForm, moduleTypeMimeType } from './chunk-3G6JZQDH.mjs';
4
+ export { createWorkerUploadForm, fromMimeType, handleUnsafeCapnp, moduleTypeMimeType } from './chunk-3G6JZQDH.mjs';
5
5
  import { __commonJS, __name, __require, __toESM, __export } from './chunk-Q72B4Q5Z.mjs';
6
6
  import assert4 from 'node:assert';
7
7
  import { readFileSync, mkdirSync, writeFileSync, createReadStream } from 'node:fs';
@@ -13,7 +13,7 @@ import { cancel } from '@cloudflare/cli-shared-helpers';
13
13
  import { UserError as UserError$1 } from '@cloudflare/workers-utils/errors';
14
14
  import { execSync, spawn } from 'node:child_process';
15
15
  import '@cloudflare/workers-utils/compliance';
16
- import { INHERIT_SYMBOL, APIError, UserError, getEnvironmentVariableFactory, isNonInteractiveOrCI, getHostFromRoute, retryOnAPIFailure, ParseError, getComplianceRegionSubdomain, configFileName, formatTime, getSubdomainMixedStateCheckDisabled, LOGGER_LEVELS, SERVICE_TAG_PREFIX, ENVIRONMENT_TAG_PREFIX, getDurableObjectExports, partitionExports, getWranglerTmpDir, parsePackageJSON, getInstalledPackageVersion, FatalError, readFileSync as readFileSync$1, parseJSON, printBindings, experimental_readRawConfig, experimental_patchConfig, PatchConfigError, COMPLIANCE_REGION_CONFIG_UNKNOWN, constructWranglerConfig, getCIMatchTag, formatConfigSnippet, DEFAULT_COMPAT_DATE, writeOutput, getBindings, hasDurableObjectExports, getDockerPath, parseNonHyphenedUuid, getWorkersCIBranchName, getCIOverrideName, getBindingTypeFriendlyName } from '@cloudflare/workers-utils';
16
+ import { INHERIT_SYMBOL, APIError, UserError, getEnvironmentVariableFactory, isNonInteractiveOrCI, getHostFromRoute, retryOnAPIFailure, ParseError, getComplianceRegionSubdomain, configFileName, formatTime, getSubdomainMixedStateCheckDisabled, LOGGER_LEVELS, getDurableObjectContainerApps, CONTAINER_IMAGES_BINDING, isDurableObjectContainerApp, SERVICE_TAG_PREFIX, ENVIRONMENT_TAG_PREFIX, getDurableObjectExports, partitionExports, getWranglerTmpDir, parsePackageJSON, getInstalledPackageVersion, FatalError, readFileSync as readFileSync$1, parseJSON, printBindings, experimental_readRawConfig, experimental_patchConfig, PatchConfigError, COMPLIANCE_REGION_CONFIG_UNKNOWN, constructWranglerConfig, getCIMatchTag, formatConfigSnippet, DEFAULT_COMPAT_DATE, writeOutput, getBindings, hasDurableObjectExports, getDockerPath, parseNonHyphenedUuid, getWorkersCIBranchName, getCIOverrideName, getBindingTypeFriendlyName } from '@cloudflare/workers-utils';
17
17
  import { Response, FormData } from 'undici';
18
18
  import chalk6 from 'chalk';
19
19
  import PQueue from 'p-queue';
@@ -24,6 +24,7 @@ import { hash as hash$1 } from 'blake3-wasm';
24
24
  import { Blob } from 'node:buffer';
25
25
  import { gzipSync } from 'node:zlib';
26
26
  import { brandColor, white, gray, bold, yellow, dim, red, blue } from '@cloudflare/cli-shared-helpers/colors';
27
+ import { isDeepStrictEqual } from 'node:util';
27
28
  import readline from 'node:readline';
28
29
  import { parse as parse$1 } from 'dotenv';
29
30
  import { getFreshSourceMapSupport, getNodeCompat } from 'miniflare';
@@ -6665,6 +6666,14 @@ __name(patchNonVersionedScriptSettings, "patchNonVersionedScriptSettings");
6665
6666
  // src/deploy/helpers/confirm-latest-deployment-overwrite.ts
6666
6667
  var BLANK_INPUT = "-";
6667
6668
  async function confirmLatestDeploymentOverwrite(config2, accountId, scriptName) {
6669
+ return (await confirmLatestDeploymentOverwriteAndGetLatest(
6670
+ config2,
6671
+ accountId,
6672
+ scriptName
6673
+ )).confirmed;
6674
+ }
6675
+ __name(confirmLatestDeploymentOverwrite, "confirmLatestDeploymentOverwrite");
6676
+ async function confirmLatestDeploymentOverwriteAndGetLatest(config2, accountId, scriptName) {
6668
6677
  try {
6669
6678
  const latest = await fetchLatestDeployment(config2, accountId, scriptName);
6670
6679
  if (latest && latest.versions.length >= 2) {
@@ -6682,7 +6691,7 @@ async function confirmLatestDeploymentOverwrite(config2, accountId, scriptName)
6682
6691
  "last",
6683
6692
  versionCache
6684
6693
  );
6685
- return inputPrompt({
6694
+ const confirmed = await inputPrompt({
6686
6695
  type: "confirm",
6687
6696
  question: `"wrangler deploy" will upload a new version and deploy it globally immediately.
6688
6697
  Are you sure you want to continue?`,
@@ -6690,15 +6699,17 @@ Are you sure you want to continue?`,
6690
6699
  defaultValue: isNonInteractiveOrCI(),
6691
6700
  acceptDefault: isNonInteractiveOrCI()
6692
6701
  });
6702
+ return { confirmed, latestDeployment: latest };
6693
6703
  }
6704
+ return { confirmed: true, latestDeployment: latest };
6694
6705
  } catch (e) {
6695
6706
  if (!isWorkerNotFoundError(e)) {
6696
6707
  throw e;
6697
6708
  }
6698
6709
  }
6699
- return true;
6710
+ return { confirmed: true, latestDeployment: void 0 };
6700
6711
  }
6701
- __name(confirmLatestDeploymentOverwrite, "confirmLatestDeploymentOverwrite");
6712
+ __name(confirmLatestDeploymentOverwriteAndGetLatest, "confirmLatestDeploymentOverwriteAndGetLatest");
6702
6713
  async function printDeployment(config2, accountId, workerName, deployment, adjective, versionCache) {
6703
6714
  const [versions, traffic] = await fetchDeploymentVersions(
6704
6715
  config2,
@@ -6730,6 +6741,172 @@ function formatVersions(versions, traffic) {
6730
6741
  }).join("\n\n");
6731
6742
  }
6732
6743
  __name(formatVersions, "formatVersions");
6744
+ async function clearRemovedContainerImagesBindings(config2, bindings, workerUrl) {
6745
+ if (getDurableObjectContainerApps(config2.containers).length > 0) {
6746
+ return;
6747
+ }
6748
+ const settings = await fetchResult(
6749
+ config2,
6750
+ `${workerUrl}/settings`
6751
+ );
6752
+ if (settings.bindings.some(({ name }) => name === CONTAINER_IMAGES_BINDING)) {
6753
+ bindings[CONTAINER_IMAGES_BINDING] ??= { type: "json", value: {} };
6754
+ }
6755
+ }
6756
+ __name(clearRemovedContainerImagesBindings, "clearRemovedContainerImagesBindings");
6757
+ function addContainerImagesBinding(config2, bindings, preparedContainerImages, options = {}) {
6758
+ const containers = getDurableObjectContainerApps(config2.containers);
6759
+ const shouldInheritExisting = options.preserveExisting && options.workerExists && options.hasExistingBinding;
6760
+ if (options.preserveExisting && !shouldInheritExisting) {
6761
+ return;
6762
+ }
6763
+ if (containers.length === 0 && !shouldInheritExisting) {
6764
+ return;
6765
+ }
6766
+ if (bindings[CONTAINER_IMAGES_BINDING] !== void 0) {
6767
+ throw new UserError(
6768
+ `The binding name "${CONTAINER_IMAGES_BINDING}" is reserved for Durable Object-managed Container images.`,
6769
+ {
6770
+ telemetryMessage: "durable object container images binding name conflict"
6771
+ }
6772
+ );
6773
+ }
6774
+ if (options.preserveExisting) {
6775
+ bindings[CONTAINER_IMAGES_BINDING] = { type: "inherit" };
6776
+ return;
6777
+ }
6778
+ bindings[CONTAINER_IMAGES_BINDING] = {
6779
+ type: "json",
6780
+ value: Object.fromEntries(
6781
+ containers.map((container) => {
6782
+ const configuredImages = Object.keys(container.images ?? {});
6783
+ const preparedImages = preparedContainerImages[container.class_name];
6784
+ if (configuredImages.length > 0 && preparedImages === void 0) {
6785
+ throw new Error(
6786
+ `Container images for Durable Object class "${container.class_name}" were not prepared before upload.`
6787
+ );
6788
+ }
6789
+ return [container.class_name, preparedImages ?? {}];
6790
+ })
6791
+ )
6792
+ };
6793
+ }
6794
+ __name(addContainerImagesBinding, "addContainerImagesBinding");
6795
+ function getContainerMetadata(config2, preparedContainerImages = {}, options = {}) {
6796
+ const metadata = config2.containers?.map((container) => {
6797
+ if (isDurableObjectContainerApp(container)) {
6798
+ const configuredImages = Object.keys(container.images ?? {});
6799
+ const images = preparedContainerImages[container.class_name];
6800
+ if (configuredImages.length > 0 && images === void 0 && !options.allowUnprepared) {
6801
+ throw new Error(
6802
+ `Container images for Durable Object class "${container.class_name}" were not prepared before upload.`
6803
+ );
6804
+ }
6805
+ return {
6806
+ name: container.name,
6807
+ class_name: container.class_name,
6808
+ ...images !== void 0 && { images }
6809
+ };
6810
+ }
6811
+ return {
6812
+ ...container.name !== void 0 && { name: container.name },
6813
+ ...container.class_name !== void 0 && {
6814
+ class_name: container.class_name
6815
+ }
6816
+ };
6817
+ }) ?? [];
6818
+ return config2.containers === void 0 ? void 0 : metadata;
6819
+ }
6820
+ __name(getContainerMetadata, "getContainerMetadata");
6821
+ async function getContainerMetadataForRolloutSkip(config2, {
6822
+ accountId,
6823
+ scriptName,
6824
+ dispatchNamespace,
6825
+ workerExists,
6826
+ latestDeployment,
6827
+ dryRun = false
6828
+ }) {
6829
+ const configuredMetadata = getContainerMetadata(
6830
+ config2,
6831
+ {},
6832
+ {
6833
+ allowUnprepared: true
6834
+ }
6835
+ );
6836
+ if (dryRun || !workerExists) {
6837
+ return {
6838
+ containers: configuredMetadata,
6839
+ hasExistingContainerImagesBinding: false
6840
+ };
6841
+ }
6842
+ if (dispatchNamespace !== void 0) {
6843
+ throw new UserError(
6844
+ "Cannot use --containers-rollout=none for an existing dispatch script because the Workers for Platforms API does not expose its deployed Container metadata. The Worker has not been uploaded. Deploy without this flag only when you intend to apply the local Container configuration.",
6845
+ {
6846
+ telemetryMessage: "rollout none dispatch container metadata unavailable"
6847
+ }
6848
+ );
6849
+ }
6850
+ if (accountId === void 0 || latestDeployment === void 0 || latestDeployment.versions.length === 0) {
6851
+ throw new UserError(
6852
+ "Cannot use --containers-rollout=none for an existing Worker because its deployed Container metadata could not be recovered. The Worker has not been uploaded. Deploy without this flag only when you intend to apply the local Container configuration.",
6853
+ {
6854
+ telemetryMessage: "rollout none deployed container metadata unavailable"
6855
+ }
6856
+ );
6857
+ }
6858
+ const versions = await fetchVersions(
6859
+ config2,
6860
+ accountId,
6861
+ scriptName,
6862
+ void 0,
6863
+ latestDeployment.versions.map(({ version_id }) => version_id)
6864
+ );
6865
+ const containerImagesBindingByVersion = versions.map(
6866
+ (version2) => version2.resources.bindings.some(
6867
+ (binding) => binding.name === CONTAINER_IMAGES_BINDING
6868
+ )
6869
+ );
6870
+ const hasExistingContainerImagesBinding = containerImagesBindingByVersion[0] ?? false;
6871
+ if (containerImagesBindingByVersion.some(
6872
+ (hasBinding) => hasBinding !== hasExistingContainerImagesBinding
6873
+ )) {
6874
+ throw new UserError(
6875
+ `All currently deployed Worker Versions must have identical ${CONTAINER_IMAGES_BINDING} binding presence when using --containers-rollout=none.`,
6876
+ {
6877
+ telemetryMessage: "rollout none inconsistent durable object container image binding"
6878
+ }
6879
+ );
6880
+ }
6881
+ const containerMetadataByVersion = versions.map(
6882
+ (version2) => version2.resources?.script_runtime?.containers
6883
+ );
6884
+ const existingMetadata = containerMetadataByVersion.filter(
6885
+ (metadata) => metadata !== void 0
6886
+ );
6887
+ if (existingMetadata.length === 0) {
6888
+ return {
6889
+ containers: void 0,
6890
+ hasExistingContainerImagesBinding
6891
+ };
6892
+ }
6893
+ const expectedMetadata = existingMetadata[0];
6894
+ if (existingMetadata.length !== containerMetadataByVersion.length || existingMetadata.some(
6895
+ (metadata) => !isDeepStrictEqual(metadata, expectedMetadata)
6896
+ )) {
6897
+ throw new UserError(
6898
+ "All currently deployed Worker Versions must have identical Container metadata when using --containers-rollout=none.",
6899
+ {
6900
+ telemetryMessage: "rollout none inconsistent deployed container metadata"
6901
+ }
6902
+ );
6903
+ }
6904
+ return {
6905
+ containers: existingMetadata[0],
6906
+ hasExistingContainerImagesBinding
6907
+ };
6908
+ }
6909
+ __name(getContainerMetadataForRolloutSkip, "getContainerMetadataForRolloutSkip");
6733
6910
 
6734
6911
  // src/deploy/helpers/deploy-wfp.ts
6735
6912
  function deployWfpUserWorker(dispatchNamespace, versionId) {
@@ -6841,8 +7018,8 @@ var suppressNotFoundError = /* @__PURE__ */ __name((err) => {
6841
7018
  }, "suppressNotFoundError");
6842
7019
  async function resolveDoLifecyclePayload(props) {
6843
7020
  const durableObjectExports = getDurableObjectExports(props.config.exports);
6844
- const hasDurableObjectExports2 = Object.keys(durableObjectExports).length > 0;
6845
- if (hasDurableObjectExports2) {
7021
+ const hasDurableObjectExports3 = Object.keys(durableObjectExports).length > 0;
7022
+ if (hasDurableObjectExports3) {
6846
7023
  return {
6847
7024
  migrations: void 0,
6848
7025
  exports: durableObjectExports
@@ -11700,13 +11877,13 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
11700
11877
  }
11701
11878
  return propValues;
11702
11879
  });
11703
- const isObject3 = isObject;
11880
+ const isObject2 = isObject;
11704
11881
  const catchall = def.catchall;
11705
11882
  let value;
11706
11883
  inst._zod.parse = (payload, ctx) => {
11707
11884
  value ?? (value = _normalized.value);
11708
11885
  const input = payload.value;
11709
- if (!isObject3(input)) {
11886
+ if (!isObject2(input)) {
11710
11887
  payload.issues.push({
11711
11888
  expected: "object",
11712
11889
  code: "invalid_type",
@@ -11833,7 +12010,7 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) =>
11833
12010
  return (payload, ctx) => fn(shape, payload, ctx);
11834
12011
  }, "generateFastpass");
11835
12012
  let fastpass;
11836
- const isObject3 = isObject;
12013
+ const isObject2 = isObject;
11837
12014
  const jit = !globalConfig.jitless;
11838
12015
  const allowsEval2 = allowsEval;
11839
12016
  const fastEnabled = jit && allowsEval2.value;
@@ -11842,7 +12019,7 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) =>
11842
12019
  inst._zod.parse = (payload, ctx) => {
11843
12020
  value ?? (value = _normalized.value);
11844
12021
  const input = payload.value;
11845
- if (!isObject3(input)) {
12022
+ if (!isObject2(input)) {
11846
12023
  payload.issues.push({
11847
12024
  expected: "object",
11848
12025
  code: "invalid_type",
@@ -24778,7 +24955,9 @@ See https://developers.cloudflare.com/workers/platform/compatibility-dates for m
24778
24955
  );
24779
24956
  }
24780
24957
  } else {
24781
- if (config2.containers && config2.containers.length > 0) {
24958
+ if (config2.containers?.some(
24959
+ (container) => !isDurableObjectContainerApp(container)
24960
+ )) {
24782
24961
  logger.warn(
24783
24962
  `Your Worker has Containers configured. Container configuration changes (such as image, max_instances, etc.) will not be gradually rolled out with versions. These changes will only take effect after running \`deploy\`.`
24784
24963
  );
@@ -24804,8 +24983,20 @@ async function preUploadApiChecks(props, config2) {
24804
24983
  let workerTag = null;
24805
24984
  let tags = [];
24806
24985
  let workerExists = true;
24807
- const skipMetadataFetch = props.command === "deploy" && !!props.dispatchNamespace;
24808
- if (!skipMetadataFetch) {
24986
+ if (props.command === "deploy" && props.dispatchNamespace) {
24987
+ try {
24988
+ await fetchResult(
24989
+ config2,
24990
+ `/accounts/${accountId}/workers/dispatch/namespaces/${props.dispatchNamespace}/scripts/${name}`
24991
+ );
24992
+ } catch (e) {
24993
+ if (typeof e === "object" && e !== null && "code" in e && e.code === 10092) {
24994
+ workerExists = false;
24995
+ } else {
24996
+ throw e;
24997
+ }
24998
+ }
24999
+ } else {
24809
25000
  try {
24810
25001
  const serviceMetaData = await fetchResult(config2, `/accounts/${accountId}/workers/services/${name}`);
24811
25002
  const {
@@ -24912,7 +25103,7 @@ Edits that have been made via the script API will be overridden by your local co
24912
25103
  !props.resourcesProvision,
24913
25104
  name
24914
25105
  );
24915
- const wantsWorkersDev = props.command === "deploy" && getSubdomainValues(config2.workers_dev, config2.preview_urls, props.routes).workers_dev;
25106
+ const wantsWorkersDev = props.command === "deploy" && props.dispatchNamespace === void 0 && getSubdomainValues(config2.workers_dev, config2.preview_urls, props.routes).workers_dev;
24916
25107
  if (!workerExists && wantsWorkersDev) {
24917
25108
  await getWorkersDevSubdomain(config2, accountId, {
24918
25109
  autoRegisterSubdomain: props.autoRegisterWorkersDevSubdomain,
@@ -24980,13 +25171,15 @@ async function deployWorker(props, config2, buildResult, callbacks) {
24980
25171
  const workerUrl = props.dispatchNamespace ? `/accounts/${accountId}/workers/dispatch/namespaces/${props.dispatchNamespace}/scripts/${scriptName}` : `/accounts/${accountId}/workers/scripts/${scriptName}`;
24981
25172
  const { format } = entry;
24982
25173
  const { projectRoot } = entry;
25174
+ let latestDeployment;
24983
25175
  if (!props.dispatchNamespace && accountId && scriptName) {
24984
- const yes = await confirmLatestDeploymentOverwrite(
25176
+ const confirmation = await confirmLatestDeploymentOverwriteAndGetLatest(
24985
25177
  config2,
24986
25178
  accountId,
24987
25179
  scriptName
24988
25180
  );
24989
- if (!yes) {
25181
+ latestDeployment = confirmation.latestDeployment;
25182
+ if (!confirmation.confirmed) {
24990
25183
  cancel("Aborting deploy...");
24991
25184
  return { versionId, workerTag };
24992
25185
  }
@@ -25001,6 +25194,21 @@ async function deployWorker(props, config2, buildResult, callbacks) {
25001
25194
  content,
25002
25195
  sourceMaps
25003
25196
  } = buildResult;
25197
+ const skipContainerChanges = props.containersRollout === "none";
25198
+ const preparedContainerImages = skipContainerChanges ? void 0 : await callbacks.prepareDurableObjectContainerApplications?.(config2, {
25199
+ dryRun: Boolean(isDryRun),
25200
+ scriptName,
25201
+ dispatchNamespace: props.dispatchNamespace
25202
+ });
25203
+ const rolloutSkipContainerState = skipContainerChanges ? await getContainerMetadataForRolloutSkip(config2, {
25204
+ accountId,
25205
+ scriptName,
25206
+ dispatchNamespace: props.dispatchNamespace,
25207
+ workerExists,
25208
+ latestDeployment,
25209
+ dryRun: isDryRun
25210
+ }) : void 0;
25211
+ const containerMetadata = rolloutSkipContainerState ? rolloutSkipContainerState.containers : getContainerMetadata(config2, preparedContainerImages);
25004
25212
  const { migrations, exports: exports$1 } = await resolveExportsUploadPayload({
25005
25213
  scriptName,
25006
25214
  isDryRun,
@@ -25054,6 +25262,14 @@ async function deployWorker(props, config2, buildResult, callbacks) {
25054
25262
  type: "deploy",
25055
25263
  workerExists
25056
25264
  });
25265
+ if (!skipContainerChanges && keepVars && !isDryRun && workerExists) {
25266
+ await clearRemovedContainerImagesBindings(config2, bindings, workerUrl);
25267
+ }
25268
+ addContainerImagesBinding(config2, bindings, preparedContainerImages ?? {}, {
25269
+ preserveExisting: skipContainerChanges,
25270
+ workerExists,
25271
+ hasExistingBinding: rolloutSkipContainerState?.hasExistingContainerImagesBinding
25272
+ });
25057
25273
  if (workersSitesAssets.manifest) {
25058
25274
  modules.push({
25059
25275
  name: "__STATIC_CONTENT_MANIFEST",
@@ -25076,7 +25292,7 @@ async function deployWorker(props, config2, buildResult, callbacks) {
25076
25292
  migrations,
25077
25293
  exports: exports$1,
25078
25294
  modules,
25079
- containers: config2.containers,
25295
+ containers: containerMetadata,
25080
25296
  sourceMaps,
25081
25297
  compatibility_date: compatibilityDate,
25082
25298
  compatibility_flags: compatibilityFlags,
@@ -25112,7 +25328,8 @@ async function deployWorker(props, config2, buildResult, callbacks) {
25112
25328
  );
25113
25329
  const bundleSize = await getSize([...modules, { content }]);
25114
25330
  printBundleSize(bundleSize);
25115
- const canUseNewVersionsDeploymentsApi = workerExists && props.dispatchNamespace === void 0 && format === "modules" && migrations === void 0 && !hasDurableObjectExports(config2.exports) && !config2.first_party_worker && config2.containers === void 0;
25331
+ const canUseNewVersionsDeploymentsApi = workerExists && props.dispatchNamespace === void 0 && format === "modules" && migrations === void 0 && !hasDurableObjectExports(config2.exports) && !config2.first_party_worker && config2.containers === void 0 && // Rollout skip can recover Container metadata absent from local config.
25332
+ containerMetadata === void 0;
25116
25333
  let workerBundle;
25117
25334
  const dockerPath = getDockerPath();
25118
25335
  if (normalisedContainerConfig.length && props.containersRollout !== "none") {
@@ -25391,9 +25608,29 @@ async function deployWorker(props, config2, buildResult, callbacks) {
25391
25608
  await callbacks.deployContainers(config2, normalisedContainerConfig, {
25392
25609
  versionId,
25393
25610
  accountId,
25394
- scriptName
25611
+ scriptName,
25612
+ dispatchNamespace: props.dispatchNamespace
25395
25613
  });
25396
25614
  }
25615
+ if (!skipContainerChanges && getDurableObjectContainerApps(config2.containers).length > 0 && callbacks.deployDurableObjectContainerApplications) {
25616
+ assert4(versionId && accountId);
25617
+ try {
25618
+ await callbacks.deployDurableObjectContainerApplications(config2, {
25619
+ versionId,
25620
+ accountId,
25621
+ scriptName,
25622
+ dispatchNamespace: props.dispatchNamespace
25623
+ });
25624
+ } catch (error51) {
25625
+ throw new UserError(
25626
+ "The Worker version was deployed, but Wrangler could not finish creating its Durable Object-managed Container applications. Re-run the same `wrangler deploy` command to retry the idempotent application creation and finish deployment.",
25627
+ {
25628
+ telemetryMessage: "deploy durable object container application creation failed after deployment",
25629
+ cause: error51
25630
+ }
25631
+ );
25632
+ }
25633
+ }
25397
25634
  if (props.dispatchNamespace !== void 0) {
25398
25635
  deployWfpUserWorker(props.dispatchNamespace, versionId);
25399
25636
  return { versionId, workerTag, assetUploadStats, bundleSize };
@@ -25462,7 +25699,10 @@ async function uploadWorkerVersion(props, config2, buildResult, callbacks) {
25462
25699
  const { entry, compatibilityDate, compatibilityFlags, keepVars, accountId } = props;
25463
25700
  const assetsOptions = resolveAssetOptions(props, config2);
25464
25701
  const { name } = validateWorkerProps(props, config2);
25465
- const { workerTag, tags, aborted: aborted2 } = await preUploadApiChecks(props, config2);
25702
+ const { workerTag, tags, workerExists, aborted: aborted2 } = await preUploadApiChecks(
25703
+ props,
25704
+ config2
25705
+ );
25466
25706
  if (aborted2) {
25467
25707
  return { versionId: null, workerTag };
25468
25708
  }
@@ -25496,6 +25736,16 @@ async function uploadWorkerVersion(props, config2, buildResult, callbacks) {
25496
25736
  config: config2,
25497
25737
  dispatchNamespace: void 0
25498
25738
  });
25739
+ if (migrations !== void 0) {
25740
+ throw new UserError(
25741
+ "This Worker has a pending Durable Object migration, which cannot be applied by `wrangler versions upload`. Durable Object migrations must be applied with `wrangler deploy`. Run `wrangler deploy` to apply the migration, then retry `wrangler versions upload`.",
25742
+ { telemetryMessage: "versions upload pending durable object migration" }
25743
+ );
25744
+ }
25745
+ const preparedContainerImages = await callbacks.prepareDurableObjectContainerApplications?.(config2, {
25746
+ dryRun: Boolean(props.dryRun),
25747
+ scriptName
25748
+ });
25499
25749
  const assetsUploadResult = assetsOptions && !props.dryRun ? await syncAssets(config2, accountId, assetsOptions.directory, scriptName) : void 0;
25500
25750
  const assetsJwt = assetsUploadResult?.jwt;
25501
25751
  if (props.secretsFile) {
@@ -25512,6 +25762,10 @@ async function uploadWorkerVersion(props, config2, buildResult, callbacks) {
25512
25762
  }
25513
25763
  }
25514
25764
  addRequiredSecretsInheritBindings(config2, bindings, { type: "upload" });
25765
+ if (keepVars && !props.dryRun && workerExists) {
25766
+ await clearRemovedContainerImagesBindings(config2, bindings, workerUrl);
25767
+ }
25768
+ addContainerImagesBinding(config2, bindings, preparedContainerImages ?? {});
25515
25769
  const placement = parseConfigPlacement(config2);
25516
25770
  const entryPointName = path__default.basename(resolvedEntryPointPath);
25517
25771
  const main = {
@@ -25526,7 +25780,7 @@ async function uploadWorkerVersion(props, config2, buildResult, callbacks) {
25526
25780
  migrations,
25527
25781
  exports: exports$1,
25528
25782
  modules,
25529
- containers: config2.containers,
25783
+ containers: getContainerMetadata(config2, preparedContainerImages),
25530
25784
  sourceMaps,
25531
25785
  compatibility_date: compatibilityDate,
25532
25786
  compatibility_flags: compatibilityFlags,
@@ -25690,6 +25944,14 @@ async function uploadWorkerVersion(props, config2, buildResult, callbacks) {
25690
25944
  return { versionId, workerTag, bundleSize };
25691
25945
  }
25692
25946
  assert4(accountId);
25947
+ if (!hasDurableObjectExports(config2.exports) && getDurableObjectContainerApps(config2.containers).length > 0 && callbacks.deployDurableObjectContainerApplications) {
25948
+ assert4(versionId);
25949
+ await callbacks.deployDurableObjectContainerApplications(config2, {
25950
+ versionId,
25951
+ accountId,
25952
+ scriptName
25953
+ });
25954
+ }
25693
25955
  const uploadMs = Date.now() - start;
25694
25956
  logger.log("Uploaded", workerName, formatTime(uploadMs));
25695
25957
  logger.log("Worker Version ID:", versionId);
@@ -25958,27 +26220,6 @@ async function patchPreviewDeployment(config2, accountId, workerName, previewIde
25958
26220
  );
25959
26221
  }
25960
26222
  __name(patchPreviewDeployment, "patchPreviewDeployment");
25961
- async function getWorkerPreviewDefaults(config2, accountId, workerName) {
25962
- const worker = await fetchResult(
25963
- config2,
25964
- `/accounts/${accountId}/workers/workers/${workerName}`
25965
- );
25966
- return worker.preview_defaults ?? {};
25967
- }
25968
- __name(getWorkerPreviewDefaults, "getWorkerPreviewDefaults");
25969
- async function editWorkerPreviewDefaults(config2, accountId, workerName, previewDefaults) {
25970
- const worker = await fetchResult(
25971
- config2,
25972
- `/accounts/${accountId}/workers/workers/${workerName}`,
25973
- {
25974
- method: "PATCH",
25975
- headers: { "Content-Type": "application/json" },
25976
- body: JSON.stringify({ preview_defaults: previewDefaults })
25977
- }
25978
- );
25979
- return worker.preview_defaults ?? {};
25980
- }
25981
- __name(editWorkerPreviewDefaults, "editWorkerPreviewDefaults");
25982
26223
  async function getPreviewBaseConfig(config2, accountId, workerName) {
25983
26224
  const worker = await fetchResult(
25984
26225
  config2,
@@ -26478,27 +26719,6 @@ function assemblePreviewScriptSettings(config2) {
26478
26719
  return result;
26479
26720
  }
26480
26721
  __name(assemblePreviewScriptSettings, "assemblePreviewScriptSettings");
26481
- function assemblePreviewDefaults(config2) {
26482
- const previews = config2.previews;
26483
- const previewDefaults = {
26484
- ...assemblePreviewScriptSettings(config2)
26485
- };
26486
- const previewEnv = extractConfigBindings(config2);
26487
- if (Object.keys(previewEnv).length > 0) {
26488
- previewDefaults.env = previewEnv;
26489
- }
26490
- if (previews?.limits || config2.limits) {
26491
- previewDefaults.limits = previews?.limits ?? config2.limits;
26492
- }
26493
- if (previews?.cache !== void 0 || config2.cache !== void 0) {
26494
- previewDefaults.cache = previews?.cache ?? config2.cache;
26495
- }
26496
- if (config2.placement) {
26497
- previewDefaults.placement = parseConfigPlacement(config2);
26498
- }
26499
- return previewDefaults;
26500
- }
26501
- __name(assemblePreviewDefaults, "assemblePreviewDefaults");
26502
26722
  function buildPreviewContainerConfig(config2, parentWorkerName, previewSlug, previewContainers) {
26503
26723
  const previews = config2.previews;
26504
26724
  const previewDOBindings = previews?.durable_objects?.bindings ?? [];
@@ -26973,14 +27193,14 @@ async function preview(accountId, args, config2, buildResult, assetsOptions, cal
26973
27193
  );
26974
27194
  const topLevelBindings = getBindings(config2);
26975
27195
  if (Object.keys(topLevelBindings).length > 0) {
26976
- const previewDefaults = await getWorkerPreviewDefaults(
27196
+ const previewBaseConfig = await getPreviewBaseConfig(
26977
27197
  config2,
26978
27198
  accountId,
26979
27199
  workerName
26980
27200
  );
26981
27201
  logMissingPreviewsBindingsWarning(
26982
27202
  topLevelBindings,
26983
- previewDefaults.env,
27203
+ previewBaseConfig.env,
26984
27204
  extractConfigBindings(config2)
26985
27205
  );
26986
27206
  }
@@ -27145,159 +27365,6 @@ function formatBindings(env, indent = " ", options = {}) {
27145
27365
  });
27146
27366
  }
27147
27367
  __name(formatBindings, "formatBindings");
27148
- function formatPreviewsSettings(workerName, previewDefaults) {
27149
- const lines = [];
27150
- lines.push(`${chalk6.bold.hex("#FFA500")("Worker:")} ${workerName}`);
27151
- lines.push("");
27152
- lines.push(` ${chalk6.bold.underline("Previews settings")}`);
27153
- lines.push("");
27154
- const settingsRows = [];
27155
- if (previewDefaults.observability && typeof previewDefaults.observability === "object") {
27156
- const enabledLabel = previewDefaults.observability.enabled ? "enabled" : "disabled";
27157
- const sampling = typeof previewDefaults.observability.head_sampling_rate === "number" ? `, ${previewDefaults.observability.head_sampling_rate.toFixed(
27158
- 1
27159
- )} sampling` : "";
27160
- settingsRows.push(["observability", `${enabledLabel}${sampling}`]);
27161
- }
27162
- if (typeof previewDefaults.logpush === "boolean") {
27163
- settingsRows.push([
27164
- "logpush",
27165
- previewDefaults.logpush ? "enabled" : "disabled"
27166
- ]);
27167
- }
27168
- if (typeof previewDefaults.limits?.cpu_ms === "number" || typeof previewDefaults.limits?.subrequests === "number") {
27169
- const limitParts = [
27170
- typeof previewDefaults.limits?.cpu_ms === "number" ? `cpu_ms: ${previewDefaults.limits.cpu_ms}` : void 0,
27171
- typeof previewDefaults.limits?.subrequests === "number" ? `subrequests: ${previewDefaults.limits.subrequests}` : void 0
27172
- ].filter((value) => value !== void 0);
27173
- settingsRows.push(["limits", limitParts.join(", ")]);
27174
- }
27175
- if (typeof previewDefaults.placement?.mode === "string") {
27176
- settingsRows.push(["placement", previewDefaults.placement.mode]);
27177
- }
27178
- if (previewDefaults.cache !== void 0) {
27179
- settingsRows.push([
27180
- "cache",
27181
- previewDefaults.cache.enabled ? "enabled" : "disabled"
27182
- ]);
27183
- }
27184
- if (settingsRows.length > 0) {
27185
- const labelWidth = Math.max(...settingsRows.map(([label]) => label.length));
27186
- for (const [label, value] of settingsRows) {
27187
- lines.push(
27188
- ` ${chalk6.cyan(padToVisibleWidth(label, labelWidth))} ${value}`
27189
- );
27190
- }
27191
- }
27192
- lines.push("");
27193
- lines.push(chalk6.bold(" Bindings"));
27194
- const env = Object.fromEntries(
27195
- Object.entries(previewDefaults.env ?? {}).map(([name, binding]) => [
27196
- name,
27197
- { ...binding, fromConfig: false }
27198
- ])
27199
- );
27200
- lines.push(...formatBindings(env));
27201
- lines.push("");
27202
- return drawBox(lines);
27203
- }
27204
- __name(formatPreviewsSettings, "formatPreviewsSettings");
27205
-
27206
- // src/preview/merge-deep.ts
27207
- function mergeDeep(target, source) {
27208
- if (typeof target !== "object" || target === null) {
27209
- return source;
27210
- }
27211
- if (typeof source !== "object" || source === null) {
27212
- return target;
27213
- }
27214
- const result = { ...target };
27215
- for (const key of Object.keys(source)) {
27216
- const srcVal = source[key];
27217
- const tgtVal = target[key];
27218
- if (isObject2(tgtVal) && isObject2(srcVal)) {
27219
- result[key] = mergeDeep(tgtVal, srcVal);
27220
- } else {
27221
- result[key] = srcVal;
27222
- }
27223
- }
27224
- return result;
27225
- }
27226
- __name(mergeDeep, "mergeDeep");
27227
- function isObject2(value) {
27228
- return typeof value === "object" && value !== null && !Array.isArray(value);
27229
- }
27230
- __name(isObject2, "isObject");
27231
- async function previewSettingsGet(accountId, args, config2) {
27232
- const workerName = resolveWorkerName(args, config2);
27233
- const previewDefaults = await getWorkerPreviewDefaults(
27234
- config2,
27235
- accountId,
27236
- workerName
27237
- );
27238
- if (args.json) {
27239
- logger.log(JSON.stringify(previewDefaults, null, 2));
27240
- return;
27241
- }
27242
- logger.log(formatPreviewsSettings(workerName, previewDefaults));
27243
- }
27244
- __name(previewSettingsGet, "previewSettingsGet");
27245
- async function previewSettingsUpdate(accountId, args, config2) {
27246
- const workerName = resolveWorkerName(args, config2);
27247
- const currentPreviewDefaults = await getWorkerPreviewDefaults(
27248
- config2,
27249
- accountId,
27250
- workerName
27251
- );
27252
- const resolvedConfigFileSettings = assemblePreviewDefaults(config2);
27253
- const requestPayloadPreviewDefaults = mergeDeep(
27254
- currentPreviewDefaults,
27255
- resolvedConfigFileSettings
27256
- );
27257
- if (currentPreviewDefaults.env !== void 0 || resolvedConfigFileSettings.env !== void 0) {
27258
- requestPayloadPreviewDefaults.env = {
27259
- ...currentPreviewDefaults.env,
27260
- ...resolvedConfigFileSettings.env
27261
- };
27262
- }
27263
- const diff = diffJsonObjects(
27264
- currentPreviewDefaults,
27265
- requestPayloadPreviewDefaults
27266
- );
27267
- if (!diff) {
27268
- logger.log(
27269
- `
27270
- \u2728 Previews settings for Worker ${chalk6.bold.cyan(
27271
- workerName
27272
- )} are already up to date.`
27273
- );
27274
- return;
27275
- }
27276
- logger.log(`${diff}`);
27277
- if (!args.skipConfirmation) {
27278
- const shouldProceed = await confirm(
27279
- `Apply these updates to the Previews settings of Worker ${chalk6.bold.cyan(
27280
- workerName
27281
- )}?`
27282
- );
27283
- if (!shouldProceed) {
27284
- logger.log("Aborted.");
27285
- return;
27286
- }
27287
- }
27288
- const updatedPreviewDefaults = await editWorkerPreviewDefaults(
27289
- config2,
27290
- accountId,
27291
- workerName,
27292
- requestPayloadPreviewDefaults
27293
- );
27294
- logger.log(
27295
- `
27296
- \u2728 Updated Previews settings for Worker ${chalk6.bold.cyan(workerName)}.`
27297
- );
27298
- logger.log(formatPreviewsSettings(workerName, updatedPreviewDefaults));
27299
- }
27300
- __name(previewSettingsUpdate, "previewSettingsUpdate");
27301
27368
  /*!
27302
27369
  * Copyright (c) 2011 Felix Geisendörfer (felix@debuggable.com)
27303
27370
  *
@@ -27320,4 +27387,4 @@ __name(previewSettingsUpdate, "previewSettingsUpdate");
27320
27387
  * THE SOFTWARE.
27321
27388
  */
27322
27389
 
27323
- export { ACTOR_BINDING_DEPENDS_ON_EXPORT_CODE, EXPORTS_RECONCILIATION_ERROR_CODE, INCONSISTENT_EXPORTS_ACROSS_VERSIONS_CODE, INVALID_INHERIT_BINDING_CODE, NO_ACTIVE_PREVIEW_URLS_MESSAGE, NoInputError, WORKER_LEGACY_ENVIRONMENT_NOT_FOUND_ERR_CODE, WORKER_NOT_FOUND_ERR_CODE, WORKFLOW_CRON_REQUIRES_PAID_PLAN_CODE, WORKFLOW_NOT_FOUND_CODE, addRequiredSecretsInheritBindings, addWorkersSitesBindings, applyServiceAndEnvironmentTags, assemblePreviewDefaults, assemblePreviewScriptSettings, buildAssetManifest, checkRemoteSecretsOverride, checkWorkflowConflicts, collectPackageDependencies, confirmLatestDeploymentOverwrite, createDeployment, createPreview, createPreviewDeployment, createPreviewDeploymentForm, createPreviewParentWorker, createTruncatedAlias, decodeJwtPayload, deletePreview, deletePullConsumer, deleteWorkerConsumer, deploy, deployWfpUserWorker, diagnoseScriptSizeError, diagnoseStartupError, diffJsonObjects, downloadWorkerConfig, drawBox, drawConnectedChildBox, editPreview, editWorkerPreviewDefaults, ensureQueuesExistByConfig, extractConfigBindings, fetchDeployableVersions, fetchDeploymentVersions, fetchLatestDeployment, fetchLatestDeployments, fetchSecrets, fetchVersion, fetchVersions, fetchWorkerConfig, formatAlignedRows, formatBindings, formatPreviewsSettings, generatePreviewAlias, getBindingValue, getBranchName2 as getBranchName, getCommitSha, getConfigPatch, getDeployConfirmFunction, getEdgeKvUploadConcurrency, getHeadCommitMessage, getHeadCommitRef, getMigrationsToUpload, getPreview, getPreviewBaseConfig, getPreviewDeployment, getPreviewOwnedContainerClassNames, getPullRequestMetadata, getQueue, getRemoteConfigDiff, getRepositoryUrl, getSettings, getSize, getSourceMappedStack, getSourceMappedString, getSubdomainValues, getSubdomainValuesAPIMock, getWorkerPreviewDefaults, getWorkersDevSubdomain, getZoneForRoute, getZoneIdFromHost, handleMissingSecretsError, hasDefinedEnvironments, hashFile, helpIfErrorIsSizeOrScriptStartup, isExportsReconciliationErrorDetails, isJwtExpired, isModifiedDiffValue, isNonDestructive, isWorkerNotFoundError, listConsumers, listQueues, maybeRetrieveFileSourceMap, mergeDeep, padToVisibleWidth, parseBulkInputToObject, parseConfigPlacement, patchNonVersionedScriptSettings, patchPreviewBaseConfig, patchPreviewDeployment, postConsumer, preview, previewContainerAppName, previewDelete, previewSettingsGet, previewSettingsUpdate, printBundleSize, printVersions, provisionBindings, publishCustomDomains, publishRoutes, putConsumer, putConsumerById, renderBindingDependsOnExportError, renderExportsReconciliationError, renderExportsReconciliationSuccess, renderInconsistentExportsAcrossVersionsError, renderRoute, resolveAssetOptions, resolveDoLifecyclePayload, resolveExportsUploadPayload, resolveWorkerName, sanitizeBranchName, shouldUseCIMetadataFallback, stripAnsi, syncAssets, tagsAreEqual, triggersDeploy, updateQueueConsumers, validateEventTriggerTargets, validateFileSecrets, validateNodeCompatMode, validateRoutes, verifyWorkerMatchesCITag, versionsUpload, visibleLength, warnOnErrorUpdatingServiceAndEnvironmentTags, workerNotFoundErrorMessage };
27390
+ export { ACTOR_BINDING_DEPENDS_ON_EXPORT_CODE, EXPORTS_RECONCILIATION_ERROR_CODE, INCONSISTENT_EXPORTS_ACROSS_VERSIONS_CODE, INVALID_INHERIT_BINDING_CODE, NO_ACTIVE_PREVIEW_URLS_MESSAGE, NoInputError, WORKER_LEGACY_ENVIRONMENT_NOT_FOUND_ERR_CODE, WORKER_NOT_FOUND_ERR_CODE, WORKFLOW_CRON_REQUIRES_PAID_PLAN_CODE, WORKFLOW_NOT_FOUND_CODE, addRequiredSecretsInheritBindings, addWorkersSitesBindings, applyServiceAndEnvironmentTags, assemblePreviewScriptSettings, buildAssetManifest, checkRemoteSecretsOverride, checkWorkflowConflicts, collectPackageDependencies, confirmLatestDeploymentOverwrite, createDeployment, createPreview, createPreviewDeployment, createPreviewDeploymentForm, createPreviewParentWorker, createTruncatedAlias, decodeJwtPayload, deletePreview, deletePullConsumer, deleteWorkerConsumer, deploy, deployWfpUserWorker, diagnoseScriptSizeError, diagnoseStartupError, diffJsonObjects, downloadWorkerConfig, drawBox, drawConnectedChildBox, editPreview, ensureQueuesExistByConfig, extractConfigBindings, fetchDeployableVersions, fetchDeploymentVersions, fetchLatestDeployment, fetchLatestDeployments, fetchSecrets, fetchVersion, fetchVersions, fetchWorkerConfig, formatAlignedRows, formatBindings, generatePreviewAlias, getBindingValue, getBranchName2 as getBranchName, getCommitSha, getConfigPatch, getDeployConfirmFunction, getEdgeKvUploadConcurrency, getHeadCommitMessage, getHeadCommitRef, getMigrationsToUpload, getPreview, getPreviewBaseConfig, getPreviewDeployment, getPreviewOwnedContainerClassNames, getPullRequestMetadata, getQueue, getRemoteConfigDiff, getRepositoryUrl, getSettings, getSize, getSourceMappedStack, getSourceMappedString, getSubdomainValues, getSubdomainValuesAPIMock, getWorkersDevSubdomain, getZoneForRoute, getZoneIdFromHost, handleMissingSecretsError, hasDefinedEnvironments, hashFile, helpIfErrorIsSizeOrScriptStartup, isExportsReconciliationErrorDetails, isJwtExpired, isModifiedDiffValue, isNonDestructive, isWorkerNotFoundError, listConsumers, listQueues, maybeRetrieveFileSourceMap, padToVisibleWidth, parseBulkInputToObject, parseConfigPlacement, patchNonVersionedScriptSettings, patchPreviewBaseConfig, patchPreviewDeployment, postConsumer, preview, previewContainerAppName, previewDelete, printBundleSize, printVersions, provisionBindings, publishCustomDomains, publishRoutes, putConsumer, putConsumerById, renderBindingDependsOnExportError, renderExportsReconciliationError, renderExportsReconciliationSuccess, renderInconsistentExportsAcrossVersionsError, renderRoute, resolveAssetOptions, resolveDoLifecyclePayload, resolveExportsUploadPayload, resolveWorkerName, sanitizeBranchName, shouldUseCIMetadataFallback, stripAnsi, syncAssets, tagsAreEqual, triggersDeploy, updateQueueConsumers, validateEventTriggerTargets, validateFileSecrets, validateNodeCompatMode, validateRoutes, verifyWorkerMatchesCITag, versionsUpload, visibleLength, warnOnErrorUpdatingServiceAndEnvironmentTags, workerNotFoundErrorMessage };