@cloudflare/deploy-helpers 0.12.2 → 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({
@@ -26765,17 +26766,22 @@ function getBindingValue(binding) {
26765
26766
  }
26766
26767
  }
26767
26768
  __name(getBindingValue, "getBindingValue");
26768
- function extractConfigBindings(config2) {
26769
- const previews = config2.previews;
26769
+ function extractBindings(previews, assets, omitIdentifierlessBindings = false) {
26770
26770
  const env = {};
26771
26771
  const vars = previews?.vars ?? {};
26772
26772
  for (const [name, value] of Object.entries(vars)) {
26773
26773
  env[name] = typeof value === "string" ? { type: "plain_text", text: value } : { type: "json", json: value };
26774
26774
  }
26775
26775
  for (const kv of previews?.kv_namespaces ?? []) {
26776
+ if (omitIdentifierlessBindings && kv.id === void 0) {
26777
+ continue;
26778
+ }
26776
26779
  env[kv.binding] = { type: "kv_namespace", namespace_id: kv.id };
26777
26780
  }
26778
26781
  for (const d1 of previews?.d1_databases ?? []) {
26782
+ if (omitIdentifierlessBindings && d1.database_id === void 0) {
26783
+ continue;
26784
+ }
26779
26785
  env[d1.binding] = {
26780
26786
  type: "d1",
26781
26787
  database_id: d1.database_id,
@@ -26783,6 +26789,9 @@ function extractConfigBindings(config2) {
26783
26789
  };
26784
26790
  }
26785
26791
  for (const r2 of previews?.r2_buckets ?? []) {
26792
+ if (omitIdentifierlessBindings && r2.bucket_name === void 0) {
26793
+ continue;
26794
+ }
26786
26795
  env[r2.binding] = {
26787
26796
  type: "r2_bucket",
26788
26797
  bucket_name: r2.bucket_name,
@@ -26796,11 +26805,33 @@ function extractConfigBindings(config2) {
26796
26805
  service: service.service,
26797
26806
  environment,
26798
26807
  entrypoint: service.entrypoint,
26808
+ props: service.props,
26799
26809
  ...crossAccountGrant !== void 0 && {
26800
26810
  cross_account_grant: crossAccountGrant
26801
26811
  }
26802
26812
  };
26803
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
+ }
26804
26835
  for (const doBinding of previews?.durable_objects?.bindings ?? []) {
26805
26836
  env[doBinding.name] = {
26806
26837
  type: "durable_object_namespace",
@@ -26938,8 +26969,8 @@ function extractConfigBindings(config2) {
26938
26969
  if (previews?.version_metadata) {
26939
26970
  env[previews.version_metadata.binding] = { type: "version_metadata" };
26940
26971
  }
26941
- if (config2.assets?.binding) {
26942
- env[config2.assets.binding] = { type: "assets" };
26972
+ if (assets?.binding) {
26973
+ env[assets.binding] = { type: "assets" };
26943
26974
  }
26944
26975
  for (const binding of previews?.unsafe?.bindings ?? []) {
26945
26976
  const { name, type, ...rest } = binding;
@@ -26947,7 +26978,15 @@ function extractConfigBindings(config2) {
26947
26978
  }
26948
26979
  return env;
26949
26980
  }
26981
+ __name(extractBindings, "extractBindings");
26982
+ function extractConfigBindings(config2) {
26983
+ return extractBindings(config2.previews, config2.assets);
26984
+ }
26950
26985
  __name(extractConfigBindings, "extractConfigBindings");
26986
+ function extractBuildOutputBindings(config2) {
26987
+ return extractBindings(config2, config2.assets, true);
26988
+ }
26989
+ __name(extractBuildOutputBindings, "extractBuildOutputBindings");
26951
26990
  function getDeclaredDOClassNames(config2) {
26952
26991
  const declared = /* @__PURE__ */ new Set();
26953
26992
  for (const migration of config2.migrations ?? []) {
@@ -27017,6 +27056,14 @@ function assemblePreviewScriptSettings(config2) {
27017
27056
  return result;
27018
27057
  }
27019
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");
27020
27067
  function buildPreviewContainerConfig(config2, parentWorkerName, previewSlug, previewContainers) {
27021
27068
  const previews = config2.previews;
27022
27069
  const previewDOBindings = previews?.durable_objects?.bindings ?? [];
@@ -27247,24 +27294,24 @@ function getPreviewMigrationsToUpload(workerName, config2, currentMigrationTag)
27247
27294
  }
27248
27295
  __name(getPreviewMigrationsToUpload, "getPreviewMigrationsToUpload");
27249
27296
  function buildResultToDeploymentModules(buildResult, assetFiles) {
27250
- const mainModuleName = path__default.basename(buildResult.resolvedEntryPointPath);
27251
- const mainContentType = moduleTypeMimeType[buildResult.bundleType] ?? "application/octet-stream";
27252
- const deploymentModules = [
27253
- {
27254
- name: mainModuleName,
27255
- content_type: mainContentType,
27256
- content: buildResult.content
27257
- },
27258
- ...buildResult.modules.map((mod) => {
27259
- const contentType = moduleTypeMimeType[mod.type ?? "text"] ?? "application/octet-stream";
27260
- 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) => ({
27261
27308
  name: mod.name,
27262
- content_type: contentType,
27309
+ content_type: moduleTypeMimeType[mod.type ?? "text"] ?? "application/octet-stream",
27263
27310
  content: mod.content
27264
- };
27265
- })
27266
- ];
27267
- if (buildResult.sourceMaps) {
27311
+ }))
27312
+ );
27313
+ }
27314
+ if (buildResult?.sourceMaps) {
27268
27315
  deploymentModules.push(
27269
27316
  ...buildResult.sourceMaps.map((sourceMap) => ({
27270
27317
  name: sourceMap.name,
@@ -27297,8 +27344,12 @@ async function assemblePreviewDeploymentSettings(config2, buildResult, accountId
27297
27344
  _headers: options.assetsOptions?._headers,
27298
27345
  _redirects: options.assetsOptions?._redirects
27299
27346
  });
27300
- request.main_module = deploymentModules.main_module;
27301
- 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
+ }
27302
27353
  if (options.assetsOptions) {
27303
27354
  const assetsUploadResult = await syncAssets(
27304
27355
  config2,
@@ -27491,8 +27542,7 @@ async function provisionParentWorker(config2, accountId, workerName, json2) {
27491
27542
  );
27492
27543
  }
27493
27544
  __name(provisionParentWorker, "provisionParentWorker");
27494
- async function preview(accountId, args, config2, buildResult, assetsOptions, callbacks) {
27495
- const workerName = resolveWorkerName(args, config2);
27545
+ async function runPreview(accountId, args, config2, buildResult, assetsOptions, callbacks, workerName, replaceTailConsumersAfterCreate = false) {
27496
27546
  let secrets;
27497
27547
  if (args.secretsFile) {
27498
27548
  secrets = (await parseBulkInputToObject(args.secretsFile))?.content;
@@ -27535,17 +27585,26 @@ async function preview(accountId, args, config2, buildResult, assetsOptions, cal
27535
27585
  }
27536
27586
  }
27537
27587
  const isNewPreview = !existingPreview;
27588
+ const previewRequest = assemblePreviewScriptSettings(config2);
27538
27589
  let previewResource;
27539
27590
  if (isNewPreview) {
27540
27591
  previewResource = await createPreview(
27541
27592
  config2,
27542
27593
  accountId,
27543
27594
  workerName,
27544
- { name: previewName, ...assemblePreviewScriptSettings(config2) },
27595
+ { name: previewName, ...previewRequest },
27545
27596
  { ignoreBaseConfig }
27546
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
+ }
27547
27607
  } else {
27548
- const previewRequest = assemblePreviewScriptSettings(config2);
27549
27608
  if (Object.keys(previewRequest).length > 0) {
27550
27609
  previewResource = await editPreview(
27551
27610
  config2,
@@ -27639,7 +27698,123 @@ async function preview(accountId, args, config2, buildResult, assetsOptions, cal
27639
27698
  }
27640
27699
  return { preview: previewResource, deployment, isNewPreview };
27641
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
+ }
27642
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");
27643
27818
  async function previewDelete(accountId, args, config2) {
27644
27819
  const workerName = resolveWorkerName(args, config2);
27645
27820
  let previewName = args.name;
@@ -27819,4 +27994,4 @@ __name(formatBindings, "formatBindings");
27819
27994
  * THE SOFTWARE.
27820
27995
  */
27821
27996
 
27822
- 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 };