@cloudflare/deploy-helpers 0.8.0 → 0.9.1

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.
@@ -44,8 +44,25 @@ function convertConfigToBindings(config, options) {
44
44
  if (pages) {
45
45
  break;
46
46
  }
47
- for (const { name, ...x } of info) {
48
- output[name] = { type: "send_email", ...x };
47
+ for (const {
48
+ name,
49
+ destination_address,
50
+ allowed_destination_addresses,
51
+ allowed_sender_addresses,
52
+ remote
53
+ } of info) {
54
+ const shared = {
55
+ type: "send_email",
56
+ allowed_sender_addresses,
57
+ remote
58
+ };
59
+ if (destination_address !== void 0) {
60
+ output[name] = { ...shared, destination_address };
61
+ } else if (allowed_destination_addresses !== void 0) {
62
+ output[name] = { ...shared, allowed_destination_addresses };
63
+ } else {
64
+ output[name] = shared;
65
+ }
49
66
  }
50
67
  break;
51
68
  }
@@ -554,16 +571,24 @@ function createWorkerUploadForm(worker, bindings, options) {
554
571
  }
555
572
  });
556
573
  send_email.forEach((emailBinding) => {
557
- const destination_address = "destination_address" in emailBinding ? emailBinding.destination_address : void 0;
558
- const allowed_destination_addresses = "allowed_destination_addresses" in emailBinding ? emailBinding.allowed_destination_addresses : void 0;
559
- const allowed_sender_addresses = "allowed_sender_addresses" in emailBinding ? emailBinding.allowed_sender_addresses : void 0;
560
- metadataBindings.push({
574
+ const shared = {
561
575
  name: emailBinding.name,
562
576
  type: "send_email",
563
- destination_address,
564
- allowed_destination_addresses,
565
- allowed_sender_addresses
566
- });
577
+ allowed_sender_addresses: emailBinding.allowed_sender_addresses
578
+ };
579
+ if (emailBinding.destination_address !== void 0) {
580
+ metadataBindings.push({
581
+ ...shared,
582
+ destination_address: emailBinding.destination_address
583
+ });
584
+ } else if (emailBinding.allowed_destination_addresses !== void 0) {
585
+ metadataBindings.push({
586
+ ...shared,
587
+ allowed_destination_addresses: emailBinding.allowed_destination_addresses
588
+ });
589
+ } else {
590
+ metadataBindings.push(shared);
591
+ }
567
592
  });
568
593
  durable_objects.forEach(({ name, class_name, script_name, environment }) => {
569
594
  metadataBindings.push({
@@ -1,2 +1,2 @@
1
- export { createWorkerUploadForm, fromMimeType, moduleTypeMimeType } from './chunk-LRKPOFWK.mjs';
1
+ export { createWorkerUploadForm, fromMimeType, moduleTypeMimeType } from './chunk-ZV7SJ2MZ.mjs';
2
2
  import './chunk-Q72B4Q5Z.mjs';
package/dist/index.d.mts CHANGED
@@ -934,16 +934,26 @@ interface DeploymentResource {
934
934
  limits?: CfUserLimits;
935
935
  placement?: CfPlacement;
936
936
  cache?: CacheOptions;
937
+ annotations?: {
938
+ "workers/commit_sha"?: string;
939
+ "workers/message"?: string;
940
+ "workers/pull_request_number"?: string;
941
+ "workers/pull_request_title"?: string;
942
+ "workers/pull_request_url"?: string;
943
+ "workers/repository_url"?: string;
944
+ "workers/tag"?: string;
945
+ };
937
946
  env?: EnvBindings;
938
947
  created_on: string;
939
948
  }
949
+ type PreviewDeploymentModule = {
950
+ name: string;
951
+ content_type: string;
952
+ content: string | Uint8Array;
953
+ };
940
954
  type CreatePreviewDeploymentRequestParams = {
941
955
  main_module?: string;
942
- modules?: Array<{
943
- name: string;
944
- content_type: string;
945
- content_base64: string;
946
- }>;
956
+ modules?: PreviewDeploymentModule[];
947
957
  assets?: {
948
958
  jwt: string;
949
959
  config: {
@@ -955,7 +965,12 @@ type CreatePreviewDeploymentRequestParams = {
955
965
  compatibility_date?: string;
956
966
  compatibility_flags?: string[];
957
967
  annotations?: {
968
+ "workers/commit_sha"?: string;
958
969
  "workers/message"?: string;
970
+ "workers/pull_request_number"?: string;
971
+ "workers/pull_request_title"?: string;
972
+ "workers/pull_request_url"?: string;
973
+ "workers/repository_url"?: string;
959
974
  "workers/tag"?: string;
960
975
  };
961
976
  migrations?: CfWorkerInit["migrations"];
@@ -1014,6 +1029,10 @@ declare function createPreview(config: Config, accountId: string, workerName: st
1014
1029
  declare function editPreview(config: Config, accountId: string, workerName: string, previewIdentifier: string, request: UpdatePreviewRequestParams): Promise<PreviewResource>;
1015
1030
  declare function deletePreview(config: Config, accountId: string, workerName: string, previewIdentifier: string): Promise<void>;
1016
1031
  declare function getPreviewDeployment(config: Config, accountId: string, workerName: string, previewIdentifier: string, deploymentIdentifier?: string): Promise<DeploymentResource>;
1032
+ /**
1033
+ * Encode preview deployment metadata and raw module files as multipart form data.
1034
+ */
1035
+ declare function createPreviewDeploymentForm(request: Partial<CreatePreviewDeploymentRequestParams>): FormData;
1017
1036
  declare function createPreviewDeployment(config: Config, accountId: string, workerName: string, previewIdentifier: string, request: Partial<CreatePreviewDeploymentRequestParams>): Promise<DeploymentResource>;
1018
1037
  declare function patchPreviewDeployment(config: Config, accountId: string, workerName: string, previewIdentifier: string, env: Record<string, Binding | null>, annotations?: {
1019
1038
  "workers/message"?: string;
@@ -1028,6 +1047,43 @@ declare function getBranchName(): string | undefined;
1028
1047
  declare function shouldUseCIMetadataFallback(): boolean;
1029
1048
  declare function getHeadCommitRef(): string | undefined;
1030
1049
  declare function getHeadCommitMessage(): string | undefined;
1050
+ /**
1051
+ * Detects the current commit's full SHA from well-known CI provider
1052
+ * environment variables (GitHub Actions, GitLab CI, CircleCI), falling back
1053
+ * to a generic `COMMIT_SHA` env var for providers without dedicated support.
1054
+ */
1055
+ declare function getCommitSha(): string | undefined;
1056
+ /**
1057
+ * Detects the current repository's URL from well-known CI provider
1058
+ * environment variables (GitLab CI, CircleCI, Buildkite, Bitbucket, GitHub
1059
+ * Actions, and a generic `REPOSITORY_URL` fallback), or from the local git
1060
+ * remote when running in CI and no env var matched.
1061
+ *
1062
+ * The local git remote fallback is intentionally gated behind
1063
+ * {@link shouldUseCIMetadataFallback}: unlike the env var checks, it shells
1064
+ * out to read the developer's `git config`, so it's only attempted in CI to
1065
+ * avoid uploading a local machine's repository details on every
1066
+ * `wrangler preview` run outside CI.
1067
+ */
1068
+ declare function getRepositoryUrl(): string | undefined;
1069
+ /**
1070
+ * The pull/merge request number, URL, and title detected from the current CI
1071
+ * environment. Any field may be missing depending on what the detected CI
1072
+ * provider exposes.
1073
+ */
1074
+ type PullRequestMetadata = {
1075
+ number?: string;
1076
+ url?: string;
1077
+ title?: string;
1078
+ };
1079
+ /**
1080
+ * Detects the pull/merge request associated with the current CI run, trying
1081
+ * each supported source in order: direct/generic env vars, GitHub Actions,
1082
+ * then GitLab CI. This is best effort — if none of the sources match (e.g.
1083
+ * an unsupported CI provider, or running locally), the deployment proceeds
1084
+ * without pull request metadata.
1085
+ */
1086
+ declare function getPullRequestMetadata(): PullRequestMetadata | undefined;
1031
1087
  declare function resolveWorkerName(args: {
1032
1088
  workerName?: string;
1033
1089
  "worker-name"?: string;
@@ -1105,6 +1161,7 @@ type PreviewCallbacks = Pick<DeployCallbacks, "getNormalizedContainerOptions"> &
1105
1161
  }) => Promise<void>) | undefined;
1106
1162
  verifyContainersScope?: (scopedConfig: Config) => Promise<void>;
1107
1163
  };
1164
+ declare const NO_ACTIVE_PREVIEW_URLS_MESSAGE = "Note: This Preview deployment has no active URLs. To get one, enable Preview Deployments on workers.dev or a custom domain. See https://developers.cloudflare.com/workers/previews/custom-domains/ for more information";
1108
1165
  /**
1109
1166
  * Full preview create/update + deployment orchestration.
1110
1167
  * The wrangler handler calls this after auth + build.
@@ -1189,4 +1246,4 @@ type DrawConnectedChildBoxOptions = {
1189
1246
  */
1190
1247
  declare function drawConnectedChildBox(contentLines: string[], options?: DrawConnectedChildBoxOptions): string;
1191
1248
 
1192
- export { ACTOR_BINDING_DEPENDS_ON_EXPORT_CODE, type ApiDeployment, type ApiVersion, type AssetManifest, type AssetUploadStats, type AssetsUploadResult, type Binding, type BulkInputNullableResult, type BulkInputResult, type Consumer, type ConsumerSettings, type CreatePreviewDeploymentRequestParams, type CreatePreviewRequestParams, type CustomDomain, type CustomDomainChangeset, type DeployCallbacks, DeployProps, type DeploymentResource, EXPORTS_RECONCILIATION_ERROR_CODE, type EnvBindings, INCONSISTENT_EXPORTS_ACROSS_VERSIONS_CODE, INVALID_INHERIT_BINDING_CODE, type JsonLike, NoInputError, type NonVersionedScriptSettings, type PackageDependency, type Percentage, type PostQueueBody, type PostQueueResponse, type PostTypedConsumerBody, type PreviewArgs, type PreviewAssetsOptions, type PreviewBaseConfig, type PreviewBaseConfigPatch, type PreviewCallbacks, type PreviewDefaults, type PreviewDefaultsPatch, type PreviewDeleteArgs, type PreviewRequestOptions, type PreviewResource, type PreviewResult, type PreviewSettingsArgs, type PreviewSettingsUpdateArgs, type Producer, 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 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, assemblePreviewDefaults, assemblePreviewScriptSettings, buildAssetManifest, checkRemoteSecretsOverride, checkWorkflowConflicts, collectPackageDependencies, confirmLatestDeploymentOverwrite, convertConfigToBindings, createDeployment, createPreview, createPreviewDeployment, createPreviewParentWorker, createTruncatedAlias, decodeJwtPayload, deletePreview, deletePullConsumer, deleteWorkerConsumer, deploy, deployWfpUserWorker, diagnoseScriptSizeError, diagnoseStartupError, diffJsonObjects, downloadWorkerConfig, drawBox, drawConnectedChildBox, editPreview, editWorkerPreviewDefaults, ensureQueuesExistByConfig, extractBindingsOfType, extractConfigBindings, fetchDeployableVersions, fetchDeploymentVersions, fetchLatestDeployment, fetchLatestDeployments, fetchSecrets, fetchVersion, fetchVersions, fetchWorkerConfig, formatAlignedRows, formatBindings, formatPreviewsSettings, generatePreviewAlias, getBindingValue, getBindings, getBranchName, getConfigPatch, getDeployConfirmFunction, getEdgeKvUploadConcurrency, getHeadCommitMessage, getHeadCommitRef, getMigrationsToUpload, getPreview, getPreviewBaseConfig, getPreviewDeployment, getPreviewOwnedContainerClassNames, getQueue, getRemoteConfigDiff, getSettings, getSourceMappedStack, getSourceMappedString, getSubdomainValues, getSubdomainValuesAPIMock, getWorkerPreviewDefaults, getWorkersDevSubdomain, getZoneForRoute, getZoneIdFromHost, handleMissingSecretsError, handleUnsafeCapnp, hasDefinedEnvironments, hashFile, helpIfErrorIsSizeOrScriptStartup, isExportsReconciliationErrorDetails, isJwtExpired, isModifiedDiffValue, isNonDestructive, isUnsafeBindingType, isWorkerNotFoundError, listConsumers, listQueues, maybeRetrieveFileSourceMap, mergeDeep, padToVisibleWidth, parseBulkInputToObject, parseConfigPlacement, patchNonVersionedScriptSettings, patchPreviewBaseConfig, patchPreviewDeployment, postConsumer, preview, previewContainerAppName, previewDelete, previewSettingsGet, previewSettingsUpdate, printBindings, 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, warnOrError, workerNotFoundErrorMessage };
1249
+ export { ACTOR_BINDING_DEPENDS_ON_EXPORT_CODE, type ApiDeployment, type ApiVersion, type AssetManifest, type AssetUploadStats, type AssetsUploadResult, type Binding, type BulkInputNullableResult, type BulkInputResult, type Consumer, type ConsumerSettings, type CreatePreviewDeploymentRequestParams, type CreatePreviewRequestParams, type CustomDomain, type CustomDomainChangeset, type DeployCallbacks, DeployProps, type DeploymentResource, 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, type PackageDependency, type Percentage, type PostQueueBody, type PostQueueResponse, type PostTypedConsumerBody, type PreviewArgs, type PreviewAssetsOptions, type PreviewBaseConfig, type PreviewBaseConfigPatch, type PreviewCallbacks, type PreviewDefaults, type PreviewDefaultsPatch, type PreviewDeleteArgs, type PreviewDeploymentModule, type PreviewRequestOptions, type PreviewResource, type PreviewResult, type PreviewSettingsArgs, type PreviewSettingsUpdateArgs, type Producer, 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 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, assemblePreviewDefaults, assemblePreviewScriptSettings, buildAssetManifest, checkRemoteSecretsOverride, checkWorkflowConflicts, collectPackageDependencies, confirmLatestDeploymentOverwrite, convertConfigToBindings, createDeployment, createPreview, createPreviewDeployment, createPreviewDeploymentForm, createPreviewParentWorker, createTruncatedAlias, decodeJwtPayload, deletePreview, deletePullConsumer, deleteWorkerConsumer, deploy, deployWfpUserWorker, diagnoseScriptSizeError, diagnoseStartupError, diffJsonObjects, downloadWorkerConfig, drawBox, drawConnectedChildBox, editPreview, editWorkerPreviewDefaults, ensureQueuesExistByConfig, extractBindingsOfType, extractConfigBindings, fetchDeployableVersions, fetchDeploymentVersions, fetchLatestDeployment, fetchLatestDeployments, fetchSecrets, fetchVersion, fetchVersions, fetchWorkerConfig, formatAlignedRows, formatBindings, formatPreviewsSettings, generatePreviewAlias, getBindingValue, getBindings, getBranchName, getCommitSha, getConfigPatch, getDeployConfirmFunction, getEdgeKvUploadConcurrency, getHeadCommitMessage, getHeadCommitRef, getMigrationsToUpload, getPreview, getPreviewBaseConfig, getPreviewDeployment, getPreviewOwnedContainerClassNames, getPullRequestMetadata, getQueue, getRemoteConfigDiff, getRepositoryUrl, getSettings, getSourceMappedStack, getSourceMappedString, getSubdomainValues, getSubdomainValuesAPIMock, getWorkerPreviewDefaults, getWorkersDevSubdomain, getZoneForRoute, getZoneIdFromHost, handleMissingSecretsError, handleUnsafeCapnp, hasDefinedEnvironments, hashFile, helpIfErrorIsSizeOrScriptStartup, isExportsReconciliationErrorDetails, isJwtExpired, isModifiedDiffValue, isNonDestructive, isUnsafeBindingType, isWorkerNotFoundError, listConsumers, listQueues, maybeRetrieveFileSourceMap, mergeDeep, padToVisibleWidth, parseBulkInputToObject, parseConfigPlacement, patchNonVersionedScriptSettings, patchPreviewBaseConfig, patchPreviewDeployment, postConsumer, preview, previewContainerAppName, previewDelete, previewSettingsGet, previewSettingsUpdate, printBindings, 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, warnOrError, workerNotFoundErrorMessage };
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 { extractBindingsOfType, isUnsafeBindingType, getBindings, createWorkerUploadForm, moduleTypeMimeType } from './chunk-LRKPOFWK.mjs';
4
- export { convertConfigToBindings, createWorkerUploadForm, extractBindingsOfType, fromMimeType, getBindings, handleUnsafeCapnp, isUnsafeBindingType, moduleTypeMimeType } from './chunk-LRKPOFWK.mjs';
3
+ import { extractBindingsOfType, isUnsafeBindingType, getBindings, createWorkerUploadForm, moduleTypeMimeType } from './chunk-ZV7SJ2MZ.mjs';
4
+ export { convertConfigToBindings, createWorkerUploadForm, extractBindingsOfType, fromMimeType, getBindings, handleUnsafeCapnp, isUnsafeBindingType, moduleTypeMimeType } from './chunk-ZV7SJ2MZ.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';
@@ -4406,6 +4406,14 @@ ${dashLink}`, {
4406
4406
  }
4407
4407
  );
4408
4408
  }
4409
+ if (workflow.concurrency) {
4410
+ throw new UserError(
4411
+ `Workflow "${workflow.name}" has "concurrency" configured but references external script "${workflow.script_name}". Configure concurrency on the worker that defines the workflow.`,
4412
+ {
4413
+ telemetryMessage: "triggers deploy workflow concurrency external script"
4414
+ }
4415
+ );
4416
+ }
4409
4417
  if (workflow.schedules) {
4410
4418
  throw new UserError(
4411
4419
  `Workflow "${workflow.name}" has "schedules" configured but references external script "${workflow.script_name}". Configure schedules on the worker that defines the workflow.`,
@@ -4414,6 +4422,14 @@ ${dashLink}`, {
4414
4422
  }
4415
4423
  );
4416
4424
  }
4425
+ if (workflow.default_retention) {
4426
+ throw new UserError(
4427
+ `Workflow "${workflow.name}" has "default_retention" configured but references external script "${workflow.script_name}". Configure default_retention on the worker that defines the workflow.`,
4428
+ {
4429
+ telemetryMessage: "triggers deploy workflow default_retention external script"
4430
+ }
4431
+ );
4432
+ }
4417
4433
  continue;
4418
4434
  }
4419
4435
  workflowDeployments.push({
@@ -4427,8 +4443,14 @@ ${dashLink}`, {
4427
4443
  script_name: scriptName,
4428
4444
  class_name: workflow.class_name,
4429
4445
  ...workflow.limits && { limits: workflow.limits },
4446
+ ...workflow.concurrency && {
4447
+ concurrency: workflow.concurrency
4448
+ },
4430
4449
  ...workflow.schedules && {
4431
4450
  schedules: (Array.isArray(workflow.schedules) ? workflow.schedules : [workflow.schedules]).map((cron) => ({ cron }))
4451
+ },
4452
+ ...workflow.default_retention && {
4453
+ default_retention: workflow.default_retention
4432
4454
  }
4433
4455
  }),
4434
4456
  headers: {
@@ -26560,8 +26582,6 @@ function renderInconsistentExportsAcrossVersionsError(serverMessage) {
26560
26582
  ].join("\n");
26561
26583
  }
26562
26584
  __name(renderInconsistentExportsAcrossVersionsError, "renderInconsistentExportsAcrossVersionsError");
26563
-
26564
- // src/preview/api.ts
26565
26585
  async function createPreviewParentWorker(config2, accountId, workerName, workersDevEnabled, previewsEnabled) {
26566
26586
  await fetchResult(config2, `/accounts/${accountId}/workers/workers`, {
26567
26587
  method: "POST",
@@ -26634,6 +26654,19 @@ async function getPreviewDeployment(config2, accountId, workerName, previewIdent
26634
26654
  );
26635
26655
  }
26636
26656
  __name(getPreviewDeployment, "getPreviewDeployment");
26657
+ function createPreviewDeploymentForm(request2) {
26658
+ const { modules, ...metadata } = request2;
26659
+ const formData = new FormData();
26660
+ formData.set("metadata", JSON.stringify(metadata));
26661
+ for (const module of modules ?? []) {
26662
+ formData.append(
26663
+ "files",
26664
+ new File([module.content], module.name, { type: module.content_type })
26665
+ );
26666
+ }
26667
+ return formData;
26668
+ }
26669
+ __name(createPreviewDeploymentForm, "createPreviewDeploymentForm");
26637
26670
  async function createPreviewDeployment(config2, accountId, workerName, previewIdentifier, request2) {
26638
26671
  return fetchResult(
26639
26672
  config2,
@@ -26642,8 +26675,8 @@ async function createPreviewDeployment(config2, accountId, workerName, previewId
26642
26675
  )}/deployments`,
26643
26676
  {
26644
26677
  method: "POST",
26645
- headers: { "Content-Type": "application/json" },
26646
- body: JSON.stringify(request2)
26678
+ // Let undici set Content-Type with the generated multipart boundary.
26679
+ body: createPreviewDeploymentForm(request2)
26647
26680
  }
26648
26681
  );
26649
26682
  }
@@ -26748,6 +26781,141 @@ function getHeadCommitMessage() {
26748
26781
  }
26749
26782
  }
26750
26783
  __name(getHeadCommitMessage, "getHeadCommitMessage");
26784
+ function getCommitSha() {
26785
+ return process.env.GITHUB_SHA || process.env.CI_COMMIT_SHA || process.env.CIRCLE_SHA1 || process.env.COMMIT_SHA || void 0;
26786
+ }
26787
+ __name(getCommitSha, "getCommitSha");
26788
+ function normalizeRepositoryUrl(repositoryUrl) {
26789
+ const trimmed = repositoryUrl.trim();
26790
+ if (!trimmed) {
26791
+ return void 0;
26792
+ }
26793
+ const scpLikeSshMatch = trimmed.match(/^git@([^:]+):(.+)$/);
26794
+ if (scpLikeSshMatch) {
26795
+ const [, host, pathname] = scpLikeSshMatch;
26796
+ return `https://${host}/${pathname.replace(/\.git$/, "")}`;
26797
+ }
26798
+ try {
26799
+ const url3 = new URL(trimmed);
26800
+ if (url3.protocol === "ssh:" && url3.username === "git") {
26801
+ return `https://${url3.host}${url3.pathname.replace(/\.git$/, "")}`;
26802
+ }
26803
+ if (url3.protocol !== "https:" && url3.protocol !== "http:") {
26804
+ return void 0;
26805
+ }
26806
+ url3.username = "";
26807
+ url3.password = "";
26808
+ url3.search = "";
26809
+ url3.hash = "";
26810
+ url3.pathname = url3.pathname.replace(/\.git$/, "");
26811
+ return url3.toString().replace(/\/$/, "");
26812
+ } catch {
26813
+ return void 0;
26814
+ }
26815
+ }
26816
+ __name(normalizeRepositoryUrl, "normalizeRepositoryUrl");
26817
+ function getRepositoryUrl() {
26818
+ const repositoryUrl = process.env.CI_PROJECT_URL || process.env.CI_REPOSITORY_URL || process.env.CIRCLE_REPOSITORY_URL || process.env.BUILDKITE_REPO || process.env.BITBUCKET_GIT_HTTP_ORIGIN || process.env.BITBUCKET_GIT_SSH_ORIGIN || process.env.REPOSITORY_URL;
26819
+ if (repositoryUrl) {
26820
+ return normalizeRepositoryUrl(repositoryUrl);
26821
+ }
26822
+ if (process.env.GITHUB_REPOSITORY) {
26823
+ const githubServerUrl = process.env.GITHUB_SERVER_URL || "https://github.com";
26824
+ return normalizeRepositoryUrl(
26825
+ `${githubServerUrl.replace(/\/$/, "")}/${process.env.GITHUB_REPOSITORY}`
26826
+ );
26827
+ }
26828
+ if (!shouldUseCIMetadataFallback()) {
26829
+ return void 0;
26830
+ }
26831
+ try {
26832
+ execSync(`git rev-parse --is-inside-work-tree`, { stdio: "ignore" });
26833
+ return normalizeRepositoryUrl(
26834
+ execSync(`git config --get remote.origin.url`).toString()
26835
+ );
26836
+ } catch {
26837
+ return void 0;
26838
+ }
26839
+ }
26840
+ __name(getRepositoryUrl, "getRepositoryUrl");
26841
+ function normalizePullRequestNumber(number4) {
26842
+ if (number4 === void 0) {
26843
+ return void 0;
26844
+ }
26845
+ const normalizedNumber = String(number4).trim();
26846
+ return normalizedNumber ? normalizedNumber : void 0;
26847
+ }
26848
+ __name(normalizePullRequestNumber, "normalizePullRequestNumber");
26849
+ function normalizePullRequestTitle(title) {
26850
+ if (title === void 0) {
26851
+ return void 0;
26852
+ }
26853
+ const trimmedTitle = title.trim();
26854
+ return trimmedTitle || void 0;
26855
+ }
26856
+ __name(normalizePullRequestTitle, "normalizePullRequestTitle");
26857
+ function getGitHubPullRequestMetadata() {
26858
+ if (process.env.GITHUB_EVENT_PATH) {
26859
+ try {
26860
+ const event = JSON.parse(
26861
+ readFileSync(process.env.GITHUB_EVENT_PATH, "utf8")
26862
+ );
26863
+ const number5 = normalizePullRequestNumber(event.pull_request?.number);
26864
+ const url3 = event.pull_request?.html_url ? normalizeRepositoryUrl(event.pull_request.html_url) : void 0;
26865
+ const title = normalizePullRequestTitle(event.pull_request?.title);
26866
+ if (number5 || url3 || title) {
26867
+ return { number: number5, url: url3, title };
26868
+ }
26869
+ } catch {
26870
+ }
26871
+ }
26872
+ const refPullRequestNumber = process.env.GITHUB_REF?.match(/^refs\/pull\/(\d+)\//)?.[1];
26873
+ const number4 = normalizePullRequestNumber(refPullRequestNumber);
26874
+ if (!number4 || !process.env.GITHUB_REPOSITORY) {
26875
+ return void 0;
26876
+ }
26877
+ const githubServerUrl = process.env.GITHUB_SERVER_URL || "https://github.com";
26878
+ return {
26879
+ number: number4,
26880
+ url: normalizeRepositoryUrl(
26881
+ `${githubServerUrl.replace(/\/$/, "")}/${process.env.GITHUB_REPOSITORY}/pull/${number4}`
26882
+ )
26883
+ };
26884
+ }
26885
+ __name(getGitHubPullRequestMetadata, "getGitHubPullRequestMetadata");
26886
+ function getGitLabPullRequestMetadata() {
26887
+ const number4 = normalizePullRequestNumber(process.env.CI_MERGE_REQUEST_IID);
26888
+ const projectUrl = process.env.CI_MERGE_REQUEST_PROJECT_URL || process.env.CI_PROJECT_URL;
26889
+ if (!number4 || !projectUrl) {
26890
+ return void 0;
26891
+ }
26892
+ const normalizedProjectUrl = projectUrl.replace(/\.git$/, "").replace(/\/$/, "");
26893
+ return {
26894
+ number: number4,
26895
+ url: normalizeRepositoryUrl(
26896
+ `${normalizedProjectUrl}/-/merge_requests/${number4}`
26897
+ ),
26898
+ title: normalizePullRequestTitle(process.env.CI_MERGE_REQUEST_TITLE)
26899
+ };
26900
+ }
26901
+ __name(getGitLabPullRequestMetadata, "getGitLabPullRequestMetadata");
26902
+ function getDirectPullRequestMetadata() {
26903
+ const directUrl = process.env.PULL_REQUEST_URL || process.env.PR_URL || process.env.CHANGE_URL || process.env.CIRCLE_PULL_REQUEST;
26904
+ const number4 = normalizePullRequestNumber(
26905
+ process.env.PULL_REQUEST_NUMBER || process.env.PR_NUMBER || process.env.CHANGE_ID
26906
+ );
26907
+ const url3 = directUrl ? normalizeRepositoryUrl(directUrl) : void 0;
26908
+ const title = normalizePullRequestTitle(process.env.PULL_REQUEST_TITLE);
26909
+ if (number4 || url3 || title) {
26910
+ return { number: number4, url: url3, title };
26911
+ }
26912
+ return void 0;
26913
+ }
26914
+ __name(getDirectPullRequestMetadata, "getDirectPullRequestMetadata");
26915
+ function getPullRequestMetadata() {
26916
+ return getDirectPullRequestMetadata() ?? getGitHubPullRequestMetadata() ?? getGitLabPullRequestMetadata();
26917
+ }
26918
+ __name(getPullRequestMetadata, "getPullRequestMetadata");
26751
26919
  function resolveWorkerName(args, config2) {
26752
26920
  const workerName = args.workerName ?? args["worker-name"] ?? config2.name;
26753
26921
  if (!workerName) {
@@ -27151,10 +27319,7 @@ async function prepareContainersForPreview(config2, workerName, previewSlug, cal
27151
27319
  return { scopedContainerConfig, normalisedContainerConfig };
27152
27320
  }
27153
27321
  __name(prepareContainersForPreview, "prepareContainersForPreview");
27154
- function toBase64(content) {
27155
- return Buffer.from(content).toString("base64");
27156
- }
27157
- __name(toBase64, "toBase64");
27322
+ var NO_ACTIVE_PREVIEW_URLS_MESSAGE = "Note: This Preview deployment has no active URLs. To get one, enable Preview Deployments on workers.dev or a custom domain. See https://developers.cloudflare.com/workers/previews/custom-domains/ for more information";
27158
27323
  function getPreviewMigrationsToUpload(workerName, config2, currentMigrationTag) {
27159
27324
  if (config2.migrations.length === 0) {
27160
27325
  return void 0;
@@ -27197,14 +27362,14 @@ function buildResultToDeploymentModules(buildResult, assetFiles) {
27197
27362
  {
27198
27363
  name: mainModuleName,
27199
27364
  content_type: mainContentType,
27200
- content_base64: toBase64(buildResult.content)
27365
+ content: buildResult.content
27201
27366
  },
27202
27367
  ...buildResult.modules.map((mod) => {
27203
27368
  const contentType = moduleTypeMimeType[mod.type ?? "text"] ?? "application/octet-stream";
27204
27369
  return {
27205
27370
  name: mod.name,
27206
27371
  content_type: contentType,
27207
- content_base64: toBase64(mod.content)
27372
+ content: mod.content
27208
27373
  };
27209
27374
  })
27210
27375
  ];
@@ -27213,7 +27378,7 @@ function buildResultToDeploymentModules(buildResult, assetFiles) {
27213
27378
  ...buildResult.sourceMaps.map((sourceMap) => ({
27214
27379
  name: sourceMap.name,
27215
27380
  content_type: "application/source-map",
27216
- content_base64: toBase64(sourceMap.content)
27381
+ content: sourceMap.content
27217
27382
  }))
27218
27383
  );
27219
27384
  }
@@ -27221,14 +27386,14 @@ function buildResultToDeploymentModules(buildResult, assetFiles) {
27221
27386
  deploymentModules.push({
27222
27387
  name: "_headers",
27223
27388
  content_type: "text/plain",
27224
- content_base64: toBase64(assetFiles._headers)
27389
+ content: assetFiles._headers
27225
27390
  });
27226
27391
  }
27227
27392
  if (assetFiles?._redirects !== void 0) {
27228
27393
  deploymentModules.push({
27229
27394
  name: "_redirects",
27230
27395
  content_type: "text/plain",
27231
- content_base64: toBase64(assetFiles._redirects)
27396
+ content: assetFiles._redirects
27232
27397
  });
27233
27398
  }
27234
27399
  return { main_module: mainModuleName, modules: deploymentModules };
@@ -27265,9 +27430,21 @@ async function assemblePreviewDeploymentSettings(config2, buildResult, accountId
27265
27430
  if (config2.compatibility_flags && config2.compatibility_flags.length > 0) {
27266
27431
  request2.compatibility_flags = config2.compatibility_flags;
27267
27432
  }
27268
- if (options.message || options.tag) {
27433
+ const repositoryUrl = options.repositoryUrl;
27434
+ const pullRequest = options.pullRequest;
27435
+ const commitSha = options.commitSha;
27436
+ if (options.message || options.tag || repositoryUrl || pullRequest || commitSha) {
27269
27437
  request2.annotations = {
27438
+ ...commitSha && { "workers/commit_sha": commitSha },
27270
27439
  ...options.message && { "workers/message": options.message },
27440
+ ...pullRequest?.number && {
27441
+ "workers/pull_request_number": pullRequest.number
27442
+ },
27443
+ ...pullRequest?.title && {
27444
+ "workers/pull_request_title": pullRequest.title
27445
+ },
27446
+ ...pullRequest?.url && { "workers/pull_request_url": pullRequest.url },
27447
+ ...repositoryUrl && { "workers/repository_url": repositoryUrl },
27271
27448
  ...options.tag && { "workers/tag": options.tag }
27272
27449
  };
27273
27450
  }
@@ -27340,14 +27517,21 @@ function formatUrlLines(label, urls) {
27340
27517
  ];
27341
27518
  }
27342
27519
  __name(formatUrlLines, "formatUrlLines");
27343
- function formatPreviewDeploymentSummary(previewResource, deployment, isNew) {
27520
+ function formatPreviewDeploymentSummary(previewResource, deployment, isNew, pullRequest) {
27344
27521
  const statusLabel = isNew ? chalk6.green("(new)") : chalk6.dim("(updated)");
27522
+ const pullRequestUrl = deployment.annotations?.["workers/pull_request_url"] ?? pullRequest?.url;
27523
+ const pullRequestNumber = deployment.annotations?.["workers/pull_request_number"] ?? pullRequest?.number;
27524
+ const hasActiveUrls = (previewResource.urls?.length ?? 0) > 0 || (deployment.urls?.length ?? 0) > 0;
27345
27525
  return [
27346
27526
  `${chalk6.bold("Preview:")} ${previewResource.name} ${statusLabel}`,
27347
27527
  ...formatUrlLines("Preview", previewResource.urls),
27348
27528
  "",
27349
27529
  `${chalk6.bold("Deployment ID:")} ${deployment.id}`,
27350
- ...formatUrlLines("Deployment", deployment.urls)
27530
+ ...formatUrlLines("Deployment", deployment.urls),
27531
+ ...pullRequestUrl || pullRequestNumber ? [
27532
+ `${chalk6.bold("Pull Request:")} ${pullRequestUrl ?? `#${pullRequestNumber}`}`
27533
+ ] : [],
27534
+ ...hasActiveUrls ? [] : [NO_ACTIVE_PREVIEW_URLS_MESSAGE]
27351
27535
  ].join("\n");
27352
27536
  }
27353
27537
  __name(formatPreviewDeploymentSummary, "formatPreviewDeploymentSummary");
@@ -27420,6 +27604,9 @@ async function preview(accountId, args, config2, buildResult, assetsOptions, cal
27420
27604
  const ignoreBaseConfig = args.ignoreBaseConfig;
27421
27605
  const fallbackTag = !args.tag && shouldUseCIMetadataFallback() ? getHeadCommitRef() : void 0;
27422
27606
  const fallbackMessage = !args.message && shouldUseCIMetadataFallback() ? getHeadCommitMessage() : void 0;
27607
+ const repositoryUrl = getRepositoryUrl();
27608
+ const pullRequest = getPullRequestMetadata();
27609
+ const commitSha = getCommitSha();
27423
27610
  let existingPreview = null;
27424
27611
  try {
27425
27612
  existingPreview = await getPreview(
@@ -27479,6 +27666,9 @@ async function preview(accountId, args, config2, buildResult, assetsOptions, cal
27479
27666
  {
27480
27667
  message: args.message ?? fallbackMessage,
27481
27668
  tag: args.tag ?? fallbackTag,
27669
+ repositoryUrl,
27670
+ pullRequest,
27671
+ commitSha,
27482
27672
  assetsOptions
27483
27673
  }
27484
27674
  );
@@ -27511,7 +27701,12 @@ async function preview(accountId, args, config2, buildResult, assetsOptions, cal
27511
27701
  );
27512
27702
  } else {
27513
27703
  logger.log(
27514
- formatPreviewDeploymentSummary(previewResource, deployment, isNewPreview)
27704
+ formatPreviewDeploymentSummary(
27705
+ previewResource,
27706
+ deployment,
27707
+ isNewPreview,
27708
+ pullRequest
27709
+ )
27515
27710
  );
27516
27711
  const topLevelBindings = getBindings(config2);
27517
27712
  if (Object.keys(topLevelBindings).length > 0) {
@@ -27862,4 +28057,4 @@ __name(previewSettingsUpdate, "previewSettingsUpdate");
27862
28057
  * THE SOFTWARE.
27863
28058
  */
27864
28059
 
27865
- export { ACTOR_BINDING_DEPENDS_ON_EXPORT_CODE, EXPORTS_RECONCILIATION_ERROR_CODE, INCONSISTENT_EXPORTS_ACROSS_VERSIONS_CODE, INVALID_INHERIT_BINDING_CODE, 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, 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, getConfigPatch, getDeployConfirmFunction, getEdgeKvUploadConcurrency, getHeadCommitMessage, getHeadCommitRef, getMigrationsToUpload, getPreview, getPreviewBaseConfig, getPreviewDeployment, getPreviewOwnedContainerClassNames, getQueue, getRemoteConfigDiff, getSettings, 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, printBindings, 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, warnOrError, workerNotFoundErrorMessage };
28060
+ 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, 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, printBindings, 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, warnOrError, workerNotFoundErrorMessage };