@cloudflare/deploy-helpers 0.12.1 → 0.13.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.d.mts CHANGED
@@ -7,6 +7,7 @@ export { createWorkerUploadForm, fromMimeType, moduleTypeMimeType } from './crea
7
7
  import { Options } from '@cspotcode/source-map-support';
8
8
  import Protocol from 'devtools-protocol';
9
9
  import { NodeJSCompatMode } from 'miniflare';
10
+ import { ParsedOutputWorkerConfig, ParsedOutputSettingsConfig } from '@cloudflare/config';
10
11
  import { ContainerNormalizedConfig } from '@cloudflare/containers-shared';
11
12
 
12
13
  interface BundleSize {
@@ -885,6 +886,7 @@ interface Binding {
885
886
  id?: string;
886
887
  service?: string;
887
888
  environment?: string;
889
+ props?: Record<string, unknown>;
888
890
  cross_account_grant?: string;
889
891
  dataset?: string;
890
892
  namespace?: string;
@@ -907,6 +909,9 @@ interface Binding {
907
909
  period: 10 | 60;
908
910
  };
909
911
  service_id?: string;
912
+ tunnel_id?: string;
913
+ network_id?: string;
914
+ destination?: string;
910
915
  staging?: boolean;
911
916
  enable_timer?: boolean;
912
917
  app_id?: string;
@@ -1086,6 +1091,7 @@ declare function resolveWorkerName(args: {
1086
1091
  */
1087
1092
  declare function getBindingValue(binding: Binding): string;
1088
1093
  declare function extractConfigBindings(config: Config): EnvBindings;
1094
+ declare function extractBuildOutputBindings(config: RawConfig): EnvBindings;
1089
1095
  /**
1090
1096
  * Returns the DO `class_name`s whose containers this preview owns: the classes
1091
1097
  * the script declares through `migrations` or `exports`, plus the classes bound
@@ -1113,7 +1119,7 @@ declare function getPreviewOwnedContainerClassNames(config: Config, previews: Pr
1113
1119
  * of the composed name.
1114
1120
  */
1115
1121
  declare function previewContainerAppName(parentWorkerName: string, previewSlug: string, className: string): string;
1116
- declare function assemblePreviewScriptSettings(config: Config): Record<string, unknown>;
1122
+ declare function assemblePreviewScriptSettings(config: Config): UpdatePreviewRequestParams;
1117
1123
 
1118
1124
  type PreviewArgs = {
1119
1125
  script?: string;
@@ -1149,6 +1155,17 @@ type PreviewResult = {
1149
1155
  deployment: DeploymentResource;
1150
1156
  isNewPreview: boolean;
1151
1157
  };
1158
+ type PreviewBuildOutputSettings = ParsedOutputSettingsConfig & {
1159
+ isPreview: true;
1160
+ };
1161
+ type PreviewBuildOutput = {
1162
+ workerConfig: ParsedOutputWorkerConfig;
1163
+ projectSettings: PreviewBuildOutputSettings;
1164
+ buildResult?: WorkerBuildResult;
1165
+ assets?: Pick<PreviewAssetsOptions, "directory" | "_headers" | "_redirects">;
1166
+ };
1167
+ /** Verify that Build Output was produced with Preview configuration. */
1168
+ declare function assertPreviewBuildOutputSettings(settings: ParsedOutputSettingsConfig | undefined): asserts settings is PreviewBuildOutputSettings;
1152
1169
  type PreviewCallbacks = {
1153
1170
  productionBindingsExpectedInPreview?: Record<string, {
1154
1171
  type: string;
@@ -1165,10 +1182,27 @@ type PreviewCallbacks = {
1165
1182
  declare const NO_ACTIVE_PREVIEW_URLS_MESSAGE = "Note: This Preview deployment has no active URLs.";
1166
1183
  declare function formatNoActivePreviewUrlsMessage(config: Config): string;
1167
1184
  /**
1168
- * Full preview create/update + deployment orchestration.
1169
- * The wrangler handler calls this after auth + build.
1185
+ * Upload a Preview from Wrangler configuration.
1186
+ *
1187
+ * Wrangler resolves its Worker name from CLI and config precedence before
1188
+ * entering the shared upload flow. Build Output already contains its final name.
1189
+ *
1190
+ * @param accountId Account that owns the parent Worker.
1191
+ * @param args Wrangler Preview arguments.
1192
+ * @param config Resolved Wrangler configuration.
1193
+ * @param buildResult Compiled Worker code and modules.
1194
+ * @param assetsOptions Static asset configuration and artifacts.
1195
+ * @param callbacks Wrangler container integrations.
1170
1196
  */
1171
1197
  declare function preview(accountId: string, args: PreviewArgs, config: Config, buildResult: WorkerBuildResult, assetsOptions: PreviewAssetsOptions | undefined, callbacks: PreviewCallbacks): Promise<PreviewResult>;
1198
+ /**
1199
+ * Upload a Preview from resolved Build Output configuration.
1200
+ *
1201
+ * @param accountId Account that owns the parent Worker.
1202
+ * @param args Preview name and deployment annotations.
1203
+ * @param buildOutput Exact configuration and artifacts emitted by the build.
1204
+ */
1205
+ declare function previewBuildOutput(accountId: string, args: Pick<PreviewArgs, "name" | "tag" | "message" | "json">, buildOutput: PreviewBuildOutput): Promise<PreviewResult>;
1172
1206
  /**
1173
1207
  * Delete a preview and all its deployments.
1174
1208
  */
@@ -1222,4 +1256,4 @@ type DrawConnectedChildBoxOptions = {
1222
1256
  */
1223
1257
  declare function drawConnectedChildBox(contentLines: string[], options?: DrawConnectedChildBoxOptions): string;
1224
1258
 
1225
- export { ACTOR_BINDING_DEPENDS_ON_EXPORT_CODE, type ApiDeployment, type ApiVersion, type AssetManifest, type AssetUploadStats, type AssetsUploadResult, type Binding, BuiltDurableObjectContainerImage, type BulkInputNullableResult, type BulkInputResult, type BundleSize, type Consumer, type ConsumerSettings, ContainerlessConfig, type CreatePreviewDeploymentRequestParams, type CreatePreviewRequestParams, type CustomDomain, type CustomDomainChangeset, type DeployCallbacks, DeployProps, type DeploymentResource, type DurableObjectContainerApplication, EXPORTS_RECONCILIATION_ERROR_CODE, type EnvBindings, INCONSISTENT_EXPORTS_ACROSS_VERSIONS_CODE, INVALID_INHERIT_BINDING_CODE, type JsonLike, NO_ACTIVE_PREVIEW_URLS_MESSAGE, NoInputError, type NonVersionedScriptSettings, PREVIEW_DOMAIN_PROVISIONING_NOTE, type PackageDependency, type Percentage, type PostQueueBody, type PostQueueResponse, type PostTypedConsumerBody, type PreparedContainerImages, type PreviewArgs, type PreviewAssetsOptions, type PreviewBaseConfig, type PreviewBaseConfigPatch, type PreviewCallbacks, type PreviewDeleteArgs, type PreviewDeploymentModule, type PreviewRequestOptions, type PreviewResource, type PreviewResult, type Producer, type ProvisionBindingsResult, type PullRequestMetadata, type PurgeQueueBody, type PurgeQueueResponse, type QueueResponse, type QueueSettings, type RetrieveSourceMapFunction, type RouteObject, type ScriptReference, type Settings, SharedDeployVersionsProps, TriggerDeployment, TriggerProps, type TypedConsumerResponse, type UpdatePreviewRequestParams, type VersionCache, type VersionId, type VersionedDurableObjectContainerApplication, type VersionsUploadCallbacks, VersionsUploadProps, WORKER_LEGACY_ENVIRONMENT_NOT_FOUND_ERR_CODE, WORKER_NOT_FOUND_ERR_CODE, WORKFLOW_CRON_REQUIRES_PAID_PLAN_CODE, WORKFLOW_NOT_FOUND_CODE, WorkerBuildResult, type Workflow, type WorkflowConflict, type Zone, type ZoneIdCache, addRequiredSecretsInheritBindings, addWorkersSitesBindings, applyServiceAndEnvironmentTags, assemblePreviewScriptSettings, buildAssetManifest, checkRemoteSecretsOverride, checkWorkflowConflicts, collectPackageDependencies, confirmLatestDeploymentOverwrite, createDeployment, createDurableObjectContainerApplication, createPreview, createPreviewDeployment, createPreviewDeploymentForm, createPreviewParentWorker, createTruncatedAlias, decodeJwtPayload, deletePreview, deletePullConsumer, deleteWorkerConsumer, deploy, deployDurableObjectContainerApplications, deployVersionedDurableObjectContainerApplications, deployWfpUserWorker, diagnoseScriptSizeError, diagnoseStartupError, diffJsonObjects, downloadWorkerConfig, drawBox, drawConnectedChildBox, editPreview, ensureQueuesExistByConfig, extractConfigBindings, fetchDeployableVersions, fetchDeploymentVersions, fetchLatestDeployment, fetchLatestDeployments, fetchSecrets, fetchVersion, fetchVersions, fetchWorkerConfig, formatAlignedRows, formatBindings, formatNoActivePreviewUrlsMessage, generatePreviewAlias, getBindingValue, getBranchName, getCommitSha, getConfigPatch, getDeployConfirmFunction, getEdgeKvUploadConcurrency, getHeadCommitMessage, getHeadCommitRef, getMigrationsToUpload, getPreview, getPreviewBaseConfig, getPreviewDeployment, getPreviewOwnedContainerClassNames, getPullRequestMetadata, getQueue, getRemoteConfigDiff, getRepositoryUrl, getSettings, getSize, getSourceMappedStack, getSourceMappedString, getSubdomainValues, getSubdomainValuesAPIMock, getVersionedDurableObjectContainerApplications, getWorkersDevSubdomain, getZoneForRoute, getZoneIdFromHost, handleMissingSecretsError, handleUnsafeCapnp, hasDefinedEnvironments, hashFile, helpIfErrorIsSizeOrScriptStartup, isExportsReconciliationErrorDetails, isJwtExpired, isModifiedDiffValue, isNonDestructive, isWorkerNotFoundError, listConsumers, listQueues, maybeRetrieveFileSourceMap, padToVisibleWidth, parseBulkInputToObject, parseConfigPlacement, patchNonVersionedScriptSettings, patchPreviewBaseConfig, patchPreviewDeployment, postConsumer, prepareDurableObjectContainerApplications, preview, previewContainerAppName, previewDelete, printBundleSize, printVersions, provisionBindings, publishCustomDomains, publishRoutes, putConsumer, putConsumerById, renderBindingDependsOnExportError, renderExportsReconciliationError, renderExportsReconciliationSuccess, renderInconsistentExportsAcrossVersionsError, renderRoute, resolveAssetOptions, resolveDoLifecyclePayload, resolveExportsUploadPayload, resolveVersionedDurableObjectContainerApplications, resolveWorkerName, sanitizeBranchName, shouldUseCIMetadataFallback, stripAnsi, syncAssets, tagsAreEqual, triggersDeploy, updateQueueConsumers, validateEventTriggerTargets, validateFileSecrets, validateNodeCompatMode, validateRoutes, verifyWorkerMatchesCITag, versionsUpload, visibleLength, warnOnErrorUpdatingServiceAndEnvironmentTags, workerNotFoundErrorMessage };
1259
+ export { ACTOR_BINDING_DEPENDS_ON_EXPORT_CODE, type ApiDeployment, type ApiVersion, type AssetManifest, type AssetUploadStats, type AssetsUploadResult, type Binding, BuiltDurableObjectContainerImage, type BulkInputNullableResult, type BulkInputResult, type BundleSize, type Consumer, type ConsumerSettings, ContainerlessConfig, type CreatePreviewDeploymentRequestParams, type CreatePreviewRequestParams, type CustomDomain, type CustomDomainChangeset, type DeployCallbacks, DeployProps, type DeploymentResource, type DurableObjectContainerApplication, EXPORTS_RECONCILIATION_ERROR_CODE, type EnvBindings, INCONSISTENT_EXPORTS_ACROSS_VERSIONS_CODE, INVALID_INHERIT_BINDING_CODE, type JsonLike, NO_ACTIVE_PREVIEW_URLS_MESSAGE, NoInputError, type NonVersionedScriptSettings, PREVIEW_DOMAIN_PROVISIONING_NOTE, type PackageDependency, type Percentage, type PostQueueBody, type PostQueueResponse, type PostTypedConsumerBody, type PreparedContainerImages, type PreviewArgs, type PreviewAssetsOptions, type PreviewBaseConfig, type PreviewBaseConfigPatch, type PreviewBuildOutput, type PreviewBuildOutputSettings, type PreviewCallbacks, type PreviewDeleteArgs, type PreviewDeploymentModule, type PreviewRequestOptions, type PreviewResource, type PreviewResult, type Producer, type ProvisionBindingsResult, type PullRequestMetadata, type PurgeQueueBody, type PurgeQueueResponse, type QueueResponse, type QueueSettings, type RetrieveSourceMapFunction, type RouteObject, type ScriptReference, type Settings, SharedDeployVersionsProps, TriggerDeployment, TriggerProps, type TypedConsumerResponse, type UpdatePreviewRequestParams, type VersionCache, type VersionId, type VersionedDurableObjectContainerApplication, type VersionsUploadCallbacks, VersionsUploadProps, WORKER_LEGACY_ENVIRONMENT_NOT_FOUND_ERR_CODE, WORKER_NOT_FOUND_ERR_CODE, WORKFLOW_CRON_REQUIRES_PAID_PLAN_CODE, WORKFLOW_NOT_FOUND_CODE, WorkerBuildResult, type Workflow, type WorkflowConflict, type Zone, type ZoneIdCache, addRequiredSecretsInheritBindings, addWorkersSitesBindings, applyServiceAndEnvironmentTags, assemblePreviewScriptSettings, assertPreviewBuildOutputSettings, buildAssetManifest, checkRemoteSecretsOverride, checkWorkflowConflicts, collectPackageDependencies, confirmLatestDeploymentOverwrite, createDeployment, createDurableObjectContainerApplication, createPreview, createPreviewDeployment, createPreviewDeploymentForm, createPreviewParentWorker, createTruncatedAlias, decodeJwtPayload, deletePreview, deletePullConsumer, deleteWorkerConsumer, deploy, deployDurableObjectContainerApplications, deployVersionedDurableObjectContainerApplications, deployWfpUserWorker, diagnoseScriptSizeError, diagnoseStartupError, diffJsonObjects, downloadWorkerConfig, drawBox, drawConnectedChildBox, editPreview, ensureQueuesExistByConfig, extractBuildOutputBindings, extractConfigBindings, fetchDeployableVersions, fetchDeploymentVersions, fetchLatestDeployment, fetchLatestDeployments, fetchSecrets, fetchVersion, fetchVersions, fetchWorkerConfig, formatAlignedRows, formatBindings, formatNoActivePreviewUrlsMessage, generatePreviewAlias, getBindingValue, getBranchName, getCommitSha, getConfigPatch, getDeployConfirmFunction, getEdgeKvUploadConcurrency, getHeadCommitMessage, getHeadCommitRef, getMigrationsToUpload, getPreview, getPreviewBaseConfig, getPreviewDeployment, getPreviewOwnedContainerClassNames, getPullRequestMetadata, getQueue, getRemoteConfigDiff, getRepositoryUrl, getSettings, getSize, getSourceMappedStack, getSourceMappedString, getSubdomainValues, getSubdomainValuesAPIMock, getVersionedDurableObjectContainerApplications, getWorkersDevSubdomain, getZoneForRoute, getZoneIdFromHost, handleMissingSecretsError, handleUnsafeCapnp, hasDefinedEnvironments, hashFile, helpIfErrorIsSizeOrScriptStartup, isExportsReconciliationErrorDetails, isJwtExpired, isModifiedDiffValue, isNonDestructive, isWorkerNotFoundError, listConsumers, listQueues, maybeRetrieveFileSourceMap, padToVisibleWidth, parseBulkInputToObject, parseConfigPlacement, patchNonVersionedScriptSettings, patchPreviewBaseConfig, patchPreviewDeployment, postConsumer, prepareDurableObjectContainerApplications, preview, previewBuildOutput, previewContainerAppName, previewDelete, printBundleSize, printVersions, provisionBindings, publishCustomDomains, publishRoutes, putConsumer, putConsumerById, renderBindingDependsOnExportError, renderExportsReconciliationError, renderExportsReconciliationSuccess, renderInconsistentExportsAcrossVersionsError, renderRoute, resolveAssetOptions, resolveDoLifecyclePayload, resolveExportsUploadPayload, resolveVersionedDurableObjectContainerApplications, resolveWorkerName, sanitizeBranchName, shouldUseCIMetadataFallback, stripAnsi, syncAssets, tagsAreEqual, triggersDeploy, updateQueueConsumers, validateEventTriggerTargets, validateFileSecrets, validateNodeCompatMode, validateRoutes, verifyWorkerMatchesCITag, versionsUpload, visibleLength, warnOnErrorUpdatingServiceAndEnvironmentTags, workerNotFoundErrorMessage };
package/dist/index.mjs CHANGED
@@ -11,7 +11,7 @@ import url2, { URLSearchParams as URLSearchParams$1 } from 'node:url';
11
11
  import * as cli from '@cloudflare/cli-shared-helpers';
12
12
  import { updateStatus, cancel } from '@cloudflare/cli-shared-helpers';
13
13
  import { SchedulingPolicy, ApplicationsService, ApiError, listDurableObjects, resolveImageName, pushImageIfChanged, ContainerImagePreparationsService, ContainerImagePreparationStatus, createDurableObjectNamespaceResolver, initContainersSharedContext, pushBuiltContainerImage, deployContainers, verifyDockerInstalled } from '@cloudflare/containers-shared';
14
- import { INHERIT_SYMBOL, APIError, UserError, getEnvironmentVariableFactory, isNonInteractiveOrCI, getHostFromRoute, retryOnAPIFailure, ParseError, getComplianceRegionSubdomain, configFileName, formatTime, getSubdomainMixedStateCheckDisabled, LOGGER_LEVELS, CONTAINER_IMAGES_BINDING, getResolvedDurableObjectContainerApps, isDurableObjectContainerApp, getDockerPath, validateDurableObjectContainerApplications, getDurableObjectClassNameToUseSQLiteMap, 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, getDurableObjectContainerApps, getBindings, hasDurableObjectExports, parseNonHyphenedUuid, getWorkersCIBranchName, getCIOverrideName, getBindingTypeFriendlyName } from '@cloudflare/workers-utils';
14
+ import { INHERIT_SYMBOL, APIError, UserError, getEnvironmentVariableFactory, isNonInteractiveOrCI, getHostFromRoute, retryOnAPIFailure, ParseError, getComplianceRegionSubdomain, configFileName, formatTime, getSubdomainMixedStateCheckDisabled, LOGGER_LEVELS, CONTAINER_IMAGES_BINDING, getResolvedDurableObjectContainerApps, isDurableObjectContainerApp, getDockerPath, validateDurableObjectContainerApplications, getDurableObjectClassNameToUseSQLiteMap, 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, getDurableObjectContainerApps, getBindings, hasDurableObjectExports, parseNonHyphenedUuid, getWorkersCIBranchName, getCIOverrideName, getBindingTypeFriendlyName, defaultWranglerConfig } from '@cloudflare/workers-utils';
15
15
  import { Response, FormData } from 'undici';
16
16
  import chalk6 from 'chalk';
17
17
  import PQueue from 'p-queue';
@@ -29,6 +29,7 @@ import { parse as parse$1 } from 'dotenv';
29
29
  import { getFreshSourceMapSupport, getNodeCompat } from 'miniflare';
30
30
  import { execSync } from 'node:child_process';
31
31
  import { createHash } from 'node:crypto';
32
+ import { convertToWranglerConfig } from '@cloudflare/config';
32
33
 
33
34
  // ../../node_modules/.pnpm/ignore@5.3.1/node_modules/ignore/index.js
34
35
  var require_ignore = __commonJS({
@@ -3373,7 +3374,7 @@ async function publishRoutesFallback(complianceConfig, routes, { scriptName, acc
3373
3374
  if (alreadyDeployedRoutes.size) {
3374
3375
  logger.warn(
3375
3376
  "Previously deployed routes:\nThe following routes were already associated with this worker, and have not been deleted:\n" + [...alreadyDeployedRoutes.values()].map((route) => ` - "${route}"
3376
- `) + "If these routes are not wanted then you can remove them in the dashboard."
3377
+ `).join("") + "If these routes are not wanted then you can remove them in the dashboard."
3377
3378
  );
3378
3379
  }
3379
3380
  return deployedRoutes;
@@ -4040,10 +4041,8 @@ async function triggersDeploy(props) {
4040
4041
  for (const worker in routesWithOtherBindings) {
4041
4042
  const assignedRoutes = routesWithOtherBindings[worker];
4042
4043
  errorMessage += `"${worker}" is already assigned to routes:
4043
- ${assignedRoutes.map(
4044
- (r) => ` - ${chalk6.underline(r)}
4045
- `
4046
- )}`;
4044
+ ${assignedRoutes.map((r) => ` - ${chalk6.underline(r)}
4045
+ `).join("")}`;
4047
4046
  }
4048
4047
  const resolution = "Unassign other workers from the routes you want to deploy to, and then try again.";
4049
4048
  const dashHref = chalk6.blue.underline(
@@ -26767,17 +26766,22 @@ function getBindingValue(binding) {
26767
26766
  }
26768
26767
  }
26769
26768
  __name(getBindingValue, "getBindingValue");
26770
- function extractConfigBindings(config2) {
26771
- const previews = config2.previews;
26769
+ function extractBindings(previews, assets, omitIdentifierlessBindings = false) {
26772
26770
  const env = {};
26773
26771
  const vars = previews?.vars ?? {};
26774
26772
  for (const [name, value] of Object.entries(vars)) {
26775
26773
  env[name] = typeof value === "string" ? { type: "plain_text", text: value } : { type: "json", json: value };
26776
26774
  }
26777
26775
  for (const kv of previews?.kv_namespaces ?? []) {
26776
+ if (omitIdentifierlessBindings && kv.id === void 0) {
26777
+ continue;
26778
+ }
26778
26779
  env[kv.binding] = { type: "kv_namespace", namespace_id: kv.id };
26779
26780
  }
26780
26781
  for (const d1 of previews?.d1_databases ?? []) {
26782
+ if (omitIdentifierlessBindings && d1.database_id === void 0) {
26783
+ continue;
26784
+ }
26781
26785
  env[d1.binding] = {
26782
26786
  type: "d1",
26783
26787
  database_id: d1.database_id,
@@ -26785,6 +26789,9 @@ function extractConfigBindings(config2) {
26785
26789
  };
26786
26790
  }
26787
26791
  for (const r2 of previews?.r2_buckets ?? []) {
26792
+ if (omitIdentifierlessBindings && r2.bucket_name === void 0) {
26793
+ continue;
26794
+ }
26788
26795
  env[r2.binding] = {
26789
26796
  type: "r2_bucket",
26790
26797
  bucket_name: r2.bucket_name,
@@ -26798,11 +26805,33 @@ function extractConfigBindings(config2) {
26798
26805
  service: service.service,
26799
26806
  environment,
26800
26807
  entrypoint: service.entrypoint,
26808
+ props: service.props,
26801
26809
  ...crossAccountGrant !== void 0 && {
26802
26810
  cross_account_grant: crossAccountGrant
26803
26811
  }
26804
26812
  };
26805
26813
  }
26814
+ for (const memory of previews?.agent_memory ?? []) {
26815
+ env[memory.binding] = {
26816
+ type: "agent_memory",
26817
+ namespace: memory.namespace
26818
+ };
26819
+ }
26820
+ for (const vpc of previews?.vpc_networks ?? []) {
26821
+ const binding = { type: "vpc_network" };
26822
+ if ("tunnel_id" in vpc) {
26823
+ binding.tunnel_id = vpc.tunnel_id;
26824
+ } else {
26825
+ binding.network_id = vpc.network_id;
26826
+ }
26827
+ env[vpc.binding] = binding;
26828
+ }
26829
+ for (const binding of previews?.logfwdr?.bindings ?? []) {
26830
+ env[binding.name] = {
26831
+ type: "logfwdr",
26832
+ destination: binding.destination
26833
+ };
26834
+ }
26806
26835
  for (const doBinding of previews?.durable_objects?.bindings ?? []) {
26807
26836
  env[doBinding.name] = {
26808
26837
  type: "durable_object_namespace",
@@ -26940,8 +26969,8 @@ function extractConfigBindings(config2) {
26940
26969
  if (previews?.version_metadata) {
26941
26970
  env[previews.version_metadata.binding] = { type: "version_metadata" };
26942
26971
  }
26943
- if (config2.assets?.binding) {
26944
- env[config2.assets.binding] = { type: "assets" };
26972
+ if (assets?.binding) {
26973
+ env[assets.binding] = { type: "assets" };
26945
26974
  }
26946
26975
  for (const binding of previews?.unsafe?.bindings ?? []) {
26947
26976
  const { name, type, ...rest } = binding;
@@ -26949,7 +26978,15 @@ function extractConfigBindings(config2) {
26949
26978
  }
26950
26979
  return env;
26951
26980
  }
26981
+ __name(extractBindings, "extractBindings");
26982
+ function extractConfigBindings(config2) {
26983
+ return extractBindings(config2.previews, config2.assets);
26984
+ }
26952
26985
  __name(extractConfigBindings, "extractConfigBindings");
26986
+ function extractBuildOutputBindings(config2) {
26987
+ return extractBindings(config2, config2.assets, true);
26988
+ }
26989
+ __name(extractBuildOutputBindings, "extractBuildOutputBindings");
26953
26990
  function getDeclaredDOClassNames(config2) {
26954
26991
  const declared = /* @__PURE__ */ new Set();
26955
26992
  for (const migration of config2.migrations ?? []) {
@@ -27019,6 +27056,14 @@ function assemblePreviewScriptSettings(config2) {
27019
27056
  return result;
27020
27057
  }
27021
27058
  __name(assemblePreviewScriptSettings, "assemblePreviewScriptSettings");
27059
+ function assertPreviewBuildOutputSettings(settings) {
27060
+ if (settings?.isPreview !== true) {
27061
+ throw new UserError("Build Output was not created by a Preview build.", {
27062
+ telemetryMessage: "preview build output missing preview intent"
27063
+ });
27064
+ }
27065
+ }
27066
+ __name(assertPreviewBuildOutputSettings, "assertPreviewBuildOutputSettings");
27022
27067
  function buildPreviewContainerConfig(config2, parentWorkerName, previewSlug, previewContainers) {
27023
27068
  const previews = config2.previews;
27024
27069
  const previewDOBindings = previews?.durable_objects?.bindings ?? [];
@@ -27249,24 +27294,24 @@ function getPreviewMigrationsToUpload(workerName, config2, currentMigrationTag)
27249
27294
  }
27250
27295
  __name(getPreviewMigrationsToUpload, "getPreviewMigrationsToUpload");
27251
27296
  function buildResultToDeploymentModules(buildResult, assetFiles) {
27252
- const mainModuleName = path__default.basename(buildResult.resolvedEntryPointPath);
27253
- const mainContentType = moduleTypeMimeType[buildResult.bundleType] ?? "application/octet-stream";
27254
- const deploymentModules = [
27255
- {
27256
- name: mainModuleName,
27257
- content_type: mainContentType,
27258
- content: buildResult.content
27259
- },
27260
- ...buildResult.modules.map((mod) => {
27261
- const contentType = moduleTypeMimeType[mod.type ?? "text"] ?? "application/octet-stream";
27262
- return {
27297
+ let mainModuleName;
27298
+ const deploymentModules = [];
27299
+ if (buildResult) {
27300
+ mainModuleName = buildResult.mainModuleName ?? path__default.basename(buildResult.resolvedEntryPointPath);
27301
+ deploymentModules.push(
27302
+ {
27303
+ name: mainModuleName,
27304
+ content_type: moduleTypeMimeType[buildResult.bundleType] ?? "application/octet-stream",
27305
+ content: buildResult.content
27306
+ },
27307
+ ...buildResult.modules.map((mod) => ({
27263
27308
  name: mod.name,
27264
- content_type: contentType,
27309
+ content_type: moduleTypeMimeType[mod.type ?? "text"] ?? "application/octet-stream",
27265
27310
  content: mod.content
27266
- };
27267
- })
27268
- ];
27269
- if (buildResult.sourceMaps) {
27311
+ }))
27312
+ );
27313
+ }
27314
+ if (buildResult?.sourceMaps) {
27270
27315
  deploymentModules.push(
27271
27316
  ...buildResult.sourceMaps.map((sourceMap) => ({
27272
27317
  name: sourceMap.name,
@@ -27299,8 +27344,12 @@ async function assemblePreviewDeploymentSettings(config2, buildResult, accountId
27299
27344
  _headers: options.assetsOptions?._headers,
27300
27345
  _redirects: options.assetsOptions?._redirects
27301
27346
  });
27302
- request.main_module = deploymentModules.main_module;
27303
- request.modules = deploymentModules.modules;
27347
+ if (deploymentModules.main_module !== void 0) {
27348
+ request.main_module = deploymentModules.main_module;
27349
+ }
27350
+ if (deploymentModules.modules.length > 0) {
27351
+ request.modules = deploymentModules.modules;
27352
+ }
27304
27353
  if (options.assetsOptions) {
27305
27354
  const assetsUploadResult = await syncAssets(
27306
27355
  config2,
@@ -27493,8 +27542,7 @@ async function provisionParentWorker(config2, accountId, workerName, json2) {
27493
27542
  );
27494
27543
  }
27495
27544
  __name(provisionParentWorker, "provisionParentWorker");
27496
- async function preview(accountId, args, config2, buildResult, assetsOptions, callbacks) {
27497
- const workerName = resolveWorkerName(args, config2);
27545
+ async function runPreview(accountId, args, config2, buildResult, assetsOptions, callbacks, workerName, replaceTailConsumersAfterCreate = false) {
27498
27546
  let secrets;
27499
27547
  if (args.secretsFile) {
27500
27548
  secrets = (await parseBulkInputToObject(args.secretsFile))?.content;
@@ -27537,17 +27585,26 @@ async function preview(accountId, args, config2, buildResult, assetsOptions, cal
27537
27585
  }
27538
27586
  }
27539
27587
  const isNewPreview = !existingPreview;
27588
+ const previewRequest = assemblePreviewScriptSettings(config2);
27540
27589
  let previewResource;
27541
27590
  if (isNewPreview) {
27542
27591
  previewResource = await createPreview(
27543
27592
  config2,
27544
27593
  accountId,
27545
27594
  workerName,
27546
- { name: previewName, ...assemblePreviewScriptSettings(config2) },
27595
+ { name: previewName, ...previewRequest },
27547
27596
  { ignoreBaseConfig }
27548
27597
  );
27598
+ if (replaceTailConsumersAfterCreate && previewRequest.tail_consumers !== void 0) {
27599
+ previewResource = await editPreview(
27600
+ config2,
27601
+ accountId,
27602
+ workerName,
27603
+ previewIdentifier,
27604
+ { tail_consumers: previewRequest.tail_consumers }
27605
+ );
27606
+ }
27549
27607
  } else {
27550
- const previewRequest = assemblePreviewScriptSettings(config2);
27551
27608
  if (Object.keys(previewRequest).length > 0) {
27552
27609
  previewResource = await editPreview(
27553
27610
  config2,
@@ -27641,7 +27698,123 @@ async function preview(accountId, args, config2, buildResult, assetsOptions, cal
27641
27698
  }
27642
27699
  return { preview: previewResource, deployment, isNewPreview };
27643
27700
  }
27701
+ __name(runPreview, "runPreview");
27702
+ async function preview(accountId, args, config2, buildResult, assetsOptions, callbacks) {
27703
+ return runPreview(
27704
+ accountId,
27705
+ args,
27706
+ config2,
27707
+ buildResult,
27708
+ assetsOptions,
27709
+ callbacks,
27710
+ resolveWorkerName(args, config2)
27711
+ );
27712
+ }
27644
27713
  __name(preview, "preview");
27714
+ async function previewBuildOutput(accountId, args, buildOutput) {
27715
+ const { workerConfig, projectSettings, buildResult, assets } = buildOutput;
27716
+ assertPreviewBuildOutputSettings(projectSettings);
27717
+ if (workerConfig.domains?.length) {
27718
+ throw new UserError(
27719
+ "Preview uploads from Build Output don't support the `domains` field.",
27720
+ {
27721
+ telemetryMessage: "preview build output custom domains not supported"
27722
+ }
27723
+ );
27724
+ }
27725
+ if (workerConfig.triggers?.length) {
27726
+ throw new UserError(
27727
+ "Preview uploads from Build Output don't support the `triggers` field.",
27728
+ {
27729
+ telemetryMessage: "preview build output triggers not supported"
27730
+ }
27731
+ );
27732
+ }
27733
+ if (workerConfig.tailConsumers?.some((consumer) => consumer.streaming)) {
27734
+ throw new UserError(
27735
+ "Preview uploads from Build Output don't support streaming tail consumers.",
27736
+ {
27737
+ telemetryMessage: "preview build output streaming tail consumer not supported"
27738
+ }
27739
+ );
27740
+ }
27741
+ if (Object.values(workerConfig.exports ?? {}).some(
27742
+ (configExport) => "container" in configExport && configExport.container !== void 0
27743
+ )) {
27744
+ throw new UserError(
27745
+ "Preview uploads from Build Output don't support Container-backed Durable Objects.",
27746
+ {
27747
+ telemetryMessage: "preview build output containers not supported"
27748
+ }
27749
+ );
27750
+ }
27751
+ if (workerConfig.unsafe?.capnp !== void 0 || Object.keys(workerConfig.unsafe?.metadata ?? {}).length > 0) {
27752
+ throw new UserError(
27753
+ "Preview uploads from Build Output don't support unsafe metadata or Cap'n Proto schemas.",
27754
+ {
27755
+ telemetryMessage: "preview build output unsafe settings not supported"
27756
+ }
27757
+ );
27758
+ }
27759
+ const convertedConfig = convertToWranglerConfig(
27760
+ workerConfig,
27761
+ projectSettings
27762
+ );
27763
+ const previewBuildResult = buildResult && {
27764
+ ...buildResult,
27765
+ mainModuleName: workerConfig.manifest?.mainModule
27766
+ };
27767
+ const bindings = extractBuildOutputBindings(convertedConfig);
27768
+ const previewConfig = {
27769
+ ...defaultWranglerConfig,
27770
+ compliance_region: convertedConfig.compliance_region,
27771
+ name: workerConfig.name,
27772
+ compatibility_date: convertedConfig.compatibility_date,
27773
+ compatibility_flags: convertedConfig.compatibility_flags ?? [],
27774
+ exports: convertedConfig.exports ?? {},
27775
+ limits: convertedConfig.limits,
27776
+ cache: convertedConfig.cache,
27777
+ placement: convertedConfig.placement,
27778
+ observability: convertedConfig.observability,
27779
+ logpush: convertedConfig.logpush,
27780
+ workers_dev: false,
27781
+ preview_urls: true,
27782
+ previews: {
27783
+ tail_consumers: convertedConfig.tail_consumers ?? (workerConfig.tailConsumers === void 0 ? void 0 : []),
27784
+ unsafe: {
27785
+ bindings: Object.entries(bindings).map(([name, binding]) => ({
27786
+ name,
27787
+ ...binding
27788
+ }))
27789
+ }
27790
+ },
27791
+ assets: convertedConfig.assets
27792
+ };
27793
+ const assetsOptions = assets && {
27794
+ ...assets,
27795
+ _headers: assets._headers ?? maybeGetFile(path__default.join(assets.directory, "_headers")),
27796
+ _redirects: assets._redirects ?? maybeGetFile(path__default.join(assets.directory, "_redirects")),
27797
+ assetConfig: {
27798
+ html_handling: convertedConfig.assets?.html_handling,
27799
+ not_found_handling: convertedConfig.assets?.not_found_handling
27800
+ },
27801
+ run_worker_first: convertedConfig.assets?.run_worker_first
27802
+ };
27803
+ return runPreview(
27804
+ accountId,
27805
+ { ...args, ignoreBaseConfig: false },
27806
+ previewConfig,
27807
+ previewBuildResult,
27808
+ assetsOptions,
27809
+ {
27810
+ getNormalizedContainerOptions: void 0,
27811
+ deployPreviewContainers: void 0
27812
+ },
27813
+ workerConfig.name,
27814
+ true
27815
+ );
27816
+ }
27817
+ __name(previewBuildOutput, "previewBuildOutput");
27645
27818
  async function previewDelete(accountId, args, config2) {
27646
27819
  const workerName = resolveWorkerName(args, config2);
27647
27820
  let previewName = args.name;
@@ -27821,4 +27994,4 @@ __name(formatBindings, "formatBindings");
27821
27994
  * THE SOFTWARE.
27822
27995
  */
27823
27996
 
27824
- 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, PREVIEW_DOMAIN_PROVISIONING_NOTE, 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, createDurableObjectContainerApplication, createPreview, createPreviewDeployment, createPreviewDeploymentForm, createPreviewParentWorker, createTruncatedAlias, decodeJwtPayload, deletePreview, deletePullConsumer, deleteWorkerConsumer, deploy, deployDurableObjectContainerApplications, deployVersionedDurableObjectContainerApplications, deployWfpUserWorker, diagnoseScriptSizeError, diagnoseStartupError, diffJsonObjects, downloadWorkerConfig, drawBox, drawConnectedChildBox, editPreview, ensureQueuesExistByConfig, extractConfigBindings, fetchDeployableVersions, fetchDeploymentVersions, fetchLatestDeployment, fetchLatestDeployments, fetchSecrets, fetchVersion, fetchVersions, fetchWorkerConfig, formatAlignedRows, formatBindings, formatNoActivePreviewUrlsMessage, 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, getVersionedDurableObjectContainerApplications, getWorkersDevSubdomain, getZoneForRoute, getZoneIdFromHost, handleMissingSecretsError, hasDefinedEnvironments, hashFile, helpIfErrorIsSizeOrScriptStartup, isExportsReconciliationErrorDetails, isJwtExpired, isModifiedDiffValue, isNonDestructive, isWorkerNotFoundError, listConsumers, listQueues, maybeRetrieveFileSourceMap, padToVisibleWidth, parseBulkInputToObject, parseConfigPlacement, patchNonVersionedScriptSettings, patchPreviewBaseConfig, patchPreviewDeployment, postConsumer, prepareDurableObjectContainerApplications, preview, previewContainerAppName, previewDelete, printBundleSize, printVersions, provisionBindings, publishCustomDomains, publishRoutes, putConsumer, putConsumerById, renderBindingDependsOnExportError, renderExportsReconciliationError, renderExportsReconciliationSuccess, renderInconsistentExportsAcrossVersionsError, renderRoute, resolveAssetOptions, resolveDoLifecyclePayload, resolveExportsUploadPayload, resolveVersionedDurableObjectContainerApplications, resolveWorkerName, sanitizeBranchName, shouldUseCIMetadataFallback, stripAnsi, syncAssets, tagsAreEqual, triggersDeploy, updateQueueConsumers, validateEventTriggerTargets, validateFileSecrets, validateNodeCompatMode, validateRoutes, verifyWorkerMatchesCITag, versionsUpload, visibleLength, warnOnErrorUpdatingServiceAndEnvironmentTags, workerNotFoundErrorMessage };
27997
+ 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, PREVIEW_DOMAIN_PROVISIONING_NOTE, 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, assertPreviewBuildOutputSettings, buildAssetManifest, checkRemoteSecretsOverride, checkWorkflowConflicts, collectPackageDependencies, confirmLatestDeploymentOverwrite, createDeployment, createDurableObjectContainerApplication, createPreview, createPreviewDeployment, createPreviewDeploymentForm, createPreviewParentWorker, createTruncatedAlias, decodeJwtPayload, deletePreview, deletePullConsumer, deleteWorkerConsumer, deploy, deployDurableObjectContainerApplications, deployVersionedDurableObjectContainerApplications, deployWfpUserWorker, diagnoseScriptSizeError, diagnoseStartupError, diffJsonObjects, downloadWorkerConfig, drawBox, drawConnectedChildBox, editPreview, ensureQueuesExistByConfig, extractBuildOutputBindings, extractConfigBindings, fetchDeployableVersions, fetchDeploymentVersions, fetchLatestDeployment, fetchLatestDeployments, fetchSecrets, fetchVersion, fetchVersions, fetchWorkerConfig, formatAlignedRows, formatBindings, formatNoActivePreviewUrlsMessage, 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, getVersionedDurableObjectContainerApplications, getWorkersDevSubdomain, getZoneForRoute, getZoneIdFromHost, handleMissingSecretsError, hasDefinedEnvironments, hashFile, helpIfErrorIsSizeOrScriptStartup, isExportsReconciliationErrorDetails, isJwtExpired, isModifiedDiffValue, isNonDestructive, isWorkerNotFoundError, listConsumers, listQueues, maybeRetrieveFileSourceMap, padToVisibleWidth, parseBulkInputToObject, parseConfigPlacement, patchNonVersionedScriptSettings, patchPreviewBaseConfig, patchPreviewDeployment, postConsumer, prepareDurableObjectContainerApplications, preview, previewBuildOutput, previewContainerAppName, previewDelete, printBundleSize, printVersions, provisionBindings, publishCustomDomains, publishRoutes, putConsumer, putConsumerById, renderBindingDependsOnExportError, renderExportsReconciliationError, renderExportsReconciliationSuccess, renderInconsistentExportsAcrossVersionsError, renderRoute, resolveAssetOptions, resolveDoLifecyclePayload, resolveExportsUploadPayload, resolveVersionedDurableObjectContainerApplications, resolveWorkerName, sanitizeBranchName, shouldUseCIMetadataFallback, stripAnsi, syncAssets, tagsAreEqual, triggersDeploy, updateQueueConsumers, validateEventTriggerTargets, validateFileSecrets, validateNodeCompatMode, validateRoutes, verifyWorkerMatchesCITag, versionsUpload, visibleLength, warnOnErrorUpdatingServiceAndEnvironmentTags, workerNotFoundErrorMessage };