wrangler 4.113.0 → 4.115.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.
@@ -3299,8 +3299,8 @@ function formatConfigSnippet(snippet, configPath, formatted = true) {
3299
3299
  }
3300
3300
  }
3301
3301
  var UserError, FatalError, CommandLineArgsError, JsonFriendlyFatalError, MissingConfigError, CharacterCodes, ParseOptions, ScanError, SyntaxKind, parse2, ParseErrorCode, TomlError, DATE_TIME_RE, TomlDate, INT_REGEX, FLOAT_REGEX, LEADING_ZERO, ESCAPE_REGEX, ESC_MAP, KEY_PART_RE, BARE_KEY, dist_default, ParseError, APIError, units, UNSUPPORTED_BOMS, INHERIT_SYMBOL, SERVICE_TAG_PREFIX, ENVIRONMENT_TAG_PREFIX, PATH_TO_DEPLOY_CONFIG, JSON_CONFIG_FORMATS, esm_default, parseRawConfigFile; exports.experimental_readRawConfig = void 0;
3302
- var init_chunk_Y3JVLYM6 = __esm({
3303
- "../workers-utils/dist/chunk-Y3JVLYM6.mjs"() {
3302
+ var init_chunk_3K53PSCY = __esm({
3303
+ "../workers-utils/dist/chunk-3K53PSCY.mjs"() {
3304
3304
  init_import_meta_url();
3305
3305
  init_chunk_Q72B4Q5Z();
3306
3306
  __name(partitionExports, "partitionExports");
@@ -3772,10 +3772,20 @@ ${codeblock}`, options);
3772
3772
  * endpoint-specific structured error payloads.
3773
3773
  */
3774
3774
  meta;
3775
- constructor({ status: status2, ...rest }) {
3775
+ /**
3776
+ * Optional number of milliseconds the API asked us to wait before retrying,
3777
+ * derived from the response's `Retry-After` header (if present).
3778
+ */
3779
+ retryAfterMs;
3780
+ constructor({
3781
+ status: status2,
3782
+ retryAfterMs,
3783
+ ...rest
3784
+ }) {
3776
3785
  super(rest);
3777
3786
  this.name = this.constructor.name;
3778
3787
  this.#status = status2;
3788
+ this.retryAfterMs = retryAfterMs;
3779
3789
  }
3780
3790
  get status() {
3781
3791
  return this.#status;
@@ -34280,14 +34290,21 @@ function normalizeAndValidateConfig(rawConfig, configPath, userConfigPath, args,
34280
34290
  const diagnostics = new Diagnostics(
34281
34291
  `Processing ${configPath ? path2__default__namespace.default.relative(process.cwd(), configPath) : "wrangler"} configuration:`
34282
34292
  );
34293
+ const isRedirectedConfig22 = isRedirectedRawConfig(
34294
+ rawConfig,
34295
+ configPath,
34296
+ userConfigPath
34297
+ );
34283
34298
  if ("legacy_env" in rawConfig) {
34284
- diagnostics.errors.push(
34285
- dedent`
34286
- The "legacy_env" field is no longer supported, so please remove it from your configuration file.
34287
- Service environments have been removed, and each environment is now deployed as its own Worker named "<name>-<environment>". This matches the behaviour of "legacy_env = true", which was the default, so removing the field will not change how your Worker is deployed.
34288
- Refer to https://developers.cloudflare.com/workers/wrangler/environments/ for more information.
34289
- `
34290
- );
34299
+ if (!isRedirectedConfig22) {
34300
+ diagnostics.errors.push(
34301
+ dedent`
34302
+ The "legacy_env" field is no longer supported, so please remove it from your configuration file.
34303
+ Service environments have been removed, and each environment is now deployed as its own Worker named "<name>-<environment>". This matches the behaviour of "legacy_env = true", which was the default, so removing the field will not change how your Worker is deployed.
34304
+ Refer to https://developers.cloudflare.com/workers/wrangler/environments/ for more information.
34305
+ `
34306
+ );
34307
+ }
34291
34308
  delete rawConfig.legacy_env;
34292
34309
  }
34293
34310
  validateOptionalProperty(
@@ -34363,11 +34380,6 @@ function normalizeAndValidateConfig(rawConfig, configPath, userConfigPath, args,
34363
34380
  isDispatchNamespace,
34364
34381
  preserveOriginalMain
34365
34382
  );
34366
- const isRedirectedConfig22 = isRedirectedRawConfig(
34367
- rawConfig,
34368
- configPath,
34369
- userConfigPath
34370
- );
34371
34383
  const definedEnvironments = Object.keys(rawConfig.env ?? {});
34372
34384
  if (isRedirectedConfig22 && definedEnvironments.length > 0) {
34373
34385
  diagnostics.errors.push(
@@ -37702,6 +37714,7 @@ async function fetchInternalBase(complianceConfig, resource, init4 = {}, userAge
37702
37714
  logHeaders(response.headers, logger6);
37703
37715
  logger6.debugWithSanitization?.("RESPONSE:", jsonText);
37704
37716
  logger6.debug("-- END CF API RESPONSE");
37717
+ const retryAfterMs = parseRetryAfterMs(response.headers);
37705
37718
  if (!jsonText && (response.status === 204 || response.status === 205)) {
37706
37719
  return {
37707
37720
  response: {
@@ -37710,7 +37723,8 @@ async function fetchInternalBase(complianceConfig, resource, init4 = {}, userAge
37710
37723
  errors: [],
37711
37724
  messages: []
37712
37725
  },
37713
- status: response.status
37726
+ status: response.status,
37727
+ retryAfterMs
37714
37728
  };
37715
37729
  }
37716
37730
  if (isWAFBlockResponse(response.headers)) {
@@ -37719,12 +37733,13 @@ async function fetchInternalBase(complianceConfig, resource, init4 = {}, userAge
37719
37733
  method,
37720
37734
  resource,
37721
37735
  response.status,
37722
- response.statusText
37736
+ response.statusText,
37737
+ retryAfterMs
37723
37738
  );
37724
37739
  }
37725
37740
  try {
37726
37741
  const json22 = parseJSON(jsonText);
37727
- return { response: json22, status: response.status };
37742
+ return { response: json22, status: response.status, retryAfterMs };
37728
37743
  } catch {
37729
37744
  const rayId = extractWAFBlockRayId(response.headers);
37730
37745
  throw new APIError({
@@ -37739,12 +37754,17 @@ async function fetchInternalBase(complianceConfig, resource, init4 = {}, userAge
37739
37754
  ...rayId ? [{ text: `Cloudflare Ray ID: ${rayId}` }] : []
37740
37755
  ],
37741
37756
  status: response.status,
37757
+ retryAfterMs,
37742
37758
  telemetryMessage: false
37743
37759
  });
37744
37760
  }
37745
37761
  }
37746
37762
  async function fetchResultBase(complianceConfig, resource, init4 = {}, userAgent, logger6, queryParams, abortSignal, credentials) {
37747
- const { response: json22, status: status2 } = await fetchInternalBase(
37763
+ const {
37764
+ response: json22,
37765
+ status: status2,
37766
+ retryAfterMs
37767
+ } = await fetchInternalBase(
37748
37768
  complianceConfig,
37749
37769
  resource,
37750
37770
  init4,
@@ -37757,7 +37777,7 @@ async function fetchResultBase(complianceConfig, resource, init4 = {}, userAgent
37757
37777
  if (json22.success) {
37758
37778
  return json22.result;
37759
37779
  } else {
37760
- throwFetchError(resource, json22, status2);
37780
+ throwFetchError(resource, json22, status2, retryAfterMs);
37761
37781
  }
37762
37782
  }
37763
37783
  async function fetchListResultBase(complianceConfig, resource, init4 = {}, userAgent, logger6, queryParams, credentials) {
@@ -37769,7 +37789,11 @@ async function fetchListResultBase(complianceConfig, resource, init4 = {}, userA
37769
37789
  queryParams = new Url.URLSearchParams(queryParams);
37770
37790
  queryParams.set("cursor", cursor);
37771
37791
  }
37772
- const { response: json22, status: status2 } = await fetchInternalBase(
37792
+ const {
37793
+ response: json22,
37794
+ status: status2,
37795
+ retryAfterMs
37796
+ } = await fetchInternalBase(
37773
37797
  complianceConfig,
37774
37798
  resource,
37775
37799
  init4,
@@ -37787,7 +37811,7 @@ async function fetchListResultBase(complianceConfig, resource, init4 = {}, userA
37787
37811
  getMoreResults = false;
37788
37812
  }
37789
37813
  } else {
37790
- throwFetchError(resource, json22, status2);
37814
+ throwFetchError(resource, json22, status2, retryAfterMs);
37791
37815
  }
37792
37816
  }
37793
37817
  return results;
@@ -37802,6 +37826,22 @@ function truncate(text, maxLength) {
37802
37826
  function isWAFBlockResponse(headers) {
37803
37827
  return headers.get("cf-mitigated") === "challenge";
37804
37828
  }
37829
+ function parseRetryAfterValue(retryAfter) {
37830
+ if (!retryAfter) {
37831
+ return void 0;
37832
+ }
37833
+ if (/^\d+$/.test(retryAfter.trim())) {
37834
+ return Number(retryAfter) * 1e3;
37835
+ }
37836
+ const retryAfterDate = new Date(retryAfter);
37837
+ if (!Number.isNaN(retryAfterDate.getTime())) {
37838
+ return Math.max(0, retryAfterDate.getTime() - Date.now());
37839
+ }
37840
+ return void 0;
37841
+ }
37842
+ function parseRetryAfterMs(headers) {
37843
+ return parseRetryAfterValue(headers.get("Retry-After"));
37844
+ }
37805
37845
  function extractWAFBlockRayId(headers) {
37806
37846
  return headers.get("cf-ray") ?? void 0;
37807
37847
  }
@@ -37872,7 +37912,7 @@ function escapeCharacter(character) {
37872
37912
  return codePoint <= 65535 ? `\\u${codePoint.toString(16).toUpperCase().padStart(4, "0")}` : `\\u{${codePoint.toString(16).toUpperCase()}}`;
37873
37913
  }).join("");
37874
37914
  }
37875
- function throwFetchError(resource, response, status2) {
37915
+ function throwFetchError(resource, response, status2, retryAfterMs) {
37876
37916
  const errors = response.errors ?? [];
37877
37917
  for (const error522 of errors) {
37878
37918
  maybeThrowFriendlyError(error522);
@@ -37890,10 +37930,19 @@ function throwFetchError(resource, response, status2) {
37890
37930
  notes.push({ text: fallbackMessage });
37891
37931
  }
37892
37932
  }
37933
+ if (retryAfterMs !== void 0) {
37934
+ notes.push({
37935
+ text: `The API responded with a "Retry-After" header indicating you should wait ${Math.ceil(retryAfterMs / 1e3)} second(s) before retrying.`
37936
+ });
37937
+ }
37893
37938
  const error512 = new APIError({
37894
37939
  text: `A request to the Cloudflare API (${resource}) failed.`,
37895
37940
  notes,
37896
37941
  status: status2,
37942
+ // hoist the parsed `Retry-After` header (if any) so consumers such as
37943
+ // `retryOnAPIFailure()` can back off for the amount of time the API
37944
+ // asked us to wait, e.g. when rate limited (HTTP 429).
37945
+ retryAfterMs,
37897
37946
  telemetryMessage: false
37898
37947
  });
37899
37948
  const code = errors[0]?.code;
@@ -37907,7 +37956,7 @@ function throwFetchError(resource, response, status2) {
37907
37956
  error512.accountTag = extractAccountTag(resource);
37908
37957
  throw error512;
37909
37958
  }
37910
- function throwWAFBlockError(headers, method, resource, status2, statusText) {
37959
+ function throwWAFBlockError(headers, method, resource, status2, statusText, retryAfterMs) {
37911
37960
  const rayId = extractWAFBlockRayId(headers);
37912
37961
  throw new APIError({
37913
37962
  text: "The Cloudflare API responded with a WAF block page instead of the expected JSON response",
@@ -37924,6 +37973,7 @@ function throwWAFBlockError(headers, method, resource, status2, statusText) {
37924
37973
  }
37925
37974
  ],
37926
37975
  status: status2,
37976
+ retryAfterMs,
37927
37977
  telemetryMessage: false
37928
37978
  });
37929
37979
  }
@@ -38015,19 +38065,36 @@ async function retryOnAPIFailure(action, logger6, backoff = 0, attempts = MAX_AT
38015
38065
  return await action();
38016
38066
  } catch (err) {
38017
38067
  if (err instanceof APIError) {
38018
- if (!err.isRetryable()) {
38068
+ if (!err.isRetryable() && err.status !== 429) {
38019
38069
  throw err;
38020
38070
  }
38021
38071
  } else if (err instanceof DOMException && err.name === "TimeoutError") ;
38022
38072
  else if (!(err instanceof TypeError)) {
38023
38073
  throw err;
38024
38074
  }
38025
- logger6.debug(`Retrying API call after error...`);
38026
- logger6.debug(err);
38075
+ const retryAfterMs = err instanceof APIError ? err.retryAfterMs : void 0;
38076
+ if (retryAfterMs !== void 0 && retryAfterMs > MAX_RETRY_AFTER_MS) {
38077
+ throw err;
38078
+ }
38027
38079
  if (attempts <= 1) {
38028
38080
  throw err;
38029
38081
  }
38030
- await timersPromises.setTimeout(backoff, void 0, { signal: abortSignal });
38082
+ const jitter = Math.random() * 1e3;
38083
+ let wait = backoff;
38084
+ if (retryAfterMs !== void 0) {
38085
+ wait = retryAfterMs + jitter;
38086
+ } else if (err instanceof APIError && err.status === 429) {
38087
+ wait = Math.max(backoff, 1e3) + jitter;
38088
+ }
38089
+ if (retryAfterMs !== void 0) {
38090
+ logger6.info(
38091
+ `Received a "Retry-After" header from the Cloudflare API. Waiting ${Math.ceil(retryAfterMs / 1e3)} second(s) before retrying...`
38092
+ );
38093
+ } else {
38094
+ logger6.debug(`Retrying API call after error...`);
38095
+ logger6.debug(err);
38096
+ }
38097
+ await timersPromises.setTimeout(wait, void 0, { signal: abortSignal });
38031
38098
  return retryOnAPIFailure(
38032
38099
  action,
38033
38100
  logger6,
@@ -38126,15 +38193,15 @@ function getWorkerNameFromProject(projectPath) {
38126
38193
  }
38127
38194
  return getWorkerName(packageJsonName, projectPath);
38128
38195
  }
38129
- var import_undici, require_vendors, require_ci_info, require_command_exists, require_command_exists2, require_ini, require_strip_json_comments, require_utils2, require_deep_extend, require_minimist, require_rc, require_registry_url, require_safe_buffer, require_base64, require_registry_auth_token, require_update_check; exports.unstable_defaultWranglerConfig = void 0; exports.experimental_patchConfig = void 0; var getJSONPath, PatchConfigError, external_exports, core_exports2, _a, NEVER, $brand, $ZodAsyncError, $ZodEncodeError, globalConfig, util_exports, EVALUATING, captureStackTrace, allowsEval, getParsedType, propertyKeyTypes, primitiveTypes, NUMBER_FORMAT_RANGES, BIGINT_FORMAT_RANGES, Class, initializer, $ZodError, $ZodRealError, _parse, parse4, _parseAsync, parseAsync, _safeParse, safeParse, _safeParseAsync, safeParseAsync, _encode, encode, _decode, decode, _encodeAsync, encodeAsync, _decodeAsync, decodeAsync, _safeEncode, safeEncode, _safeDecode, safeDecode, _safeEncodeAsync, safeEncodeAsync, _safeDecodeAsync, safeDecodeAsync, regexes_exports, cuid, cuid2, ulid, xid, ksuid, nanoid, duration, extendedDuration, guid, uuid, uuid4, uuid6, uuid7, email, html5Email, rfc5322Email, unicodeEmail, idnEmail, browserEmail, _emoji, ipv4, ipv6, mac, cidrv4, cidrv6, base64, base64url, hostname, domain, httpProtocol, e164, dateSource, date, string, bigint, integer, number, boolean, _null, _undefined, lowercase, uppercase, hex, md5_hex, md5_base64, md5_base64url, sha1_hex, sha1_base64, sha1_base64url, sha256_hex, sha256_base64, sha256_base64url, sha384_hex, sha384_base64, sha384_base64url, sha512_hex, sha512_base64, sha512_base64url, $ZodCheck, numericOriginMap, $ZodCheckLessThan, $ZodCheckGreaterThan, $ZodCheckMultipleOf, $ZodCheckNumberFormat, $ZodCheckBigIntFormat, $ZodCheckMaxSize, $ZodCheckMinSize, $ZodCheckSizeEquals, $ZodCheckMaxLength, $ZodCheckMinLength, $ZodCheckLengthEquals, $ZodCheckStringFormat, $ZodCheckRegex, $ZodCheckLowerCase, $ZodCheckUpperCase, $ZodCheckIncludes, $ZodCheckStartsWith, $ZodCheckEndsWith, $ZodCheckProperty, $ZodCheckMimeType, $ZodCheckOverwrite, Doc, version, $ZodType, $ZodString, $ZodStringFormat, $ZodGUID, $ZodUUID, $ZodEmail, $ZodURL, $ZodEmoji, $ZodNanoID, $ZodCUID, $ZodCUID2, $ZodULID, $ZodXID, $ZodKSUID, $ZodISODateTime, $ZodISODate, $ZodISOTime, $ZodISODuration, $ZodIPv4, $ZodIPv6, $ZodMAC, $ZodCIDRv4, $ZodCIDRv6, $ZodBase64, $ZodBase64URL, $ZodE164, $ZodJWT, $ZodCustomStringFormat, $ZodNumber, $ZodNumberFormat, $ZodBoolean, $ZodBigInt, $ZodBigIntFormat, $ZodSymbol, $ZodUndefined, $ZodNull, $ZodAny, $ZodUnknown, $ZodNever, $ZodVoid, $ZodDate, $ZodArray, $ZodObject, $ZodObjectJIT, $ZodUnion, $ZodXor, $ZodDiscriminatedUnion, $ZodIntersection, $ZodTuple, $ZodRecord, $ZodMap, $ZodSet, $ZodEnum, $ZodLiteral, $ZodFile, $ZodTransform, $ZodOptional, $ZodExactOptional, $ZodNullable, $ZodDefault, $ZodPrefault, $ZodNonOptional, $ZodSuccess, $ZodCatch, $ZodNaN, $ZodPipe, $ZodCodec, $ZodPreprocess, $ZodReadonly, $ZodTemplateLiteral, $ZodFunction, $ZodPromise, $ZodLazy, $ZodCustom, locales_exports, error, error2, error3, error4, error5, error6, error7, error8, error9, error10, error11, error12, error13, error14, error15, error16, error17, error18, error19, error20, error21, error22, error23, error24, error25, error26, error27, capitalizeFirstCharacter, error28, error29, error30, error31, error32, error33, error34, error35, error36, error37, error38, error39, error40, error41, error42, error43, error44, error45, error46, error47, error48, error49, error50, _a2, $output, $input, $ZodRegistry, globalRegistry, TimePrecision, createToJSONSchemaMethod, createStandardJSONSchemaMethod, formatMap, stringProcessor, numberProcessor, booleanProcessor, bigintProcessor, symbolProcessor, nullProcessor, undefinedProcessor, voidProcessor, neverProcessor, anyProcessor, unknownProcessor, dateProcessor, enumProcessor, literalProcessor, nanProcessor, templateLiteralProcessor, fileProcessor, successProcessor, customProcessor, functionProcessor, transformProcessor, mapProcessor, setProcessor, arrayProcessor, objectProcessor, unionProcessor, intersectionProcessor, tupleProcessor, recordProcessor, nullableProcessor, nonoptionalProcessor, defaultProcessor, prefaultProcessor, catchProcessor, pipeProcessor, readonlyProcessor, promiseProcessor, optionalProcessor, lazyProcessor, allProcessors, JSONSchemaGenerator, json_schema_exports, schemas_exports2, checks_exports2, iso_exports, ZodISODateTime, ZodISODate, ZodISOTime, ZodISODuration, initializer2, ZodError, ZodRealError, parse22, parseAsync2, safeParse2, safeParseAsync2, encode2, decode2, encodeAsync2, decodeAsync2, safeEncode2, safeDecode2, safeEncodeAsync2, safeDecodeAsync2, _installedGroups, ZodType, _ZodString, ZodString, ZodStringFormat, ZodEmail, ZodGUID, ZodUUID, ZodURL, ZodEmoji, ZodNanoID, ZodCUID, ZodCUID2, ZodULID, ZodXID, ZodKSUID, ZodIPv4, ZodMAC, ZodIPv6, ZodCIDRv4, ZodCIDRv6, ZodBase64, ZodBase64URL, ZodE164, ZodJWT, ZodCustomStringFormat, ZodNumber, ZodNumberFormat, ZodBoolean, ZodBigInt, ZodBigIntFormat, ZodSymbol, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodNever, ZodVoid, ZodDate, ZodArray, ZodObject, ZodUnion, ZodXor, ZodDiscriminatedUnion, ZodIntersection, ZodTuple, ZodRecord, ZodMap, ZodSet, ZodEnum, ZodLiteral, ZodFile, ZodTransform, ZodOptional, ZodExactOptional, ZodNullable, ZodDefault, ZodPrefault, ZodNonOptional, ZodSuccess, ZodCatch, ZodNaN, ZodPipe, ZodCodec, ZodPreprocess, ZodReadonly, ZodTemplateLiteral, ZodLazy, ZodPromise, ZodFunction, ZodCustom, describe2, meta2, stringbool, ZodIssueCode, ZodFirstPartyTypeKind, z, RECOGNIZED_KEYS, coerce_exports, SENSITIVE_STEP_OUTPUT, MAX_WORKFLOW_NAME_LENGTH, ALLOWED_STRING_ID_PATTERN, ALLOWED_WORKFLOW_INSTANCE_ID_REGEX, ALLOWED_WORKFLOW_NAME_REGEX, getC3CommandFromEnv, getWranglerSendMetricsFromEnv, getWranglerSendErrorReportsFromEnv, getCloudflareApiEnvironmentFromEnv, COMPLIANCE_REGION_CONFIG_PUBLIC, COMPLIANCE_REGION_CONFIG_UNKNOWN, getCloudflareComplianceRegionFromEnv, getCloudflareComplianceRegion, getCloudflareApiBaseUrlFromEnv, getCloudflareApiBaseUrl, getSanitizeLogs, getOutputFileDirectoryFromEnv, getOutputFilePathFromEnv, getCIMatchTag, getCIOverrideName, getCIOverrideNetworkModeHost, getCIGeneratePreviewAlias, getWorkersCIBranchName, getBuildConditionsFromEnv, getBuildPlatformFromEnv, getRegistryPath, getD1ExtraLocationChoices, getDockerPath, getSubdomainMixedStateCheckDisabled, getCloudflareLoadDevVarsFromDotEnv, getCloudflareIncludeProcessEnvFromEnv, getTraceHeader, getDisableConfigWatching, getWranglerHideBanner, getCloudflareEnv, getOpenNextDeployFromEnv, getLocalExplorerEnabledFromEnv, getBrowserRenderingHeadfulFromEnv, getWranglerCacheDirFromEnv, getCloudflaredPathFromEnv, Diagnostics, appendEnvName, isString, isValidName, isValidDateTimeStringFormat, isStringArray, isOneOf, all, isMutuallyExclusiveWith, isBoolean, validateRequiredProperty, validateAtLeastOnePropertyRequired, validateOptionalProperty, validateTypedArray, validateOptionalTypedArray, isRequiredProperty, isOptionalProperty, hasProperty, validateAdditionalProperties, getBindingNames, isBindingList, isNamespaceList, isRecord, validateUniqueNameProperty, bucketFormatMessage, friendlyBindingNames, bindingTypeFriendlyNames, ENGLISH, ALLOWED_INSTANCE_TYPES, isRoute, isRouteArray, validateTailConsumers, validateStreamingTailConsumers, validateAndNormalizeRules, validateTriggers, validateRules, validateRule, validateDefines, validateVars, validateSecrets, validateBindingsProperty, validateUnsafeSettings, validateDurableObjectBinding, workflowNameFormatMessage, validateWorkflowBinding, validateCflogfwdrObject, validateCflogfwdrBinding, validateAssetsConfig, validateNamedSimpleBinding, validateAIBinding, validateVersionMetadataBinding, validateUnsafeBinding, validateBindingArray, validateCloudchamberConfig, validateKVBinding, validateSendEmailBinding, validateQueueBinding, validateR2Binding, validateD1Binding, validateVectorizeBinding, validateAISearchNamespaceBinding, validateAISearchBinding, validateAgentMemoryBinding, validateHyperdriveBinding, validateVpcServiceBinding, validateVpcNetworkBinding, validateBindingsHaveUniqueNames, validateServiceBinding, validateAnalyticsEngineBinding, validateWorkerNamespaceBinding, validateMTlsCertificateBinding, validateConsumer, validateCompatibilityDate, validatePipelineBinding, validateSecretsStoreSecretBinding, validateArtifactsBinding, validateHelloWorldBinding, validateFlagshipBinding, validateWorkerLoaderBinding, validateRateLimitBinding, validatePreviewsConfig, validateMigrations, VALID_EXPORT_STORAGES, JS_IDENTIFIER_RE, validateExports, validateObservability, validateCache, validatePythonModules, BINDING_LOCAL_SUPPORT, supportedPagesConfigFields, import_ci_info, arrayFormatter, signals, processOk, kExitEmitter, global2, ObjectDefineProperty, Emitter, SignalExitBase, signalExitWrap, SignalExitFallback, SignalExit, process3, onExit, load, unload, STALE_WRANGLER_TMP_DIR_MS, sweptTmpRoots, import_command_exists, UPDATE_SERVICE_URL, CLOUDFLARED_VERSION_PATTERN, GITHUB_RELEASE_BASE, TUNNEL_STARTUP_TIMEOUT_MS, TUNNEL_FORCE_KILL_TIMEOUT_MS, DEFAULT_TUNNEL_EXPIRY_MS, DEFAULT_TUNNEL_EXTENSION_MS, DEFAULT_TUNNEL_MAX_REMAINING_MS, DEFAULT_TUNNEL_REMINDER_INTERVAL_MS, QUICK_TUNNEL_URL_REGEX, import_update_check, UPDATE_CHECK_TIMEOUT_MS, TIMED_OUT, LOGGER_LEVELS, MAX_ATTEMPTS, NpmPackageManager, PnpmPackageManager, YarnPackageManager, BunPackageManager, NubPackageManager, invalidWorkerNameCharsRegex, invalidWorkerNameStartEndRegex, workerNameLengthLimit, friendlyBindingNames2;
38196
+ var import_undici, require_vendors, require_ci_info, require_command_exists, require_command_exists2, require_ini, require_strip_json_comments, require_utils2, require_deep_extend, require_minimist, require_rc, require_registry_url, require_safe_buffer, require_base64, require_registry_auth_token, require_update_check; exports.unstable_defaultWranglerConfig = void 0; exports.experimental_patchConfig = void 0; var getJSONPath, PatchConfigError, external_exports, core_exports2, _a, NEVER, $brand, $ZodAsyncError, $ZodEncodeError, globalConfig, util_exports, EVALUATING, captureStackTrace, allowsEval, getParsedType, propertyKeyTypes, primitiveTypes, NUMBER_FORMAT_RANGES, BIGINT_FORMAT_RANGES, Class, initializer, $ZodError, $ZodRealError, _parse, parse4, _parseAsync, parseAsync, _safeParse, safeParse, _safeParseAsync, safeParseAsync, _encode, encode, _decode, decode, _encodeAsync, encodeAsync, _decodeAsync, decodeAsync, _safeEncode, safeEncode, _safeDecode, safeDecode, _safeEncodeAsync, safeEncodeAsync, _safeDecodeAsync, safeDecodeAsync, regexes_exports, cuid, cuid2, ulid, xid, ksuid, nanoid, duration, extendedDuration, guid, uuid, uuid4, uuid6, uuid7, email, html5Email, rfc5322Email, unicodeEmail, idnEmail, browserEmail, _emoji, ipv4, ipv6, mac, cidrv4, cidrv6, base64, base64url, hostname, domain, httpProtocol, e164, dateSource, date, string, bigint, integer, number, boolean, _null, _undefined, lowercase, uppercase, hex, md5_hex, md5_base64, md5_base64url, sha1_hex, sha1_base64, sha1_base64url, sha256_hex, sha256_base64, sha256_base64url, sha384_hex, sha384_base64, sha384_base64url, sha512_hex, sha512_base64, sha512_base64url, $ZodCheck, numericOriginMap, $ZodCheckLessThan, $ZodCheckGreaterThan, $ZodCheckMultipleOf, $ZodCheckNumberFormat, $ZodCheckBigIntFormat, $ZodCheckMaxSize, $ZodCheckMinSize, $ZodCheckSizeEquals, $ZodCheckMaxLength, $ZodCheckMinLength, $ZodCheckLengthEquals, $ZodCheckStringFormat, $ZodCheckRegex, $ZodCheckLowerCase, $ZodCheckUpperCase, $ZodCheckIncludes, $ZodCheckStartsWith, $ZodCheckEndsWith, $ZodCheckProperty, $ZodCheckMimeType, $ZodCheckOverwrite, Doc, version, $ZodType, $ZodString, $ZodStringFormat, $ZodGUID, $ZodUUID, $ZodEmail, $ZodURL, $ZodEmoji, $ZodNanoID, $ZodCUID, $ZodCUID2, $ZodULID, $ZodXID, $ZodKSUID, $ZodISODateTime, $ZodISODate, $ZodISOTime, $ZodISODuration, $ZodIPv4, $ZodIPv6, $ZodMAC, $ZodCIDRv4, $ZodCIDRv6, $ZodBase64, $ZodBase64URL, $ZodE164, $ZodJWT, $ZodCustomStringFormat, $ZodNumber, $ZodNumberFormat, $ZodBoolean, $ZodBigInt, $ZodBigIntFormat, $ZodSymbol, $ZodUndefined, $ZodNull, $ZodAny, $ZodUnknown, $ZodNever, $ZodVoid, $ZodDate, $ZodArray, $ZodObject, $ZodObjectJIT, $ZodUnion, $ZodXor, $ZodDiscriminatedUnion, $ZodIntersection, $ZodTuple, $ZodRecord, $ZodMap, $ZodSet, $ZodEnum, $ZodLiteral, $ZodFile, $ZodTransform, $ZodOptional, $ZodExactOptional, $ZodNullable, $ZodDefault, $ZodPrefault, $ZodNonOptional, $ZodSuccess, $ZodCatch, $ZodNaN, $ZodPipe, $ZodCodec, $ZodPreprocess, $ZodReadonly, $ZodTemplateLiteral, $ZodFunction, $ZodPromise, $ZodLazy, $ZodCustom, locales_exports, error, error2, error3, error4, error5, error6, error7, error8, error9, error10, error11, error12, error13, error14, error15, error16, error17, error18, error19, error20, error21, error22, error23, error24, error25, error26, error27, capitalizeFirstCharacter, error28, error29, error30, error31, error32, error33, error34, error35, error36, error37, error38, error39, error40, error41, error42, error43, error44, error45, error46, error47, error48, error49, error50, _a2, $output, $input, $ZodRegistry, globalRegistry, TimePrecision, createToJSONSchemaMethod, createStandardJSONSchemaMethod, formatMap, stringProcessor, numberProcessor, booleanProcessor, bigintProcessor, symbolProcessor, nullProcessor, undefinedProcessor, voidProcessor, neverProcessor, anyProcessor, unknownProcessor, dateProcessor, enumProcessor, literalProcessor, nanProcessor, templateLiteralProcessor, fileProcessor, successProcessor, customProcessor, functionProcessor, transformProcessor, mapProcessor, setProcessor, arrayProcessor, objectProcessor, unionProcessor, intersectionProcessor, tupleProcessor, recordProcessor, nullableProcessor, nonoptionalProcessor, defaultProcessor, prefaultProcessor, catchProcessor, pipeProcessor, readonlyProcessor, promiseProcessor, optionalProcessor, lazyProcessor, allProcessors, JSONSchemaGenerator, json_schema_exports, schemas_exports2, checks_exports2, iso_exports, ZodISODateTime, ZodISODate, ZodISOTime, ZodISODuration, initializer2, ZodError, ZodRealError, parse22, parseAsync2, safeParse2, safeParseAsync2, encode2, decode2, encodeAsync2, decodeAsync2, safeEncode2, safeDecode2, safeEncodeAsync2, safeDecodeAsync2, _installedGroups, ZodType, _ZodString, ZodString, ZodStringFormat, ZodEmail, ZodGUID, ZodUUID, ZodURL, ZodEmoji, ZodNanoID, ZodCUID, ZodCUID2, ZodULID, ZodXID, ZodKSUID, ZodIPv4, ZodMAC, ZodIPv6, ZodCIDRv4, ZodCIDRv6, ZodBase64, ZodBase64URL, ZodE164, ZodJWT, ZodCustomStringFormat, ZodNumber, ZodNumberFormat, ZodBoolean, ZodBigInt, ZodBigIntFormat, ZodSymbol, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodNever, ZodVoid, ZodDate, ZodArray, ZodObject, ZodUnion, ZodXor, ZodDiscriminatedUnion, ZodIntersection, ZodTuple, ZodRecord, ZodMap, ZodSet, ZodEnum, ZodLiteral, ZodFile, ZodTransform, ZodOptional, ZodExactOptional, ZodNullable, ZodDefault, ZodPrefault, ZodNonOptional, ZodSuccess, ZodCatch, ZodNaN, ZodPipe, ZodCodec, ZodPreprocess, ZodReadonly, ZodTemplateLiteral, ZodLazy, ZodPromise, ZodFunction, ZodCustom, describe2, meta2, stringbool, ZodIssueCode, ZodFirstPartyTypeKind, z, RECOGNIZED_KEYS, coerce_exports, SENSITIVE_STEP_OUTPUT, MAX_WORKFLOW_NAME_LENGTH, ALLOWED_STRING_ID_PATTERN, ALLOWED_WORKFLOW_INSTANCE_ID_REGEX, ALLOWED_WORKFLOW_NAME_REGEX, getC3CommandFromEnv, getWranglerSendMetricsFromEnv, getWranglerSendErrorReportsFromEnv, getCloudflareApiEnvironmentFromEnv, COMPLIANCE_REGION_CONFIG_PUBLIC, COMPLIANCE_REGION_CONFIG_UNKNOWN, getCloudflareComplianceRegionFromEnv, getCloudflareComplianceRegion, getCloudflareApiBaseUrlFromEnv, getCloudflareApiBaseUrl, getSanitizeLogs, getOutputFileDirectoryFromEnv, getOutputFilePathFromEnv, getCIMatchTag, getCIOverrideName, getCIOverrideNetworkModeHost, getCIGeneratePreviewAlias, getWorkersCIBranchName, getBuildConditionsFromEnv, getBuildPlatformFromEnv, getRegistryPath, getD1ExtraLocationChoices, getDockerPath, getSubdomainMixedStateCheckDisabled, getCloudflareLoadDevVarsFromDotEnv, getCloudflareIncludeProcessEnvFromEnv, getTraceHeader, getDisableConfigWatching, getWranglerHideBanner, getCloudflareEnv, getOpenNextDeployFromEnv, getLocalExplorerEnabledFromEnv, getLocalObservabilityEnabledFromEnv, getBrowserRenderingHeadfulFromEnv, getWranglerCacheDirFromEnv, getCloudflaredPathFromEnv, Diagnostics, appendEnvName, isString, isValidName, isValidDateTimeStringFormat, isStringArray, isOneOf, all, isMutuallyExclusiveWith, isBoolean, validateRequiredProperty, validateAtLeastOnePropertyRequired, validateOptionalProperty, validateTypedArray, validateOptionalTypedArray, isRequiredProperty, isOptionalProperty, hasProperty, validateAdditionalProperties, getBindingNames, isBindingList, isNamespaceList, isRecord, validateUniqueNameProperty, bucketFormatMessage, friendlyBindingNames, bindingTypeFriendlyNames, ENGLISH, ALLOWED_INSTANCE_TYPES, isRoute, isRouteArray, validateTailConsumers, validateStreamingTailConsumers, validateAndNormalizeRules, validateTriggers, validateRules, validateRule, validateDefines, validateVars, validateSecrets, validateBindingsProperty, validateUnsafeSettings, validateDurableObjectBinding, workflowNameFormatMessage, validateWorkflowBinding, validateCflogfwdrObject, validateCflogfwdrBinding, validateAssetsConfig, validateNamedSimpleBinding, validateAIBinding, validateVersionMetadataBinding, validateUnsafeBinding, validateBindingArray, validateCloudchamberConfig, validateKVBinding, validateSendEmailBinding, validateQueueBinding, validateR2Binding, validateD1Binding, validateVectorizeBinding, validateAISearchNamespaceBinding, validateAISearchBinding, validateAgentMemoryBinding, validateHyperdriveBinding, validateVpcServiceBinding, validateVpcNetworkBinding, validateBindingsHaveUniqueNames, validateServiceBinding, validateAnalyticsEngineBinding, validateWorkerNamespaceBinding, validateMTlsCertificateBinding, validateConsumer, validateCompatibilityDate, validatePipelineBinding, validateSecretsStoreSecretBinding, validateArtifactsBinding, validateHelloWorldBinding, validateFlagshipBinding, validateWorkerLoaderBinding, validateRateLimitBinding, validatePreviewsConfig, validateMigrations, VALID_EXPORT_STORAGES, JS_IDENTIFIER_RE, validateExports, validateObservability, validateCache, validatePythonModules, BINDING_LOCAL_SUPPORT, supportedPagesConfigFields, import_ci_info, arrayFormatter, signals, processOk, kExitEmitter, global2, ObjectDefineProperty, Emitter, SignalExitBase, signalExitWrap, SignalExitFallback, SignalExit, process3, onExit, load, unload, STALE_WRANGLER_TMP_DIR_MS, sweptTmpRoots, import_command_exists, UPDATE_SERVICE_URL, CLOUDFLARED_VERSION_PATTERN, GITHUB_RELEASE_BASE, TUNNEL_STARTUP_TIMEOUT_MS, TUNNEL_FORCE_KILL_TIMEOUT_MS, DEFAULT_TUNNEL_EXPIRY_MS, DEFAULT_TUNNEL_EXTENSION_MS, DEFAULT_TUNNEL_MAX_REMAINING_MS, DEFAULT_TUNNEL_REMINDER_INTERVAL_MS, QUICK_TUNNEL_URL_REGEX, import_update_check, UPDATE_CHECK_TIMEOUT_MS, TIMED_OUT, LOGGER_LEVELS, MAX_ATTEMPTS, MAX_RETRY_AFTER_MS, NpmPackageManager, PnpmPackageManager, YarnPackageManager, BunPackageManager, NubPackageManager, invalidWorkerNameCharsRegex, invalidWorkerNameStartEndRegex, workerNameLengthLimit, friendlyBindingNames2;
38130
38197
  var init_dist = __esm({
38131
38198
  "../workers-utils/dist/index.mjs"() {
38132
38199
  init_import_meta_url();
38133
38200
  init_chunk_J6JRMPLM();
38134
38201
  init_chunk_34VZWBGB();
38135
38202
  init_chunk_34VZWBGB();
38136
- init_chunk_Y3JVLYM6();
38137
- init_chunk_Y3JVLYM6();
38203
+ init_chunk_3K53PSCY();
38204
+ init_chunk_3K53PSCY();
38138
38205
  init_chunk_53IMCORZ();
38139
38206
  init_chunk_53IMCORZ();
38140
38207
  init_chunk_Q72B4Q5Z();
@@ -51508,6 +51575,10 @@ var init_dist = __esm({
51508
51575
  variableName: "X_LOCAL_EXPLORER",
51509
51576
  defaultValue: true
51510
51577
  });
51578
+ getLocalObservabilityEnabledFromEnv = getBooleanEnvironmentVariableFactory({
51579
+ variableName: "X_LOCAL_OBSERVABILITY",
51580
+ defaultValue: false
51581
+ });
51511
51582
  getBrowserRenderingHeadfulFromEnv = getBooleanEnvironmentVariableFactory({
51512
51583
  variableName: "X_BROWSER_HEADFUL",
51513
51584
  defaultValue: false
@@ -53120,12 +53191,47 @@ Please add a binding for "${configBindingName}" to "env.${envName}.${field}.bind
53120
53191
  if (!isRemoteValid(value, field, diagnostics)) {
53121
53192
  isValid3 = false;
53122
53193
  }
53194
+ if (hasProperty(value, "local_dev")) {
53195
+ const localDev = value.local_dev;
53196
+ if (typeof localDev !== "object" || localDev === null) {
53197
+ diagnostics.errors.push(
53198
+ `"${field}" bindings should, optionally, have an object "local_dev" field but got ${JSON.stringify(
53199
+ value
53200
+ )}.`
53201
+ );
53202
+ isValid3 = false;
53203
+ } else {
53204
+ experimental(
53205
+ diagnostics,
53206
+ { local_dev: localDev },
53207
+ "local_dev.experimental_s3_credentials"
53208
+ );
53209
+ if (hasProperty(localDev, "experimental_s3_credentials")) {
53210
+ const credentials = localDev.experimental_s3_credentials;
53211
+ if (typeof credentials !== "object" || credentials === null || !isRequiredProperty(credentials, "accessKeyId", "string") || !isRequiredProperty(credentials, "secretAccessKey", "string")) {
53212
+ diagnostics.errors.push(
53213
+ `"${field}" bindings should, optionally, have a "local_dev.experimental_s3_credentials" field with string "accessKeyId" and "secretAccessKey" fields, but got ${JSON.stringify(
53214
+ value
53215
+ )}.`
53216
+ );
53217
+ isValid3 = false;
53218
+ }
53219
+ }
53220
+ validateAdditionalProperties(
53221
+ diagnostics,
53222
+ `${field}.local_dev`,
53223
+ Object.keys(localDev),
53224
+ ["experimental_s3_credentials"]
53225
+ );
53226
+ }
53227
+ }
53123
53228
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
53124
53229
  "binding",
53125
53230
  "bucket_name",
53126
53231
  "preview_bucket_name",
53127
53232
  "jurisdiction",
53128
- "remote"
53233
+ "remote",
53234
+ "local_dev"
53129
53235
  ]);
53130
53236
  return isValid3;
53131
53237
  }, "validateR2Binding");
@@ -55165,6 +55271,10 @@ ${resolution}`);
55165
55271
  __name2(truncate, "truncate");
55166
55272
  __name(isWAFBlockResponse, "isWAFBlockResponse");
55167
55273
  __name2(isWAFBlockResponse, "isWAFBlockResponse");
55274
+ __name(parseRetryAfterValue, "parseRetryAfterValue");
55275
+ __name2(parseRetryAfterValue, "parseRetryAfterValue");
55276
+ __name(parseRetryAfterMs, "parseRetryAfterMs");
55277
+ __name2(parseRetryAfterMs, "parseRetryAfterMs");
55168
55278
  __name(extractWAFBlockRayId, "extractWAFBlockRayId");
55169
55279
  __name2(extractWAFBlockRayId, "extractWAFBlockRayId");
55170
55280
  __name(extractAccountTag, "extractAccountTag");
@@ -55213,6 +55323,7 @@ ${resolution}`);
55213
55323
  __name(handleBrowserOpenError, "handleBrowserOpenError");
55214
55324
  __name2(handleBrowserOpenError, "handleBrowserOpenError");
55215
55325
  MAX_ATTEMPTS = 3;
55326
+ MAX_RETRY_AFTER_MS = 6e4;
55216
55327
  __name(retryOnAPIFailure, "retryOnAPIFailure");
55217
55328
  __name2(retryOnAPIFailure, "retryOnAPIFailure");
55218
55329
  __name(formatTime, "formatTime");
@@ -57111,7 +57222,7 @@ var name, version2;
57111
57222
  var init_package = __esm({
57112
57223
  "package.json"() {
57113
57224
  name = "wrangler";
57114
- version2 = "4.113.0";
57225
+ version2 = "4.115.0";
57115
57226
  }
57116
57227
  });
57117
57228
 
@@ -59829,6 +59940,19 @@ function getDebugFilepath() {
59829
59940
  const filepath = dir4.endsWith(".log") ? dir4 : path2__default__namespace.default.join(dir4, `wrangler-${date7}.log`);
59830
59941
  return path2__default__namespace.default.resolve(filepath);
59831
59942
  }
59943
+ function parseLogFileTimestamp(filename) {
59944
+ const match4 = /^wrangler-(\d{4}-\d{2}-\d{2})_(\d{2})-(\d{2})-(\d{2})_(\d{3})\.log$/.exec(
59945
+ filename
59946
+ );
59947
+ if (!match4) {
59948
+ return void 0;
59949
+ }
59950
+ const [, date7, hours, minutes, seconds, milliseconds] = match4;
59951
+ const timestamp = Date.parse(
59952
+ `${date7}T${hours}:${minutes}:${seconds}.${milliseconds}Z`
59953
+ );
59954
+ return Number.isNaN(timestamp) ? void 0 : timestamp;
59955
+ }
59832
59956
  async function cleanupOldLogFiles(logsDir) {
59833
59957
  if (!fs6.existsSync(logsDir)) {
59834
59958
  return;
@@ -59838,15 +59962,13 @@ async function cleanupOldLogFiles(logsDir) {
59838
59962
  try {
59839
59963
  const files = await fs$1.readdir(logsDir);
59840
59964
  const now = Date.now();
59841
- for (const f7 of files.filter(
59842
- (filename) => filename.startsWith("wrangler-") && filename.endsWith(".log")
59843
- )) {
59844
- const filePath = path2__default__namespace.default.join(logsDir, f7);
59965
+ for (const f7 of files) {
59966
+ const timestamp = parseLogFileTimestamp(f7);
59967
+ if (timestamp === void 0 || now - timestamp <= cutoffMs) {
59968
+ continue;
59969
+ }
59845
59970
  try {
59846
- const fileStat = await fs$1.stat(filePath);
59847
- if (now - fileStat.mtimeMs > cutoffMs) {
59848
- await fs$1.unlink(filePath);
59849
- }
59971
+ await fs$1.unlink(path2__default__namespace.default.join(logsDir, f7));
59850
59972
  } catch {
59851
59973
  }
59852
59974
  }
@@ -59912,6 +60034,7 @@ var init_log_file = __esm({
59912
60034
  }
59913
60035
  });
59914
60036
  __name(getDebugFilepath, "getDebugFilepath");
60037
+ __name(parseLogFileTimestamp, "parseLogFileTimestamp");
59915
60038
  __name(cleanupOldLogFiles, "cleanupOldLogFiles");
59916
60039
  debugLogFilepath = getDebugFilepath();
59917
60040
  mutex = new miniflare.Mutex();
@@ -120956,7 +121079,7 @@ function createProfileStore(args) {
120956
121079
  throw new UserError(
120957
121080
  `No profile is directly bound to "${formatDirectoryForUserError(normalizedDir)}". The active profile "${parentBinding.profile}" is bound at "${formatDirectoryForUserError(
120958
121081
  parentBinding.dir
120959
- )}". Run \`wrangler auth deactivate\` from that directory instead.`,
121082
+ )}". Run the deactivate command from that directory instead.`,
120960
121083
  { telemetryMessage: "auth deactivate wrong directory" }
120961
121084
  );
120962
121085
  }
@@ -121034,7 +121157,7 @@ function createProfileStore(args) {
121034
121157
  function validateProfileName(name2) {
121035
121158
  if (RESERVED_PROFILE_NAMES.includes(name2.toLowerCase())) {
121036
121159
  throw new UserError(
121037
- `"${name2}" is a reserved profile name. Use \`wrangler login\` and \`wrangler logout\` to manage the default profile, which applies as a global fallback.`,
121160
+ `"${name2}" is a reserved profile name. Use the login and logout commands to manage the default profile, which applies as a global fallback.`,
121038
121161
  { telemetryMessage: "auth profile reserved name" }
121039
121162
  );
121040
121163
  }
@@ -122293,8 +122416,8 @@ function scrubEncryptedCredentials(options) {
122293
122416
  return { backendAvailable: false, encryptedFileExisted };
122294
122417
  }
122295
122418
  var import_undici2, hasWarnedAboutDeprecatedV1ApiToken, getCloudflareAPITokenFromEnv, getCloudflareGlobalAuthKeyFromEnv, getCloudflareGlobalAuthEmailFromEnv, getAuthDomainFromEnv, getAuthUrlFromEnv, getTokenUrlFromEnv, getRevokeUrlFromEnv, getCloudflareAccountIdFromEnv, getAccessClientIdFromEnv, getAccessClientSecretFromEnv, getCfAuthorizationTokenFromEnv, getCloudflareAuthUseKeyringFromEnv, headersCache, usesAccessCache, RECOMMENDED_CODE_VERIFIER_LENGTH, RECOMMENDED_STATE_LENGTH, PKCE_CHARSET, generateAuthUrl, POW_MAX_ITERATIONS, TEMPORARY_TERMS_URLS, TEMPORARY_TERMS_PROMPT, TEMPORARY_TERMS_NOTICE, TEMPORARY_TERMS_ERROR, esm_default3, ErrorOAuth2, ErrorUnknown, ErrorNoAuthCode, ErrorInvalidReturnedStateParam, ErrorInvalidJson, ErrorInvalidScope, ErrorInvalidRequest, ErrorInvalidToken, ErrorAuthenticationGrant, ErrorUnauthorizedClient, ErrorAccessDenied, ErrorUnsupportedResponseType, ErrorServerError, ErrorTemporarilyUnavailable, ErrorAccessTokenResponse, ErrorInvalidClient, ErrorInvalidGrant, ErrorUnsupportedGrantType, RESERVED_PROFILE_NAMES, TomlError2, DATE_TIME_RE2, TomlDate2, INT_REGEX2, FLOAT_REGEX2, LEADING_ZERO2, ESCAPE_REGEX2, ESC_MAP2, KEY_PART_RE2, BARE_KEY2, dist_default2, FILE_FORMATS, USER_AUTH_CONFIG_PATH, FileCredentialStore, KEY_LENGTH_BYTES, IV_LENGTH_BYTES, TAG_LENGTH_BYTES, ALGORITHM_LABEL, CIPHER_NAME, EncryptedFileCredentialStore, PINNED_KEYRING_VERSION, npmRunner, cachedBindingPathByDir, entryFactoryOverride, runner, cachedProbeResult, LinuxSecretToolKeyProvider, SECURITY_EXIT_ITEM_NOT_FOUND, runner2, MacSecurityKeyProvider, NapiKeyringKeyProvider, testProviderFactory, sessionFlags;
122296
- var init_chunk_N7JTI7BC = __esm({
122297
- "../workers-auth/dist/chunk-N7JTI7BC.mjs"() {
122419
+ var init_chunk_5WRJ2ZUV = __esm({
122420
+ "../workers-auth/dist/chunk-5WRJ2ZUV.mjs"() {
122298
122421
  init_import_meta_url();
122299
122422
  init_chunk_O6YSETKJ();
122300
122423
  init_dist();
@@ -123329,7 +123452,7 @@ ${codeblock}`, options);
123329
123452
  var init_dist2 = __esm({
123330
123453
  "../workers-auth/dist/index.mjs"() {
123331
123454
  init_import_meta_url();
123332
- init_chunk_N7JTI7BC();
123455
+ init_chunk_5WRJ2ZUV();
123333
123456
  }
123334
123457
  });
123335
123458
  function createPreferences(getConfigPath2) {
@@ -124226,10 +124349,10 @@ function createAuthConfigFileHelpers(deps) {
124226
124349
  };
124227
124350
  }
124228
124351
  var millisecondsInMinute, minutesInYear, minutesInMonth, minutesInDay, constructFromSymbol, defaultOptions2, formatDistanceLocale, formatDistance, dateFormats, timeFormats, dateTimeFormats, formatLong, formatRelativeLocale, formatRelative, eraValues, quarterValues, monthValues, dayValues, dayPeriodValues, formattingDayPeriodValues, ordinalNumber, localize, matchOrdinalNumberPattern, parseOrdinalNumberPattern, matchEraPatterns, parseEraPatterns, matchQuarterPatterns, parseQuarterPatterns, matchMonthPatterns, parseMonthPatterns, matchDayPatterns, parseDayPatterns, matchDayPeriodPatterns, parseDayPeriodPatterns, match, enUS, MEMBERSHIPS_INACCESSIBLE_CODES, DIRECTORY_BINDINGS_FILE, ENCRYPTED_PROFILE_CONFIG_EXTENSION;
124229
- var init_chunk_FVDIXAPS = __esm({
124230
- "../workers-auth/dist/chunk-FVDIXAPS.mjs"() {
124352
+ var init_chunk_7PS36DJW = __esm({
124353
+ "../workers-auth/dist/chunk-7PS36DJW.mjs"() {
124231
124354
  init_import_meta_url();
124232
- init_chunk_N7JTI7BC();
124355
+ init_chunk_5WRJ2ZUV();
124233
124356
  init_chunk_O6YSETKJ();
124234
124357
  init_dist();
124235
124358
  __name(createPreferences, "createPreferences");
@@ -124743,7 +124866,7 @@ var DefaultScopes, DefaultScopeKeys, WRANGLER_KEYRING_SERVICE_NAME, WRANGLER_CLI
124743
124866
  var init_wrangler = __esm({
124744
124867
  "../workers-auth/dist/wrangler/index.mjs"() {
124745
124868
  init_import_meta_url();
124746
- init_chunk_FVDIXAPS();
124869
+ init_chunk_7PS36DJW();
124747
124870
  init_chunk_O6YSETKJ();
124748
124871
  init_dist();
124749
124872
  DefaultScopes = {
@@ -130271,6 +130394,7 @@ async function fetchR2Objects(complianceConfig, resource, bodyInit = {}) {
130271
130394
  text: `Failed to fetch ${resource} - ${response.status}: ${response.statusText};`,
130272
130395
  status: response.status,
130273
130396
  notes,
130397
+ retryAfterMs: parseRetryAfterMs(response.headers),
130274
130398
  telemetryMessage: false
130275
130399
  });
130276
130400
  if (errorCode !== void 0) {
@@ -130398,7 +130522,16 @@ async function fetchPagedListResult2(complianceConfig, resource, init4 = {}, que
130398
130522
  while (getMoreResults) {
130399
130523
  queryParams = new Url.URLSearchParams(queryParams);
130400
130524
  queryParams.set("page", String(page));
130401
- const { response: json3, status: status2 } = await fetchInternal(complianceConfig, resource, init4, queryParams);
130525
+ const {
130526
+ response: json3,
130527
+ status: status2,
130528
+ retryAfterMs
130529
+ } = await fetchInternal(
130530
+ complianceConfig,
130531
+ resource,
130532
+ init4,
130533
+ queryParams
130534
+ );
130402
130535
  if (json3.success) {
130403
130536
  results.push(...json3.result);
130404
130537
  if (hasMorePages(json3.result_info)) {
@@ -130407,7 +130540,7 @@ async function fetchPagedListResult2(complianceConfig, resource, init4 = {}, que
130407
130540
  getMoreResults = false;
130408
130541
  }
130409
130542
  } else {
130410
- throwFetchError(resource, json3, status2);
130543
+ throwFetchError(resource, json3, status2, retryAfterMs);
130411
130544
  }
130412
130545
  }
130413
130546
  return results;
@@ -130422,7 +130555,16 @@ async function fetchCursorPage(complianceConfig, resource, init4 = {}, queryPara
130422
130555
  if (cursor) {
130423
130556
  pageQueryParams.set("cursor", cursor);
130424
130557
  }
130425
- const { response: json3, status: status2 } = await fetchInternal(complianceConfig, resource, init4, pageQueryParams);
130558
+ const {
130559
+ response: json3,
130560
+ status: status2,
130561
+ retryAfterMs
130562
+ } = await fetchInternal(
130563
+ complianceConfig,
130564
+ resource,
130565
+ init4,
130566
+ pageQueryParams
130567
+ );
130426
130568
  if (json3.success) {
130427
130569
  if (currentPage === page) {
130428
130570
  results = json3.result;
@@ -130436,7 +130578,7 @@ async function fetchCursorPage(complianceConfig, resource, init4 = {}, queryPara
130436
130578
  break;
130437
130579
  }
130438
130580
  } else {
130439
- throwFetchError(resource, json3, status2);
130581
+ throwFetchError(resource, json3, status2, retryAfterMs);
130440
130582
  }
130441
130583
  }
130442
130584
  return results;
@@ -139416,7 +139558,7 @@ function renderEmailRoutingPlan(plan, workerName) {
139416
139558
  lines.push(zone.zone_name ?? zone.zone_id);
139417
139559
  for (const change of zone.changes) {
139418
139560
  counts[change.type]++;
139419
- const marker = CHANGE_MARKERS[change.type];
139561
+ const marker = CHANGE_MARKERS[change.type]();
139420
139562
  switch (change.type) {
139421
139563
  case "added":
139422
139564
  case "updated":
@@ -139640,37 +139782,47 @@ async function applyEmailRoutingAddresses({
139640
139782
  );
139641
139783
  }
139642
139784
  }
139643
- const failures = [];
139644
139785
  const totalChanges = plan.zones.reduce(
139645
139786
  (total, zone) => total + zone.changes.length,
139646
139787
  0
139647
139788
  );
139648
139789
  const progress = startApplyProgress(totalChanges);
139649
139790
  let completedChanges = 0;
139791
+ const queue = new PQueue({ concurrency: APPLY_ZONE_CONCURRENCY });
139792
+ const failuresByZone = [];
139793
+ const zonePromises = [];
139650
139794
  try {
139651
139795
  for (const zone of plan.zones) {
139652
- for (const change of zone.changes) {
139653
- try {
139654
- await applyChange(
139655
- config3,
139656
- zone.zone_id,
139657
- change,
139658
- scriptName,
139659
- ownerWorkerTag
139660
- );
139661
- } catch (e9) {
139662
- failures.push(
139663
- `${change.target}: ${e9 instanceof Error ? e9.message : String(e9)}`
139664
- );
139665
- } finally {
139666
- completedChanges++;
139667
- progress.update(completedChanges);
139668
- }
139669
- }
139796
+ const zoneFailures = [];
139797
+ failuresByZone.push(zoneFailures);
139798
+ zonePromises.push(
139799
+ queue.add(async () => {
139800
+ for (const change of zone.changes) {
139801
+ try {
139802
+ await applyChange(
139803
+ config3,
139804
+ zone.zone_id,
139805
+ change,
139806
+ scriptName,
139807
+ ownerWorkerTag
139808
+ );
139809
+ } catch (e9) {
139810
+ zoneFailures.push(
139811
+ `${change.target}: ${e9 instanceof Error ? e9.message : String(e9)}`
139812
+ );
139813
+ } finally {
139814
+ completedChanges++;
139815
+ progress.update(completedChanges);
139816
+ }
139817
+ }
139818
+ })
139819
+ );
139670
139820
  }
139821
+ await Promise.all(zonePromises);
139671
139822
  } finally {
139672
139823
  progress.stop();
139673
139824
  }
139825
+ const failures = failuresByZone.flat();
139674
139826
  if (failures.length > 0) {
139675
139827
  for (const failure of failures) {
139676
139828
  logger.error(`Email Routing change failed: ${failure}`);
@@ -142870,7 +143022,19 @@ async function createD1Database(complianceConfig, accountId, name2) {
142870
143022
  }
142871
143023
  if (errorCode === 7406) {
142872
143024
  throw new UserError(
142873
- "You have reached the maximum number of D1 databases for your account. Please consider deleting unused databases, or visit the D1 documentation to learn more: https://developers.cloudflare.com/d1/",
143025
+ esm_default5`
143026
+ You have reached the maximum number of D1 databases for your account.
143027
+
143028
+ On the Workers Free plan? Upgrade to create more:
143029
+ https://dash.cloudflare.com/${accountId}/workers/plans
143030
+
143031
+ Already on a paid plan? You can request a higher limit — learn more in the D1 docs:
143032
+ https://developers.cloudflare.com/d1/
143033
+
143034
+ Or free up space:
143035
+ To list your existing databases, run: wrangler d1 list
143036
+ To delete a database, run: wrangler d1 delete <database-name>
143037
+ `,
142874
143038
  { telemetryMessage: "d1 create database limit reached" }
142875
143039
  );
142876
143040
  }
@@ -146375,7 +146539,7 @@ async function previewSettingsUpdate(accountId, args, config3) {
146375
146539
  );
146376
146540
  logger.log(formatPreviewsSettings(workerName, updatedPreviewDefaults));
146377
146541
  }
146378
- var import_undici5, import_dotenv, require_ignore, require_heap, require_heap2, require_difflib, require_difflib2, require_util9, require_styles2, require_has_flag2, require_supports_colors2, require_trap2, require_zalgo2, require_america2, require_zebra2, require_rainbow2, require_random2, require_colors2, require_safe2, require_colorize, require_lib4, ApplicationRollout2, BadRequestWithCodeError2, CreateApplicationRolloutRequest2, DeploymentNotFoundError2, ImageRegistryAlreadyExistsError2, ImageRegistryIsPublic2, ImageRegistryNotAllowedError2, ImageRegistryNotFoundError2, ImageRegistryProtocolAlreadyExists2, ImageRegistryProtocolIsReferencedError2, ImageRegistryProtocolNotFound2, ProvisionerConfiguration2, RolloutStep2, SecretNameAlreadyExists2, SecretNotFound2, SSHPublicKeyNotFoundError2, UpdateApplicationRolloutRequest2, runDockerCmd2, isDockerRunning2, verifyDockerInstalled2, INVALID_INHERIT_BINDING_CODE, EXPORTS_RECONCILIATION_ERROR_CODE, INCONSISTENT_EXPORTS_ACROSS_VERSIONS_CODE, ACTOR_BINDING_DEPENDS_ON_EXPORT_CODE, WORKFLOW_CRON_REQUIRES_PAID_PLAN_CODE, WORKER_NOT_FOUND_ERR_CODE, WORKER_LEGACY_ENVIRONMENT_NOT_FOUND_ERR_CODE, CHANGE_MARKERS, PLAN_RETRY_WORKER_NOT_FOUND_CODE, PLAN_RETRY_TIMEOUT_MS, PLAN_RETRY_DELAY_MS, NON_INTERACTIVE_PROGRESS_INTERVAL, RESET_CATCH_ALL_BODY, queuesUrl, MAX_ROUTES_RULES, MAX_ROUTES_RULE_LENGTH, formatInvalidRoutes, MAX_ASSET_SIZE, CF_ASSETS_IGNORE_FILENAME, REDIRECTS_FILENAME, HEADERS_FILENAME, import_ignore, types, other_default, types2, standard_default, __classPrivateFieldGet7, _Mime_extensionToType, _Mime_typeToExtension, _Mime_typeToExtensions, Mime, Mime_default, src_default, normalizeFilePath, getContentType, hashFile, decodeJwtPayload, isJwtExpired, BULK_UPLOAD_CONCURRENCY, EDGE_KV_UPLOAD_CONCURRENCY, MAX_UPLOAD_ATTEMPTS, MAX_UPLOAD_GATEWAY_ERRORS, MAX_DIFF_LINES, syncAssets, buildAssetManifest, WORKER_JS_FILENAME, ONE_KIB_BYTES, MAX_GZIP_SIZE_BYTES, BLANK_INPUT, suppressNotFoundError, esm_default5, MAX_PACKAGE_DEPENDENCIES, isConnectedStatusExplained, ProvisionResourceHandler, R2Handler, AISearchNamespaceHandler, AgentMemoryNamespaceHandler, QueueHandler, DispatchNamespaceHandler, FlagshipHandler, KVHandler, D1Handler, HANDLERS, external_exports2, util, objectUtil, ZodParsedType, getParsedType2, ZodIssueCode2, quotelessJson, ZodError2, errorMap, en_default2, overrideErrorMap, makeIssue, EMPTY_PATH, ParseStatus, INVALID, DIRTY, OK, isAborted, isDirty, isValid, isAsync, errorUtil, ParseInputLazyPath, handleResult, ZodType2, cuidRegex, cuid2Regex, ulidRegex, uuidRegex, nanoidRegex, jwtRegex, durationRegex, emailRegex, _emojiRegex, emojiRegex2, ipv4Regex, ipv4CidrRegex, ipv6Regex, ipv6CidrRegex, base64Regex, base64urlRegex, dateRegexSource, dateRegex, ZodString2, ZodNumber2, ZodBigInt2, ZodBoolean2, ZodDate2, ZodSymbol2, ZodUndefined2, ZodNull2, ZodAny2, ZodUnknown2, ZodNever2, ZodVoid2, ZodArray2, ZodObject2, ZodUnion2, getDiscriminator, ZodDiscriminatedUnion2, ZodIntersection2, ZodTuple2, ZodRecord2, ZodMap2, ZodSet2, ZodFunction2, ZodLazy2, ZodLiteral2, ZodEnum2, ZodNativeEnum, ZodPromise2, ZodEffects, ZodOptional2, ZodNullable2, ZodDefault2, ZodCatch2, ZodNaN2, BRAND, ZodBranded, ZodPipeline, ZodReadonly2, late, ZodFirstPartyTypeKind2, instanceOfType, stringType, numberType, nanType, bigIntType, booleanType, dateType, symbolType, undefinedType, nullType, anyType, unknownType, neverType, voidType, arrayType, objectType, strictObjectType, unionType, discriminatedUnionType, intersectionType, tupleType, recordType, mapType, setType, functionType, lazyType, literalType, enumType, nativeEnumType, promiseType, effectsType, optionalType, nullableType, preprocessType, pipelineType, ostring, onumber, oboolean, coerce, NEVER2, InternalConfigSchema, StaticRoutingSchema, MetadataStaticRedirectEntry, MetadataRedirectEntry, MetadataStaticRedirects, MetadataRedirects, MetadataHeaderEntry, MetadataHeaders, RedirectsSchema, HeadersSchema, sourceMappingPrepareStackTrace, retrieveSourceMapOverride, placeholderError, CALL_SITE_REGEXP, CallSite, WORKFLOW_NOT_FOUND_CODE, import_json_diff, reorderableBindings, getCloudflareAccountIdFromEnv2, validateRoutes2, MAX_DNS_LABEL_LENGTH, HASH_LENGTH, ALIAS_VALIDATION_REGEX, BOX, CONFIG_MARKER;
146542
+ var import_undici5, import_dotenv, require_ignore, require_heap, require_heap2, require_difflib, require_difflib2, require_util9, require_styles2, require_has_flag2, require_supports_colors2, require_trap2, require_zalgo2, require_america2, require_zebra2, require_rainbow2, require_random2, require_colors2, require_safe2, require_colorize, require_lib4, ApplicationRollout2, BadRequestWithCodeError2, CreateApplicationRolloutRequest2, DeploymentNotFoundError2, ImageRegistryAlreadyExistsError2, ImageRegistryIsPublic2, ImageRegistryNotAllowedError2, ImageRegistryNotFoundError2, ImageRegistryProtocolAlreadyExists2, ImageRegistryProtocolIsReferencedError2, ImageRegistryProtocolNotFound2, ProvisionerConfiguration2, RolloutStep2, SecretNameAlreadyExists2, SecretNotFound2, SSHPublicKeyNotFoundError2, UpdateApplicationRolloutRequest2, runDockerCmd2, isDockerRunning2, verifyDockerInstalled2, INVALID_INHERIT_BINDING_CODE, EXPORTS_RECONCILIATION_ERROR_CODE, INCONSISTENT_EXPORTS_ACROSS_VERSIONS_CODE, ACTOR_BINDING_DEPENDS_ON_EXPORT_CODE, WORKFLOW_CRON_REQUIRES_PAID_PLAN_CODE, WORKER_NOT_FOUND_ERR_CODE, WORKER_LEGACY_ENVIRONMENT_NOT_FOUND_ERR_CODE, CHANGE_MARKERS, PLAN_RETRY_WORKER_NOT_FOUND_CODE, PLAN_RETRY_TIMEOUT_MS, PLAN_RETRY_DELAY_MS, NON_INTERACTIVE_PROGRESS_INTERVAL, APPLY_ZONE_CONCURRENCY, RESET_CATCH_ALL_BODY, queuesUrl, MAX_ROUTES_RULES, MAX_ROUTES_RULE_LENGTH, formatInvalidRoutes, MAX_ASSET_SIZE, CF_ASSETS_IGNORE_FILENAME, REDIRECTS_FILENAME, HEADERS_FILENAME, import_ignore, types, other_default, types2, standard_default, __classPrivateFieldGet7, _Mime_extensionToType, _Mime_typeToExtension, _Mime_typeToExtensions, Mime, Mime_default, src_default, normalizeFilePath, getContentType, hashFile, decodeJwtPayload, isJwtExpired, BULK_UPLOAD_CONCURRENCY, EDGE_KV_UPLOAD_CONCURRENCY, MAX_UPLOAD_ATTEMPTS, MAX_UPLOAD_GATEWAY_ERRORS, MAX_DIFF_LINES, syncAssets, buildAssetManifest, WORKER_JS_FILENAME, ONE_KIB_BYTES, MAX_GZIP_SIZE_BYTES, BLANK_INPUT, suppressNotFoundError, esm_default5, MAX_PACKAGE_DEPENDENCIES, isConnectedStatusExplained, ProvisionResourceHandler, R2Handler, AISearchNamespaceHandler, AgentMemoryNamespaceHandler, QueueHandler, DispatchNamespaceHandler, FlagshipHandler, KVHandler, D1Handler, HANDLERS, external_exports2, util, objectUtil, ZodParsedType, getParsedType2, ZodIssueCode2, quotelessJson, ZodError2, errorMap, en_default2, overrideErrorMap, makeIssue, EMPTY_PATH, ParseStatus, INVALID, DIRTY, OK, isAborted, isDirty, isValid, isAsync, errorUtil, ParseInputLazyPath, handleResult, ZodType2, cuidRegex, cuid2Regex, ulidRegex, uuidRegex, nanoidRegex, jwtRegex, durationRegex, emailRegex, _emojiRegex, emojiRegex2, ipv4Regex, ipv4CidrRegex, ipv6Regex, ipv6CidrRegex, base64Regex, base64urlRegex, dateRegexSource, dateRegex, ZodString2, ZodNumber2, ZodBigInt2, ZodBoolean2, ZodDate2, ZodSymbol2, ZodUndefined2, ZodNull2, ZodAny2, ZodUnknown2, ZodNever2, ZodVoid2, ZodArray2, ZodObject2, ZodUnion2, getDiscriminator, ZodDiscriminatedUnion2, ZodIntersection2, ZodTuple2, ZodRecord2, ZodMap2, ZodSet2, ZodFunction2, ZodLazy2, ZodLiteral2, ZodEnum2, ZodNativeEnum, ZodPromise2, ZodEffects, ZodOptional2, ZodNullable2, ZodDefault2, ZodCatch2, ZodNaN2, BRAND, ZodBranded, ZodPipeline, ZodReadonly2, late, ZodFirstPartyTypeKind2, instanceOfType, stringType, numberType, nanType, bigIntType, booleanType, dateType, symbolType, undefinedType, nullType, anyType, unknownType, neverType, voidType, arrayType, objectType, strictObjectType, unionType, discriminatedUnionType, intersectionType, tupleType, recordType, mapType, setType, functionType, lazyType, literalType, enumType, nativeEnumType, promiseType, effectsType, optionalType, nullableType, preprocessType, pipelineType, ostring, onumber, oboolean, coerce, NEVER2, InternalConfigSchema, StaticRoutingSchema, MetadataStaticRedirectEntry, MetadataRedirectEntry, MetadataStaticRedirects, MetadataRedirects, MetadataHeaderEntry, MetadataHeaders, RedirectsSchema, HeadersSchema, sourceMappingPrepareStackTrace, retrieveSourceMapOverride, placeholderError, CALL_SITE_REGEXP, CallSite, WORKFLOW_NOT_FOUND_CODE, import_json_diff, reorderableBindings, getCloudflareAccountIdFromEnv2, validateRoutes2, MAX_DNS_LABEL_LENGTH, HASH_LENGTH, ALIAS_VALIDATION_REGEX, BOX, CONFIG_MARKER;
146379
146543
  var init_dist8 = __esm({
146380
146544
  "../deploy-helpers/dist/index.mjs"() {
146381
146545
  init_import_meta_url();
@@ -149327,10 +149491,10 @@ var init_dist8 = __esm({
149327
149491
  __name(planHasDestructiveChanges, "planHasDestructiveChanges");
149328
149492
  __name3(planHasDestructiveChanges, "planHasDestructiveChanges");
149329
149493
  CHANGE_MARKERS = {
149330
- added: "+",
149331
- updated: "~",
149332
- deleted: "-",
149333
- conflict: "!"
149494
+ added: /* @__PURE__ */ __name3(() => source_default.green("+"), "added"),
149495
+ updated: /* @__PURE__ */ __name3(() => source_default.yellow("~"), "updated"),
149496
+ deleted: /* @__PURE__ */ __name3(() => source_default.red("-"), "deleted"),
149497
+ conflict: /* @__PURE__ */ __name3(() => source_default.red("!"), "conflict")
149334
149498
  };
149335
149499
  __name(describeRemoteAction, "describeRemoteAction");
149336
149500
  __name3(describeRemoteAction, "describeRemoteAction");
@@ -149342,6 +149506,7 @@ var init_dist8 = __esm({
149342
149506
  PLAN_RETRY_TIMEOUT_MS = 3e4;
149343
149507
  PLAN_RETRY_DELAY_MS = 3e3;
149344
149508
  NON_INTERACTIVE_PROGRESS_INTERVAL = 10;
149509
+ APPLY_ZONE_CONCURRENCY = 10;
149345
149510
  __name(applyProgressMessage, "applyProgressMessage");
149346
149511
  __name3(applyProgressMessage, "applyProgressMessage");
149347
149512
  __name(startApplyProgress, "startApplyProgress");
@@ -156903,18 +157068,18 @@ var require_async = __commonJS({
156903
157068
  ];
156904
157069
  }, "defaultPaths");
156905
157070
  var defaultIsFile = /* @__PURE__ */ __name(function isFile3(file5, cb2) {
156906
- fs34.stat(file5, function(err, stat11) {
157071
+ fs34.stat(file5, function(err, stat10) {
156907
157072
  if (!err) {
156908
- return cb2(null, stat11.isFile() || stat11.isFIFO());
157073
+ return cb2(null, stat10.isFile() || stat10.isFIFO());
156909
157074
  }
156910
157075
  if (err.code === "ENOENT" || err.code === "ENOTDIR") return cb2(null, false);
156911
157076
  return cb2(err);
156912
157077
  });
156913
157078
  }, "isFile");
156914
157079
  var defaultIsDir = /* @__PURE__ */ __name(function isDirectory4(dir4, cb2) {
156915
- fs34.stat(dir4, function(err, stat11) {
157080
+ fs34.stat(dir4, function(err, stat10) {
156916
157081
  if (!err) {
156917
- return cb2(null, stat11.isDirectory());
157082
+ return cb2(null, stat10.isDirectory());
156918
157083
  }
156919
157084
  if (err.code === "ENOENT" || err.code === "ENOTDIR") return cb2(null, false);
156920
157085
  return cb2(err);
@@ -157405,21 +157570,21 @@ var require_sync = __commonJS({
157405
157570
  }, "defaultPaths");
157406
157571
  var defaultIsFile = /* @__PURE__ */ __name(function isFile3(file5) {
157407
157572
  try {
157408
- var stat11 = fs34.statSync(file5, { throwIfNoEntry: false });
157573
+ var stat10 = fs34.statSync(file5, { throwIfNoEntry: false });
157409
157574
  } catch (e9) {
157410
157575
  if (e9 && (e9.code === "ENOENT" || e9.code === "ENOTDIR")) return false;
157411
157576
  throw e9;
157412
157577
  }
157413
- return !!stat11 && (stat11.isFile() || stat11.isFIFO());
157578
+ return !!stat10 && (stat10.isFile() || stat10.isFIFO());
157414
157579
  }, "isFile");
157415
157580
  var defaultIsDir = /* @__PURE__ */ __name(function isDirectory4(dir4) {
157416
157581
  try {
157417
- var stat11 = fs34.statSync(dir4, { throwIfNoEntry: false });
157582
+ var stat10 = fs34.statSync(dir4, { throwIfNoEntry: false });
157418
157583
  } catch (e9) {
157419
157584
  if (e9 && (e9.code === "ENOENT" || e9.code === "ENOTDIR")) return false;
157420
157585
  throw e9;
157421
157586
  }
157422
- return !!stat11 && stat11.isDirectory();
157587
+ return !!stat10 && stat10.isDirectory();
157423
157588
  }, "isDirectory");
157424
157589
  var defaultRealpathSync = /* @__PURE__ */ __name(function realpathSync5(x6) {
157425
157590
  try {
@@ -160024,9 +160189,9 @@ var init_fs = __esm({
160024
160189
  if (dirPath === (await destDirPromise).symbolic) return;
160025
160190
  await prepareDirectory(path2__default__namespace.dirname(dirPath));
160026
160191
  try {
160027
- const stat11 = await fs$1__namespace.lstat(dirPath);
160028
- if (stat11.isDirectory()) return;
160029
- if (stat11.isSymbolicLink()) try {
160192
+ const stat10 = await fs$1__namespace.lstat(dirPath);
160193
+ if (stat10.isDirectory()) return;
160194
+ if (stat10.isSymbolicLink()) try {
160030
160195
  const realPath = await getRealDir(dirPath, `Symlink "${dirPath}" points outside the extraction directory.`);
160031
160196
  if ((await fs$1__namespace.stat(realPath)).isDirectory()) return;
160032
160197
  } catch (err) {
@@ -163391,16 +163556,16 @@ var require_windows = __commonJS({
163391
163556
  return false;
163392
163557
  }
163393
163558
  __name(checkPathExt, "checkPathExt");
163394
- function checkStat(stat11, path89, options) {
163395
- if (!stat11.isSymbolicLink() && !stat11.isFile()) {
163559
+ function checkStat(stat10, path89, options) {
163560
+ if (!stat10.isSymbolicLink() && !stat10.isFile()) {
163396
163561
  return false;
163397
163562
  }
163398
163563
  return checkPathExt(path89, options);
163399
163564
  }
163400
163565
  __name(checkStat, "checkStat");
163401
163566
  function isexe(path89, options, cb2) {
163402
- fs34.stat(path89, function(er2, stat11) {
163403
- cb2(er2, er2 ? false : checkStat(stat11, path89, options));
163567
+ fs34.stat(path89, function(er2, stat10) {
163568
+ cb2(er2, er2 ? false : checkStat(stat10, path89, options));
163404
163569
  });
163405
163570
  }
163406
163571
  __name(isexe, "isexe");
@@ -163419,8 +163584,8 @@ var require_mode = __commonJS({
163419
163584
  isexe.sync = sync2;
163420
163585
  var fs34 = __require("fs");
163421
163586
  function isexe(path89, options, cb2) {
163422
- fs34.stat(path89, function(er2, stat11) {
163423
- cb2(er2, er2 ? false : checkStat(stat11, options));
163587
+ fs34.stat(path89, function(er2, stat10) {
163588
+ cb2(er2, er2 ? false : checkStat(stat10, options));
163424
163589
  });
163425
163590
  }
163426
163591
  __name(isexe, "isexe");
@@ -163428,14 +163593,14 @@ var require_mode = __commonJS({
163428
163593
  return checkStat(fs34.statSync(path89), options);
163429
163594
  }
163430
163595
  __name(sync2, "sync");
163431
- function checkStat(stat11, options) {
163432
- return stat11.isFile() && checkMode(stat11, options);
163596
+ function checkStat(stat10, options) {
163597
+ return stat10.isFile() && checkMode(stat10, options);
163433
163598
  }
163434
163599
  __name(checkStat, "checkStat");
163435
- function checkMode(stat11, options) {
163436
- var mod2 = stat11.mode;
163437
- var uid = stat11.uid;
163438
- var gid = stat11.gid;
163600
+ function checkMode(stat10, options) {
163601
+ var mod2 = stat10.mode;
163602
+ var uid = stat10.uid;
163603
+ var gid = stat10.gid;
163439
163604
  var myUid = options.uid !== void 0 ? options.uid : process.getuid && process.getuid();
163440
163605
  var myGid = options.gid !== void 0 ? options.gid : process.getgid && process.getgid();
163441
163606
  var u8 = parseInt("100", 8);
@@ -165775,10 +165940,13 @@ function kvNamespaceEntry({ binding, id: originalId, remote }, remoteProxyConnec
165775
165940
  }
165776
165941
  return [binding, { id, remoteProxyConnectionString }];
165777
165942
  }
165778
- function r2BucketEntry({ binding, bucket_name, remote }, remoteProxyConnectionString) {
165943
+ function r2BucketEntry({ binding, bucket_name, remote, local_dev }, remoteProxyConnectionString) {
165779
165944
  const id = getRemoteId(bucket_name) ?? binding;
165780
165945
  if (!remoteProxyConnectionString || !remote) {
165781
- return [binding, { id }];
165946
+ return [
165947
+ binding,
165948
+ { id, s3Credentials: local_dev?.experimental_s3_credentials }
165949
+ ];
165782
165950
  }
165783
165951
  return [binding, { id, remoteProxyConnectionString }];
165784
165952
  }
@@ -166414,6 +166582,9 @@ async function buildMiniflareOptions(log2, config3, proxyToUserWorkerAuthenticat
166414
166582
  unsafeProxySharedSecret: proxyToUserWorkerAuthenticationSecret,
166415
166583
  unsafeTriggerHandlers: true,
166416
166584
  unsafeLocalExplorer: getLocalExplorerEnabledFromEnv(),
166585
+ // The one switch for local observability: this env var tells Miniflare core
166586
+ // to attach the trace collector to each user worker.
166587
+ unsafeObservability: getLocalObservabilityEnabledFromEnv(),
166417
166588
  unsafeInspectDurableObjects: true,
166418
166589
  telemetry: getMetricsConfig({ sendMetrics: config3.sendMetrics }),
166419
166590
  // The way we run Miniflare instances with wrangler dev is that there are two:
@@ -166903,7 +167074,7 @@ var CF_KEYRING_SERVICE_NAME, CF_CLI_NAME, CF_OAUTH_CALLBACK_URL, CF_CONSENT_PAGE
166903
167074
  var init_cf = __esm({
166904
167075
  "../workers-auth/dist/cf/index.mjs"() {
166905
167076
  init_import_meta_url();
166906
- init_chunk_FVDIXAPS();
167077
+ init_chunk_7PS36DJW();
166907
167078
  init_chunk_O6YSETKJ();
166908
167079
  init_dist();
166909
167080
  CF_KEYRING_SERVICE_NAME = "cloudflare";
@@ -167038,7 +167209,8 @@ var init_cf = __esm({
167038
167209
  cliName: CF_CLI_NAME,
167039
167210
  commands: {
167040
167211
  login: "cf auth login",
167041
- whoami: "cf auth whoami"
167212
+ whoami: "cf auth whoami",
167213
+ createProfile: "cf auth create"
167042
167214
  },
167043
167215
  keyringServiceName: CF_KEYRING_SERVICE_NAME,
167044
167216
  clientId: getClientIdFromEnv2,
@@ -171094,6 +171266,7 @@ function handleUserFriendlyError(error54, accountId) {
171094
171266
  if (error54 instanceof APIError) switch (error54.code) {
171095
171267
  case 9106:
171096
171268
  case 1e4:
171269
+ case 10405:
171097
171270
  throw new RemoteSessionAuthenticationError(error54);
171098
171271
  case 10063: {
171099
171272
  const onboardingLink = accountId ? `https://dash.cloudflare.com/${accountId}/workers/onboarding` : "https://dash.cloudflare.com/?to=/:account/workers/onboarding";
@@ -171132,6 +171305,7 @@ function findRemoteSessionAuthError(error54) {
171132
171305
  if (error54 instanceof Error) return findRemoteSessionAuthError(error54.cause);
171133
171306
  }
171134
171307
  async function startRemoteProxySession(bindings2, options) {
171308
+ for (const [name2, binding] of Object.entries(bindings2 ?? {})) if (binding.type === "flagship" && binding.app_id === void 0) throw new UserError(`Flagship binding "${name2}" has no \`app_id\` and has not been created, but needs to run remotely. Run \`wrangler flagship apps create\` to create an app.`, { telemetryMessage: "flagship remote binding missing app_id" });
171135
171309
  options.logger.log(source_default.dim("\u2394 Establishing remote connection..."));
171136
171310
  initLogger(getInternalLogger(options.logger));
171137
171311
  const rawBindings = toRawBindings(bindings2);
@@ -171280,7 +171454,7 @@ var init_dist12 = __esm({
171280
171454
  init_wrapper();
171281
171455
  init_create_worker_upload_form();
171282
171456
  import_undici8 = __toESM(require_undici(), 1);
171283
- version3 = "0.0.1";
171457
+ version3 = "0.0.3";
171284
171458
  NoDefaultValueProvided2 = class extends UserError {
171285
171459
  static {
171286
171460
  __name(this, "NoDefaultValueProvided");
@@ -171291,7 +171465,7 @@ var init_dist12 = __esm({
171291
171465
  };
171292
171466
  __name(createRemoteBindingsAuth, "createRemoteBindingsAuth");
171293
171467
  __name(getRemoteBindingsAuthHook, "getRemoteBindingsAuthHook");
171294
- ProxyServerWorker_default = '// ../../node_modules/.pnpm/capnweb@0.5.0/node_modules/capnweb/dist/index-workers.js\nimport * as cfw from "cloudflare:workers";\nvar WORKERS_MODULE_SYMBOL = /* @__PURE__ */ Symbol("workers-module");\nglobalThis[WORKERS_MODULE_SYMBOL] = cfw;\nif (!Symbol.dispose) {\n Symbol.dispose = /* @__PURE__ */ Symbol.for("dispose");\n}\nif (!Symbol.asyncDispose) {\n Symbol.asyncDispose = /* @__PURE__ */ Symbol.for("asyncDispose");\n}\nif (!Promise.withResolvers) {\n Promise.withResolvers = function() {\n let resolve;\n let reject;\n const promise = new Promise((res, rej) => {\n resolve = res;\n reject = rej;\n });\n return { promise, resolve, reject };\n };\n}\nvar workersModule = globalThis[WORKERS_MODULE_SYMBOL];\nvar RpcTarget = workersModule ? workersModule.RpcTarget : class {\n};\nvar AsyncFunction = (async function() {\n}).constructor;\nfunction typeForRpc(value) {\n switch (typeof value) {\n case "boolean":\n case "number":\n case "string":\n return "primitive";\n case "undefined":\n return "undefined";\n case "object":\n case "function":\n break;\n case "bigint":\n return "bigint";\n default:\n return "unsupported";\n }\n if (value === null) {\n return "primitive";\n }\n let prototype = Object.getPrototypeOf(value);\n switch (prototype) {\n case Object.prototype:\n return "object";\n case Function.prototype:\n case AsyncFunction.prototype:\n return "function";\n case Array.prototype:\n return "array";\n case Date.prototype:\n return "date";\n case Uint8Array.prototype:\n return "bytes";\n case WritableStream.prototype:\n return "writable";\n case ReadableStream.prototype:\n return "readable";\n case Headers.prototype:\n return "headers";\n case Request.prototype:\n return "request";\n case Response.prototype:\n return "response";\n // TODO: All other structured clone types.\n case RpcStub.prototype:\n return "stub";\n case RpcPromise.prototype:\n return "rpc-promise";\n // TODO: Promise<T> or thenable\n default:\n if (workersModule) {\n if (prototype == workersModule.RpcStub.prototype || value instanceof workersModule.ServiceStub) {\n return "rpc-target";\n } else if (prototype == workersModule.RpcPromise.prototype || prototype == workersModule.RpcProperty.prototype) {\n return "rpc-thenable";\n }\n }\n if (value instanceof RpcTarget) {\n return "rpc-target";\n }\n if (value instanceof Error) {\n return "error";\n }\n return "unsupported";\n }\n}\nfunction mapNotLoaded() {\n throw new Error("RPC map() implementation was not loaded.");\n}\nvar mapImpl = { applyMap: mapNotLoaded, sendMap: mapNotLoaded };\nfunction streamNotLoaded() {\n throw new Error("Stream implementation was not loaded.");\n}\nvar streamImpl = {\n createWritableStreamHook: streamNotLoaded,\n createWritableStreamFromHook: streamNotLoaded,\n createReadableStreamHook: streamNotLoaded\n};\nvar StubHook = class {\n // Like call(), but designed for streaming calls (e.g. WritableStream writes). Returns:\n // - promise: A Promise<void> for the completion of the call.\n // - size: If the call was remote, the byte size of the serialized message. For local calls,\n // undefined is returned, indicating the caller should await the promise to serialize writes\n // (no overlapping).\n stream(path, args) {\n let hook = this.call(path, args);\n let pulled = hook.pull();\n let promise;\n if (pulled instanceof Promise) {\n promise = pulled.then((p) => {\n p.dispose();\n });\n } else {\n pulled.dispose();\n promise = Promise.resolve();\n }\n return { promise };\n }\n};\nvar ErrorStubHook = class extends StubHook {\n constructor(error) {\n super();\n this.error = error;\n }\n call(path, args) {\n return this;\n }\n map(path, captures, instructions) {\n return this;\n }\n get(path) {\n return this;\n }\n dup() {\n return this;\n }\n pull() {\n return Promise.reject(this.error);\n }\n ignoreUnhandledRejections() {\n }\n dispose() {\n }\n onBroken(callback) {\n try {\n callback(this.error);\n } catch (err) {\n Promise.resolve(err);\n }\n }\n};\nvar DISPOSED_HOOK = new ErrorStubHook(\n new Error("Attempted to use RPC stub after it has been disposed.")\n);\nvar doCall = (hook, path, params) => {\n return hook.call(path, params);\n};\nfunction withCallInterceptor(interceptor, callback) {\n let oldValue = doCall;\n doCall = interceptor;\n try {\n return callback();\n } finally {\n doCall = oldValue;\n }\n}\nvar RAW_STUB = /* @__PURE__ */ Symbol("realStub");\nvar PROXY_HANDLERS = {\n apply(target, thisArg, argumentsList) {\n let stub = target.raw;\n return new RpcPromise(doCall(\n stub.hook,\n stub.pathIfPromise || [],\n RpcPayload.fromAppParams(argumentsList)\n ), []);\n },\n get(target, prop, receiver) {\n let stub = target.raw;\n if (prop === RAW_STUB) {\n return stub;\n } else if (prop in RpcPromise.prototype) {\n return stub[prop];\n } else if (typeof prop === "string") {\n return new RpcPromise(\n stub.hook,\n stub.pathIfPromise ? [...stub.pathIfPromise, prop] : [prop]\n );\n } else if (prop === Symbol.dispose && (!stub.pathIfPromise || stub.pathIfPromise.length == 0)) {\n return () => {\n stub.hook.dispose();\n stub.hook = DISPOSED_HOOK;\n };\n } else {\n return void 0;\n }\n },\n has(target, prop) {\n let stub = target.raw;\n if (prop === RAW_STUB) {\n return true;\n } else if (prop in RpcPromise.prototype) {\n return prop in stub;\n } else if (typeof prop === "string") {\n return true;\n } else if (prop === Symbol.dispose && (!stub.pathIfPromise || stub.pathIfPromise.length == 0)) {\n return true;\n } else {\n return false;\n }\n },\n construct(target, args) {\n throw new Error("An RPC stub cannot be used as a constructor.");\n },\n defineProperty(target, property, attributes) {\n throw new Error("Can\'t define properties on RPC stubs.");\n },\n deleteProperty(target, p) {\n throw new Error("Can\'t delete properties on RPC stubs.");\n },\n getOwnPropertyDescriptor(target, p) {\n return void 0;\n },\n getPrototypeOf(target) {\n return Object.getPrototypeOf(target.raw);\n },\n isExtensible(target) {\n return false;\n },\n ownKeys(target) {\n return [];\n },\n preventExtensions(target) {\n return true;\n },\n set(target, p, newValue, receiver) {\n throw new Error("Can\'t assign properties on RPC stubs.");\n },\n setPrototypeOf(target, v) {\n throw new Error("Can\'t override prototype of RPC stubs.");\n }\n};\nvar RpcStub = class _RpcStub extends RpcTarget {\n // Although `hook` and `path` are declared `public` here, they are effectively hidden by the\n // proxy.\n constructor(hook, pathIfPromise) {\n super();\n if (!(hook instanceof StubHook)) {\n let value = hook;\n if (value instanceof RpcTarget || value instanceof Function) {\n hook = TargetStubHook.create(value, void 0);\n } else {\n hook = new PayloadStubHook(RpcPayload.fromAppReturn(value));\n }\n if (pathIfPromise) {\n throw new TypeError("RpcStub constructor expected one argument, received two.");\n }\n }\n this.hook = hook;\n this.pathIfPromise = pathIfPromise;\n let func = () => {\n };\n func.raw = this;\n return new Proxy(func, PROXY_HANDLERS);\n }\n hook;\n pathIfPromise;\n dup() {\n let target = this[RAW_STUB];\n if (target.pathIfPromise) {\n return new _RpcStub(target.hook.get(target.pathIfPromise));\n } else {\n return new _RpcStub(target.hook.dup());\n }\n }\n onRpcBroken(callback) {\n this[RAW_STUB].hook.onBroken(callback);\n }\n map(func) {\n let { hook, pathIfPromise } = this[RAW_STUB];\n return mapImpl.sendMap(hook, pathIfPromise || [], func);\n }\n toString() {\n return "[object RpcStub]";\n }\n};\nvar RpcPromise = class extends RpcStub {\n // TODO: Support passing target value or promise to constructor.\n constructor(hook, pathIfPromise) {\n super(hook, pathIfPromise);\n }\n then(onfulfilled, onrejected) {\n return pullPromise(this).then(...arguments);\n }\n catch(onrejected) {\n return pullPromise(this).catch(...arguments);\n }\n finally(onfinally) {\n return pullPromise(this).finally(...arguments);\n }\n toString() {\n return "[object RpcPromise]";\n }\n};\nfunction unwrapStubTakingOwnership(stub) {\n let { hook, pathIfPromise } = stub[RAW_STUB];\n if (pathIfPromise && pathIfPromise.length > 0) {\n return hook.get(pathIfPromise);\n } else {\n return hook;\n }\n}\nfunction unwrapStubAndDup(stub) {\n let { hook, pathIfPromise } = stub[RAW_STUB];\n if (pathIfPromise) {\n return hook.get(pathIfPromise);\n } else {\n return hook.dup();\n }\n}\nfunction unwrapStubNoProperties(stub) {\n let { hook, pathIfPromise } = stub[RAW_STUB];\n if (pathIfPromise && pathIfPromise.length > 0) {\n return void 0;\n }\n return hook;\n}\nfunction unwrapStubOrParent(stub) {\n return stub[RAW_STUB].hook;\n}\nfunction unwrapStubAndPath(stub) {\n return stub[RAW_STUB];\n}\nasync function pullPromise(promise) {\n let { hook, pathIfPromise } = promise[RAW_STUB];\n if (pathIfPromise.length > 0) {\n hook = hook.get(pathIfPromise);\n }\n let payload = await hook.pull();\n return payload.deliverResolve();\n}\nvar RpcPayload = class _RpcPayload {\n // Private constructor; use factory functions above to construct.\n constructor(value, source, hooks, promises) {\n this.value = value;\n this.source = source;\n this.hooks = hooks;\n this.promises = promises;\n }\n // Create a payload from a value passed as params to an RPC from the app.\n //\n // The payload does NOT take ownership of any stubs in `value`, and but promises not to modify\n // `value`. If the payload is delivered locally, `value` will be deep-copied first, so as not\n // to have the sender and recipient end up sharing the same mutable object. `value` will not be\n // touched again after the call returns synchronously (returns a promise) -- by that point,\n // the value has either been copied or serialized to the wire.\n static fromAppParams(value) {\n return new _RpcPayload(value, "params");\n }\n // Create a payload from a value return from an RPC implementation by the app.\n //\n // Unlike fromAppParams(), in this case the payload takes ownership of all stubs in `value`, and\n // may hold onto `value` for an arbitrarily long time (e.g. to serve pipelined requests). It\n // will still avoid modifying `value` and will make a deep copy if it is delivered locally.\n static fromAppReturn(value) {\n return new _RpcPayload(value, "return");\n }\n // Combine an array of payloads into a single payload whose value is an array. Ownership of all\n // stubs is transferred from the inputs to the outputs, hence if the output is disposed, the\n // inputs should not be. (In case of exception, nothing is disposed, though.)\n static fromArray(array) {\n let hooks = [];\n let promises = [];\n let resultArray = [];\n for (let payload of array) {\n payload.ensureDeepCopied();\n for (let hook of payload.hooks) {\n hooks.push(hook);\n }\n for (let promise of payload.promises) {\n if (promise.parent === payload) {\n promise = {\n parent: resultArray,\n property: resultArray.length,\n promise: promise.promise\n };\n }\n promises.push(promise);\n }\n resultArray.push(payload.value);\n }\n return new _RpcPayload(resultArray, "owned", hooks, promises);\n }\n // Create a payload from a value parsed off the wire using Evaluator.evaluate().\n //\n // A payload is constructed with a null value and the given hooks and promises arrays. The value\n // is expected to be filled in by the evaluator, and the hooks and promises arrays are expected\n // to be extended with stubs found during parsing. (This weird usage model is necessary so that\n // if the root value turns out to be a promise, its `parent` in `promises` can be the payload\n // object itself.)\n //\n // When done, the payload takes ownership of the final value and all the stubs within. It may\n // modify the value in preparation for delivery, and may deliver the value directly to the app\n // without copying.\n static forEvaluate(hooks, promises) {\n return new _RpcPayload(null, "owned", hooks, promises);\n }\n // Deep-copy the given value, including dup()ing all stubs.\n //\n // If `value` is a function, it should be bound to `oldParent` as its `this`.\n //\n // If deep-copying from a branch of some other RpcPayload, it must be provided, to make sure\n // RpcTargets found within don\'t get duplicate stubs.\n static deepCopyFrom(value, oldParent, owner) {\n let result = new _RpcPayload(null, "owned", [], []);\n result.value = result.deepCopy(\n value,\n oldParent,\n "value",\n result,\n /*dupStubs=*/\n true,\n owner\n );\n return result;\n }\n // For `source === "return"` payloads only, this tracks any StubHooks created around RpcTargets\n // or WritableStreams found in the payload at the time that it is serialized (or deep-copied) for\n // return, so that we can make sure they are not disposed before the pipeline ends.\n //\n // This is initialized on first use.\n rpcTargets;\n // Get the StubHook representing the given RpcTarget found inside this payload.\n getHookForRpcTarget(target, parent, dupStubs = true) {\n if (this.source === "params") {\n if (dupStubs) {\n let dupable = target;\n if (typeof dupable.dup === "function") {\n target = dupable.dup();\n }\n }\n return TargetStubHook.create(target, parent);\n } else if (this.source === "return") {\n let hook = this.rpcTargets?.get(target);\n if (hook) {\n if (dupStubs) {\n return hook.dup();\n } else {\n this.rpcTargets?.delete(target);\n return hook;\n }\n } else {\n hook = TargetStubHook.create(target, parent);\n if (dupStubs) {\n if (!this.rpcTargets) {\n this.rpcTargets = /* @__PURE__ */ new Map();\n }\n this.rpcTargets.set(target, hook);\n return hook.dup();\n } else {\n return hook;\n }\n }\n } else {\n throw new Error("owned payload shouldn\'t contain raw RpcTargets");\n }\n }\n // Get the StubHook representing the given WritableStream found inside this payload.\n getHookForWritableStream(stream, parent, dupStubs = true) {\n if (this.source === "params") {\n return streamImpl.createWritableStreamHook(stream);\n } else if (this.source === "return") {\n let hook = this.rpcTargets?.get(stream);\n if (hook) {\n if (dupStubs) {\n return hook.dup();\n } else {\n this.rpcTargets?.delete(stream);\n return hook;\n }\n } else {\n hook = streamImpl.createWritableStreamHook(stream);\n if (dupStubs) {\n if (!this.rpcTargets) {\n this.rpcTargets = /* @__PURE__ */ new Map();\n }\n this.rpcTargets.set(stream, hook);\n return hook.dup();\n } else {\n return hook;\n }\n }\n } else {\n throw new Error("owned payload shouldn\'t contain raw WritableStreams");\n }\n }\n // Get the StubHook representing the given ReadableStream found inside this payload.\n getHookForReadableStream(stream, parent, dupStubs = true) {\n if (this.source === "params") {\n return streamImpl.createReadableStreamHook(stream);\n } else if (this.source === "return") {\n let hook = this.rpcTargets?.get(stream);\n if (hook) {\n if (dupStubs) {\n return hook.dup();\n } else {\n this.rpcTargets?.delete(stream);\n return hook;\n }\n } else {\n hook = streamImpl.createReadableStreamHook(stream);\n if (dupStubs) {\n if (!this.rpcTargets) {\n this.rpcTargets = /* @__PURE__ */ new Map();\n }\n this.rpcTargets.set(stream, hook);\n return hook.dup();\n } else {\n return hook;\n }\n }\n } else {\n throw new Error("owned payload shouldn\'t contain raw ReadableStreams");\n }\n }\n deepCopy(value, oldParent, property, parent, dupStubs, owner) {\n let kind = typeForRpc(value);\n switch (kind) {\n case "unsupported":\n return value;\n case "primitive":\n case "bigint":\n case "date":\n case "bytes":\n case "error":\n case "undefined":\n return value;\n case "array": {\n let array = value;\n let len = array.length;\n let result = new Array(len);\n for (let i = 0; i < len; i++) {\n result[i] = this.deepCopy(array[i], array, i, result, dupStubs, owner);\n }\n return result;\n }\n case "object": {\n let result = {};\n let object = value;\n for (let i in object) {\n result[i] = this.deepCopy(object[i], object, i, result, dupStubs, owner);\n }\n return result;\n }\n case "stub":\n case "rpc-promise": {\n let stub = value;\n let hook;\n if (dupStubs) {\n hook = unwrapStubAndDup(stub);\n } else {\n hook = unwrapStubTakingOwnership(stub);\n }\n if (stub instanceof RpcPromise) {\n let promise = new RpcPromise(hook, []);\n this.promises.push({ parent, property, promise });\n return promise;\n } else {\n this.hooks.push(hook);\n return new RpcStub(hook);\n }\n }\n case "function":\n case "rpc-target": {\n let target = value;\n let hook;\n if (owner) {\n hook = owner.getHookForRpcTarget(target, oldParent, dupStubs);\n } else {\n hook = TargetStubHook.create(target, oldParent);\n }\n this.hooks.push(hook);\n return new RpcStub(hook);\n }\n case "rpc-thenable": {\n let target = value;\n let promise;\n if (owner) {\n promise = new RpcPromise(owner.getHookForRpcTarget(target, oldParent, dupStubs), []);\n } else {\n promise = new RpcPromise(TargetStubHook.create(target, oldParent), []);\n }\n this.promises.push({ parent, property, promise });\n return promise;\n }\n case "writable": {\n let stream = value;\n let hook;\n if (owner) {\n hook = owner.getHookForWritableStream(stream, oldParent, dupStubs);\n } else {\n hook = streamImpl.createWritableStreamHook(stream);\n }\n this.hooks.push(hook);\n return stream;\n }\n case "readable": {\n let stream = value;\n let hook;\n if (owner) {\n hook = owner.getHookForReadableStream(stream, oldParent, dupStubs);\n } else {\n hook = streamImpl.createReadableStreamHook(stream);\n }\n this.hooks.push(hook);\n return stream;\n }\n case "headers":\n return new Headers(value);\n case "request": {\n let req = value;\n if (req.body) {\n this.deepCopy(req.body, req, "body", req, dupStubs, owner);\n }\n return new Request(req);\n }\n case "response": {\n let resp = value;\n if (resp.body) {\n this.deepCopy(resp.body, resp, "body", resp, dupStubs, owner);\n }\n return new Response(resp.body, resp);\n }\n default:\n throw new Error("unreachable");\n }\n }\n // Ensures that if the value originally came from an unowned source, we have replaced it with a\n // deep copy.\n ensureDeepCopied() {\n if (this.source !== "owned") {\n let dupStubs = this.source === "params";\n this.hooks = [];\n this.promises = [];\n try {\n this.value = this.deepCopy(this.value, void 0, "value", this, dupStubs, this);\n } catch (err) {\n this.hooks = void 0;\n this.promises = void 0;\n throw err;\n }\n this.source = "owned";\n if (this.rpcTargets && this.rpcTargets.size > 0) {\n throw new Error("Not all rpcTargets were accounted for in deep-copy?");\n }\n this.rpcTargets = void 0;\n }\n }\n // Resolve all promises in this payload and then assign the final value into `parent[property]`.\n deliverTo(parent, property, promises) {\n this.ensureDeepCopied();\n if (this.value instanceof RpcPromise) {\n _RpcPayload.deliverRpcPromiseTo(this.value, parent, property, promises);\n } else {\n parent[property] = this.value;\n for (let record of this.promises) {\n _RpcPayload.deliverRpcPromiseTo(record.promise, record.parent, record.property, promises);\n }\n }\n }\n static deliverRpcPromiseTo(promise, parent, property, promises) {\n let hook = unwrapStubNoProperties(promise);\n if (!hook) {\n throw new Error("property promises should have been resolved earlier");\n }\n let inner = hook.pull();\n if (inner instanceof _RpcPayload) {\n inner.deliverTo(parent, property, promises);\n } else {\n promises.push(inner.then((payload) => {\n let subPromises = [];\n payload.deliverTo(parent, property, subPromises);\n if (subPromises.length > 0) {\n return Promise.all(subPromises);\n }\n }));\n }\n }\n // Call the given function with the payload as an argument. The call is made synchronously if\n // possible, in order to maintain e-order. However, if any RpcPromises exist in the payload,\n // they are awaited and substituted before calling the function. The result of the call is\n // wrapped into another payload.\n //\n // The payload is automatically disposed after the call completes. The caller should not call\n // dispose().\n async deliverCall(func, thisArg) {\n try {\n let promises = [];\n this.deliverTo(this, "value", promises);\n if (promises.length > 0) {\n await Promise.all(promises);\n }\n let result = Function.prototype.apply.call(func, thisArg, this.value);\n if (result instanceof RpcPromise) {\n return _RpcPayload.fromAppReturn(result);\n } else {\n return _RpcPayload.fromAppReturn(await result);\n }\n } finally {\n this.dispose();\n }\n }\n // Produce a promise for this payload for return to the application. Any RpcPromises in the\n // payload are awaited and substituted with their results first.\n //\n // The returned object will have a disposer which disposes the payload. The caller should not\n // separately dispose it.\n async deliverResolve() {\n try {\n let promises = [];\n this.deliverTo(this, "value", promises);\n if (promises.length > 0) {\n await Promise.all(promises);\n }\n let result = this.value;\n if (result instanceof Object) {\n if (!(Symbol.dispose in result)) {\n Object.defineProperty(result, Symbol.dispose, {\n // NOTE: Using `this.dispose.bind(this)` here causes Playwright\'s build of\n // Chromium 140.0.7339.16 to fail when the object is assigned to a `using` variable,\n // with the error:\n // TypeError: Symbol(Symbol.dispose) is not a function\n // I cannot reproduce this problem in Chrome 140.0.7339.127 nor in Node or workerd,\n // so maybe it was a short-lived V8 bug or something. To be safe, though, we use\n // `() => this.dispose()`, which seems to always work.\n value: () => this.dispose(),\n writable: true,\n enumerable: false,\n configurable: true\n });\n }\n }\n return result;\n } catch (err) {\n this.dispose();\n throw err;\n }\n }\n dispose() {\n if (this.source === "owned") {\n this.hooks.forEach((hook) => hook.dispose());\n this.promises.forEach((promise) => promise.promise[Symbol.dispose]());\n } else if (this.source === "return") {\n this.disposeImpl(this.value, void 0);\n if (this.rpcTargets && this.rpcTargets.size > 0) {\n throw new Error("Not all rpcTargets were accounted for in disposeImpl()?");\n }\n } else ;\n this.source = "owned";\n this.hooks = [];\n this.promises = [];\n }\n // Recursive dispose, called only when `source` is "return".\n disposeImpl(value, parent) {\n let kind = typeForRpc(value);\n switch (kind) {\n case "unsupported":\n case "primitive":\n case "bigint":\n case "bytes":\n case "date":\n case "error":\n case "undefined":\n return;\n case "array": {\n let array = value;\n let len = array.length;\n for (let i = 0; i < len; i++) {\n this.disposeImpl(array[i], array);\n }\n return;\n }\n case "object": {\n let object = value;\n for (let i in object) {\n this.disposeImpl(object[i], object);\n }\n return;\n }\n case "stub":\n case "rpc-promise": {\n let stub = value;\n let hook = unwrapStubNoProperties(stub);\n if (hook) {\n hook.dispose();\n }\n return;\n }\n case "function":\n case "rpc-target": {\n let target = value;\n let hook = this.rpcTargets?.get(target);\n if (hook) {\n hook.dispose();\n this.rpcTargets.delete(target);\n } else {\n disposeRpcTarget(target);\n }\n return;\n }\n case "rpc-thenable":\n return;\n case "headers":\n return;\n case "request": {\n let req = value;\n if (req.body) this.disposeImpl(req.body, req);\n return;\n }\n case "response": {\n let resp = value;\n if (resp.body) this.disposeImpl(resp.body, resp);\n return;\n }\n case "writable": {\n let stream = value;\n let hook = this.rpcTargets?.get(stream);\n if (hook) {\n this.rpcTargets.delete(stream);\n } else {\n hook = streamImpl.createWritableStreamHook(stream);\n }\n hook.dispose();\n return;\n }\n case "readable": {\n let stream = value;\n let hook = this.rpcTargets?.get(stream);\n if (hook) {\n this.rpcTargets.delete(stream);\n } else {\n hook = streamImpl.createReadableStreamHook(stream);\n }\n hook.dispose();\n return;\n }\n default:\n return;\n }\n }\n // Ignore unhandled rejections in all promises in this payload -- that is, all promises that\n // *would* be awaited if this payload were to be delivered. See the similarly-named method of\n // StubHook for explanation.\n ignoreUnhandledRejections() {\n if (this.hooks) {\n this.hooks.forEach((hook) => {\n hook.ignoreUnhandledRejections();\n });\n this.promises.forEach(\n (promise) => unwrapStubOrParent(promise.promise).ignoreUnhandledRejections()\n );\n } else {\n this.ignoreUnhandledRejectionsImpl(this.value);\n }\n }\n ignoreUnhandledRejectionsImpl(value) {\n let kind = typeForRpc(value);\n switch (kind) {\n case "unsupported":\n case "primitive":\n case "bigint":\n case "bytes":\n case "date":\n case "error":\n case "undefined":\n case "function":\n case "rpc-target":\n case "writable":\n case "readable":\n case "headers":\n case "request":\n case "response":\n return;\n case "array": {\n let array = value;\n let len = array.length;\n for (let i = 0; i < len; i++) {\n this.ignoreUnhandledRejectionsImpl(array[i]);\n }\n return;\n }\n case "object": {\n let object = value;\n for (let i in object) {\n this.ignoreUnhandledRejectionsImpl(object[i]);\n }\n return;\n }\n case "stub":\n case "rpc-promise":\n unwrapStubOrParent(value).ignoreUnhandledRejections();\n return;\n case "rpc-thenable":\n value.then((_) => {\n }, (_) => {\n });\n return;\n default:\n return;\n }\n }\n};\nfunction followPath(value, parent, path, owner) {\n for (let i = 0; i < path.length; i++) {\n parent = value;\n let part = path[i];\n if (part in Object.prototype) {\n value = void 0;\n continue;\n }\n let kind = typeForRpc(value);\n switch (kind) {\n case "object":\n case "function":\n if (Object.hasOwn(value, part)) {\n value = value[part];\n } else {\n value = void 0;\n }\n break;\n case "array":\n if (Number.isInteger(part) && part >= 0) {\n value = value[part];\n } else {\n value = void 0;\n }\n break;\n case "rpc-target":\n case "rpc-thenable": {\n if (Object.hasOwn(value, part)) {\n throw new TypeError(\n `Attempted to access property \'${part}\', which is an instance property of the RpcTarget. To avoid leaking private internals, instance properties cannot be accessed over RPC. If you want to make this property available over RPC, define it as a method or getter on the class, instead of an instance property.`\n );\n } else {\n value = value[part];\n }\n owner = null;\n break;\n }\n case "stub":\n case "rpc-promise": {\n let { hook, pathIfPromise } = unwrapStubAndPath(value);\n return { hook, remainingPath: pathIfPromise ? pathIfPromise.concat(path.slice(i)) : path.slice(i) };\n }\n case "writable":\n value = void 0;\n break;\n case "readable":\n value = void 0;\n break;\n case "primitive":\n case "bigint":\n case "bytes":\n case "date":\n case "error":\n case "headers":\n case "request":\n case "response":\n value = void 0;\n break;\n case "undefined":\n value = value[part];\n break;\n case "unsupported": {\n if (i === 0) {\n throw new TypeError(`RPC stub points at a non-serializable type.`);\n } else {\n let prefix = path.slice(0, i).join(".");\n let remainder = path.slice(0, i).join(".");\n throw new TypeError(\n `\'${prefix}\' is not a serializable type, so property ${remainder} cannot be accessed.`\n );\n }\n }\n default:\n throw new TypeError("unreachable");\n }\n }\n if (value instanceof RpcPromise) {\n let { hook, pathIfPromise } = unwrapStubAndPath(value);\n return { hook, remainingPath: pathIfPromise || [] };\n }\n return {\n value,\n parent,\n owner\n };\n}\nvar ValueStubHook = class extends StubHook {\n call(path, args) {\n try {\n let { value, owner } = this.getValue();\n let followResult = followPath(value, void 0, path, owner);\n if (followResult.hook) {\n return followResult.hook.call(followResult.remainingPath, args);\n }\n if (typeof followResult.value != "function") {\n throw new TypeError(`\'${path.join(".")}\' is not a function.`);\n }\n let promise = args.deliverCall(followResult.value, followResult.parent);\n return new PromiseStubHook(promise.then((payload) => {\n return new PayloadStubHook(payload);\n }));\n } catch (err) {\n return new ErrorStubHook(err);\n }\n }\n map(path, captures, instructions) {\n try {\n let followResult;\n try {\n let { value, owner } = this.getValue();\n followResult = followPath(value, void 0, path, owner);\n ;\n } catch (err) {\n for (let cap of captures) {\n cap.dispose();\n }\n throw err;\n }\n if (followResult.hook) {\n return followResult.hook.map(followResult.remainingPath, captures, instructions);\n }\n return mapImpl.applyMap(\n followResult.value,\n followResult.parent,\n followResult.owner,\n captures,\n instructions\n );\n } catch (err) {\n return new ErrorStubHook(err);\n }\n }\n get(path) {\n try {\n let { value, owner } = this.getValue();\n if (path.length === 0 && owner === null) {\n throw new Error("Can\'t dup an RpcTarget stub as a promise.");\n }\n let followResult = followPath(value, void 0, path, owner);\n if (followResult.hook) {\n return followResult.hook.get(followResult.remainingPath);\n }\n return new PayloadStubHook(RpcPayload.deepCopyFrom(\n followResult.value,\n followResult.parent,\n followResult.owner\n ));\n } catch (err) {\n return new ErrorStubHook(err);\n }\n }\n};\nvar PayloadStubHook = class _PayloadStubHook extends ValueStubHook {\n constructor(payload) {\n super();\n this.payload = payload;\n }\n payload;\n // cleared when disposed\n getPayload() {\n if (this.payload) {\n return this.payload;\n } else {\n throw new Error("Attempted to use an RPC StubHook after it was disposed.");\n }\n }\n getValue() {\n let payload = this.getPayload();\n return { value: payload.value, owner: payload };\n }\n dup() {\n let thisPayload = this.getPayload();\n return new _PayloadStubHook(RpcPayload.deepCopyFrom(\n thisPayload.value,\n void 0,\n thisPayload\n ));\n }\n pull() {\n return this.getPayload();\n }\n ignoreUnhandledRejections() {\n if (this.payload) {\n this.payload.ignoreUnhandledRejections();\n }\n }\n dispose() {\n if (this.payload) {\n this.payload.dispose();\n this.payload = void 0;\n }\n }\n onBroken(callback) {\n if (this.payload) {\n if (this.payload.value instanceof RpcStub) {\n this.payload.value.onRpcBroken(callback);\n }\n }\n }\n};\nfunction disposeRpcTarget(target) {\n if (Symbol.dispose in target) {\n try {\n target[Symbol.dispose]();\n } catch (err) {\n Promise.reject(err);\n }\n }\n}\nvar TargetStubHook = class _TargetStubHook extends ValueStubHook {\n // Constructs a TargetStubHook that is not duplicated from an existing hook.\n //\n // If `value` is a function, `parent` is bound as its "this".\n static create(value, parent) {\n if (typeof value !== "function") {\n parent = void 0;\n }\n return new _TargetStubHook(value, parent);\n }\n constructor(target, parent, dupFrom) {\n super();\n this.target = target;\n this.parent = parent;\n if (dupFrom) {\n if (dupFrom.refcount) {\n this.refcount = dupFrom.refcount;\n ++this.refcount.count;\n }\n } else if (Symbol.dispose in target) {\n this.refcount = { count: 1 };\n }\n }\n target;\n // cleared when disposed\n parent;\n // `this` parameter when calling `target`\n refcount;\n // undefined if not needed (because target has no disposer)\n getTarget() {\n if (this.target) {\n return this.target;\n } else {\n throw new Error("Attempted to use an RPC StubHook after it was disposed.");\n }\n }\n getValue() {\n return { value: this.getTarget(), owner: null };\n }\n dup() {\n return new _TargetStubHook(this.getTarget(), this.parent, this);\n }\n pull() {\n let target = this.getTarget();\n if ("then" in target) {\n return Promise.resolve(target).then((resolution) => {\n return RpcPayload.fromAppReturn(resolution);\n });\n } else {\n return Promise.reject(new Error("Tried to resolve a non-promise stub."));\n }\n }\n ignoreUnhandledRejections() {\n }\n dispose() {\n if (this.target) {\n if (this.refcount) {\n if (--this.refcount.count == 0) {\n disposeRpcTarget(this.target);\n }\n }\n this.target = void 0;\n }\n }\n onBroken(callback) {\n }\n};\nvar PromiseStubHook = class _PromiseStubHook extends StubHook {\n promise;\n resolution;\n constructor(promise) {\n super();\n this.promise = promise.then((res) => {\n this.resolution = res;\n return res;\n });\n }\n call(path, args) {\n args.ensureDeepCopied();\n return new _PromiseStubHook(this.promise.then((hook) => hook.call(path, args)));\n }\n stream(path, args) {\n args.ensureDeepCopied();\n let promise = this.promise.then((hook) => {\n let result = hook.stream(path, args);\n return result.promise;\n });\n return { promise };\n }\n map(path, captures, instructions) {\n return new _PromiseStubHook(this.promise.then(\n (hook) => hook.map(path, captures, instructions),\n (err) => {\n for (let cap of captures) {\n cap.dispose();\n }\n throw err;\n }\n ));\n }\n get(path) {\n return new _PromiseStubHook(this.promise.then((hook) => hook.get(path)));\n }\n dup() {\n if (this.resolution) {\n return this.resolution.dup();\n } else {\n return new _PromiseStubHook(this.promise.then((hook) => hook.dup()));\n }\n }\n pull() {\n if (this.resolution) {\n return this.resolution.pull();\n } else {\n return this.promise.then((hook) => hook.pull());\n }\n }\n ignoreUnhandledRejections() {\n if (this.resolution) {\n this.resolution.ignoreUnhandledRejections();\n } else {\n this.promise.then((res) => {\n res.ignoreUnhandledRejections();\n }, (err) => {\n });\n }\n }\n dispose() {\n if (this.resolution) {\n this.resolution.dispose();\n } else {\n this.promise.then((hook) => {\n hook.dispose();\n }, (err) => {\n });\n }\n }\n onBroken(callback) {\n if (this.resolution) {\n this.resolution.onBroken(callback);\n } else {\n this.promise.then((hook) => {\n hook.onBroken(callback);\n }, callback);\n }\n }\n};\nvar NullExporter = class {\n exportStub(stub) {\n throw new Error("Cannot serialize RPC stubs without an RPC session.");\n }\n exportPromise(stub) {\n throw new Error("Cannot serialize RPC stubs without an RPC session.");\n }\n getImport(hook) {\n return void 0;\n }\n unexport(ids) {\n }\n createPipe(readable) {\n throw new Error("Cannot create pipes without an RPC session.");\n }\n onSendError(error) {\n }\n};\nvar NULL_EXPORTER = new NullExporter();\nvar ERROR_TYPES = {\n Error,\n EvalError,\n RangeError,\n ReferenceError,\n SyntaxError,\n TypeError,\n URIError,\n AggregateError\n // TODO: DOMError? Others?\n};\nvar Devaluator = class _Devaluator {\n constructor(exporter, source) {\n this.exporter = exporter;\n this.source = source;\n }\n // Devaluate the given value.\n // * value: The value to devaluate.\n // * parent: The value\'s parent object, which would be used as `this` if the value were called\n // as a function.\n // * exporter: Callbacks to the RPC session for exporting capabilities found in this message.\n // * source: The RpcPayload which contains the value, and therefore owns stubs within.\n //\n // Returns: The devaluated value, ready to be JSON-serialized.\n static devaluate(value, parent, exporter = NULL_EXPORTER, source) {\n let devaluator = new _Devaluator(exporter, source);\n try {\n return devaluator.devaluateImpl(value, parent, 0);\n } catch (err) {\n if (devaluator.exports) {\n try {\n exporter.unexport(devaluator.exports);\n } catch (err2) {\n }\n }\n throw err;\n }\n }\n exports;\n devaluateImpl(value, parent, depth) {\n if (depth >= 64) {\n throw new Error(\n "Serialization exceeded maximum allowed depth. (Does the message contain cycles?)"\n );\n }\n let kind = typeForRpc(value);\n switch (kind) {\n case "unsupported": {\n let msg;\n try {\n msg = `Cannot serialize value: ${value}`;\n } catch (err) {\n msg = "Cannot serialize value: (couldn\'t stringify value)";\n }\n throw new TypeError(msg);\n }\n case "primitive":\n if (typeof value === "number" && !isFinite(value)) {\n if (value === Infinity) {\n return ["inf"];\n } else if (value === -Infinity) {\n return ["-inf"];\n } else {\n return ["nan"];\n }\n } else {\n return value;\n }\n case "object": {\n let object = value;\n let result = {};\n for (let key in object) {\n result[key] = this.devaluateImpl(object[key], object, depth + 1);\n }\n return result;\n }\n case "array": {\n let array = value;\n let len = array.length;\n let result = new Array(len);\n for (let i = 0; i < len; i++) {\n result[i] = this.devaluateImpl(array[i], array, depth + 1);\n }\n return [result];\n }\n case "bigint":\n return ["bigint", value.toString()];\n case "date":\n return ["date", value.getTime()];\n case "bytes": {\n let bytes = value;\n if (bytes.toBase64) {\n return ["bytes", bytes.toBase64({ omitPadding: true })];\n } else {\n return [\n "bytes",\n btoa(String.fromCharCode.apply(null, bytes).replace(/=*$/, ""))\n ];\n }\n }\n case "headers":\n return ["headers", [...value]];\n case "request": {\n let req = value;\n let init = {};\n if (req.method !== "GET") init.method = req.method;\n let headers = [...req.headers];\n if (headers.length > 0) {\n init.headers = headers;\n }\n if (req.body) {\n init.body = this.devaluateImpl(req.body, req, depth + 1);\n init.duplex = req.duplex || "half";\n } else if (req.body === void 0 && !["GET", "HEAD", "OPTIONS", "TRACE", "DELETE"].includes(req.method)) {\n let bodyPromise = req.arrayBuffer();\n let readable = new ReadableStream({\n async start(controller) {\n try {\n controller.enqueue(new Uint8Array(await bodyPromise));\n controller.close();\n } catch (err) {\n controller.error(err);\n }\n }\n });\n let hook = streamImpl.createReadableStreamHook(readable);\n let importId = this.exporter.createPipe(readable, hook);\n init.body = ["readable", importId];\n init.duplex = req.duplex || "half";\n }\n if (req.cache && req.cache !== "default") init.cache = req.cache;\n if (req.redirect !== "follow") init.redirect = req.redirect;\n if (req.integrity) init.integrity = req.integrity;\n if (req.mode && req.mode !== "cors") init.mode = req.mode;\n if (req.credentials && req.credentials !== "same-origin") {\n init.credentials = req.credentials;\n }\n if (req.referrer && req.referrer !== "about:client") init.referrer = req.referrer;\n if (req.referrerPolicy) init.referrerPolicy = req.referrerPolicy;\n if (req.keepalive) init.keepalive = req.keepalive;\n let cfReq = req;\n if (cfReq.cf) init.cf = cfReq.cf;\n if (cfReq.encodeResponseBody && cfReq.encodeResponseBody !== "automatic") {\n init.encodeResponseBody = cfReq.encodeResponseBody;\n }\n return ["request", req.url, init];\n }\n case "response": {\n let resp = value;\n let body = this.devaluateImpl(resp.body, resp, depth + 1);\n let init = {};\n if (resp.status !== 200) init.status = resp.status;\n if (resp.statusText) init.statusText = resp.statusText;\n let headers = [...resp.headers];\n if (headers.length > 0) {\n init.headers = headers;\n }\n let cfResp = resp;\n if (cfResp.cf) init.cf = cfResp.cf;\n if (cfResp.encodeBody && cfResp.encodeBody !== "automatic") {\n init.encodeBody = cfResp.encodeBody;\n }\n if (cfResp.webSocket) {\n throw new TypeError("Can\'t serialize a Response containing a webSocket.");\n }\n return ["response", body, init];\n }\n case "error": {\n let e = value;\n let rewritten = this.exporter.onSendError(e);\n if (rewritten) {\n e = rewritten;\n }\n let result = ["error", e.name, e.message];\n if (rewritten && rewritten.stack) {\n result.push(rewritten.stack);\n }\n return result;\n }\n case "undefined":\n return ["undefined"];\n case "stub":\n case "rpc-promise": {\n if (!this.source) {\n throw new Error("Can\'t serialize RPC stubs in this context.");\n }\n let { hook, pathIfPromise } = unwrapStubAndPath(value);\n let importId = this.exporter.getImport(hook);\n if (importId !== void 0) {\n if (pathIfPromise) {\n if (pathIfPromise.length > 0) {\n return ["pipeline", importId, pathIfPromise];\n } else {\n return ["pipeline", importId];\n }\n } else {\n return ["import", importId];\n }\n }\n if (pathIfPromise) {\n hook = hook.get(pathIfPromise);\n } else {\n hook = hook.dup();\n }\n return this.devaluateHook(pathIfPromise ? "promise" : "export", hook);\n }\n case "function":\n case "rpc-target": {\n if (!this.source) {\n throw new Error("Can\'t serialize RPC stubs in this context.");\n }\n let hook = this.source.getHookForRpcTarget(value, parent);\n return this.devaluateHook("export", hook);\n }\n case "rpc-thenable": {\n if (!this.source) {\n throw new Error("Can\'t serialize RPC stubs in this context.");\n }\n let hook = this.source.getHookForRpcTarget(value, parent);\n return this.devaluateHook("promise", hook);\n }\n case "writable": {\n if (!this.source) {\n throw new Error("Can\'t serialize WritableStream in this context.");\n }\n let hook = this.source.getHookForWritableStream(value, parent);\n return this.devaluateHook("writable", hook);\n }\n case "readable": {\n if (!this.source) {\n throw new Error("Can\'t serialize ReadableStream in this context.");\n }\n let ws = value;\n let hook = this.source.getHookForReadableStream(ws, parent);\n let importId = this.exporter.createPipe(ws, hook);\n return ["readable", importId];\n }\n default:\n throw new Error("unreachable");\n }\n }\n devaluateHook(type, hook) {\n if (!this.exports) this.exports = [];\n let exportId = type === "promise" ? this.exporter.exportPromise(hook) : this.exporter.exportStub(hook);\n this.exports.push(exportId);\n return [type, exportId];\n }\n};\nvar NullImporter = class {\n importStub(idx) {\n throw new Error("Cannot deserialize RPC stubs without an RPC session.");\n }\n importPromise(idx) {\n throw new Error("Cannot deserialize RPC stubs without an RPC session.");\n }\n getExport(idx) {\n return void 0;\n }\n getPipeReadable(exportId) {\n throw new Error("Cannot retrieve pipe readable without an RPC session.");\n }\n};\nvar NULL_IMPORTER = new NullImporter();\nfunction fixBrokenRequestBody(request, body) {\n let promise = new Response(body).arrayBuffer().then((arrayBuffer) => {\n let bytes = new Uint8Array(arrayBuffer);\n let result = new Request(request, { body: bytes });\n return new PayloadStubHook(RpcPayload.fromAppReturn(result));\n });\n return new RpcPromise(new PromiseStubHook(promise), []);\n}\nvar Evaluator = class _Evaluator {\n constructor(importer) {\n this.importer = importer;\n }\n hooks = [];\n promises = [];\n evaluate(value) {\n let payload = RpcPayload.forEvaluate(this.hooks, this.promises);\n try {\n payload.value = this.evaluateImpl(value, payload, "value");\n return payload;\n } catch (err) {\n payload.dispose();\n throw err;\n }\n }\n // Evaluate the value without destroying it.\n evaluateCopy(value) {\n return this.evaluate(structuredClone(value));\n }\n evaluateImpl(value, parent, property) {\n if (value instanceof Array) {\n if (value.length == 1 && value[0] instanceof Array) {\n let result = value[0];\n for (let i = 0; i < result.length; i++) {\n result[i] = this.evaluateImpl(result[i], result, i);\n }\n return result;\n } else switch (value[0]) {\n case "bigint":\n if (typeof value[1] == "string") {\n return BigInt(value[1]);\n }\n break;\n case "date":\n if (typeof value[1] == "number") {\n return new Date(value[1]);\n }\n break;\n case "bytes": {\n let b64 = Uint8Array;\n if (typeof value[1] == "string") {\n if (b64.fromBase64) {\n return b64.fromBase64(value[1]);\n } else {\n let bs = atob(value[1]);\n let len = bs.length;\n let bytes = new Uint8Array(len);\n for (let i = 0; i < len; i++) {\n bytes[i] = bs.charCodeAt(i);\n }\n return bytes;\n }\n }\n break;\n }\n case "error":\n if (value.length >= 3 && typeof value[1] === "string" && typeof value[2] === "string") {\n let cls = ERROR_TYPES[value[1]] || Error;\n let result = new cls(value[2]);\n if (typeof value[3] === "string") {\n result.stack = value[3];\n }\n return result;\n }\n break;\n case "undefined":\n if (value.length === 1) {\n return void 0;\n }\n break;\n case "inf":\n return Infinity;\n case "-inf":\n return -Infinity;\n case "nan":\n return NaN;\n case "headers":\n if (value.length === 2 && value[1] instanceof Array) {\n return new Headers(value[1]);\n }\n break;\n case "request": {\n if (value.length !== 3 || typeof value[1] !== "string") break;\n let url = value[1];\n let init = value[2];\n if (typeof init !== "object" || init === null) break;\n if (init.body) {\n init.body = this.evaluateImpl(init.body, init, "body");\n if (init.body === null || typeof init.body === "string" || init.body instanceof Uint8Array || init.body instanceof ReadableStream) ;\n else {\n throw new TypeError("Request body must be of type ReadableStream.");\n }\n }\n if (init.signal) {\n init.signal = this.evaluateImpl(init.signal, init, "signal");\n if (!(init.signal instanceof AbortSignal)) {\n throw new TypeError("Request siganl must be of type AbortSignal.");\n }\n }\n if (init.headers && !(init.headers instanceof Array)) {\n throw new TypeError("Request headers must be serialized as an array of pairs.");\n }\n let result = new Request(url, init);\n if (init.body instanceof ReadableStream && result.body === void 0) {\n let promise = fixBrokenRequestBody(result, init.body);\n this.promises.push({ promise, parent, property });\n return promise;\n } else {\n return result;\n }\n }\n case "response": {\n if (value.length !== 3) break;\n let body = this.evaluateImpl(value[1], parent, property);\n if (body === null || typeof body === "string" || body instanceof Uint8Array || body instanceof ReadableStream) ;\n else {\n throw new TypeError("Response body must be of type ReadableStream.");\n }\n let init = value[2];\n if (typeof init !== "object" || init === null) break;\n if (init.webSocket) {\n throw new TypeError("Can\'t deserialize a Response containing a webSocket.");\n }\n if (init.headers && !(init.headers instanceof Array)) {\n throw new TypeError("Request headers must be serialized as an array of pairs.");\n }\n return new Response(body, init);\n }\n case "import":\n case "pipeline": {\n if (value.length < 2 || value.length > 4) {\n break;\n }\n if (typeof value[1] != "number") {\n break;\n }\n let hook = this.importer.getExport(value[1]);\n if (!hook) {\n throw new Error(`no such entry on exports table: ${value[1]}`);\n }\n let isPromise = value[0] == "pipeline";\n let addStub = (hook2) => {\n if (isPromise) {\n let promise = new RpcPromise(hook2, []);\n this.promises.push({ promise, parent, property });\n return promise;\n } else {\n this.hooks.push(hook2);\n return new RpcPromise(hook2, []);\n }\n };\n if (value.length == 2) {\n if (isPromise) {\n return addStub(hook.get([]));\n } else {\n return addStub(hook.dup());\n }\n }\n let path = value[2];\n if (!(path instanceof Array)) {\n break;\n }\n if (!path.every(\n (part) => {\n return typeof part == "string" || typeof part == "number";\n }\n )) {\n break;\n }\n if (value.length == 3) {\n return addStub(hook.get(path));\n }\n let args = value[3];\n if (!(args instanceof Array)) {\n break;\n }\n let subEval = new _Evaluator(this.importer);\n args = subEval.evaluate([args]);\n return addStub(hook.call(path, args));\n }\n case "remap": {\n if (value.length !== 5 || typeof value[1] !== "number" || !(value[2] instanceof Array) || !(value[3] instanceof Array) || !(value[4] instanceof Array)) {\n break;\n }\n let hook = this.importer.getExport(value[1]);\n if (!hook) {\n throw new Error(`no such entry on exports table: ${value[1]}`);\n }\n let path = value[2];\n if (!path.every(\n (part) => {\n return typeof part == "string" || typeof part == "number";\n }\n )) {\n break;\n }\n let captures = value[3].map((cap) => {\n if (!(cap instanceof Array) || cap.length !== 2 || cap[0] !== "import" && cap[0] !== "export" || typeof cap[1] !== "number") {\n throw new TypeError(`unknown map capture: ${JSON.stringify(cap)}`);\n }\n if (cap[0] === "export") {\n return this.importer.importStub(cap[1]);\n } else {\n let exp = this.importer.getExport(cap[1]);\n if (!exp) {\n throw new Error(`no such entry on exports table: ${cap[1]}`);\n }\n return exp.dup();\n }\n });\n let instructions = value[4];\n let resultHook = hook.map(path, captures, instructions);\n let promise = new RpcPromise(resultHook, []);\n this.promises.push({ promise, parent, property });\n return promise;\n }\n case "export":\n case "promise":\n if (typeof value[1] == "number") {\n if (value[0] == "promise") {\n let hook = this.importer.importPromise(value[1]);\n let promise = new RpcPromise(hook, []);\n this.promises.push({ parent, property, promise });\n return promise;\n } else {\n let hook = this.importer.importStub(value[1]);\n this.hooks.push(hook);\n return new RpcStub(hook);\n }\n }\n break;\n case "writable":\n if (typeof value[1] == "number") {\n let hook = this.importer.importStub(value[1]);\n let stream = streamImpl.createWritableStreamFromHook(hook);\n this.hooks.push(hook);\n return stream;\n }\n break;\n case "readable":\n if (typeof value[1] == "number") {\n let stream = this.importer.getPipeReadable(value[1]);\n let hook = streamImpl.createReadableStreamHook(stream);\n this.hooks.push(hook);\n return stream;\n }\n break;\n }\n throw new TypeError(`unknown special value: ${JSON.stringify(value)}`);\n } else if (value instanceof Object) {\n let result = value;\n for (let key in result) {\n if (key in Object.prototype || key === "toJSON") {\n this.evaluateImpl(result[key], result, key);\n delete result[key];\n } else {\n result[key] = this.evaluateImpl(result[key], result, key);\n }\n }\n return result;\n } else {\n return value;\n }\n }\n};\nvar ImportTableEntry = class {\n constructor(session, importId, pulling) {\n this.session = session;\n this.importId = importId;\n if (pulling) {\n this.activePull = Promise.withResolvers();\n }\n }\n localRefcount = 0;\n remoteRefcount = 1;\n activePull;\n resolution;\n // List of integer indexes into session.onBrokenCallbacks which are callbacks registered on\n // this import. Initialized on first use (so `undefined` is the same as an empty list).\n onBrokenRegistrations;\n resolve(resolution) {\n if (this.localRefcount == 0) {\n resolution.dispose();\n return;\n }\n this.resolution = resolution;\n this.sendRelease();\n if (this.onBrokenRegistrations) {\n for (let i of this.onBrokenRegistrations) {\n let callback = this.session.onBrokenCallbacks[i];\n let endIndex = this.session.onBrokenCallbacks.length;\n resolution.onBroken(callback);\n if (this.session.onBrokenCallbacks[endIndex] === callback) {\n delete this.session.onBrokenCallbacks[endIndex];\n } else {\n delete this.session.onBrokenCallbacks[i];\n }\n }\n this.onBrokenRegistrations = void 0;\n }\n if (this.activePull) {\n this.activePull.resolve();\n this.activePull = void 0;\n }\n }\n async awaitResolution() {\n if (!this.activePull) {\n this.session.sendPull(this.importId);\n this.activePull = Promise.withResolvers();\n }\n await this.activePull.promise;\n return this.resolution.pull();\n }\n dispose() {\n if (this.resolution) {\n this.resolution.dispose();\n } else {\n this.abort(new Error("RPC was canceled because the RpcPromise was disposed."));\n this.sendRelease();\n }\n }\n abort(error) {\n if (!this.resolution) {\n this.resolution = new ErrorStubHook(error);\n if (this.activePull) {\n this.activePull.reject(error);\n this.activePull = void 0;\n }\n this.onBrokenRegistrations = void 0;\n }\n }\n onBroken(callback) {\n if (this.resolution) {\n this.resolution.onBroken(callback);\n } else {\n let index = this.session.onBrokenCallbacks.length;\n this.session.onBrokenCallbacks.push(callback);\n if (!this.onBrokenRegistrations) this.onBrokenRegistrations = [];\n this.onBrokenRegistrations.push(index);\n }\n }\n sendRelease() {\n if (this.remoteRefcount > 0) {\n this.session.sendRelease(this.importId, this.remoteRefcount);\n this.remoteRefcount = 0;\n }\n }\n};\nvar RpcImportHook = class _RpcImportHook extends StubHook {\n // undefined when we\'re disposed\n // `pulling` is true if we already expect that this import is going to be resolved later, and\n // null if this import is not allowed to be pulled (i.e. it\'s a stub not a promise).\n constructor(isPromise, entry) {\n super();\n this.isPromise = isPromise;\n ++entry.localRefcount;\n this.entry = entry;\n }\n entry;\n collectPath(path) {\n return this;\n }\n getEntry() {\n if (this.entry) {\n return this.entry;\n } else {\n throw new Error("This RpcImportHook was already disposed.");\n }\n }\n // -------------------------------------------------------------------------------------\n // implements StubHook\n call(path, args) {\n let entry = this.getEntry();\n if (entry.resolution) {\n return entry.resolution.call(path, args);\n } else {\n return entry.session.sendCall(entry.importId, path, args);\n }\n }\n stream(path, args) {\n let entry = this.getEntry();\n if (entry.resolution) {\n return entry.resolution.stream(path, args);\n } else {\n return entry.session.sendStream(entry.importId, path, args);\n }\n }\n map(path, captures, instructions) {\n let entry;\n try {\n entry = this.getEntry();\n } catch (err) {\n for (let cap of captures) {\n cap.dispose();\n }\n throw err;\n }\n if (entry.resolution) {\n return entry.resolution.map(path, captures, instructions);\n } else {\n return entry.session.sendMap(entry.importId, path, captures, instructions);\n }\n }\n get(path) {\n let entry = this.getEntry();\n if (entry.resolution) {\n return entry.resolution.get(path);\n } else {\n return entry.session.sendCall(entry.importId, path);\n }\n }\n dup() {\n return new _RpcImportHook(false, this.getEntry());\n }\n pull() {\n let entry = this.getEntry();\n if (!this.isPromise) {\n throw new Error("Can\'t pull this hook because it\'s not a promise hook.");\n }\n if (entry.resolution) {\n return entry.resolution.pull();\n }\n return entry.awaitResolution();\n }\n ignoreUnhandledRejections() {\n }\n dispose() {\n let entry = this.entry;\n this.entry = void 0;\n if (entry) {\n if (--entry.localRefcount === 0) {\n entry.dispose();\n }\n }\n }\n onBroken(callback) {\n if (this.entry) {\n this.entry.onBroken(callback);\n }\n }\n};\nvar RpcMainHook = class extends RpcImportHook {\n session;\n constructor(entry) {\n super(false, entry);\n this.session = entry.session;\n }\n dispose() {\n if (this.session) {\n let session = this.session;\n this.session = void 0;\n session.shutdown();\n }\n }\n};\nvar RpcSessionImpl = class {\n constructor(transport, mainHook, options) {\n this.transport = transport;\n this.options = options;\n this.exports.push({ hook: mainHook, refcount: 1 });\n this.imports.push(new ImportTableEntry(this, 0, false));\n let rejectFunc;\n let abortPromise = new Promise((resolve, reject) => {\n rejectFunc = reject;\n });\n this.cancelReadLoop = rejectFunc;\n this.readLoop(abortPromise).catch((err) => this.abort(err));\n }\n exports = [];\n reverseExports = /* @__PURE__ */ new Map();\n imports = [];\n abortReason;\n cancelReadLoop;\n // We assign positive numbers to imports we initiate, and negative numbers to exports we\n // initiate. So the next import ID is just `imports.length`, but the next export ID needs\n // to be tracked explicitly.\n nextExportId = -1;\n // If set, call this when all incoming calls are complete.\n onBatchDone;\n // How many promises is our peer expecting us to resolve?\n pullCount = 0;\n // Sparse array of onBrokenCallback registrations. Items are strictly appended to the end but\n // may be deleted from the middle (hence leaving the array sparse).\n onBrokenCallbacks = [];\n // Should only be called once immediately after construction.\n getMainImport() {\n return new RpcMainHook(this.imports[0]);\n }\n shutdown() {\n this.abort(new Error("RPC session was shut down by disposing the main stub"), false);\n }\n exportStub(hook) {\n if (this.abortReason) throw this.abortReason;\n let existingExportId = this.reverseExports.get(hook);\n if (existingExportId !== void 0) {\n ++this.exports[existingExportId].refcount;\n return existingExportId;\n } else {\n let exportId = this.nextExportId--;\n this.exports[exportId] = { hook, refcount: 1 };\n this.reverseExports.set(hook, exportId);\n return exportId;\n }\n }\n exportPromise(hook) {\n if (this.abortReason) throw this.abortReason;\n let exportId = this.nextExportId--;\n this.exports[exportId] = { hook, refcount: 1 };\n this.reverseExports.set(hook, exportId);\n this.ensureResolvingExport(exportId);\n return exportId;\n }\n unexport(ids) {\n for (let id of ids) {\n this.releaseExport(id, 1);\n }\n }\n releaseExport(exportId, refcount) {\n let entry = this.exports[exportId];\n if (!entry) {\n throw new Error(`no such export ID: ${exportId}`);\n }\n if (entry.refcount < refcount) {\n throw new Error(`refcount would go negative: ${entry.refcount} < ${refcount}`);\n }\n entry.refcount -= refcount;\n if (entry.refcount === 0) {\n delete this.exports[exportId];\n this.reverseExports.delete(entry.hook);\n entry.hook.dispose();\n }\n }\n onSendError(error) {\n if (this.options.onSendError) {\n return this.options.onSendError(error);\n }\n }\n ensureResolvingExport(exportId) {\n let exp = this.exports[exportId];\n if (!exp) {\n throw new Error(`no such export ID: ${exportId}`);\n }\n if (!exp.pull) {\n let resolve = async () => {\n let hook = exp.hook;\n for (; ; ) {\n let payload = await hook.pull();\n if (payload.value instanceof RpcStub) {\n let { hook: inner, pathIfPromise } = unwrapStubAndPath(payload.value);\n if (pathIfPromise && pathIfPromise.length == 0) {\n if (this.getImport(hook) === void 0) {\n hook = inner;\n continue;\n }\n }\n }\n return payload;\n }\n };\n let autoRelease = exp.autoRelease;\n ++this.pullCount;\n exp.pull = resolve().then(\n (payload) => {\n let value = Devaluator.devaluate(payload.value, void 0, this, payload);\n this.send(["resolve", exportId, value]);\n if (autoRelease) this.releaseExport(exportId, 1);\n },\n (error) => {\n this.send(["reject", exportId, Devaluator.devaluate(error, void 0, this)]);\n if (autoRelease) this.releaseExport(exportId, 1);\n }\n ).catch(\n (error) => {\n try {\n this.send(["reject", exportId, Devaluator.devaluate(error, void 0, this)]);\n if (autoRelease) this.releaseExport(exportId, 1);\n } catch (error2) {\n this.abort(error2);\n }\n }\n ).finally(() => {\n if (--this.pullCount === 0) {\n if (this.onBatchDone) {\n this.onBatchDone.resolve();\n }\n }\n });\n }\n }\n getImport(hook) {\n if (hook instanceof RpcImportHook && hook.entry && hook.entry.session === this) {\n return hook.entry.importId;\n } else {\n return void 0;\n }\n }\n importStub(idx) {\n if (this.abortReason) throw this.abortReason;\n let entry = this.imports[idx];\n if (!entry) {\n entry = new ImportTableEntry(this, idx, false);\n this.imports[idx] = entry;\n }\n return new RpcImportHook(\n /*isPromise=*/\n false,\n entry\n );\n }\n importPromise(idx) {\n if (this.abortReason) throw this.abortReason;\n if (this.imports[idx]) {\n return new ErrorStubHook(new Error(\n "Bug in RPC system: The peer sent a promise reusing an existing export ID."\n ));\n }\n let entry = new ImportTableEntry(this, idx, true);\n this.imports[idx] = entry;\n return new RpcImportHook(\n /*isPromise=*/\n true,\n entry\n );\n }\n getExport(idx) {\n return this.exports[idx]?.hook;\n }\n getPipeReadable(exportId) {\n let entry = this.exports[exportId];\n if (!entry || !entry.pipeReadable) {\n throw new Error(`Export ${exportId} is not a pipe or its readable end was already consumed.`);\n }\n let readable = entry.pipeReadable;\n entry.pipeReadable = void 0;\n return readable;\n }\n createPipe(readable, readableHook) {\n if (this.abortReason) throw this.abortReason;\n this.send(["pipe"]);\n let importId = this.imports.length;\n let entry = new ImportTableEntry(this, importId, false);\n this.imports.push(entry);\n let hook = new RpcImportHook(\n /*isPromise=*/\n false,\n entry\n );\n let writable = streamImpl.createWritableStreamFromHook(hook);\n readable.pipeTo(writable).catch(() => {\n }).finally(() => readableHook.dispose());\n return importId;\n }\n // Serializes and sends a message. Returns the byte length of the serialized message.\n send(msg) {\n if (this.abortReason !== void 0) {\n return 0;\n }\n let msgText;\n try {\n msgText = JSON.stringify(msg);\n } catch (err) {\n try {\n this.abort(err);\n } catch (err2) {\n }\n throw err;\n }\n this.transport.send(msgText).catch((err) => this.abort(err, false));\n return msgText.length;\n }\n sendCall(id, path, args) {\n if (this.abortReason) throw this.abortReason;\n let value = ["pipeline", id, path];\n if (args) {\n let devalue = Devaluator.devaluate(args.value, void 0, this, args);\n value.push(devalue[0]);\n }\n this.send(["push", value]);\n let entry = new ImportTableEntry(this, this.imports.length, false);\n this.imports.push(entry);\n return new RpcImportHook(\n /*isPromise=*/\n true,\n entry\n );\n }\n sendStream(id, path, args) {\n if (this.abortReason) throw this.abortReason;\n let value = ["pipeline", id, path];\n let devalue = Devaluator.devaluate(args.value, void 0, this, args);\n value.push(devalue[0]);\n let size = this.send(["stream", value]);\n let importId = this.imports.length;\n let entry = new ImportTableEntry(\n this,\n importId,\n /*pulling=*/\n true\n );\n entry.remoteRefcount = 0;\n entry.localRefcount = 1;\n this.imports.push(entry);\n let promise = entry.awaitResolution().then(\n (p) => {\n p.dispose();\n delete this.imports[importId];\n },\n (err) => {\n delete this.imports[importId];\n throw err;\n }\n );\n return { promise, size };\n }\n sendMap(id, path, captures, instructions) {\n if (this.abortReason) {\n for (let cap of captures) {\n cap.dispose();\n }\n throw this.abortReason;\n }\n let devaluedCaptures = captures.map((hook) => {\n let importId = this.getImport(hook);\n if (importId !== void 0) {\n return ["import", importId];\n } else {\n return ["export", this.exportStub(hook)];\n }\n });\n let value = ["remap", id, path, devaluedCaptures, instructions];\n this.send(["push", value]);\n let entry = new ImportTableEntry(this, this.imports.length, false);\n this.imports.push(entry);\n return new RpcImportHook(\n /*isPromise=*/\n true,\n entry\n );\n }\n sendPull(id) {\n if (this.abortReason) throw this.abortReason;\n this.send(["pull", id]);\n }\n sendRelease(id, remoteRefcount) {\n if (this.abortReason) return;\n this.send(["release", id, remoteRefcount]);\n delete this.imports[id];\n }\n abort(error, trySendAbortMessage = true) {\n if (this.abortReason !== void 0) return;\n this.cancelReadLoop(error);\n if (trySendAbortMessage) {\n try {\n this.transport.send(JSON.stringify(["abort", Devaluator.devaluate(error, void 0, this)])).catch((err) => {\n });\n } catch (err) {\n }\n }\n if (error === void 0) {\n error = "undefined";\n }\n this.abortReason = error;\n if (this.onBatchDone) {\n this.onBatchDone.reject(error);\n }\n if (this.transport.abort) {\n try {\n this.transport.abort(error);\n } catch (err) {\n Promise.resolve(err);\n }\n }\n for (let i in this.onBrokenCallbacks) {\n try {\n this.onBrokenCallbacks[i](error);\n } catch (err) {\n Promise.resolve(err);\n }\n }\n for (let i in this.imports) {\n this.imports[i].abort(error);\n }\n for (let i in this.exports) {\n this.exports[i].hook.dispose();\n }\n }\n async readLoop(abortPromise) {\n while (!this.abortReason) {\n let msg = JSON.parse(await Promise.race([this.transport.receive(), abortPromise]));\n if (this.abortReason) break;\n if (msg instanceof Array) {\n switch (msg[0]) {\n case "push":\n if (msg.length > 1) {\n let payload = new Evaluator(this).evaluate(msg[1]);\n let hook = new PayloadStubHook(payload);\n hook.ignoreUnhandledRejections();\n this.exports.push({ hook, refcount: 1 });\n continue;\n }\n break;\n case "stream": {\n if (msg.length > 1) {\n let payload = new Evaluator(this).evaluate(msg[1]);\n let hook = new PayloadStubHook(payload);\n hook.ignoreUnhandledRejections();\n let exportId = this.exports.length;\n this.exports.push({ hook, refcount: 1, autoRelease: true });\n this.ensureResolvingExport(exportId);\n continue;\n }\n break;\n }\n case "pipe": {\n let { readable, writable } = new TransformStream();\n let hook = streamImpl.createWritableStreamHook(writable);\n this.exports.push({ hook, refcount: 1, pipeReadable: readable });\n continue;\n }\n case "pull": {\n let exportId = msg[1];\n if (typeof exportId == "number") {\n this.ensureResolvingExport(exportId);\n continue;\n }\n break;\n }\n case "resolve":\n // ["resolve", ExportId, Expression]\n case "reject": {\n let importId = msg[1];\n if (typeof importId == "number" && msg.length > 2) {\n let imp = this.imports[importId];\n if (imp) {\n if (msg[0] == "resolve") {\n imp.resolve(new PayloadStubHook(new Evaluator(this).evaluate(msg[2])));\n } else {\n let payload = new Evaluator(this).evaluate(msg[2]);\n payload.dispose();\n imp.resolve(new ErrorStubHook(payload.value));\n }\n } else {\n if (msg[0] == "resolve") {\n new Evaluator(this).evaluate(msg[2]).dispose();\n }\n }\n continue;\n }\n break;\n }\n case "release": {\n let exportId = msg[1];\n let refcount = msg[2];\n if (typeof exportId == "number" && typeof refcount == "number") {\n this.releaseExport(exportId, refcount);\n continue;\n }\n break;\n }\n case "abort": {\n let payload = new Evaluator(this).evaluate(msg[1]);\n payload.dispose();\n this.abort(payload, false);\n break;\n }\n }\n }\n throw new Error(`bad RPC message: ${JSON.stringify(msg)}`);\n }\n }\n async drain() {\n if (this.abortReason) {\n throw this.abortReason;\n }\n if (this.pullCount > 0) {\n let { promise, resolve, reject } = Promise.withResolvers();\n this.onBatchDone = { resolve, reject };\n await promise;\n }\n }\n getStats() {\n let result = { imports: 0, exports: 0 };\n for (let i in this.imports) {\n ++result.imports;\n }\n for (let i in this.exports) {\n ++result.exports;\n }\n return result;\n }\n};\nvar RpcSession = class {\n #session;\n #mainStub;\n constructor(transport, localMain, options = {}) {\n let mainHook;\n if (localMain) {\n mainHook = new PayloadStubHook(RpcPayload.fromAppReturn(localMain));\n } else {\n mainHook = new ErrorStubHook(new Error("This connection has no main object."));\n }\n this.#session = new RpcSessionImpl(transport, mainHook, options);\n this.#mainStub = new RpcStub(this.#session.getMainImport());\n }\n getRemoteMain() {\n return this.#mainStub;\n }\n getStats() {\n return this.#session.getStats();\n }\n drain() {\n return this.#session.drain();\n }\n};\nfunction newWebSocketRpcSession(webSocket, localMain, options) {\n if (typeof webSocket === "string") {\n webSocket = new WebSocket(webSocket);\n }\n let transport = new WebSocketTransport(webSocket);\n let rpc = new RpcSession(transport, localMain, options);\n return rpc.getRemoteMain();\n}\nfunction newWorkersWebSocketRpcResponse(request, localMain, options) {\n if (request.headers.get("Upgrade")?.toLowerCase() !== "websocket") {\n return new Response("This endpoint only accepts WebSocket requests.", { status: 400 });\n }\n let pair = new WebSocketPair();\n let server = pair[0];\n server.accept();\n newWebSocketRpcSession(server, localMain, options);\n return new Response(null, {\n status: 101,\n webSocket: pair[1]\n });\n}\nvar WebSocketTransport = class {\n constructor(webSocket) {\n this.#webSocket = webSocket;\n if (webSocket.readyState === WebSocket.CONNECTING) {\n this.#sendQueue = [];\n webSocket.addEventListener("open", (event) => {\n try {\n for (let message of this.#sendQueue) {\n webSocket.send(message);\n }\n } catch (err) {\n this.#receivedError(err);\n }\n this.#sendQueue = void 0;\n });\n }\n webSocket.addEventListener("message", (event) => {\n if (this.#error) ;\n else if (typeof event.data === "string") {\n if (this.#receiveResolver) {\n this.#receiveResolver(event.data);\n this.#receiveResolver = void 0;\n this.#receiveRejecter = void 0;\n } else {\n this.#receiveQueue.push(event.data);\n }\n } else {\n this.#receivedError(new TypeError("Received non-string message from WebSocket."));\n }\n });\n webSocket.addEventListener("close", (event) => {\n this.#receivedError(new Error(`Peer closed WebSocket: ${event.code} ${event.reason}`));\n });\n webSocket.addEventListener("error", (event) => {\n this.#receivedError(new Error(`WebSocket connection failed.`));\n });\n }\n #webSocket;\n #sendQueue;\n // only if not opened yet\n #receiveResolver;\n #receiveRejecter;\n #receiveQueue = [];\n #error;\n async send(message) {\n if (this.#sendQueue === void 0) {\n this.#webSocket.send(message);\n } else {\n this.#sendQueue.push(message);\n }\n }\n async receive() {\n if (this.#receiveQueue.length > 0) {\n return this.#receiveQueue.shift();\n } else if (this.#error) {\n throw this.#error;\n } else {\n return new Promise((resolve, reject) => {\n this.#receiveResolver = resolve;\n this.#receiveRejecter = reject;\n });\n }\n }\n abort(reason) {\n let message;\n if (reason instanceof Error) {\n message = reason.message;\n } else {\n message = `${reason}`;\n }\n this.#webSocket.close(3e3, message);\n if (!this.#error) {\n this.#error = reason;\n }\n }\n #receivedError(reason) {\n if (!this.#error) {\n this.#error = reason;\n if (this.#receiveRejecter) {\n this.#receiveRejecter(reason);\n this.#receiveResolver = void 0;\n this.#receiveRejecter = void 0;\n }\n }\n }\n};\nvar BatchServerTransport = class {\n constructor(batch) {\n this.#batchToReceive = batch;\n }\n #batchToSend = [];\n #batchToReceive;\n #allReceived = Promise.withResolvers();\n async send(message) {\n this.#batchToSend.push(message);\n }\n async receive() {\n let msg = this.#batchToReceive.shift();\n if (msg !== void 0) {\n return msg;\n } else {\n this.#allReceived.resolve();\n return new Promise((r) => {\n });\n }\n }\n abort(reason) {\n this.#allReceived.reject(reason);\n }\n whenAllReceived() {\n return this.#allReceived.promise;\n }\n getResponseBody() {\n return this.#batchToSend.join("\\n");\n }\n};\nasync function newHttpBatchRpcResponse(request, localMain, options) {\n if (request.method !== "POST") {\n return new Response("This endpoint only accepts POST requests.", { status: 405 });\n }\n let body = await request.text();\n let batch = body === "" ? [] : body.split("\\n");\n let transport = new BatchServerTransport(batch);\n let rpc = new RpcSession(transport, localMain, options);\n await transport.whenAllReceived();\n await rpc.drain();\n return new Response(transport.getResponseBody());\n}\nvar currentMapBuilder;\nvar MapBuilder = class {\n context;\n captureMap = /* @__PURE__ */ new Map();\n instructions = [];\n constructor(subject, path) {\n if (currentMapBuilder) {\n this.context = {\n parent: currentMapBuilder,\n captures: [],\n subject: currentMapBuilder.capture(subject),\n path\n };\n } else {\n this.context = {\n parent: void 0,\n captures: [],\n subject,\n path\n };\n }\n currentMapBuilder = this;\n }\n unregister() {\n currentMapBuilder = this.context.parent;\n }\n makeInput() {\n return new MapVariableHook(this, 0);\n }\n makeOutput(result) {\n let devalued;\n try {\n devalued = Devaluator.devaluate(result.value, void 0, this, result);\n } finally {\n result.dispose();\n }\n this.instructions.push(devalued);\n if (this.context.parent) {\n this.context.parent.instructions.push(\n [\n "remap",\n this.context.subject,\n this.context.path,\n this.context.captures.map((cap) => ["import", cap]),\n this.instructions\n ]\n );\n return new MapVariableHook(this.context.parent, this.context.parent.instructions.length);\n } else {\n return this.context.subject.map(this.context.path, this.context.captures, this.instructions);\n }\n }\n pushCall(hook, path, params) {\n let devalued = Devaluator.devaluate(params.value, void 0, this, params);\n devalued = devalued[0];\n let subject = this.capture(hook.dup());\n this.instructions.push(["pipeline", subject, path, devalued]);\n return new MapVariableHook(this, this.instructions.length);\n }\n pushGet(hook, path) {\n let subject = this.capture(hook.dup());\n this.instructions.push(["pipeline", subject, path]);\n return new MapVariableHook(this, this.instructions.length);\n }\n capture(hook) {\n if (hook instanceof MapVariableHook && hook.mapper === this) {\n return hook.idx;\n }\n let result = this.captureMap.get(hook);\n if (result === void 0) {\n if (this.context.parent) {\n let parentIdx = this.context.parent.capture(hook);\n this.context.captures.push(parentIdx);\n } else {\n this.context.captures.push(hook);\n }\n result = -this.context.captures.length;\n this.captureMap.set(hook, result);\n }\n return result;\n }\n // ---------------------------------------------------------------------------\n // implements Exporter\n exportStub(hook) {\n throw new Error(\n "Can\'t construct an RpcTarget or RPC callback inside a mapper function. Try creating a new RpcStub outside the callback first, then using it inside the callback."\n );\n }\n exportPromise(hook) {\n return this.exportStub(hook);\n }\n getImport(hook) {\n return this.capture(hook);\n }\n unexport(ids) {\n }\n createPipe(readable) {\n throw new Error("Cannot send ReadableStream inside a mapper function.");\n }\n onSendError(error) {\n }\n};\nmapImpl.sendMap = (hook, path, func) => {\n let builder = new MapBuilder(hook, path);\n let result;\n try {\n result = RpcPayload.fromAppReturn(withCallInterceptor(builder.pushCall.bind(builder), () => {\n return func(new RpcPromise(builder.makeInput(), []));\n }));\n } finally {\n builder.unregister();\n }\n if (result instanceof Promise) {\n result.catch((err) => {\n });\n throw new Error("RPC map() callbacks cannot be async.");\n }\n return new RpcPromise(builder.makeOutput(result), []);\n};\nfunction throwMapperBuilderUseError() {\n throw new Error(\n "Attempted to use an abstract placeholder from a mapper function. Please make sure your map function has no side effects."\n );\n}\nvar MapVariableHook = class extends StubHook {\n constructor(mapper, idx) {\n super();\n this.mapper = mapper;\n this.idx = idx;\n }\n // We don\'t have anything we actually need to dispose, so dup() can just return the same hook.\n dup() {\n return this;\n }\n dispose() {\n }\n get(path) {\n if (path.length == 0) {\n return this;\n } else if (currentMapBuilder) {\n return currentMapBuilder.pushGet(this, path);\n } else {\n throwMapperBuilderUseError();\n }\n }\n // Other methods should never be called.\n call(path, args) {\n throwMapperBuilderUseError();\n }\n map(path, captures, instructions) {\n throwMapperBuilderUseError();\n }\n pull() {\n throwMapperBuilderUseError();\n }\n ignoreUnhandledRejections() {\n }\n onBroken(callback) {\n throwMapperBuilderUseError();\n }\n};\nvar MapApplicator = class {\n constructor(captures, input) {\n this.captures = captures;\n this.variables = [input];\n }\n variables;\n dispose() {\n for (let variable of this.variables) {\n variable.dispose();\n }\n }\n apply(instructions) {\n try {\n if (instructions.length < 1) {\n throw new Error("Invalid empty mapper function.");\n }\n for (let instruction of instructions.slice(0, -1)) {\n let payload = new Evaluator(this).evaluateCopy(instruction);\n if (payload.value instanceof RpcStub) {\n let hook = unwrapStubNoProperties(payload.value);\n if (hook) {\n this.variables.push(hook);\n continue;\n }\n }\n this.variables.push(new PayloadStubHook(payload));\n }\n return new Evaluator(this).evaluateCopy(instructions[instructions.length - 1]);\n } finally {\n for (let variable of this.variables) {\n variable.dispose();\n }\n }\n }\n importStub(idx) {\n throw new Error("A mapper function cannot refer to exports.");\n }\n importPromise(idx) {\n return this.importStub(idx);\n }\n getExport(idx) {\n if (idx < 0) {\n return this.captures[-idx - 1];\n } else {\n return this.variables[idx];\n }\n }\n getPipeReadable(exportId) {\n throw new Error("A mapper function cannot use pipe readables.");\n }\n};\nfunction applyMapToElement(input, parent, owner, captures, instructions) {\n let inputHook = new PayloadStubHook(RpcPayload.deepCopyFrom(input, parent, owner));\n let mapper = new MapApplicator(captures, inputHook);\n try {\n return mapper.apply(instructions);\n } finally {\n mapper.dispose();\n }\n}\nmapImpl.applyMap = (input, parent, owner, captures, instructions) => {\n try {\n let result;\n if (input instanceof RpcPromise) {\n throw new Error("applyMap() can\'t be called on RpcPromise");\n } else if (input instanceof Array) {\n let payloads = [];\n try {\n for (let elem of input) {\n payloads.push(applyMapToElement(elem, input, owner, captures, instructions));\n }\n } catch (err) {\n for (let payload of payloads) {\n payload.dispose();\n }\n throw err;\n }\n result = RpcPayload.fromArray(payloads);\n } else if (input === null || input === void 0) {\n result = RpcPayload.fromAppReturn(input);\n } else {\n result = applyMapToElement(input, parent, owner, captures, instructions);\n }\n return new PayloadStubHook(result);\n } finally {\n for (let cap of captures) {\n cap.dispose();\n }\n }\n};\nvar WritableStreamStubHook = class _WritableStreamStubHook extends StubHook {\n state;\n // undefined when disposed\n // Creates a new WritableStreamStubHook that is not duplicated from an existing hook.\n static create(stream) {\n let writer = stream.getWriter();\n return new _WritableStreamStubHook({ refcount: 1, writer, closed: false });\n }\n constructor(state, dupFrom) {\n super();\n this.state = state;\n if (dupFrom) {\n ++state.refcount;\n }\n }\n getState() {\n if (this.state) {\n return this.state;\n } else {\n throw new Error("Attempted to use a WritableStreamStubHook after it was disposed.");\n }\n }\n call(path, args) {\n try {\n let state = this.getState();\n if (path.length !== 1 || typeof path[0] !== "string") {\n throw new Error("WritableStream stub only supports direct method calls");\n }\n const method = path[0];\n if (method !== "write" && method !== "close" && method !== "abort") {\n args.dispose();\n throw new Error(`Unknown WritableStream method: ${method}`);\n }\n if (method === "close" || method === "abort") {\n state.closed = true;\n }\n let func = state.writer[method];\n let promise = args.deliverCall(func, state.writer);\n return new PromiseStubHook(promise.then((payload) => new PayloadStubHook(payload)));\n } catch (err) {\n return new ErrorStubHook(err);\n }\n }\n map(path, captures, instructions) {\n for (let cap of captures) {\n cap.dispose();\n }\n return new ErrorStubHook(new Error("Cannot use map() on a WritableStream"));\n }\n get(path) {\n return new ErrorStubHook(new Error("Cannot access properties on a WritableStream stub"));\n }\n dup() {\n let state = this.getState();\n return new _WritableStreamStubHook(state, this);\n }\n pull() {\n return Promise.reject(new Error("Cannot pull a WritableStream stub"));\n }\n ignoreUnhandledRejections() {\n }\n dispose() {\n let state = this.state;\n this.state = void 0;\n if (state) {\n if (--state.refcount === 0) {\n if (!state.closed) {\n state.writer.abort(new Error("WritableStream RPC stub was disposed without calling close()")).catch(() => {\n });\n }\n state.writer.releaseLock();\n }\n }\n }\n onBroken(callback) {\n }\n};\nvar INITIAL_WINDOW = 256 * 1024;\nvar MAX_WINDOW = 1024 * 1024 * 1024;\nvar MIN_WINDOW = 64 * 1024;\nvar STARTUP_GROWTH_FACTOR = 2;\nvar STEADY_GROWTH_FACTOR = 1.25;\nvar DECAY_FACTOR = 0.9;\nvar STARTUP_EXIT_ROUNDS = 3;\nvar FlowController = class {\n constructor(now) {\n this.now = now;\n }\n // The current window size in bytes. The sender blocks when bytesInFlight >= window.\n window = INITIAL_WINDOW;\n // Total bytes currently in flight (sent but not yet acked).\n bytesInFlight = 0;\n // Whether we\'re still in the startup phase.\n inStartupPhase = true;\n // ----- BDP estimation state (private) -----\n // Total bytes acked so far.\n delivered = 0;\n // Time of most recent ack.\n deliveredTime = 0;\n // Time when the very first ack was received.\n firstAckTime = 0;\n firstAckDelivered = 0;\n // Global minimum RTT observed (milliseconds).\n minRtt = Infinity;\n // For startup exit: count of consecutive RTT rounds where the window didn\'t meaningfully grow.\n roundsWithoutIncrease = 0;\n // Window size at the start of the current round, for startup exit detection.\n lastRoundWindow = 0;\n // Time when the current round started.\n roundStartTime = 0;\n // Called when a write of `size` bytes is about to be sent. Returns a token that must be\n // passed to onAck() when the ack arrives, and whether the sender should block (window full).\n onSend(size) {\n this.bytesInFlight += size;\n let token = {\n sentTime: this.now(),\n size,\n deliveredAtSend: this.delivered,\n deliveredTimeAtSend: this.deliveredTime,\n windowAtSend: this.window,\n windowFullAtSend: this.bytesInFlight >= this.window\n };\n return { token, shouldBlock: token.windowFullAtSend };\n }\n // Called when a previously-sent write fails. Restores bytesInFlight without updating\n // any BDP estimates.\n onError(token) {\n this.bytesInFlight -= token.size;\n }\n // Called when an ack is received for a previously-sent write. Updates BDP estimates and\n // the window. Returns whether a blocked sender should now unblock.\n onAck(token) {\n let ackTime = this.now();\n this.delivered += token.size;\n this.deliveredTime = ackTime;\n this.bytesInFlight -= token.size;\n let rtt = ackTime - token.sentTime;\n this.minRtt = Math.min(this.minRtt, rtt);\n if (this.firstAckTime === 0) {\n this.firstAckTime = ackTime;\n this.firstAckDelivered = this.delivered;\n } else {\n let baseTime;\n let baseDelivered;\n if (token.deliveredTimeAtSend === 0) {\n baseTime = this.firstAckTime;\n baseDelivered = this.firstAckDelivered;\n } else {\n baseTime = token.deliveredTimeAtSend;\n baseDelivered = token.deliveredAtSend;\n }\n let interval = ackTime - baseTime;\n let bytes = this.delivered - baseDelivered;\n let bandwidth = bytes / interval;\n let growthFactor = this.inStartupPhase ? STARTUP_GROWTH_FACTOR : STEADY_GROWTH_FACTOR;\n let newWindow = bandwidth * this.minRtt * growthFactor;\n newWindow = Math.min(newWindow, token.windowAtSend * growthFactor);\n if (token.windowFullAtSend) {\n newWindow = Math.max(newWindow, token.windowAtSend * DECAY_FACTOR);\n } else {\n newWindow = Math.max(newWindow, this.window);\n }\n this.window = Math.max(Math.min(newWindow, MAX_WINDOW), MIN_WINDOW);\n if (this.inStartupPhase && token.sentTime >= this.roundStartTime) {\n if (this.window > this.lastRoundWindow * STEADY_GROWTH_FACTOR) {\n this.roundsWithoutIncrease = 0;\n } else {\n if (++this.roundsWithoutIncrease >= STARTUP_EXIT_ROUNDS) {\n this.inStartupPhase = false;\n }\n }\n this.roundStartTime = ackTime;\n this.lastRoundWindow = this.window;\n }\n }\n return this.bytesInFlight < this.window;\n }\n};\nfunction createWritableStreamFromHook(hook) {\n let pendingError = void 0;\n let hookDisposed = false;\n let fc = new FlowController(() => performance.now());\n let windowResolve;\n let windowReject;\n const disposeHook = () => {\n if (!hookDisposed) {\n hookDisposed = true;\n hook.dispose();\n }\n };\n return new WritableStream({\n write(chunk, controller) {\n if (pendingError !== void 0) {\n throw pendingError;\n }\n const payload = RpcPayload.fromAppParams([chunk]);\n const { promise, size } = hook.stream(["write"], payload);\n if (size === void 0) {\n return promise.catch((err) => {\n if (pendingError === void 0) {\n pendingError = err;\n }\n throw err;\n });\n } else {\n let { token, shouldBlock } = fc.onSend(size);\n promise.then(() => {\n let hasCapacity = fc.onAck(token);\n if (hasCapacity && windowResolve) {\n windowResolve();\n windowResolve = void 0;\n windowReject = void 0;\n }\n }, (err) => {\n fc.onError(token);\n if (pendingError === void 0) {\n pendingError = err;\n controller.error(err);\n disposeHook();\n }\n if (windowReject) {\n windowReject(err);\n windowResolve = void 0;\n windowReject = void 0;\n }\n });\n if (shouldBlock) {\n return new Promise((resolve, reject) => {\n windowResolve = resolve;\n windowReject = reject;\n });\n }\n }\n },\n async close() {\n if (pendingError !== void 0) {\n disposeHook();\n throw pendingError;\n }\n const { promise } = hook.stream(["close"], RpcPayload.fromAppParams([]));\n try {\n await promise;\n } catch (err) {\n throw pendingError ?? err;\n } finally {\n disposeHook();\n }\n },\n abort(reason) {\n if (pendingError !== void 0) {\n return;\n }\n pendingError = reason ?? new Error("WritableStream was aborted");\n if (windowReject) {\n windowReject(pendingError);\n windowResolve = void 0;\n windowReject = void 0;\n }\n const { promise } = hook.stream(["abort"], RpcPayload.fromAppParams([reason]));\n promise.then(() => disposeHook(), () => disposeHook());\n }\n });\n}\nvar ReadableStreamStubHook = class _ReadableStreamStubHook extends StubHook {\n state;\n // undefined when disposed\n // Creates a new ReadableStreamStubHook.\n static create(stream) {\n return new _ReadableStreamStubHook({ refcount: 1, stream, canceled: false });\n }\n constructor(state, dupFrom) {\n super();\n this.state = state;\n if (dupFrom) {\n ++state.refcount;\n }\n }\n call(path, args) {\n args.dispose();\n return new ErrorStubHook(new Error("Cannot call methods on a ReadableStream stub"));\n }\n map(path, captures, instructions) {\n for (let cap of captures) {\n cap.dispose();\n }\n return new ErrorStubHook(new Error("Cannot use map() on a ReadableStream"));\n }\n get(path) {\n return new ErrorStubHook(new Error("Cannot access properties on a ReadableStream stub"));\n }\n dup() {\n let state = this.state;\n if (!state) {\n throw new Error("Attempted to dup a ReadableStreamStubHook after it was disposed.");\n }\n return new _ReadableStreamStubHook(state, this);\n }\n pull() {\n return Promise.reject(new Error("Cannot pull a ReadableStream stub"));\n }\n ignoreUnhandledRejections() {\n }\n dispose() {\n let state = this.state;\n this.state = void 0;\n if (state) {\n if (--state.refcount === 0) {\n if (!state.canceled) {\n state.canceled = true;\n if (!state.stream.locked) {\n state.stream.cancel(\n new Error("ReadableStream RPC stub was disposed without being consumed")\n ).catch(() => {\n });\n }\n }\n }\n }\n }\n onBroken(callback) {\n }\n};\nstreamImpl.createWritableStreamHook = WritableStreamStubHook.create;\nstreamImpl.createWritableStreamFromHook = createWritableStreamFromHook;\nstreamImpl.createReadableStreamHook = ReadableStreamStubHook.create;\nasync function newWorkersRpcResponse(request, localMain) {\n if (request.method === "POST") {\n let response = await newHttpBatchRpcResponse(request, localMain);\n response.headers.set("Access-Control-Allow-Origin", "*");\n return response;\n } else if (request.headers.get("Upgrade")?.toLowerCase() === "websocket") {\n return newWorkersWebSocketRpcResponse(request, localMain);\n } else {\n return new Response("This endpoint only accepts POST or WebSocket requests.", { status: 400 });\n }\n}\n\n// templates/remoteBindings/ProxyServerWorker.ts\nimport { EmailMessage } from "cloudflare:email";\nvar BindingNotFoundError = class extends Error {\n constructor(name) {\n super(`Binding ${name ? `"${name}"` : ""} not found`);\n }\n};\nfunction getExposedJSRPCBinding(request, env) {\n const url = new URL(request.url);\n const bindingName = url.searchParams.get("MF-Binding");\n if (!bindingName) {\n throw new BindingNotFoundError();\n }\n const targetBinding = env[bindingName];\n if (!targetBinding) {\n throw new BindingNotFoundError(bindingName);\n }\n if (targetBinding.constructor.name === "SendEmail") {\n return {\n async send(e) {\n if ("EmailMessage::raw" in e) {\n const message = new EmailMessage(\n e.from,\n e.to,\n e["EmailMessage::raw"]\n );\n return targetBinding.send(message);\n } else {\n return targetBinding.send(e);\n }\n }\n };\n }\n const dispatchNamespaceOptions = url.searchParams.get(\n "MF-Dispatch-Namespace-Options"\n );\n if (dispatchNamespaceOptions) {\n const { name, args, options } = JSON.parse(dispatchNamespaceOptions);\n return targetBinding.get(name, args, options);\n }\n return targetBinding;\n}\nfunction getExposedFetcher(request, env) {\n const bindingName = request.headers.get("MF-Binding");\n if (!bindingName) {\n throw new BindingNotFoundError();\n }\n const targetBinding = env[bindingName];\n if (!targetBinding) {\n throw new BindingNotFoundError(bindingName);\n }\n const dispatchNamespaceOptions = request.headers.get(\n "MF-Dispatch-Namespace-Options"\n );\n if (dispatchNamespaceOptions) {\n const { name, args, options } = JSON.parse(dispatchNamespaceOptions);\n return targetBinding.get(name, args, options);\n }\n return targetBinding;\n}\nfunction isJSRPCBinding(request) {\n const url = new URL(request.url);\n return request.headers.has("Upgrade") && url.searchParams.has("MF-Binding");\n}\nvar ProxyServerWorker_default = {\n async fetch(request, env) {\n try {\n if (isJSRPCBinding(request)) {\n return await newWorkersRpcResponse(\n request,\n getExposedJSRPCBinding(request, env)\n );\n } else {\n const fetcher = getExposedFetcher(request, env);\n const originalHeaders = new Headers();\n for (const [name, value] of request.headers) {\n if (name.startsWith("mf-header-")) {\n originalHeaders.set(name.slice("mf-header-".length), value);\n } else if (name === "upgrade") {\n originalHeaders.set(name, value);\n }\n }\n return await fetcher.fetch(\n request.headers.get("MF-URL") ?? "http://example.com",\n new Request(request, {\n redirect: "manual",\n headers: originalHeaders\n })\n );\n }\n } catch (e) {\n if (e instanceof BindingNotFoundError) {\n return new Response(e.message, { status: 400 });\n }\n return new Response(e.message, { status: 500 });\n }\n }\n};\nexport {\n ProxyServerWorker_default as default\n};\n';
171468
+ ProxyServerWorker_default = '// ../../node_modules/.pnpm/capnweb@0.5.0/node_modules/capnweb/dist/index-workers.js\nimport * as cfw from "cloudflare:workers";\nvar WORKERS_MODULE_SYMBOL = /* @__PURE__ */ Symbol("workers-module");\nglobalThis[WORKERS_MODULE_SYMBOL] = cfw;\nif (!Symbol.dispose) {\n Symbol.dispose = /* @__PURE__ */ Symbol.for("dispose");\n}\nif (!Symbol.asyncDispose) {\n Symbol.asyncDispose = /* @__PURE__ */ Symbol.for("asyncDispose");\n}\nif (!Promise.withResolvers) {\n Promise.withResolvers = function() {\n let resolve;\n let reject;\n const promise = new Promise((res, rej) => {\n resolve = res;\n reject = rej;\n });\n return { promise, resolve, reject };\n };\n}\nvar workersModule = globalThis[WORKERS_MODULE_SYMBOL];\nvar RpcTarget = workersModule ? workersModule.RpcTarget : class {\n};\nvar AsyncFunction = (async function() {\n}).constructor;\nfunction typeForRpc(value) {\n switch (typeof value) {\n case "boolean":\n case "number":\n case "string":\n return "primitive";\n case "undefined":\n return "undefined";\n case "object":\n case "function":\n break;\n case "bigint":\n return "bigint";\n default:\n return "unsupported";\n }\n if (value === null) {\n return "primitive";\n }\n let prototype = Object.getPrototypeOf(value);\n switch (prototype) {\n case Object.prototype:\n return "object";\n case Function.prototype:\n case AsyncFunction.prototype:\n return "function";\n case Array.prototype:\n return "array";\n case Date.prototype:\n return "date";\n case Uint8Array.prototype:\n return "bytes";\n case WritableStream.prototype:\n return "writable";\n case ReadableStream.prototype:\n return "readable";\n case Headers.prototype:\n return "headers";\n case Request.prototype:\n return "request";\n case Response.prototype:\n return "response";\n // TODO: All other structured clone types.\n case RpcStub.prototype:\n return "stub";\n case RpcPromise.prototype:\n return "rpc-promise";\n // TODO: Promise<T> or thenable\n default:\n if (workersModule) {\n if (prototype == workersModule.RpcStub.prototype || value instanceof workersModule.ServiceStub) {\n return "rpc-target";\n } else if (prototype == workersModule.RpcPromise.prototype || prototype == workersModule.RpcProperty.prototype) {\n return "rpc-thenable";\n }\n }\n if (value instanceof RpcTarget) {\n return "rpc-target";\n }\n if (value instanceof Error) {\n return "error";\n }\n return "unsupported";\n }\n}\nfunction mapNotLoaded() {\n throw new Error("RPC map() implementation was not loaded.");\n}\nvar mapImpl = { applyMap: mapNotLoaded, sendMap: mapNotLoaded };\nfunction streamNotLoaded() {\n throw new Error("Stream implementation was not loaded.");\n}\nvar streamImpl = {\n createWritableStreamHook: streamNotLoaded,\n createWritableStreamFromHook: streamNotLoaded,\n createReadableStreamHook: streamNotLoaded\n};\nvar StubHook = class {\n // Like call(), but designed for streaming calls (e.g. WritableStream writes). Returns:\n // - promise: A Promise<void> for the completion of the call.\n // - size: If the call was remote, the byte size of the serialized message. For local calls,\n // undefined is returned, indicating the caller should await the promise to serialize writes\n // (no overlapping).\n stream(path, args) {\n let hook = this.call(path, args);\n let pulled = hook.pull();\n let promise;\n if (pulled instanceof Promise) {\n promise = pulled.then((p) => {\n p.dispose();\n });\n } else {\n pulled.dispose();\n promise = Promise.resolve();\n }\n return { promise };\n }\n};\nvar ErrorStubHook = class extends StubHook {\n constructor(error) {\n super();\n this.error = error;\n }\n call(path, args) {\n return this;\n }\n map(path, captures, instructions) {\n return this;\n }\n get(path) {\n return this;\n }\n dup() {\n return this;\n }\n pull() {\n return Promise.reject(this.error);\n }\n ignoreUnhandledRejections() {\n }\n dispose() {\n }\n onBroken(callback) {\n try {\n callback(this.error);\n } catch (err) {\n Promise.resolve(err);\n }\n }\n};\nvar DISPOSED_HOOK = new ErrorStubHook(\n new Error("Attempted to use RPC stub after it has been disposed.")\n);\nvar doCall = (hook, path, params) => {\n return hook.call(path, params);\n};\nfunction withCallInterceptor(interceptor, callback) {\n let oldValue = doCall;\n doCall = interceptor;\n try {\n return callback();\n } finally {\n doCall = oldValue;\n }\n}\nvar RAW_STUB = /* @__PURE__ */ Symbol("realStub");\nvar PROXY_HANDLERS = {\n apply(target, thisArg, argumentsList) {\n let stub = target.raw;\n return new RpcPromise(doCall(\n stub.hook,\n stub.pathIfPromise || [],\n RpcPayload.fromAppParams(argumentsList)\n ), []);\n },\n get(target, prop, receiver) {\n let stub = target.raw;\n if (prop === RAW_STUB) {\n return stub;\n } else if (prop in RpcPromise.prototype) {\n return stub[prop];\n } else if (typeof prop === "string") {\n return new RpcPromise(\n stub.hook,\n stub.pathIfPromise ? [...stub.pathIfPromise, prop] : [prop]\n );\n } else if (prop === Symbol.dispose && (!stub.pathIfPromise || stub.pathIfPromise.length == 0)) {\n return () => {\n stub.hook.dispose();\n stub.hook = DISPOSED_HOOK;\n };\n } else {\n return void 0;\n }\n },\n has(target, prop) {\n let stub = target.raw;\n if (prop === RAW_STUB) {\n return true;\n } else if (prop in RpcPromise.prototype) {\n return prop in stub;\n } else if (typeof prop === "string") {\n return true;\n } else if (prop === Symbol.dispose && (!stub.pathIfPromise || stub.pathIfPromise.length == 0)) {\n return true;\n } else {\n return false;\n }\n },\n construct(target, args) {\n throw new Error("An RPC stub cannot be used as a constructor.");\n },\n defineProperty(target, property, attributes) {\n throw new Error("Can\'t define properties on RPC stubs.");\n },\n deleteProperty(target, p) {\n throw new Error("Can\'t delete properties on RPC stubs.");\n },\n getOwnPropertyDescriptor(target, p) {\n return void 0;\n },\n getPrototypeOf(target) {\n return Object.getPrototypeOf(target.raw);\n },\n isExtensible(target) {\n return false;\n },\n ownKeys(target) {\n return [];\n },\n preventExtensions(target) {\n return true;\n },\n set(target, p, newValue, receiver) {\n throw new Error("Can\'t assign properties on RPC stubs.");\n },\n setPrototypeOf(target, v) {\n throw new Error("Can\'t override prototype of RPC stubs.");\n }\n};\nvar RpcStub = class _RpcStub extends RpcTarget {\n // Although `hook` and `path` are declared `public` here, they are effectively hidden by the\n // proxy.\n constructor(hook, pathIfPromise) {\n super();\n if (!(hook instanceof StubHook)) {\n let value = hook;\n if (value instanceof RpcTarget || value instanceof Function) {\n hook = TargetStubHook.create(value, void 0);\n } else {\n hook = new PayloadStubHook(RpcPayload.fromAppReturn(value));\n }\n if (pathIfPromise) {\n throw new TypeError("RpcStub constructor expected one argument, received two.");\n }\n }\n this.hook = hook;\n this.pathIfPromise = pathIfPromise;\n let func = () => {\n };\n func.raw = this;\n return new Proxy(func, PROXY_HANDLERS);\n }\n hook;\n pathIfPromise;\n dup() {\n let target = this[RAW_STUB];\n if (target.pathIfPromise) {\n return new _RpcStub(target.hook.get(target.pathIfPromise));\n } else {\n return new _RpcStub(target.hook.dup());\n }\n }\n onRpcBroken(callback) {\n this[RAW_STUB].hook.onBroken(callback);\n }\n map(func) {\n let { hook, pathIfPromise } = this[RAW_STUB];\n return mapImpl.sendMap(hook, pathIfPromise || [], func);\n }\n toString() {\n return "[object RpcStub]";\n }\n};\nvar RpcPromise = class extends RpcStub {\n // TODO: Support passing target value or promise to constructor.\n constructor(hook, pathIfPromise) {\n super(hook, pathIfPromise);\n }\n then(onfulfilled, onrejected) {\n return pullPromise(this).then(...arguments);\n }\n catch(onrejected) {\n return pullPromise(this).catch(...arguments);\n }\n finally(onfinally) {\n return pullPromise(this).finally(...arguments);\n }\n toString() {\n return "[object RpcPromise]";\n }\n};\nfunction unwrapStubTakingOwnership(stub) {\n let { hook, pathIfPromise } = stub[RAW_STUB];\n if (pathIfPromise && pathIfPromise.length > 0) {\n return hook.get(pathIfPromise);\n } else {\n return hook;\n }\n}\nfunction unwrapStubAndDup(stub) {\n let { hook, pathIfPromise } = stub[RAW_STUB];\n if (pathIfPromise) {\n return hook.get(pathIfPromise);\n } else {\n return hook.dup();\n }\n}\nfunction unwrapStubNoProperties(stub) {\n let { hook, pathIfPromise } = stub[RAW_STUB];\n if (pathIfPromise && pathIfPromise.length > 0) {\n return void 0;\n }\n return hook;\n}\nfunction unwrapStubOrParent(stub) {\n return stub[RAW_STUB].hook;\n}\nfunction unwrapStubAndPath(stub) {\n return stub[RAW_STUB];\n}\nasync function pullPromise(promise) {\n let { hook, pathIfPromise } = promise[RAW_STUB];\n if (pathIfPromise.length > 0) {\n hook = hook.get(pathIfPromise);\n }\n let payload = await hook.pull();\n return payload.deliverResolve();\n}\nvar RpcPayload = class _RpcPayload {\n // Private constructor; use factory functions above to construct.\n constructor(value, source, hooks, promises) {\n this.value = value;\n this.source = source;\n this.hooks = hooks;\n this.promises = promises;\n }\n // Create a payload from a value passed as params to an RPC from the app.\n //\n // The payload does NOT take ownership of any stubs in `value`, and but promises not to modify\n // `value`. If the payload is delivered locally, `value` will be deep-copied first, so as not\n // to have the sender and recipient end up sharing the same mutable object. `value` will not be\n // touched again after the call returns synchronously (returns a promise) -- by that point,\n // the value has either been copied or serialized to the wire.\n static fromAppParams(value) {\n return new _RpcPayload(value, "params");\n }\n // Create a payload from a value return from an RPC implementation by the app.\n //\n // Unlike fromAppParams(), in this case the payload takes ownership of all stubs in `value`, and\n // may hold onto `value` for an arbitrarily long time (e.g. to serve pipelined requests). It\n // will still avoid modifying `value` and will make a deep copy if it is delivered locally.\n static fromAppReturn(value) {\n return new _RpcPayload(value, "return");\n }\n // Combine an array of payloads into a single payload whose value is an array. Ownership of all\n // stubs is transferred from the inputs to the outputs, hence if the output is disposed, the\n // inputs should not be. (In case of exception, nothing is disposed, though.)\n static fromArray(array) {\n let hooks = [];\n let promises = [];\n let resultArray = [];\n for (let payload of array) {\n payload.ensureDeepCopied();\n for (let hook of payload.hooks) {\n hooks.push(hook);\n }\n for (let promise of payload.promises) {\n if (promise.parent === payload) {\n promise = {\n parent: resultArray,\n property: resultArray.length,\n promise: promise.promise\n };\n }\n promises.push(promise);\n }\n resultArray.push(payload.value);\n }\n return new _RpcPayload(resultArray, "owned", hooks, promises);\n }\n // Create a payload from a value parsed off the wire using Evaluator.evaluate().\n //\n // A payload is constructed with a null value and the given hooks and promises arrays. The value\n // is expected to be filled in by the evaluator, and the hooks and promises arrays are expected\n // to be extended with stubs found during parsing. (This weird usage model is necessary so that\n // if the root value turns out to be a promise, its `parent` in `promises` can be the payload\n // object itself.)\n //\n // When done, the payload takes ownership of the final value and all the stubs within. It may\n // modify the value in preparation for delivery, and may deliver the value directly to the app\n // without copying.\n static forEvaluate(hooks, promises) {\n return new _RpcPayload(null, "owned", hooks, promises);\n }\n // Deep-copy the given value, including dup()ing all stubs.\n //\n // If `value` is a function, it should be bound to `oldParent` as its `this`.\n //\n // If deep-copying from a branch of some other RpcPayload, it must be provided, to make sure\n // RpcTargets found within don\'t get duplicate stubs.\n static deepCopyFrom(value, oldParent, owner) {\n let result = new _RpcPayload(null, "owned", [], []);\n result.value = result.deepCopy(\n value,\n oldParent,\n "value",\n result,\n /*dupStubs=*/\n true,\n owner\n );\n return result;\n }\n // For `source === "return"` payloads only, this tracks any StubHooks created around RpcTargets\n // or WritableStreams found in the payload at the time that it is serialized (or deep-copied) for\n // return, so that we can make sure they are not disposed before the pipeline ends.\n //\n // This is initialized on first use.\n rpcTargets;\n // Get the StubHook representing the given RpcTarget found inside this payload.\n getHookForRpcTarget(target, parent, dupStubs = true) {\n if (this.source === "params") {\n if (dupStubs) {\n let dupable = target;\n if (typeof dupable.dup === "function") {\n target = dupable.dup();\n }\n }\n return TargetStubHook.create(target, parent);\n } else if (this.source === "return") {\n let hook = this.rpcTargets?.get(target);\n if (hook) {\n if (dupStubs) {\n return hook.dup();\n } else {\n this.rpcTargets?.delete(target);\n return hook;\n }\n } else {\n hook = TargetStubHook.create(target, parent);\n if (dupStubs) {\n if (!this.rpcTargets) {\n this.rpcTargets = /* @__PURE__ */ new Map();\n }\n this.rpcTargets.set(target, hook);\n return hook.dup();\n } else {\n return hook;\n }\n }\n } else {\n throw new Error("owned payload shouldn\'t contain raw RpcTargets");\n }\n }\n // Get the StubHook representing the given WritableStream found inside this payload.\n getHookForWritableStream(stream, parent, dupStubs = true) {\n if (this.source === "params") {\n return streamImpl.createWritableStreamHook(stream);\n } else if (this.source === "return") {\n let hook = this.rpcTargets?.get(stream);\n if (hook) {\n if (dupStubs) {\n return hook.dup();\n } else {\n this.rpcTargets?.delete(stream);\n return hook;\n }\n } else {\n hook = streamImpl.createWritableStreamHook(stream);\n if (dupStubs) {\n if (!this.rpcTargets) {\n this.rpcTargets = /* @__PURE__ */ new Map();\n }\n this.rpcTargets.set(stream, hook);\n return hook.dup();\n } else {\n return hook;\n }\n }\n } else {\n throw new Error("owned payload shouldn\'t contain raw WritableStreams");\n }\n }\n // Get the StubHook representing the given ReadableStream found inside this payload.\n getHookForReadableStream(stream, parent, dupStubs = true) {\n if (this.source === "params") {\n return streamImpl.createReadableStreamHook(stream);\n } else if (this.source === "return") {\n let hook = this.rpcTargets?.get(stream);\n if (hook) {\n if (dupStubs) {\n return hook.dup();\n } else {\n this.rpcTargets?.delete(stream);\n return hook;\n }\n } else {\n hook = streamImpl.createReadableStreamHook(stream);\n if (dupStubs) {\n if (!this.rpcTargets) {\n this.rpcTargets = /* @__PURE__ */ new Map();\n }\n this.rpcTargets.set(stream, hook);\n return hook.dup();\n } else {\n return hook;\n }\n }\n } else {\n throw new Error("owned payload shouldn\'t contain raw ReadableStreams");\n }\n }\n deepCopy(value, oldParent, property, parent, dupStubs, owner) {\n let kind = typeForRpc(value);\n switch (kind) {\n case "unsupported":\n return value;\n case "primitive":\n case "bigint":\n case "date":\n case "bytes":\n case "error":\n case "undefined":\n return value;\n case "array": {\n let array = value;\n let len = array.length;\n let result = new Array(len);\n for (let i = 0; i < len; i++) {\n result[i] = this.deepCopy(array[i], array, i, result, dupStubs, owner);\n }\n return result;\n }\n case "object": {\n let result = {};\n let object = value;\n for (let i in object) {\n result[i] = this.deepCopy(object[i], object, i, result, dupStubs, owner);\n }\n return result;\n }\n case "stub":\n case "rpc-promise": {\n let stub = value;\n let hook;\n if (dupStubs) {\n hook = unwrapStubAndDup(stub);\n } else {\n hook = unwrapStubTakingOwnership(stub);\n }\n if (stub instanceof RpcPromise) {\n let promise = new RpcPromise(hook, []);\n this.promises.push({ parent, property, promise });\n return promise;\n } else {\n this.hooks.push(hook);\n return new RpcStub(hook);\n }\n }\n case "function":\n case "rpc-target": {\n let target = value;\n let hook;\n if (owner) {\n hook = owner.getHookForRpcTarget(target, oldParent, dupStubs);\n } else {\n hook = TargetStubHook.create(target, oldParent);\n }\n this.hooks.push(hook);\n return new RpcStub(hook);\n }\n case "rpc-thenable": {\n let target = value;\n let promise;\n if (owner) {\n promise = new RpcPromise(owner.getHookForRpcTarget(target, oldParent, dupStubs), []);\n } else {\n promise = new RpcPromise(TargetStubHook.create(target, oldParent), []);\n }\n this.promises.push({ parent, property, promise });\n return promise;\n }\n case "writable": {\n let stream = value;\n let hook;\n if (owner) {\n hook = owner.getHookForWritableStream(stream, oldParent, dupStubs);\n } else {\n hook = streamImpl.createWritableStreamHook(stream);\n }\n this.hooks.push(hook);\n return stream;\n }\n case "readable": {\n let stream = value;\n let hook;\n if (owner) {\n hook = owner.getHookForReadableStream(stream, oldParent, dupStubs);\n } else {\n hook = streamImpl.createReadableStreamHook(stream);\n }\n this.hooks.push(hook);\n return stream;\n }\n case "headers":\n return new Headers(value);\n case "request": {\n let req = value;\n if (req.body) {\n this.deepCopy(req.body, req, "body", req, dupStubs, owner);\n }\n return new Request(req);\n }\n case "response": {\n let resp = value;\n if (resp.body) {\n this.deepCopy(resp.body, resp, "body", resp, dupStubs, owner);\n }\n return new Response(resp.body, resp);\n }\n default:\n throw new Error("unreachable");\n }\n }\n // Ensures that if the value originally came from an unowned source, we have replaced it with a\n // deep copy.\n ensureDeepCopied() {\n if (this.source !== "owned") {\n let dupStubs = this.source === "params";\n this.hooks = [];\n this.promises = [];\n try {\n this.value = this.deepCopy(this.value, void 0, "value", this, dupStubs, this);\n } catch (err) {\n this.hooks = void 0;\n this.promises = void 0;\n throw err;\n }\n this.source = "owned";\n if (this.rpcTargets && this.rpcTargets.size > 0) {\n throw new Error("Not all rpcTargets were accounted for in deep-copy?");\n }\n this.rpcTargets = void 0;\n }\n }\n // Resolve all promises in this payload and then assign the final value into `parent[property]`.\n deliverTo(parent, property, promises) {\n this.ensureDeepCopied();\n if (this.value instanceof RpcPromise) {\n _RpcPayload.deliverRpcPromiseTo(this.value, parent, property, promises);\n } else {\n parent[property] = this.value;\n for (let record of this.promises) {\n _RpcPayload.deliverRpcPromiseTo(record.promise, record.parent, record.property, promises);\n }\n }\n }\n static deliverRpcPromiseTo(promise, parent, property, promises) {\n let hook = unwrapStubNoProperties(promise);\n if (!hook) {\n throw new Error("property promises should have been resolved earlier");\n }\n let inner = hook.pull();\n if (inner instanceof _RpcPayload) {\n inner.deliverTo(parent, property, promises);\n } else {\n promises.push(inner.then((payload) => {\n let subPromises = [];\n payload.deliverTo(parent, property, subPromises);\n if (subPromises.length > 0) {\n return Promise.all(subPromises);\n }\n }));\n }\n }\n // Call the given function with the payload as an argument. The call is made synchronously if\n // possible, in order to maintain e-order. However, if any RpcPromises exist in the payload,\n // they are awaited and substituted before calling the function. The result of the call is\n // wrapped into another payload.\n //\n // The payload is automatically disposed after the call completes. The caller should not call\n // dispose().\n async deliverCall(func, thisArg) {\n try {\n let promises = [];\n this.deliverTo(this, "value", promises);\n if (promises.length > 0) {\n await Promise.all(promises);\n }\n let result = Function.prototype.apply.call(func, thisArg, this.value);\n if (result instanceof RpcPromise) {\n return _RpcPayload.fromAppReturn(result);\n } else {\n return _RpcPayload.fromAppReturn(await result);\n }\n } finally {\n this.dispose();\n }\n }\n // Produce a promise for this payload for return to the application. Any RpcPromises in the\n // payload are awaited and substituted with their results first.\n //\n // The returned object will have a disposer which disposes the payload. The caller should not\n // separately dispose it.\n async deliverResolve() {\n try {\n let promises = [];\n this.deliverTo(this, "value", promises);\n if (promises.length > 0) {\n await Promise.all(promises);\n }\n let result = this.value;\n if (result instanceof Object) {\n if (!(Symbol.dispose in result)) {\n Object.defineProperty(result, Symbol.dispose, {\n // NOTE: Using `this.dispose.bind(this)` here causes Playwright\'s build of\n // Chromium 140.0.7339.16 to fail when the object is assigned to a `using` variable,\n // with the error:\n // TypeError: Symbol(Symbol.dispose) is not a function\n // I cannot reproduce this problem in Chrome 140.0.7339.127 nor in Node or workerd,\n // so maybe it was a short-lived V8 bug or something. To be safe, though, we use\n // `() => this.dispose()`, which seems to always work.\n value: () => this.dispose(),\n writable: true,\n enumerable: false,\n configurable: true\n });\n }\n }\n return result;\n } catch (err) {\n this.dispose();\n throw err;\n }\n }\n dispose() {\n if (this.source === "owned") {\n this.hooks.forEach((hook) => hook.dispose());\n this.promises.forEach((promise) => promise.promise[Symbol.dispose]());\n } else if (this.source === "return") {\n this.disposeImpl(this.value, void 0);\n if (this.rpcTargets && this.rpcTargets.size > 0) {\n throw new Error("Not all rpcTargets were accounted for in disposeImpl()?");\n }\n } else ;\n this.source = "owned";\n this.hooks = [];\n this.promises = [];\n }\n // Recursive dispose, called only when `source` is "return".\n disposeImpl(value, parent) {\n let kind = typeForRpc(value);\n switch (kind) {\n case "unsupported":\n case "primitive":\n case "bigint":\n case "bytes":\n case "date":\n case "error":\n case "undefined":\n return;\n case "array": {\n let array = value;\n let len = array.length;\n for (let i = 0; i < len; i++) {\n this.disposeImpl(array[i], array);\n }\n return;\n }\n case "object": {\n let object = value;\n for (let i in object) {\n this.disposeImpl(object[i], object);\n }\n return;\n }\n case "stub":\n case "rpc-promise": {\n let stub = value;\n let hook = unwrapStubNoProperties(stub);\n if (hook) {\n hook.dispose();\n }\n return;\n }\n case "function":\n case "rpc-target": {\n let target = value;\n let hook = this.rpcTargets?.get(target);\n if (hook) {\n hook.dispose();\n this.rpcTargets.delete(target);\n } else {\n disposeRpcTarget(target);\n }\n return;\n }\n case "rpc-thenable":\n return;\n case "headers":\n return;\n case "request": {\n let req = value;\n if (req.body) this.disposeImpl(req.body, req);\n return;\n }\n case "response": {\n let resp = value;\n if (resp.body) this.disposeImpl(resp.body, resp);\n return;\n }\n case "writable": {\n let stream = value;\n let hook = this.rpcTargets?.get(stream);\n if (hook) {\n this.rpcTargets.delete(stream);\n } else {\n hook = streamImpl.createWritableStreamHook(stream);\n }\n hook.dispose();\n return;\n }\n case "readable": {\n let stream = value;\n let hook = this.rpcTargets?.get(stream);\n if (hook) {\n this.rpcTargets.delete(stream);\n } else {\n hook = streamImpl.createReadableStreamHook(stream);\n }\n hook.dispose();\n return;\n }\n default:\n return;\n }\n }\n // Ignore unhandled rejections in all promises in this payload -- that is, all promises that\n // *would* be awaited if this payload were to be delivered. See the similarly-named method of\n // StubHook for explanation.\n ignoreUnhandledRejections() {\n if (this.hooks) {\n this.hooks.forEach((hook) => {\n hook.ignoreUnhandledRejections();\n });\n this.promises.forEach(\n (promise) => unwrapStubOrParent(promise.promise).ignoreUnhandledRejections()\n );\n } else {\n this.ignoreUnhandledRejectionsImpl(this.value);\n }\n }\n ignoreUnhandledRejectionsImpl(value) {\n let kind = typeForRpc(value);\n switch (kind) {\n case "unsupported":\n case "primitive":\n case "bigint":\n case "bytes":\n case "date":\n case "error":\n case "undefined":\n case "function":\n case "rpc-target":\n case "writable":\n case "readable":\n case "headers":\n case "request":\n case "response":\n return;\n case "array": {\n let array = value;\n let len = array.length;\n for (let i = 0; i < len; i++) {\n this.ignoreUnhandledRejectionsImpl(array[i]);\n }\n return;\n }\n case "object": {\n let object = value;\n for (let i in object) {\n this.ignoreUnhandledRejectionsImpl(object[i]);\n }\n return;\n }\n case "stub":\n case "rpc-promise":\n unwrapStubOrParent(value).ignoreUnhandledRejections();\n return;\n case "rpc-thenable":\n value.then((_) => {\n }, (_) => {\n });\n return;\n default:\n return;\n }\n }\n};\nfunction followPath(value, parent, path, owner) {\n for (let i = 0; i < path.length; i++) {\n parent = value;\n let part = path[i];\n if (part in Object.prototype) {\n value = void 0;\n continue;\n }\n let kind = typeForRpc(value);\n switch (kind) {\n case "object":\n case "function":\n if (Object.hasOwn(value, part)) {\n value = value[part];\n } else {\n value = void 0;\n }\n break;\n case "array":\n if (Number.isInteger(part) && part >= 0) {\n value = value[part];\n } else {\n value = void 0;\n }\n break;\n case "rpc-target":\n case "rpc-thenable": {\n if (Object.hasOwn(value, part)) {\n throw new TypeError(\n `Attempted to access property \'${part}\', which is an instance property of the RpcTarget. To avoid leaking private internals, instance properties cannot be accessed over RPC. If you want to make this property available over RPC, define it as a method or getter on the class, instead of an instance property.`\n );\n } else {\n value = value[part];\n }\n owner = null;\n break;\n }\n case "stub":\n case "rpc-promise": {\n let { hook, pathIfPromise } = unwrapStubAndPath(value);\n return { hook, remainingPath: pathIfPromise ? pathIfPromise.concat(path.slice(i)) : path.slice(i) };\n }\n case "writable":\n value = void 0;\n break;\n case "readable":\n value = void 0;\n break;\n case "primitive":\n case "bigint":\n case "bytes":\n case "date":\n case "error":\n case "headers":\n case "request":\n case "response":\n value = void 0;\n break;\n case "undefined":\n value = value[part];\n break;\n case "unsupported": {\n if (i === 0) {\n throw new TypeError(`RPC stub points at a non-serializable type.`);\n } else {\n let prefix = path.slice(0, i).join(".");\n let remainder = path.slice(0, i).join(".");\n throw new TypeError(\n `\'${prefix}\' is not a serializable type, so property ${remainder} cannot be accessed.`\n );\n }\n }\n default:\n throw new TypeError("unreachable");\n }\n }\n if (value instanceof RpcPromise) {\n let { hook, pathIfPromise } = unwrapStubAndPath(value);\n return { hook, remainingPath: pathIfPromise || [] };\n }\n return {\n value,\n parent,\n owner\n };\n}\nvar ValueStubHook = class extends StubHook {\n call(path, args) {\n try {\n let { value, owner } = this.getValue();\n let followResult = followPath(value, void 0, path, owner);\n if (followResult.hook) {\n return followResult.hook.call(followResult.remainingPath, args);\n }\n if (typeof followResult.value != "function") {\n throw new TypeError(`\'${path.join(".")}\' is not a function.`);\n }\n let promise = args.deliverCall(followResult.value, followResult.parent);\n return new PromiseStubHook(promise.then((payload) => {\n return new PayloadStubHook(payload);\n }));\n } catch (err) {\n return new ErrorStubHook(err);\n }\n }\n map(path, captures, instructions) {\n try {\n let followResult;\n try {\n let { value, owner } = this.getValue();\n followResult = followPath(value, void 0, path, owner);\n ;\n } catch (err) {\n for (let cap of captures) {\n cap.dispose();\n }\n throw err;\n }\n if (followResult.hook) {\n return followResult.hook.map(followResult.remainingPath, captures, instructions);\n }\n return mapImpl.applyMap(\n followResult.value,\n followResult.parent,\n followResult.owner,\n captures,\n instructions\n );\n } catch (err) {\n return new ErrorStubHook(err);\n }\n }\n get(path) {\n try {\n let { value, owner } = this.getValue();\n if (path.length === 0 && owner === null) {\n throw new Error("Can\'t dup an RpcTarget stub as a promise.");\n }\n let followResult = followPath(value, void 0, path, owner);\n if (followResult.hook) {\n return followResult.hook.get(followResult.remainingPath);\n }\n return new PayloadStubHook(RpcPayload.deepCopyFrom(\n followResult.value,\n followResult.parent,\n followResult.owner\n ));\n } catch (err) {\n return new ErrorStubHook(err);\n }\n }\n};\nvar PayloadStubHook = class _PayloadStubHook extends ValueStubHook {\n constructor(payload) {\n super();\n this.payload = payload;\n }\n payload;\n // cleared when disposed\n getPayload() {\n if (this.payload) {\n return this.payload;\n } else {\n throw new Error("Attempted to use an RPC StubHook after it was disposed.");\n }\n }\n getValue() {\n let payload = this.getPayload();\n return { value: payload.value, owner: payload };\n }\n dup() {\n let thisPayload = this.getPayload();\n return new _PayloadStubHook(RpcPayload.deepCopyFrom(\n thisPayload.value,\n void 0,\n thisPayload\n ));\n }\n pull() {\n return this.getPayload();\n }\n ignoreUnhandledRejections() {\n if (this.payload) {\n this.payload.ignoreUnhandledRejections();\n }\n }\n dispose() {\n if (this.payload) {\n this.payload.dispose();\n this.payload = void 0;\n }\n }\n onBroken(callback) {\n if (this.payload) {\n if (this.payload.value instanceof RpcStub) {\n this.payload.value.onRpcBroken(callback);\n }\n }\n }\n};\nfunction disposeRpcTarget(target) {\n if (Symbol.dispose in target) {\n try {\n target[Symbol.dispose]();\n } catch (err) {\n Promise.reject(err);\n }\n }\n}\nvar TargetStubHook = class _TargetStubHook extends ValueStubHook {\n // Constructs a TargetStubHook that is not duplicated from an existing hook.\n //\n // If `value` is a function, `parent` is bound as its "this".\n static create(value, parent) {\n if (typeof value !== "function") {\n parent = void 0;\n }\n return new _TargetStubHook(value, parent);\n }\n constructor(target, parent, dupFrom) {\n super();\n this.target = target;\n this.parent = parent;\n if (dupFrom) {\n if (dupFrom.refcount) {\n this.refcount = dupFrom.refcount;\n ++this.refcount.count;\n }\n } else if (Symbol.dispose in target) {\n this.refcount = { count: 1 };\n }\n }\n target;\n // cleared when disposed\n parent;\n // `this` parameter when calling `target`\n refcount;\n // undefined if not needed (because target has no disposer)\n getTarget() {\n if (this.target) {\n return this.target;\n } else {\n throw new Error("Attempted to use an RPC StubHook after it was disposed.");\n }\n }\n getValue() {\n return { value: this.getTarget(), owner: null };\n }\n dup() {\n return new _TargetStubHook(this.getTarget(), this.parent, this);\n }\n pull() {\n let target = this.getTarget();\n if ("then" in target) {\n return Promise.resolve(target).then((resolution) => {\n return RpcPayload.fromAppReturn(resolution);\n });\n } else {\n return Promise.reject(new Error("Tried to resolve a non-promise stub."));\n }\n }\n ignoreUnhandledRejections() {\n }\n dispose() {\n if (this.target) {\n if (this.refcount) {\n if (--this.refcount.count == 0) {\n disposeRpcTarget(this.target);\n }\n }\n this.target = void 0;\n }\n }\n onBroken(callback) {\n }\n};\nvar PromiseStubHook = class _PromiseStubHook extends StubHook {\n promise;\n resolution;\n constructor(promise) {\n super();\n this.promise = promise.then((res) => {\n this.resolution = res;\n return res;\n });\n }\n call(path, args) {\n args.ensureDeepCopied();\n return new _PromiseStubHook(this.promise.then((hook) => hook.call(path, args)));\n }\n stream(path, args) {\n args.ensureDeepCopied();\n let promise = this.promise.then((hook) => {\n let result = hook.stream(path, args);\n return result.promise;\n });\n return { promise };\n }\n map(path, captures, instructions) {\n return new _PromiseStubHook(this.promise.then(\n (hook) => hook.map(path, captures, instructions),\n (err) => {\n for (let cap of captures) {\n cap.dispose();\n }\n throw err;\n }\n ));\n }\n get(path) {\n return new _PromiseStubHook(this.promise.then((hook) => hook.get(path)));\n }\n dup() {\n if (this.resolution) {\n return this.resolution.dup();\n } else {\n return new _PromiseStubHook(this.promise.then((hook) => hook.dup()));\n }\n }\n pull() {\n if (this.resolution) {\n return this.resolution.pull();\n } else {\n return this.promise.then((hook) => hook.pull());\n }\n }\n ignoreUnhandledRejections() {\n if (this.resolution) {\n this.resolution.ignoreUnhandledRejections();\n } else {\n this.promise.then((res) => {\n res.ignoreUnhandledRejections();\n }, (err) => {\n });\n }\n }\n dispose() {\n if (this.resolution) {\n this.resolution.dispose();\n } else {\n this.promise.then((hook) => {\n hook.dispose();\n }, (err) => {\n });\n }\n }\n onBroken(callback) {\n if (this.resolution) {\n this.resolution.onBroken(callback);\n } else {\n this.promise.then((hook) => {\n hook.onBroken(callback);\n }, callback);\n }\n }\n};\nvar NullExporter = class {\n exportStub(stub) {\n throw new Error("Cannot serialize RPC stubs without an RPC session.");\n }\n exportPromise(stub) {\n throw new Error("Cannot serialize RPC stubs without an RPC session.");\n }\n getImport(hook) {\n return void 0;\n }\n unexport(ids) {\n }\n createPipe(readable) {\n throw new Error("Cannot create pipes without an RPC session.");\n }\n onSendError(error) {\n }\n};\nvar NULL_EXPORTER = new NullExporter();\nvar ERROR_TYPES = {\n Error,\n EvalError,\n RangeError,\n ReferenceError,\n SyntaxError,\n TypeError,\n URIError,\n AggregateError\n // TODO: DOMError? Others?\n};\nvar Devaluator = class _Devaluator {\n constructor(exporter, source) {\n this.exporter = exporter;\n this.source = source;\n }\n // Devaluate the given value.\n // * value: The value to devaluate.\n // * parent: The value\'s parent object, which would be used as `this` if the value were called\n // as a function.\n // * exporter: Callbacks to the RPC session for exporting capabilities found in this message.\n // * source: The RpcPayload which contains the value, and therefore owns stubs within.\n //\n // Returns: The devaluated value, ready to be JSON-serialized.\n static devaluate(value, parent, exporter = NULL_EXPORTER, source) {\n let devaluator = new _Devaluator(exporter, source);\n try {\n return devaluator.devaluateImpl(value, parent, 0);\n } catch (err) {\n if (devaluator.exports) {\n try {\n exporter.unexport(devaluator.exports);\n } catch (err2) {\n }\n }\n throw err;\n }\n }\n exports;\n devaluateImpl(value, parent, depth) {\n if (depth >= 64) {\n throw new Error(\n "Serialization exceeded maximum allowed depth. (Does the message contain cycles?)"\n );\n }\n let kind = typeForRpc(value);\n switch (kind) {\n case "unsupported": {\n let msg;\n try {\n msg = `Cannot serialize value: ${value}`;\n } catch (err) {\n msg = "Cannot serialize value: (couldn\'t stringify value)";\n }\n throw new TypeError(msg);\n }\n case "primitive":\n if (typeof value === "number" && !isFinite(value)) {\n if (value === Infinity) {\n return ["inf"];\n } else if (value === -Infinity) {\n return ["-inf"];\n } else {\n return ["nan"];\n }\n } else {\n return value;\n }\n case "object": {\n let object = value;\n let result = {};\n for (let key in object) {\n result[key] = this.devaluateImpl(object[key], object, depth + 1);\n }\n return result;\n }\n case "array": {\n let array = value;\n let len = array.length;\n let result = new Array(len);\n for (let i = 0; i < len; i++) {\n result[i] = this.devaluateImpl(array[i], array, depth + 1);\n }\n return [result];\n }\n case "bigint":\n return ["bigint", value.toString()];\n case "date":\n return ["date", value.getTime()];\n case "bytes": {\n let bytes = value;\n if (bytes.toBase64) {\n return ["bytes", bytes.toBase64({ omitPadding: true })];\n } else {\n return [\n "bytes",\n btoa(String.fromCharCode.apply(null, bytes).replace(/=*$/, ""))\n ];\n }\n }\n case "headers":\n return ["headers", [...value]];\n case "request": {\n let req = value;\n let init = {};\n if (req.method !== "GET") init.method = req.method;\n let headers = [...req.headers];\n if (headers.length > 0) {\n init.headers = headers;\n }\n if (req.body) {\n init.body = this.devaluateImpl(req.body, req, depth + 1);\n init.duplex = req.duplex || "half";\n } else if (req.body === void 0 && !["GET", "HEAD", "OPTIONS", "TRACE", "DELETE"].includes(req.method)) {\n let bodyPromise = req.arrayBuffer();\n let readable = new ReadableStream({\n async start(controller) {\n try {\n controller.enqueue(new Uint8Array(await bodyPromise));\n controller.close();\n } catch (err) {\n controller.error(err);\n }\n }\n });\n let hook = streamImpl.createReadableStreamHook(readable);\n let importId = this.exporter.createPipe(readable, hook);\n init.body = ["readable", importId];\n init.duplex = req.duplex || "half";\n }\n if (req.cache && req.cache !== "default") init.cache = req.cache;\n if (req.redirect !== "follow") init.redirect = req.redirect;\n if (req.integrity) init.integrity = req.integrity;\n if (req.mode && req.mode !== "cors") init.mode = req.mode;\n if (req.credentials && req.credentials !== "same-origin") {\n init.credentials = req.credentials;\n }\n if (req.referrer && req.referrer !== "about:client") init.referrer = req.referrer;\n if (req.referrerPolicy) init.referrerPolicy = req.referrerPolicy;\n if (req.keepalive) init.keepalive = req.keepalive;\n let cfReq = req;\n if (cfReq.cf) init.cf = cfReq.cf;\n if (cfReq.encodeResponseBody && cfReq.encodeResponseBody !== "automatic") {\n init.encodeResponseBody = cfReq.encodeResponseBody;\n }\n return ["request", req.url, init];\n }\n case "response": {\n let resp = value;\n let body = this.devaluateImpl(resp.body, resp, depth + 1);\n let init = {};\n if (resp.status !== 200) init.status = resp.status;\n if (resp.statusText) init.statusText = resp.statusText;\n let headers = [...resp.headers];\n if (headers.length > 0) {\n init.headers = headers;\n }\n let cfResp = resp;\n if (cfResp.cf) init.cf = cfResp.cf;\n if (cfResp.encodeBody && cfResp.encodeBody !== "automatic") {\n init.encodeBody = cfResp.encodeBody;\n }\n if (cfResp.webSocket) {\n throw new TypeError("Can\'t serialize a Response containing a webSocket.");\n }\n return ["response", body, init];\n }\n case "error": {\n let e = value;\n let rewritten = this.exporter.onSendError(e);\n if (rewritten) {\n e = rewritten;\n }\n let result = ["error", e.name, e.message];\n if (rewritten && rewritten.stack) {\n result.push(rewritten.stack);\n }\n return result;\n }\n case "undefined":\n return ["undefined"];\n case "stub":\n case "rpc-promise": {\n if (!this.source) {\n throw new Error("Can\'t serialize RPC stubs in this context.");\n }\n let { hook, pathIfPromise } = unwrapStubAndPath(value);\n let importId = this.exporter.getImport(hook);\n if (importId !== void 0) {\n if (pathIfPromise) {\n if (pathIfPromise.length > 0) {\n return ["pipeline", importId, pathIfPromise];\n } else {\n return ["pipeline", importId];\n }\n } else {\n return ["import", importId];\n }\n }\n if (pathIfPromise) {\n hook = hook.get(pathIfPromise);\n } else {\n hook = hook.dup();\n }\n return this.devaluateHook(pathIfPromise ? "promise" : "export", hook);\n }\n case "function":\n case "rpc-target": {\n if (!this.source) {\n throw new Error("Can\'t serialize RPC stubs in this context.");\n }\n let hook = this.source.getHookForRpcTarget(value, parent);\n return this.devaluateHook("export", hook);\n }\n case "rpc-thenable": {\n if (!this.source) {\n throw new Error("Can\'t serialize RPC stubs in this context.");\n }\n let hook = this.source.getHookForRpcTarget(value, parent);\n return this.devaluateHook("promise", hook);\n }\n case "writable": {\n if (!this.source) {\n throw new Error("Can\'t serialize WritableStream in this context.");\n }\n let hook = this.source.getHookForWritableStream(value, parent);\n return this.devaluateHook("writable", hook);\n }\n case "readable": {\n if (!this.source) {\n throw new Error("Can\'t serialize ReadableStream in this context.");\n }\n let ws = value;\n let hook = this.source.getHookForReadableStream(ws, parent);\n let importId = this.exporter.createPipe(ws, hook);\n return ["readable", importId];\n }\n default:\n throw new Error("unreachable");\n }\n }\n devaluateHook(type, hook) {\n if (!this.exports) this.exports = [];\n let exportId = type === "promise" ? this.exporter.exportPromise(hook) : this.exporter.exportStub(hook);\n this.exports.push(exportId);\n return [type, exportId];\n }\n};\nvar NullImporter = class {\n importStub(idx) {\n throw new Error("Cannot deserialize RPC stubs without an RPC session.");\n }\n importPromise(idx) {\n throw new Error("Cannot deserialize RPC stubs without an RPC session.");\n }\n getExport(idx) {\n return void 0;\n }\n getPipeReadable(exportId) {\n throw new Error("Cannot retrieve pipe readable without an RPC session.");\n }\n};\nvar NULL_IMPORTER = new NullImporter();\nfunction fixBrokenRequestBody(request, body) {\n let promise = new Response(body).arrayBuffer().then((arrayBuffer) => {\n let bytes = new Uint8Array(arrayBuffer);\n let result = new Request(request, { body: bytes });\n return new PayloadStubHook(RpcPayload.fromAppReturn(result));\n });\n return new RpcPromise(new PromiseStubHook(promise), []);\n}\nvar Evaluator = class _Evaluator {\n constructor(importer) {\n this.importer = importer;\n }\n hooks = [];\n promises = [];\n evaluate(value) {\n let payload = RpcPayload.forEvaluate(this.hooks, this.promises);\n try {\n payload.value = this.evaluateImpl(value, payload, "value");\n return payload;\n } catch (err) {\n payload.dispose();\n throw err;\n }\n }\n // Evaluate the value without destroying it.\n evaluateCopy(value) {\n return this.evaluate(structuredClone(value));\n }\n evaluateImpl(value, parent, property) {\n if (value instanceof Array) {\n if (value.length == 1 && value[0] instanceof Array) {\n let result = value[0];\n for (let i = 0; i < result.length; i++) {\n result[i] = this.evaluateImpl(result[i], result, i);\n }\n return result;\n } else switch (value[0]) {\n case "bigint":\n if (typeof value[1] == "string") {\n return BigInt(value[1]);\n }\n break;\n case "date":\n if (typeof value[1] == "number") {\n return new Date(value[1]);\n }\n break;\n case "bytes": {\n let b64 = Uint8Array;\n if (typeof value[1] == "string") {\n if (b64.fromBase64) {\n return b64.fromBase64(value[1]);\n } else {\n let bs = atob(value[1]);\n let len = bs.length;\n let bytes = new Uint8Array(len);\n for (let i = 0; i < len; i++) {\n bytes[i] = bs.charCodeAt(i);\n }\n return bytes;\n }\n }\n break;\n }\n case "error":\n if (value.length >= 3 && typeof value[1] === "string" && typeof value[2] === "string") {\n let cls = ERROR_TYPES[value[1]] || Error;\n let result = new cls(value[2]);\n if (typeof value[3] === "string") {\n result.stack = value[3];\n }\n return result;\n }\n break;\n case "undefined":\n if (value.length === 1) {\n return void 0;\n }\n break;\n case "inf":\n return Infinity;\n case "-inf":\n return -Infinity;\n case "nan":\n return NaN;\n case "headers":\n if (value.length === 2 && value[1] instanceof Array) {\n return new Headers(value[1]);\n }\n break;\n case "request": {\n if (value.length !== 3 || typeof value[1] !== "string") break;\n let url = value[1];\n let init = value[2];\n if (typeof init !== "object" || init === null) break;\n if (init.body) {\n init.body = this.evaluateImpl(init.body, init, "body");\n if (init.body === null || typeof init.body === "string" || init.body instanceof Uint8Array || init.body instanceof ReadableStream) ;\n else {\n throw new TypeError("Request body must be of type ReadableStream.");\n }\n }\n if (init.signal) {\n init.signal = this.evaluateImpl(init.signal, init, "signal");\n if (!(init.signal instanceof AbortSignal)) {\n throw new TypeError("Request siganl must be of type AbortSignal.");\n }\n }\n if (init.headers && !(init.headers instanceof Array)) {\n throw new TypeError("Request headers must be serialized as an array of pairs.");\n }\n let result = new Request(url, init);\n if (init.body instanceof ReadableStream && result.body === void 0) {\n let promise = fixBrokenRequestBody(result, init.body);\n this.promises.push({ promise, parent, property });\n return promise;\n } else {\n return result;\n }\n }\n case "response": {\n if (value.length !== 3) break;\n let body = this.evaluateImpl(value[1], parent, property);\n if (body === null || typeof body === "string" || body instanceof Uint8Array || body instanceof ReadableStream) ;\n else {\n throw new TypeError("Response body must be of type ReadableStream.");\n }\n let init = value[2];\n if (typeof init !== "object" || init === null) break;\n if (init.webSocket) {\n throw new TypeError("Can\'t deserialize a Response containing a webSocket.");\n }\n if (init.headers && !(init.headers instanceof Array)) {\n throw new TypeError("Request headers must be serialized as an array of pairs.");\n }\n return new Response(body, init);\n }\n case "import":\n case "pipeline": {\n if (value.length < 2 || value.length > 4) {\n break;\n }\n if (typeof value[1] != "number") {\n break;\n }\n let hook = this.importer.getExport(value[1]);\n if (!hook) {\n throw new Error(`no such entry on exports table: ${value[1]}`);\n }\n let isPromise = value[0] == "pipeline";\n let addStub = (hook2) => {\n if (isPromise) {\n let promise = new RpcPromise(hook2, []);\n this.promises.push({ promise, parent, property });\n return promise;\n } else {\n this.hooks.push(hook2);\n return new RpcPromise(hook2, []);\n }\n };\n if (value.length == 2) {\n if (isPromise) {\n return addStub(hook.get([]));\n } else {\n return addStub(hook.dup());\n }\n }\n let path = value[2];\n if (!(path instanceof Array)) {\n break;\n }\n if (!path.every(\n (part) => {\n return typeof part == "string" || typeof part == "number";\n }\n )) {\n break;\n }\n if (value.length == 3) {\n return addStub(hook.get(path));\n }\n let args = value[3];\n if (!(args instanceof Array)) {\n break;\n }\n let subEval = new _Evaluator(this.importer);\n args = subEval.evaluate([args]);\n return addStub(hook.call(path, args));\n }\n case "remap": {\n if (value.length !== 5 || typeof value[1] !== "number" || !(value[2] instanceof Array) || !(value[3] instanceof Array) || !(value[4] instanceof Array)) {\n break;\n }\n let hook = this.importer.getExport(value[1]);\n if (!hook) {\n throw new Error(`no such entry on exports table: ${value[1]}`);\n }\n let path = value[2];\n if (!path.every(\n (part) => {\n return typeof part == "string" || typeof part == "number";\n }\n )) {\n break;\n }\n let captures = value[3].map((cap) => {\n if (!(cap instanceof Array) || cap.length !== 2 || cap[0] !== "import" && cap[0] !== "export" || typeof cap[1] !== "number") {\n throw new TypeError(`unknown map capture: ${JSON.stringify(cap)}`);\n }\n if (cap[0] === "export") {\n return this.importer.importStub(cap[1]);\n } else {\n let exp = this.importer.getExport(cap[1]);\n if (!exp) {\n throw new Error(`no such entry on exports table: ${cap[1]}`);\n }\n return exp.dup();\n }\n });\n let instructions = value[4];\n let resultHook = hook.map(path, captures, instructions);\n let promise = new RpcPromise(resultHook, []);\n this.promises.push({ promise, parent, property });\n return promise;\n }\n case "export":\n case "promise":\n if (typeof value[1] == "number") {\n if (value[0] == "promise") {\n let hook = this.importer.importPromise(value[1]);\n let promise = new RpcPromise(hook, []);\n this.promises.push({ parent, property, promise });\n return promise;\n } else {\n let hook = this.importer.importStub(value[1]);\n this.hooks.push(hook);\n return new RpcStub(hook);\n }\n }\n break;\n case "writable":\n if (typeof value[1] == "number") {\n let hook = this.importer.importStub(value[1]);\n let stream = streamImpl.createWritableStreamFromHook(hook);\n this.hooks.push(hook);\n return stream;\n }\n break;\n case "readable":\n if (typeof value[1] == "number") {\n let stream = this.importer.getPipeReadable(value[1]);\n let hook = streamImpl.createReadableStreamHook(stream);\n this.hooks.push(hook);\n return stream;\n }\n break;\n }\n throw new TypeError(`unknown special value: ${JSON.stringify(value)}`);\n } else if (value instanceof Object) {\n let result = value;\n for (let key in result) {\n if (key in Object.prototype || key === "toJSON") {\n this.evaluateImpl(result[key], result, key);\n delete result[key];\n } else {\n result[key] = this.evaluateImpl(result[key], result, key);\n }\n }\n return result;\n } else {\n return value;\n }\n }\n};\nvar ImportTableEntry = class {\n constructor(session, importId, pulling) {\n this.session = session;\n this.importId = importId;\n if (pulling) {\n this.activePull = Promise.withResolvers();\n }\n }\n localRefcount = 0;\n remoteRefcount = 1;\n activePull;\n resolution;\n // List of integer indexes into session.onBrokenCallbacks which are callbacks registered on\n // this import. Initialized on first use (so `undefined` is the same as an empty list).\n onBrokenRegistrations;\n resolve(resolution) {\n if (this.localRefcount == 0) {\n resolution.dispose();\n return;\n }\n this.resolution = resolution;\n this.sendRelease();\n if (this.onBrokenRegistrations) {\n for (let i of this.onBrokenRegistrations) {\n let callback = this.session.onBrokenCallbacks[i];\n let endIndex = this.session.onBrokenCallbacks.length;\n resolution.onBroken(callback);\n if (this.session.onBrokenCallbacks[endIndex] === callback) {\n delete this.session.onBrokenCallbacks[endIndex];\n } else {\n delete this.session.onBrokenCallbacks[i];\n }\n }\n this.onBrokenRegistrations = void 0;\n }\n if (this.activePull) {\n this.activePull.resolve();\n this.activePull = void 0;\n }\n }\n async awaitResolution() {\n if (!this.activePull) {\n this.session.sendPull(this.importId);\n this.activePull = Promise.withResolvers();\n }\n await this.activePull.promise;\n return this.resolution.pull();\n }\n dispose() {\n if (this.resolution) {\n this.resolution.dispose();\n } else {\n this.abort(new Error("RPC was canceled because the RpcPromise was disposed."));\n this.sendRelease();\n }\n }\n abort(error) {\n if (!this.resolution) {\n this.resolution = new ErrorStubHook(error);\n if (this.activePull) {\n this.activePull.reject(error);\n this.activePull = void 0;\n }\n this.onBrokenRegistrations = void 0;\n }\n }\n onBroken(callback) {\n if (this.resolution) {\n this.resolution.onBroken(callback);\n } else {\n let index = this.session.onBrokenCallbacks.length;\n this.session.onBrokenCallbacks.push(callback);\n if (!this.onBrokenRegistrations) this.onBrokenRegistrations = [];\n this.onBrokenRegistrations.push(index);\n }\n }\n sendRelease() {\n if (this.remoteRefcount > 0) {\n this.session.sendRelease(this.importId, this.remoteRefcount);\n this.remoteRefcount = 0;\n }\n }\n};\nvar RpcImportHook = class _RpcImportHook extends StubHook {\n // undefined when we\'re disposed\n // `pulling` is true if we already expect that this import is going to be resolved later, and\n // null if this import is not allowed to be pulled (i.e. it\'s a stub not a promise).\n constructor(isPromise, entry) {\n super();\n this.isPromise = isPromise;\n ++entry.localRefcount;\n this.entry = entry;\n }\n entry;\n collectPath(path) {\n return this;\n }\n getEntry() {\n if (this.entry) {\n return this.entry;\n } else {\n throw new Error("This RpcImportHook was already disposed.");\n }\n }\n // -------------------------------------------------------------------------------------\n // implements StubHook\n call(path, args) {\n let entry = this.getEntry();\n if (entry.resolution) {\n return entry.resolution.call(path, args);\n } else {\n return entry.session.sendCall(entry.importId, path, args);\n }\n }\n stream(path, args) {\n let entry = this.getEntry();\n if (entry.resolution) {\n return entry.resolution.stream(path, args);\n } else {\n return entry.session.sendStream(entry.importId, path, args);\n }\n }\n map(path, captures, instructions) {\n let entry;\n try {\n entry = this.getEntry();\n } catch (err) {\n for (let cap of captures) {\n cap.dispose();\n }\n throw err;\n }\n if (entry.resolution) {\n return entry.resolution.map(path, captures, instructions);\n } else {\n return entry.session.sendMap(entry.importId, path, captures, instructions);\n }\n }\n get(path) {\n let entry = this.getEntry();\n if (entry.resolution) {\n return entry.resolution.get(path);\n } else {\n return entry.session.sendCall(entry.importId, path);\n }\n }\n dup() {\n return new _RpcImportHook(false, this.getEntry());\n }\n pull() {\n let entry = this.getEntry();\n if (!this.isPromise) {\n throw new Error("Can\'t pull this hook because it\'s not a promise hook.");\n }\n if (entry.resolution) {\n return entry.resolution.pull();\n }\n return entry.awaitResolution();\n }\n ignoreUnhandledRejections() {\n }\n dispose() {\n let entry = this.entry;\n this.entry = void 0;\n if (entry) {\n if (--entry.localRefcount === 0) {\n entry.dispose();\n }\n }\n }\n onBroken(callback) {\n if (this.entry) {\n this.entry.onBroken(callback);\n }\n }\n};\nvar RpcMainHook = class extends RpcImportHook {\n session;\n constructor(entry) {\n super(false, entry);\n this.session = entry.session;\n }\n dispose() {\n if (this.session) {\n let session = this.session;\n this.session = void 0;\n session.shutdown();\n }\n }\n};\nvar RpcSessionImpl = class {\n constructor(transport, mainHook, options) {\n this.transport = transport;\n this.options = options;\n this.exports.push({ hook: mainHook, refcount: 1 });\n this.imports.push(new ImportTableEntry(this, 0, false));\n let rejectFunc;\n let abortPromise = new Promise((resolve, reject) => {\n rejectFunc = reject;\n });\n this.cancelReadLoop = rejectFunc;\n this.readLoop(abortPromise).catch((err) => this.abort(err));\n }\n exports = [];\n reverseExports = /* @__PURE__ */ new Map();\n imports = [];\n abortReason;\n cancelReadLoop;\n // We assign positive numbers to imports we initiate, and negative numbers to exports we\n // initiate. So the next import ID is just `imports.length`, but the next export ID needs\n // to be tracked explicitly.\n nextExportId = -1;\n // If set, call this when all incoming calls are complete.\n onBatchDone;\n // How many promises is our peer expecting us to resolve?\n pullCount = 0;\n // Sparse array of onBrokenCallback registrations. Items are strictly appended to the end but\n // may be deleted from the middle (hence leaving the array sparse).\n onBrokenCallbacks = [];\n // Should only be called once immediately after construction.\n getMainImport() {\n return new RpcMainHook(this.imports[0]);\n }\n shutdown() {\n this.abort(new Error("RPC session was shut down by disposing the main stub"), false);\n }\n exportStub(hook) {\n if (this.abortReason) throw this.abortReason;\n let existingExportId = this.reverseExports.get(hook);\n if (existingExportId !== void 0) {\n ++this.exports[existingExportId].refcount;\n return existingExportId;\n } else {\n let exportId = this.nextExportId--;\n this.exports[exportId] = { hook, refcount: 1 };\n this.reverseExports.set(hook, exportId);\n return exportId;\n }\n }\n exportPromise(hook) {\n if (this.abortReason) throw this.abortReason;\n let exportId = this.nextExportId--;\n this.exports[exportId] = { hook, refcount: 1 };\n this.reverseExports.set(hook, exportId);\n this.ensureResolvingExport(exportId);\n return exportId;\n }\n unexport(ids) {\n for (let id of ids) {\n this.releaseExport(id, 1);\n }\n }\n releaseExport(exportId, refcount) {\n let entry = this.exports[exportId];\n if (!entry) {\n throw new Error(`no such export ID: ${exportId}`);\n }\n if (entry.refcount < refcount) {\n throw new Error(`refcount would go negative: ${entry.refcount} < ${refcount}`);\n }\n entry.refcount -= refcount;\n if (entry.refcount === 0) {\n delete this.exports[exportId];\n this.reverseExports.delete(entry.hook);\n entry.hook.dispose();\n }\n }\n onSendError(error) {\n if (this.options.onSendError) {\n return this.options.onSendError(error);\n }\n }\n ensureResolvingExport(exportId) {\n let exp = this.exports[exportId];\n if (!exp) {\n throw new Error(`no such export ID: ${exportId}`);\n }\n if (!exp.pull) {\n let resolve = async () => {\n let hook = exp.hook;\n for (; ; ) {\n let payload = await hook.pull();\n if (payload.value instanceof RpcStub) {\n let { hook: inner, pathIfPromise } = unwrapStubAndPath(payload.value);\n if (pathIfPromise && pathIfPromise.length == 0) {\n if (this.getImport(hook) === void 0) {\n hook = inner;\n continue;\n }\n }\n }\n return payload;\n }\n };\n let autoRelease = exp.autoRelease;\n ++this.pullCount;\n exp.pull = resolve().then(\n (payload) => {\n let value = Devaluator.devaluate(payload.value, void 0, this, payload);\n this.send(["resolve", exportId, value]);\n if (autoRelease) this.releaseExport(exportId, 1);\n },\n (error) => {\n this.send(["reject", exportId, Devaluator.devaluate(error, void 0, this)]);\n if (autoRelease) this.releaseExport(exportId, 1);\n }\n ).catch(\n (error) => {\n try {\n this.send(["reject", exportId, Devaluator.devaluate(error, void 0, this)]);\n if (autoRelease) this.releaseExport(exportId, 1);\n } catch (error2) {\n this.abort(error2);\n }\n }\n ).finally(() => {\n if (--this.pullCount === 0) {\n if (this.onBatchDone) {\n this.onBatchDone.resolve();\n }\n }\n });\n }\n }\n getImport(hook) {\n if (hook instanceof RpcImportHook && hook.entry && hook.entry.session === this) {\n return hook.entry.importId;\n } else {\n return void 0;\n }\n }\n importStub(idx) {\n if (this.abortReason) throw this.abortReason;\n let entry = this.imports[idx];\n if (!entry) {\n entry = new ImportTableEntry(this, idx, false);\n this.imports[idx] = entry;\n }\n return new RpcImportHook(\n /*isPromise=*/\n false,\n entry\n );\n }\n importPromise(idx) {\n if (this.abortReason) throw this.abortReason;\n if (this.imports[idx]) {\n return new ErrorStubHook(new Error(\n "Bug in RPC system: The peer sent a promise reusing an existing export ID."\n ));\n }\n let entry = new ImportTableEntry(this, idx, true);\n this.imports[idx] = entry;\n return new RpcImportHook(\n /*isPromise=*/\n true,\n entry\n );\n }\n getExport(idx) {\n return this.exports[idx]?.hook;\n }\n getPipeReadable(exportId) {\n let entry = this.exports[exportId];\n if (!entry || !entry.pipeReadable) {\n throw new Error(`Export ${exportId} is not a pipe or its readable end was already consumed.`);\n }\n let readable = entry.pipeReadable;\n entry.pipeReadable = void 0;\n return readable;\n }\n createPipe(readable, readableHook) {\n if (this.abortReason) throw this.abortReason;\n this.send(["pipe"]);\n let importId = this.imports.length;\n let entry = new ImportTableEntry(this, importId, false);\n this.imports.push(entry);\n let hook = new RpcImportHook(\n /*isPromise=*/\n false,\n entry\n );\n let writable = streamImpl.createWritableStreamFromHook(hook);\n readable.pipeTo(writable).catch(() => {\n }).finally(() => readableHook.dispose());\n return importId;\n }\n // Serializes and sends a message. Returns the byte length of the serialized message.\n send(msg) {\n if (this.abortReason !== void 0) {\n return 0;\n }\n let msgText;\n try {\n msgText = JSON.stringify(msg);\n } catch (err) {\n try {\n this.abort(err);\n } catch (err2) {\n }\n throw err;\n }\n this.transport.send(msgText).catch((err) => this.abort(err, false));\n return msgText.length;\n }\n sendCall(id, path, args) {\n if (this.abortReason) throw this.abortReason;\n let value = ["pipeline", id, path];\n if (args) {\n let devalue = Devaluator.devaluate(args.value, void 0, this, args);\n value.push(devalue[0]);\n }\n this.send(["push", value]);\n let entry = new ImportTableEntry(this, this.imports.length, false);\n this.imports.push(entry);\n return new RpcImportHook(\n /*isPromise=*/\n true,\n entry\n );\n }\n sendStream(id, path, args) {\n if (this.abortReason) throw this.abortReason;\n let value = ["pipeline", id, path];\n let devalue = Devaluator.devaluate(args.value, void 0, this, args);\n value.push(devalue[0]);\n let size = this.send(["stream", value]);\n let importId = this.imports.length;\n let entry = new ImportTableEntry(\n this,\n importId,\n /*pulling=*/\n true\n );\n entry.remoteRefcount = 0;\n entry.localRefcount = 1;\n this.imports.push(entry);\n let promise = entry.awaitResolution().then(\n (p) => {\n p.dispose();\n delete this.imports[importId];\n },\n (err) => {\n delete this.imports[importId];\n throw err;\n }\n );\n return { promise, size };\n }\n sendMap(id, path, captures, instructions) {\n if (this.abortReason) {\n for (let cap of captures) {\n cap.dispose();\n }\n throw this.abortReason;\n }\n let devaluedCaptures = captures.map((hook) => {\n let importId = this.getImport(hook);\n if (importId !== void 0) {\n return ["import", importId];\n } else {\n return ["export", this.exportStub(hook)];\n }\n });\n let value = ["remap", id, path, devaluedCaptures, instructions];\n this.send(["push", value]);\n let entry = new ImportTableEntry(this, this.imports.length, false);\n this.imports.push(entry);\n return new RpcImportHook(\n /*isPromise=*/\n true,\n entry\n );\n }\n sendPull(id) {\n if (this.abortReason) throw this.abortReason;\n this.send(["pull", id]);\n }\n sendRelease(id, remoteRefcount) {\n if (this.abortReason) return;\n this.send(["release", id, remoteRefcount]);\n delete this.imports[id];\n }\n abort(error, trySendAbortMessage = true) {\n if (this.abortReason !== void 0) return;\n this.cancelReadLoop(error);\n if (trySendAbortMessage) {\n try {\n this.transport.send(JSON.stringify(["abort", Devaluator.devaluate(error, void 0, this)])).catch((err) => {\n });\n } catch (err) {\n }\n }\n if (error === void 0) {\n error = "undefined";\n }\n this.abortReason = error;\n if (this.onBatchDone) {\n this.onBatchDone.reject(error);\n }\n if (this.transport.abort) {\n try {\n this.transport.abort(error);\n } catch (err) {\n Promise.resolve(err);\n }\n }\n for (let i in this.onBrokenCallbacks) {\n try {\n this.onBrokenCallbacks[i](error);\n } catch (err) {\n Promise.resolve(err);\n }\n }\n for (let i in this.imports) {\n this.imports[i].abort(error);\n }\n for (let i in this.exports) {\n this.exports[i].hook.dispose();\n }\n }\n async readLoop(abortPromise) {\n while (!this.abortReason) {\n let msg = JSON.parse(await Promise.race([this.transport.receive(), abortPromise]));\n if (this.abortReason) break;\n if (msg instanceof Array) {\n switch (msg[0]) {\n case "push":\n if (msg.length > 1) {\n let payload = new Evaluator(this).evaluate(msg[1]);\n let hook = new PayloadStubHook(payload);\n hook.ignoreUnhandledRejections();\n this.exports.push({ hook, refcount: 1 });\n continue;\n }\n break;\n case "stream": {\n if (msg.length > 1) {\n let payload = new Evaluator(this).evaluate(msg[1]);\n let hook = new PayloadStubHook(payload);\n hook.ignoreUnhandledRejections();\n let exportId = this.exports.length;\n this.exports.push({ hook, refcount: 1, autoRelease: true });\n this.ensureResolvingExport(exportId);\n continue;\n }\n break;\n }\n case "pipe": {\n let { readable, writable } = new TransformStream();\n let hook = streamImpl.createWritableStreamHook(writable);\n this.exports.push({ hook, refcount: 1, pipeReadable: readable });\n continue;\n }\n case "pull": {\n let exportId = msg[1];\n if (typeof exportId == "number") {\n this.ensureResolvingExport(exportId);\n continue;\n }\n break;\n }\n case "resolve":\n // ["resolve", ExportId, Expression]\n case "reject": {\n let importId = msg[1];\n if (typeof importId == "number" && msg.length > 2) {\n let imp = this.imports[importId];\n if (imp) {\n if (msg[0] == "resolve") {\n imp.resolve(new PayloadStubHook(new Evaluator(this).evaluate(msg[2])));\n } else {\n let payload = new Evaluator(this).evaluate(msg[2]);\n payload.dispose();\n imp.resolve(new ErrorStubHook(payload.value));\n }\n } else {\n if (msg[0] == "resolve") {\n new Evaluator(this).evaluate(msg[2]).dispose();\n }\n }\n continue;\n }\n break;\n }\n case "release": {\n let exportId = msg[1];\n let refcount = msg[2];\n if (typeof exportId == "number" && typeof refcount == "number") {\n this.releaseExport(exportId, refcount);\n continue;\n }\n break;\n }\n case "abort": {\n let payload = new Evaluator(this).evaluate(msg[1]);\n payload.dispose();\n this.abort(payload, false);\n break;\n }\n }\n }\n throw new Error(`bad RPC message: ${JSON.stringify(msg)}`);\n }\n }\n async drain() {\n if (this.abortReason) {\n throw this.abortReason;\n }\n if (this.pullCount > 0) {\n let { promise, resolve, reject } = Promise.withResolvers();\n this.onBatchDone = { resolve, reject };\n await promise;\n }\n }\n getStats() {\n let result = { imports: 0, exports: 0 };\n for (let i in this.imports) {\n ++result.imports;\n }\n for (let i in this.exports) {\n ++result.exports;\n }\n return result;\n }\n};\nvar RpcSession = class {\n #session;\n #mainStub;\n constructor(transport, localMain, options = {}) {\n let mainHook;\n if (localMain) {\n mainHook = new PayloadStubHook(RpcPayload.fromAppReturn(localMain));\n } else {\n mainHook = new ErrorStubHook(new Error("This connection has no main object."));\n }\n this.#session = new RpcSessionImpl(transport, mainHook, options);\n this.#mainStub = new RpcStub(this.#session.getMainImport());\n }\n getRemoteMain() {\n return this.#mainStub;\n }\n getStats() {\n return this.#session.getStats();\n }\n drain() {\n return this.#session.drain();\n }\n};\nfunction newWebSocketRpcSession(webSocket, localMain, options) {\n if (typeof webSocket === "string") {\n webSocket = new WebSocket(webSocket);\n }\n let transport = new WebSocketTransport(webSocket);\n let rpc = new RpcSession(transport, localMain, options);\n return rpc.getRemoteMain();\n}\nfunction newWorkersWebSocketRpcResponse(request, localMain, options) {\n if (request.headers.get("Upgrade")?.toLowerCase() !== "websocket") {\n return new Response("This endpoint only accepts WebSocket requests.", { status: 400 });\n }\n let pair = new WebSocketPair();\n let server = pair[0];\n server.accept();\n newWebSocketRpcSession(server, localMain, options);\n return new Response(null, {\n status: 101,\n webSocket: pair[1]\n });\n}\nvar WebSocketTransport = class {\n constructor(webSocket) {\n this.#webSocket = webSocket;\n if (webSocket.readyState === WebSocket.CONNECTING) {\n this.#sendQueue = [];\n webSocket.addEventListener("open", (event) => {\n try {\n for (let message of this.#sendQueue) {\n webSocket.send(message);\n }\n } catch (err) {\n this.#receivedError(err);\n }\n this.#sendQueue = void 0;\n });\n }\n webSocket.addEventListener("message", (event) => {\n if (this.#error) ;\n else if (typeof event.data === "string") {\n if (this.#receiveResolver) {\n this.#receiveResolver(event.data);\n this.#receiveResolver = void 0;\n this.#receiveRejecter = void 0;\n } else {\n this.#receiveQueue.push(event.data);\n }\n } else {\n this.#receivedError(new TypeError("Received non-string message from WebSocket."));\n }\n });\n webSocket.addEventListener("close", (event) => {\n this.#receivedError(new Error(`Peer closed WebSocket: ${event.code} ${event.reason}`));\n });\n webSocket.addEventListener("error", (event) => {\n this.#receivedError(new Error(`WebSocket connection failed.`));\n });\n }\n #webSocket;\n #sendQueue;\n // only if not opened yet\n #receiveResolver;\n #receiveRejecter;\n #receiveQueue = [];\n #error;\n async send(message) {\n if (this.#sendQueue === void 0) {\n this.#webSocket.send(message);\n } else {\n this.#sendQueue.push(message);\n }\n }\n async receive() {\n if (this.#receiveQueue.length > 0) {\n return this.#receiveQueue.shift();\n } else if (this.#error) {\n throw this.#error;\n } else {\n return new Promise((resolve, reject) => {\n this.#receiveResolver = resolve;\n this.#receiveRejecter = reject;\n });\n }\n }\n abort(reason) {\n let message;\n if (reason instanceof Error) {\n message = reason.message;\n } else {\n message = `${reason}`;\n }\n this.#webSocket.close(3e3, message);\n if (!this.#error) {\n this.#error = reason;\n }\n }\n #receivedError(reason) {\n if (!this.#error) {\n this.#error = reason;\n if (this.#receiveRejecter) {\n this.#receiveRejecter(reason);\n this.#receiveResolver = void 0;\n this.#receiveRejecter = void 0;\n }\n }\n }\n};\nvar BatchServerTransport = class {\n constructor(batch) {\n this.#batchToReceive = batch;\n }\n #batchToSend = [];\n #batchToReceive;\n #allReceived = Promise.withResolvers();\n async send(message) {\n this.#batchToSend.push(message);\n }\n async receive() {\n let msg = this.#batchToReceive.shift();\n if (msg !== void 0) {\n return msg;\n } else {\n this.#allReceived.resolve();\n return new Promise((r) => {\n });\n }\n }\n abort(reason) {\n this.#allReceived.reject(reason);\n }\n whenAllReceived() {\n return this.#allReceived.promise;\n }\n getResponseBody() {\n return this.#batchToSend.join("\\n");\n }\n};\nasync function newHttpBatchRpcResponse(request, localMain, options) {\n if (request.method !== "POST") {\n return new Response("This endpoint only accepts POST requests.", { status: 405 });\n }\n let body = await request.text();\n let batch = body === "" ? [] : body.split("\\n");\n let transport = new BatchServerTransport(batch);\n let rpc = new RpcSession(transport, localMain, options);\n await transport.whenAllReceived();\n await rpc.drain();\n return new Response(transport.getResponseBody());\n}\nvar currentMapBuilder;\nvar MapBuilder = class {\n context;\n captureMap = /* @__PURE__ */ new Map();\n instructions = [];\n constructor(subject, path) {\n if (currentMapBuilder) {\n this.context = {\n parent: currentMapBuilder,\n captures: [],\n subject: currentMapBuilder.capture(subject),\n path\n };\n } else {\n this.context = {\n parent: void 0,\n captures: [],\n subject,\n path\n };\n }\n currentMapBuilder = this;\n }\n unregister() {\n currentMapBuilder = this.context.parent;\n }\n makeInput() {\n return new MapVariableHook(this, 0);\n }\n makeOutput(result) {\n let devalued;\n try {\n devalued = Devaluator.devaluate(result.value, void 0, this, result);\n } finally {\n result.dispose();\n }\n this.instructions.push(devalued);\n if (this.context.parent) {\n this.context.parent.instructions.push(\n [\n "remap",\n this.context.subject,\n this.context.path,\n this.context.captures.map((cap) => ["import", cap]),\n this.instructions\n ]\n );\n return new MapVariableHook(this.context.parent, this.context.parent.instructions.length);\n } else {\n return this.context.subject.map(this.context.path, this.context.captures, this.instructions);\n }\n }\n pushCall(hook, path, params) {\n let devalued = Devaluator.devaluate(params.value, void 0, this, params);\n devalued = devalued[0];\n let subject = this.capture(hook.dup());\n this.instructions.push(["pipeline", subject, path, devalued]);\n return new MapVariableHook(this, this.instructions.length);\n }\n pushGet(hook, path) {\n let subject = this.capture(hook.dup());\n this.instructions.push(["pipeline", subject, path]);\n return new MapVariableHook(this, this.instructions.length);\n }\n capture(hook) {\n if (hook instanceof MapVariableHook && hook.mapper === this) {\n return hook.idx;\n }\n let result = this.captureMap.get(hook);\n if (result === void 0) {\n if (this.context.parent) {\n let parentIdx = this.context.parent.capture(hook);\n this.context.captures.push(parentIdx);\n } else {\n this.context.captures.push(hook);\n }\n result = -this.context.captures.length;\n this.captureMap.set(hook, result);\n }\n return result;\n }\n // ---------------------------------------------------------------------------\n // implements Exporter\n exportStub(hook) {\n throw new Error(\n "Can\'t construct an RpcTarget or RPC callback inside a mapper function. Try creating a new RpcStub outside the callback first, then using it inside the callback."\n );\n }\n exportPromise(hook) {\n return this.exportStub(hook);\n }\n getImport(hook) {\n return this.capture(hook);\n }\n unexport(ids) {\n }\n createPipe(readable) {\n throw new Error("Cannot send ReadableStream inside a mapper function.");\n }\n onSendError(error) {\n }\n};\nmapImpl.sendMap = (hook, path, func) => {\n let builder = new MapBuilder(hook, path);\n let result;\n try {\n result = RpcPayload.fromAppReturn(withCallInterceptor(builder.pushCall.bind(builder), () => {\n return func(new RpcPromise(builder.makeInput(), []));\n }));\n } finally {\n builder.unregister();\n }\n if (result instanceof Promise) {\n result.catch((err) => {\n });\n throw new Error("RPC map() callbacks cannot be async.");\n }\n return new RpcPromise(builder.makeOutput(result), []);\n};\nfunction throwMapperBuilderUseError() {\n throw new Error(\n "Attempted to use an abstract placeholder from a mapper function. Please make sure your map function has no side effects."\n );\n}\nvar MapVariableHook = class extends StubHook {\n constructor(mapper, idx) {\n super();\n this.mapper = mapper;\n this.idx = idx;\n }\n // We don\'t have anything we actually need to dispose, so dup() can just return the same hook.\n dup() {\n return this;\n }\n dispose() {\n }\n get(path) {\n if (path.length == 0) {\n return this;\n } else if (currentMapBuilder) {\n return currentMapBuilder.pushGet(this, path);\n } else {\n throwMapperBuilderUseError();\n }\n }\n // Other methods should never be called.\n call(path, args) {\n throwMapperBuilderUseError();\n }\n map(path, captures, instructions) {\n throwMapperBuilderUseError();\n }\n pull() {\n throwMapperBuilderUseError();\n }\n ignoreUnhandledRejections() {\n }\n onBroken(callback) {\n throwMapperBuilderUseError();\n }\n};\nvar MapApplicator = class {\n constructor(captures, input) {\n this.captures = captures;\n this.variables = [input];\n }\n variables;\n dispose() {\n for (let variable of this.variables) {\n variable.dispose();\n }\n }\n apply(instructions) {\n try {\n if (instructions.length < 1) {\n throw new Error("Invalid empty mapper function.");\n }\n for (let instruction of instructions.slice(0, -1)) {\n let payload = new Evaluator(this).evaluateCopy(instruction);\n if (payload.value instanceof RpcStub) {\n let hook = unwrapStubNoProperties(payload.value);\n if (hook) {\n this.variables.push(hook);\n continue;\n }\n }\n this.variables.push(new PayloadStubHook(payload));\n }\n return new Evaluator(this).evaluateCopy(instructions[instructions.length - 1]);\n } finally {\n for (let variable of this.variables) {\n variable.dispose();\n }\n }\n }\n importStub(idx) {\n throw new Error("A mapper function cannot refer to exports.");\n }\n importPromise(idx) {\n return this.importStub(idx);\n }\n getExport(idx) {\n if (idx < 0) {\n return this.captures[-idx - 1];\n } else {\n return this.variables[idx];\n }\n }\n getPipeReadable(exportId) {\n throw new Error("A mapper function cannot use pipe readables.");\n }\n};\nfunction applyMapToElement(input, parent, owner, captures, instructions) {\n let inputHook = new PayloadStubHook(RpcPayload.deepCopyFrom(input, parent, owner));\n let mapper = new MapApplicator(captures, inputHook);\n try {\n return mapper.apply(instructions);\n } finally {\n mapper.dispose();\n }\n}\nmapImpl.applyMap = (input, parent, owner, captures, instructions) => {\n try {\n let result;\n if (input instanceof RpcPromise) {\n throw new Error("applyMap() can\'t be called on RpcPromise");\n } else if (input instanceof Array) {\n let payloads = [];\n try {\n for (let elem of input) {\n payloads.push(applyMapToElement(elem, input, owner, captures, instructions));\n }\n } catch (err) {\n for (let payload of payloads) {\n payload.dispose();\n }\n throw err;\n }\n result = RpcPayload.fromArray(payloads);\n } else if (input === null || input === void 0) {\n result = RpcPayload.fromAppReturn(input);\n } else {\n result = applyMapToElement(input, parent, owner, captures, instructions);\n }\n return new PayloadStubHook(result);\n } finally {\n for (let cap of captures) {\n cap.dispose();\n }\n }\n};\nvar WritableStreamStubHook = class _WritableStreamStubHook extends StubHook {\n state;\n // undefined when disposed\n // Creates a new WritableStreamStubHook that is not duplicated from an existing hook.\n static create(stream) {\n let writer = stream.getWriter();\n return new _WritableStreamStubHook({ refcount: 1, writer, closed: false });\n }\n constructor(state, dupFrom) {\n super();\n this.state = state;\n if (dupFrom) {\n ++state.refcount;\n }\n }\n getState() {\n if (this.state) {\n return this.state;\n } else {\n throw new Error("Attempted to use a WritableStreamStubHook after it was disposed.");\n }\n }\n call(path, args) {\n try {\n let state = this.getState();\n if (path.length !== 1 || typeof path[0] !== "string") {\n throw new Error("WritableStream stub only supports direct method calls");\n }\n const method = path[0];\n if (method !== "write" && method !== "close" && method !== "abort") {\n args.dispose();\n throw new Error(`Unknown WritableStream method: ${method}`);\n }\n if (method === "close" || method === "abort") {\n state.closed = true;\n }\n let func = state.writer[method];\n let promise = args.deliverCall(func, state.writer);\n return new PromiseStubHook(promise.then((payload) => new PayloadStubHook(payload)));\n } catch (err) {\n return new ErrorStubHook(err);\n }\n }\n map(path, captures, instructions) {\n for (let cap of captures) {\n cap.dispose();\n }\n return new ErrorStubHook(new Error("Cannot use map() on a WritableStream"));\n }\n get(path) {\n return new ErrorStubHook(new Error("Cannot access properties on a WritableStream stub"));\n }\n dup() {\n let state = this.getState();\n return new _WritableStreamStubHook(state, this);\n }\n pull() {\n return Promise.reject(new Error("Cannot pull a WritableStream stub"));\n }\n ignoreUnhandledRejections() {\n }\n dispose() {\n let state = this.state;\n this.state = void 0;\n if (state) {\n if (--state.refcount === 0) {\n if (!state.closed) {\n state.writer.abort(new Error("WritableStream RPC stub was disposed without calling close()")).catch(() => {\n });\n }\n state.writer.releaseLock();\n }\n }\n }\n onBroken(callback) {\n }\n};\nvar INITIAL_WINDOW = 256 * 1024;\nvar MAX_WINDOW = 1024 * 1024 * 1024;\nvar MIN_WINDOW = 64 * 1024;\nvar STARTUP_GROWTH_FACTOR = 2;\nvar STEADY_GROWTH_FACTOR = 1.25;\nvar DECAY_FACTOR = 0.9;\nvar STARTUP_EXIT_ROUNDS = 3;\nvar FlowController = class {\n constructor(now) {\n this.now = now;\n }\n // The current window size in bytes. The sender blocks when bytesInFlight >= window.\n window = INITIAL_WINDOW;\n // Total bytes currently in flight (sent but not yet acked).\n bytesInFlight = 0;\n // Whether we\'re still in the startup phase.\n inStartupPhase = true;\n // ----- BDP estimation state (private) -----\n // Total bytes acked so far.\n delivered = 0;\n // Time of most recent ack.\n deliveredTime = 0;\n // Time when the very first ack was received.\n firstAckTime = 0;\n firstAckDelivered = 0;\n // Global minimum RTT observed (milliseconds).\n minRtt = Infinity;\n // For startup exit: count of consecutive RTT rounds where the window didn\'t meaningfully grow.\n roundsWithoutIncrease = 0;\n // Window size at the start of the current round, for startup exit detection.\n lastRoundWindow = 0;\n // Time when the current round started.\n roundStartTime = 0;\n // Called when a write of `size` bytes is about to be sent. Returns a token that must be\n // passed to onAck() when the ack arrives, and whether the sender should block (window full).\n onSend(size) {\n this.bytesInFlight += size;\n let token = {\n sentTime: this.now(),\n size,\n deliveredAtSend: this.delivered,\n deliveredTimeAtSend: this.deliveredTime,\n windowAtSend: this.window,\n windowFullAtSend: this.bytesInFlight >= this.window\n };\n return { token, shouldBlock: token.windowFullAtSend };\n }\n // Called when a previously-sent write fails. Restores bytesInFlight without updating\n // any BDP estimates.\n onError(token) {\n this.bytesInFlight -= token.size;\n }\n // Called when an ack is received for a previously-sent write. Updates BDP estimates and\n // the window. Returns whether a blocked sender should now unblock.\n onAck(token) {\n let ackTime = this.now();\n this.delivered += token.size;\n this.deliveredTime = ackTime;\n this.bytesInFlight -= token.size;\n let rtt = ackTime - token.sentTime;\n this.minRtt = Math.min(this.minRtt, rtt);\n if (this.firstAckTime === 0) {\n this.firstAckTime = ackTime;\n this.firstAckDelivered = this.delivered;\n } else {\n let baseTime;\n let baseDelivered;\n if (token.deliveredTimeAtSend === 0) {\n baseTime = this.firstAckTime;\n baseDelivered = this.firstAckDelivered;\n } else {\n baseTime = token.deliveredTimeAtSend;\n baseDelivered = token.deliveredAtSend;\n }\n let interval = ackTime - baseTime;\n let bytes = this.delivered - baseDelivered;\n let bandwidth = bytes / interval;\n let growthFactor = this.inStartupPhase ? STARTUP_GROWTH_FACTOR : STEADY_GROWTH_FACTOR;\n let newWindow = bandwidth * this.minRtt * growthFactor;\n newWindow = Math.min(newWindow, token.windowAtSend * growthFactor);\n if (token.windowFullAtSend) {\n newWindow = Math.max(newWindow, token.windowAtSend * DECAY_FACTOR);\n } else {\n newWindow = Math.max(newWindow, this.window);\n }\n this.window = Math.max(Math.min(newWindow, MAX_WINDOW), MIN_WINDOW);\n if (this.inStartupPhase && token.sentTime >= this.roundStartTime) {\n if (this.window > this.lastRoundWindow * STEADY_GROWTH_FACTOR) {\n this.roundsWithoutIncrease = 0;\n } else {\n if (++this.roundsWithoutIncrease >= STARTUP_EXIT_ROUNDS) {\n this.inStartupPhase = false;\n }\n }\n this.roundStartTime = ackTime;\n this.lastRoundWindow = this.window;\n }\n }\n return this.bytesInFlight < this.window;\n }\n};\nfunction createWritableStreamFromHook(hook) {\n let pendingError = void 0;\n let hookDisposed = false;\n let fc = new FlowController(() => performance.now());\n let windowResolve;\n let windowReject;\n const disposeHook = () => {\n if (!hookDisposed) {\n hookDisposed = true;\n hook.dispose();\n }\n };\n return new WritableStream({\n write(chunk, controller) {\n if (pendingError !== void 0) {\n throw pendingError;\n }\n const payload = RpcPayload.fromAppParams([chunk]);\n const { promise, size } = hook.stream(["write"], payload);\n if (size === void 0) {\n return promise.catch((err) => {\n if (pendingError === void 0) {\n pendingError = err;\n }\n throw err;\n });\n } else {\n let { token, shouldBlock } = fc.onSend(size);\n promise.then(() => {\n let hasCapacity = fc.onAck(token);\n if (hasCapacity && windowResolve) {\n windowResolve();\n windowResolve = void 0;\n windowReject = void 0;\n }\n }, (err) => {\n fc.onError(token);\n if (pendingError === void 0) {\n pendingError = err;\n controller.error(err);\n disposeHook();\n }\n if (windowReject) {\n windowReject(err);\n windowResolve = void 0;\n windowReject = void 0;\n }\n });\n if (shouldBlock) {\n return new Promise((resolve, reject) => {\n windowResolve = resolve;\n windowReject = reject;\n });\n }\n }\n },\n async close() {\n if (pendingError !== void 0) {\n disposeHook();\n throw pendingError;\n }\n const { promise } = hook.stream(["close"], RpcPayload.fromAppParams([]));\n try {\n await promise;\n } catch (err) {\n throw pendingError ?? err;\n } finally {\n disposeHook();\n }\n },\n abort(reason) {\n if (pendingError !== void 0) {\n return;\n }\n pendingError = reason ?? new Error("WritableStream was aborted");\n if (windowReject) {\n windowReject(pendingError);\n windowResolve = void 0;\n windowReject = void 0;\n }\n const { promise } = hook.stream(["abort"], RpcPayload.fromAppParams([reason]));\n promise.then(() => disposeHook(), () => disposeHook());\n }\n });\n}\nvar ReadableStreamStubHook = class _ReadableStreamStubHook extends StubHook {\n state;\n // undefined when disposed\n // Creates a new ReadableStreamStubHook.\n static create(stream) {\n return new _ReadableStreamStubHook({ refcount: 1, stream, canceled: false });\n }\n constructor(state, dupFrom) {\n super();\n this.state = state;\n if (dupFrom) {\n ++state.refcount;\n }\n }\n call(path, args) {\n args.dispose();\n return new ErrorStubHook(new Error("Cannot call methods on a ReadableStream stub"));\n }\n map(path, captures, instructions) {\n for (let cap of captures) {\n cap.dispose();\n }\n return new ErrorStubHook(new Error("Cannot use map() on a ReadableStream"));\n }\n get(path) {\n return new ErrorStubHook(new Error("Cannot access properties on a ReadableStream stub"));\n }\n dup() {\n let state = this.state;\n if (!state) {\n throw new Error("Attempted to dup a ReadableStreamStubHook after it was disposed.");\n }\n return new _ReadableStreamStubHook(state, this);\n }\n pull() {\n return Promise.reject(new Error("Cannot pull a ReadableStream stub"));\n }\n ignoreUnhandledRejections() {\n }\n dispose() {\n let state = this.state;\n this.state = void 0;\n if (state) {\n if (--state.refcount === 0) {\n if (!state.canceled) {\n state.canceled = true;\n if (!state.stream.locked) {\n state.stream.cancel(\n new Error("ReadableStream RPC stub was disposed without being consumed")\n ).catch(() => {\n });\n }\n }\n }\n }\n }\n onBroken(callback) {\n }\n};\nstreamImpl.createWritableStreamHook = WritableStreamStubHook.create;\nstreamImpl.createWritableStreamFromHook = createWritableStreamFromHook;\nstreamImpl.createReadableStreamHook = ReadableStreamStubHook.create;\nasync function newWorkersRpcResponse(request, localMain) {\n if (request.method === "POST") {\n let response = await newHttpBatchRpcResponse(request, localMain);\n response.headers.set("Access-Control-Allow-Origin", "*");\n return response;\n } else if (request.headers.get("Upgrade")?.toLowerCase() === "websocket") {\n return newWorkersWebSocketRpcResponse(request, localMain);\n } else {\n return new Response("This endpoint only accepts POST or WebSocket requests.", { status: 400 });\n }\n}\n\n// templates/remoteBindings/ProxyServerWorker.ts\nimport { EmailMessage } from "cloudflare:email";\nvar BindingNotFoundError = class extends Error {\n constructor(name) {\n super(`Binding ${name ? `"${name}"` : ""} not found`);\n }\n};\nfunction getExposedJSRPCBinding(request, env) {\n const url = new URL(request.url);\n const bindingName = url.searchParams.get("MF-Binding");\n if (!bindingName) {\n throw new BindingNotFoundError();\n }\n const targetBinding = env[bindingName];\n if (!targetBinding) {\n throw new BindingNotFoundError(bindingName);\n }\n if (targetBinding.constructor.name === "SendEmail") {\n return {\n async send(e) {\n if ("EmailMessage::raw" in e) {\n const message = new EmailMessage(\n e.from,\n e.to,\n e["EmailMessage::raw"]\n );\n return targetBinding.send(message);\n } else {\n return targetBinding.send(e);\n }\n }\n };\n }\n const dispatchNamespaceOptions = url.searchParams.get(\n "MF-Dispatch-Namespace-Options"\n );\n if (dispatchNamespaceOptions) {\n const { name, args, options } = JSON.parse(dispatchNamespaceOptions);\n return targetBinding.get(name, args, options);\n }\n return targetBinding;\n}\nfunction getExposedFetcher(request, env) {\n const bindingName = request.headers.get("MF-Binding");\n if (!bindingName) {\n throw new BindingNotFoundError();\n }\n const targetBinding = env[bindingName];\n if (!targetBinding) {\n throw new BindingNotFoundError(bindingName);\n }\n const dispatchNamespaceOptions = request.headers.get(\n "MF-Dispatch-Namespace-Options"\n );\n if (dispatchNamespaceOptions) {\n const { name, args, options } = JSON.parse(dispatchNamespaceOptions);\n return targetBinding.get(name, args, options);\n }\n return targetBinding;\n}\nfunction isJSRPCBinding(request) {\n const url = new URL(request.url);\n return request.headers.has("Upgrade") && url.searchParams.has("MF-Binding");\n}\nfunction isConnectBinding(request) {\n return request.headers.get("Upgrade") === "websocket" && request.headers.has("MF-Connect-Address");\n}\nfunction handleConnect(request, env) {\n const address = request.headers.get("MF-Connect-Address");\n if (address === null) {\n return new Response("Missing MF-Connect-Address header", { status: 400 });\n }\n const fetcher = getExposedFetcher(request, env);\n const { 0: client, 1: server } = new WebSocketPair();\n server.accept();\n const socket = fetcher.connect(address);\n pipeSocketOverWebSocket(socket, server).catch(() => {\n });\n return new Response(null, { status: 101, webSocket: client });\n}\nfunction truncateCloseReason(reason) {\n const bytes = new TextEncoder().encode(reason);\n if (bytes.length <= 123) {\n return reason;\n }\n let end = 123;\n while (end > 0 && ((bytes[end] ?? 0) & 192) === 128) {\n end--;\n }\n return new TextDecoder().decode(bytes.subarray(0, end));\n}\nasync function pipeSocketOverWebSocket(socket, ws) {\n const writer = socket.writable.getWriter();\n const reader = socket.readable.getReader();\n let wsClosed = false;\n function closeWebSocket(code, reason) {\n if (wsClosed) {\n return;\n }\n wsClosed = true;\n try {\n ws.close(\n code,\n reason === void 0 ? void 0 : truncateCloseReason(reason)\n );\n } catch {\n }\n }\n let writeChain = Promise.resolve();\n let writerClosed = false;\n function closeWriter() {\n if (writerClosed) {\n return Promise.resolve();\n }\n writerClosed = true;\n return writeChain.then(() => writer.close());\n }\n let resolveFromWs;\n let rejectFromWs;\n const fromWebSocket = new Promise((resolve, reject) => {\n resolveFromWs = resolve;\n rejectFromWs = reject;\n });\n ws.addEventListener("message", (event) => {\n const chunk = typeof event.data === "string" ? new TextEncoder().encode(event.data) : new Uint8Array(event.data);\n writeChain = writeChain.then(() => writer.write(chunk)).catch((error) => {\n closeWebSocket(\n 1011,\n error?.message ?? "socket write failed"\n );\n reader.cancel().catch(() => {\n });\n rejectFromWs(error);\n });\n });\n ws.addEventListener("close", (event) => {\n wsClosed = true;\n reader.cancel().catch(() => {\n });\n if (event.code === 1011) {\n rejectFromWs(\n new Error(event.reason || "Remote tunnel closed with an error")\n );\n return;\n }\n closeWriter().then(resolveFromWs, rejectFromWs);\n });\n ws.addEventListener("error", () => {\n wsClosed = true;\n reader.cancel().catch(() => {\n });\n rejectFromWs(new Error("Tunnel WebSocket errored"));\n });\n const toWebSocket = (async () => {\n try {\n for (; ; ) {\n const { value, done } = await reader.read();\n if (done) {\n break;\n }\n if (wsClosed) {\n break;\n }\n ws.send(\n value.buffer.slice(\n value.byteOffset,\n value.byteOffset + value.byteLength\n )\n );\n }\n closeWebSocket(1e3);\n } catch (error) {\n closeWebSocket(1011, error?.message ?? "socket read failed");\n throw error;\n } finally {\n reader.releaseLock();\n closeWriter().then(resolveFromWs, rejectFromWs);\n }\n })();\n await Promise.all([toWebSocket, fromWebSocket]);\n}\nvar ProxyServerWorker_default = {\n async fetch(request, env) {\n try {\n if (isConnectBinding(request)) {\n return handleConnect(request, env);\n } else if (isJSRPCBinding(request)) {\n return await newWorkersRpcResponse(\n request,\n getExposedJSRPCBinding(request, env)\n );\n } else {\n const fetcher = getExposedFetcher(request, env);\n const originalHeaders = new Headers();\n for (const [name, value] of request.headers) {\n if (name.startsWith("mf-header-")) {\n originalHeaders.set(name.slice("mf-header-".length), value);\n } else if (name === "upgrade") {\n originalHeaders.set(name, value);\n }\n }\n return await fetcher.fetch(\n request.headers.get("MF-URL") ?? "http://example.com",\n new Request(request, {\n redirect: "manual",\n headers: originalHeaders\n })\n );\n }\n } catch (e) {\n if (e instanceof BindingNotFoundError) {\n return new Response(e.message, { status: 400 });\n }\n return new Response(e.message, { status: 500 });\n }\n }\n};\nexport {\n ProxyServerWorker_default as default\n};\n';
171295
171469
  __name(initLogger, "initLogger");
171296
171470
  ProxyWorker_default = '// src/startDevWorker/utils.ts\nimport assert from "node:assert";\nvar PREVIEW_TOKEN_REFRESH_INTERVAL = 50 * 60 * 1e3;\nfunction createDeferred(previousDeferred) {\n let resolve, reject;\n const newPromise = new Promise((_resolve, _reject) => {\n resolve = _resolve;\n reject = _reject;\n });\n assert(resolve);\n assert(reject);\n previousDeferred?.resolve(newPromise);\n return {\n promise: newPromise,\n resolve,\n reject\n };\n}\nfunction urlFromParts(parts, base = "http://localhost") {\n const url = new URL(base);\n Object.assign(url, parts);\n return url;\n}\nfunction rewriteUrlInHeaderValue(value, from, to) {\n return value.replace(\n /(https?:\\/\\/[^/?#\\s,;"\']+)([^\\s,;"\']*)/gi,\n (match, origin, rest) => {\n let url;\n try {\n url = new URL(origin);\n } catch {\n return match;\n }\n if (url.host !== from.host) {\n return match;\n }\n return to.origin + rest;\n }\n );\n}\n\n// templates/startDevWorker/ProxyWorker.ts\nvar ProxyWorker_default = {\n fetch(req, env) {\n const singleton = env.DURABLE_OBJECT.idFromName("");\n const inspectorProxy = env.DURABLE_OBJECT.get(singleton);\n return inspectorProxy.fetch(req);\n }\n};\nvar ProxyWorker = class {\n constructor(_state, env) {\n this.env = env;\n }\n env;\n proxyData;\n requestQueue = /* @__PURE__ */ new Map();\n requestRetryQueue = /* @__PURE__ */ new Map();\n fetch(request) {\n if (isRequestFromProxyController(request, this.env)) {\n return this.processProxyControllerRequest(request);\n }\n const deferred = createDeferred();\n this.requestQueue.set(request, deferred);\n this.processQueue();\n return deferred.promise;\n }\n processProxyControllerRequest(request) {\n const event = request.cf?.hostMetadata;\n switch (event?.type) {\n case "pause":\n this.proxyData = void 0;\n break;\n case "play":\n this.proxyData = event.proxyData;\n this.processQueue();\n break;\n }\n return new Response(null, { status: 204 });\n }\n /**\n * Process requests that are being retried first, then process newer requests.\n * Requests that are being retried are, by definition, older than requests which haven\'t been processed yet.\n * We don\'t need to be more accurate than this re ordering, since the requests are being fired off synchronously.\n */\n *getOrderedQueue() {\n yield* this.requestRetryQueue;\n yield* this.requestQueue;\n }\n processQueue() {\n const { proxyData } = this;\n if (proxyData === void 0) {\n return;\n }\n for (const [request, deferredResponse] of this.getOrderedQueue()) {\n this.requestRetryQueue.delete(request);\n this.requestQueue.delete(request);\n const outerUrl = new URL(request.url);\n const headers = new Headers(request.headers);\n const userWorkerUrl = new URL(request.url);\n Object.assign(userWorkerUrl, proxyData.userWorkerUrl);\n const innerUrl = urlFromParts(\n proxyData.userWorkerInnerUrlOverrides ?? {},\n request.url\n );\n const encoding = request.cf?.clientAcceptEncoding;\n if (encoding !== void 0) {\n headers.set("Accept-Encoding", encoding);\n }\n rewriteUrlRelatedHeaders(headers, outerUrl, innerUrl);\n headers.set("MF-Original-URL", innerUrl.href);\n for (const [key, value] of Object.entries(proxyData.headers ?? {})) {\n if (value === void 0) {\n continue;\n }\n if (key.toLowerCase() === "cookie") {\n const existing = request.headers.get("cookie") ?? "";\n headers.set("cookie", `${existing};${value}`);\n } else {\n headers.set(key, value);\n }\n }\n void fetch(userWorkerUrl, new Request(request, { headers })).then(async (res) => {\n res = new Response(res.body, res);\n rewriteUrlRelatedHeaders(res.headers, innerUrl, outerUrl);\n await checkForPreviewTokenError(res, this.env, proxyData);\n deferredResponse.resolve(res);\n }).catch((error) => {\n const newUserWorkerUrl = this.proxyData && urlFromParts(this.proxyData.userWorkerUrl);\n if (userWorkerUrl.href === newUserWorkerUrl?.href) {\n void sendMessageToProxyController(this.env, {\n type: "error",\n error: {\n name: error.name,\n message: error.message,\n stack: error.stack,\n cause: error.cause\n }\n });\n deferredResponse.reject(error);\n } else if (request.method === "GET" || request.method === "HEAD") {\n this.requestRetryQueue.set(request, deferredResponse);\n } else {\n deferredResponse.resolve(\n new Response(\n "Your worker restarted mid-request. Please try sending the request again. Only GET or HEAD requests are retried automatically.",\n {\n status: 503,\n headers: { "Retry-After": "0" }\n }\n )\n );\n }\n });\n }\n }\n};\nfunction isRequestFromProxyController(req, env) {\n return req.headers.get("Authorization") === env.PROXY_CONTROLLER_AUTH_SECRET;\n}\nfunction sendMessageToProxyController(env, message) {\n return env.PROXY_CONTROLLER.fetch("http://dummy", {\n method: "POST",\n body: JSON.stringify(message)\n });\n}\nasync function checkForPreviewTokenError(response, env, proxyData) {\n if (response.status !== 400) {\n return;\n }\n const clone = response.clone();\n const text = await clone.text();\n if (text.includes("Invalid Workers Preview configuration") || text.includes("error code: 1031")) {\n void sendMessageToProxyController(env, {\n type: "previewTokenExpired",\n proxyData\n });\n }\n}\nfunction rewriteUrlRelatedHeaders(headers, from, to) {\n const setCookie = headers.getAll("Set-Cookie");\n headers.delete("Set-Cookie");\n headers.forEach((value, key) => {\n if (typeof value === "string" && value.includes(from.host)) {\n headers.set(key, rewriteUrlInHeaderValue(value, from, to));\n }\n });\n for (const cookie of setCookie) {\n headers.append(\n "Set-Cookie",\n cookie.replace(\n new RegExp(`Domain=${from.hostname}($|;|,)`),\n `Domain=${to.hostname}$1`\n )\n );\n }\n}\nexport {\n ProxyWorker,\n ProxyWorker_default as default\n};\n';
171297
171471
  __name(castLogLevel2, "castLogLevel");
@@ -171476,11 +171650,11 @@ var init_dist12 = __esm({
171476
171650
  }
171477
171651
  /**
171478
171652
  * @param cause - The original error that triggered the authentication
171479
- * failure (e.g. an {@link APIError} with code 9106 or 10000).
171653
+ * failure (e.g. an {@link APIError} with code 9106, 10000, or 10405).
171480
171654
  */
171481
171655
  constructor(cause) {
171482
171656
  const envAuth = getAuthFromEnv();
171483
- let errorMessage = "Failed to establish remote session due to an authentication issue.\n";
171657
+ let errorMessage = "This Worker uses bindings that need to run remotely, even when developing locally, but the remote session could not be authenticated.\n";
171484
171658
  if (envAuth !== void 0) {
171485
171659
  const method = "apiToken" in envAuth ? "a custom API token (`CLOUDFLARE_API_TOKEN`)" : "a Global API Key (`CLOUDFLARE_API_KEY`)";
171486
171660
  errorMessage += `It looks like you are authenticating via ${method} set in an environment variable.
@@ -180666,10 +180840,16 @@ ${codeblock}`, options);
180666
180840
  * endpoint-specific structured error payloads.
180667
180841
  */
180668
180842
  meta;
180669
- constructor({ status: status2, ...rest }) {
180843
+ /**
180844
+ * Optional number of milliseconds the API asked us to wait before retrying,
180845
+ * derived from the response's `Retry-After` header (if present).
180846
+ */
180847
+ retryAfterMs;
180848
+ constructor({ status: status2, retryAfterMs, ...rest }) {
180670
180849
  super(rest);
180671
180850
  this.name = this.constructor.name;
180672
180851
  this.#status = status2;
180852
+ this.retryAfterMs = retryAfterMs;
180673
180853
  }
180674
180854
  get status() {
180675
180855
  return this.#status;
@@ -183681,8 +183861,8 @@ var init_esm6 = __esm({
183681
183861
  }
183682
183862
  return this._userIgnored(path89, stats);
183683
183863
  }
183684
- _isntIgnored(path89, stat11) {
183685
- return !this._isIgnored(path89, stat11);
183864
+ _isntIgnored(path89, stat10) {
183865
+ return !this._isIgnored(path89, stat10);
183686
183866
  }
183687
183867
  /**
183688
183868
  * Provides a set of common helpers and properties relating to symlink handling.
@@ -204025,7 +204205,7 @@ async function ensureImageFitsLimits(options) {
204025
204205
  );
204026
204206
  if (options.availableSizeInBytes < requiredSizeInBytes) {
204027
204207
  throw new UserError(
204028
- `Image too large: needs ${Math.ceil(requiredSizeInBytes / MB)}MB, but your app is limited to images with size ${options.availableSizeInBytes / MB}MB. Your need more disk for this image.`,
204208
+ `Image too large: needs ${Math.ceil(requiredSizeInBytes / MB)}MB, but your app is limited to images with size ${options.availableSizeInBytes / MB}MB. You need more disk for this image.`,
204029
204209
  { telemetryMessage: "cloudchamber limits image too large" }
204030
204210
  );
204031
204211
  }
@@ -220252,6 +220432,7 @@ async function fetchBrowserRendering(config3, resource, options = {}) {
220252
220432
  text: `Browser Run API error: ${errorMessage}`,
220253
220433
  notes: [{ text: `${method} ${url5} -> ${response.status}` }],
220254
220434
  status: response.status,
220435
+ retryAfterMs: parseRetryAfterMs(response.headers),
220255
220436
  telemetryMessage: false
220256
220437
  });
220257
220438
  }
@@ -220265,6 +220446,7 @@ async function fetchBrowserRendering(config3, resource, options = {}) {
220265
220446
  { text: `${method} ${url5} -> ${response.status}` }
220266
220447
  ],
220267
220448
  status: response.status,
220449
+ retryAfterMs: parseRetryAfterMs(response.headers),
220268
220450
  telemetryMessage: false
220269
220451
  });
220270
220452
  }
@@ -224865,14 +225047,24 @@ async function requestFromCmd(args, _config) {
224865
225047
  if (args.useStdin) {
224866
225048
  args.data = await read(process.stdin);
224867
225049
  }
224868
- try {
224869
- const headers = (args.header ?? []).reduce(
224870
- (prev, now) => ({
225050
+ const headers = (args.header ?? []).reduce(
225051
+ (prev, now) => {
225052
+ const header = now.toString();
225053
+ const separatorIndex = header.indexOf(":");
225054
+ if (separatorIndex <= 0) {
225055
+ throw new UserError(
225056
+ `Invalid header "${header}". Headers must be in the form of --header <name>:<value>`,
225057
+ { telemetryMessage: "cloudchamber curl invalid header" }
225058
+ );
225059
+ }
225060
+ return {
224871
225061
  ...prev,
224872
- [now.toString().split(":")[0].trim()]: now.toString().split(":")[1].trim()
224873
- }),
224874
- { "coordinator-request-id": requestId }
224875
- );
225062
+ [header.slice(0, separatorIndex).trim()]: header.slice(separatorIndex + 1).trim()
225063
+ };
225064
+ },
225065
+ { "coordinator-request-id": requestId }
225066
+ );
225067
+ try {
224876
225068
  const data = args.data ?? args.dataDeprecated;
224877
225069
  const res = await request(OpenAPI, {
224878
225070
  url: args.path,
@@ -224934,6 +225126,7 @@ var init_curl = __esm({
224934
225126
  init_colors();
224935
225127
  init_containers_shared();
224936
225128
  init_request();
225129
+ init_dist();
224937
225130
  init_create_command();
224938
225131
  init_render_labelled_values();
224939
225132
  init_common();
@@ -238079,13 +238272,25 @@ function createHandler2(def, argv) {
238079
238272
  type: "command-failed",
238080
238273
  version: 1,
238081
238274
  code,
238082
- message: outputErr.message
238275
+ message: outputErr.message,
238276
+ retry_after_ms: getRetryAfterMs(outputErr)
238083
238277
  });
238084
238278
  }
238085
238279
  throw err;
238086
238280
  }
238087
238281
  }, "handler");
238088
238282
  }
238283
+ function getRetryAfterMs(err) {
238284
+ if ("retryAfterMs" in err && typeof err.retryAfterMs === "number") {
238285
+ return err.retryAfterMs;
238286
+ }
238287
+ if ("headers" in err && err.headers && typeof err.headers === "object") {
238288
+ return parseRetryAfterValue(
238289
+ err.headers["retry-after"]
238290
+ );
238291
+ }
238292
+ return void 0;
238293
+ }
238089
238294
  var init_register_yargs_command = __esm({
238090
238295
  "src/core/register-yargs-command.ts"() {
238091
238296
  init_import_meta_url();
@@ -238115,6 +238320,7 @@ var init_register_yargs_command = __esm({
238115
238320
  init_temporary_commands();
238116
238321
  __name(createRegisterYargsCommand, "createRegisterYargsCommand");
238117
238322
  __name(createHandler2, "createHandler");
238323
+ __name(getRetryAfterMs, "getRetryAfterMs");
238118
238324
  }
238119
238325
  });
238120
238326
 
@@ -238286,8 +238492,14 @@ async function createD1Database2(complianceConfig, accountId, name2, location, j
238286
238492
  throw new UserError(
238287
238493
  esm_default4`
238288
238494
  You have reached the maximum number of D1 databases for your account.
238289
- Please consider deleting unused databases, or visit the D1 documentation to learn more: ${D1_DOCS_URL}
238290
238495
 
238496
+ On the Workers Free plan? Upgrade to create more:
238497
+ https://dash.cloudflare.com/${accountId}/workers/plans
238498
+
238499
+ Already on a paid plan? You can request a higher limit — learn more in the D1 docs:
238500
+ ${D1_DOCS_URL}
238501
+
238502
+ Or free up space:
238291
238503
  To list your existing databases, run: wrangler d1 list
238292
238504
  To delete a database, run: wrangler d1 delete <database-name>
238293
238505
  `,
@@ -303205,6 +303417,12 @@ var init_kv2 = __esm({
303205
303417
  type: "boolean",
303206
303418
  describe: "Interact with a preview namespace"
303207
303419
  },
303420
+ jurisdiction: {
303421
+ type: "string",
303422
+ describe: 'The jurisdiction where the new namespace will be created (e.g. "us", "eu", "fedramp")',
303423
+ requiresArg: true,
303424
+ hidden: true
303425
+ },
303208
303426
  ...sharedResourceCreationArgs
303209
303427
  },
303210
303428
  positionalArgs: ["namespace"],
@@ -303213,15 +303431,20 @@ var init_kv2 = __esm({
303213
303431
  const environment = args.env ? `${args.env}-` : "";
303214
303432
  const preview2 = args.preview ? "_preview" : "";
303215
303433
  const title = `${environment}${args.namespace}${preview2}`;
303434
+ const { jurisdiction } = args;
303216
303435
  const accountId = await requireAuth(config3);
303217
303436
  printResourceLocation("remote");
303218
- logger2.log(`\u{1F300} Creating namespace with title "${title}"`);
303437
+ logger2.log(
303438
+ `\u{1F300} Creating namespace with title "${title}"${jurisdiction ? ` (jurisdiction: ${jurisdiction})` : ""}`
303439
+ );
303219
303440
  let namespaceId;
303220
303441
  try {
303221
- const result = await sdk.kv.namespaces.create({
303442
+ const createParams = {
303222
303443
  account_id: accountId,
303223
- title
303224
- });
303444
+ title,
303445
+ jurisdiction
303446
+ };
303447
+ const result = await sdk.kv.namespaces.create(createParams);
303225
303448
  namespaceId = result.id;
303226
303449
  } catch (e9) {
303227
303450
  if (e9 instanceof Cloudflare.APIError && e9.errors.some((err) => err.code === 10014)) {
@@ -353857,13 +354080,13 @@ function validateBulkPutFile(filename) {
353857
354080
  telemetryMessage: "r2 object bulk put entry file not found"
353858
354081
  });
353859
354082
  }
353860
- const stat11 = fs6__namespace.default.statSync(entry.file, { throwIfNoEntry: false });
353861
- if (!stat11?.isFile()) {
354083
+ const stat10 = fs6__namespace.default.statSync(entry.file, { throwIfNoEntry: false });
354084
+ if (!stat10?.isFile()) {
353862
354085
  throw new UserError(`The path "${entry.file}" is not a file.`, {
353863
354086
  telemetryMessage: "r2 object bulk put entry path not file"
353864
354087
  });
353865
354088
  }
353866
- if (stat11.size > MAX_UPLOAD_SIZE_BYTES) {
354089
+ if (stat10.size > MAX_UPLOAD_SIZE_BYTES) {
353867
354090
  throw new UserError(
353868
354091
  `The file "${entry.file}" exceeds the maximum upload size of ${prettyBytes(
353869
354092
  MAX_UPLOAD_SIZE_BYTES,
@@ -353872,7 +354095,7 @@ function validateBulkPutFile(filename) {
353872
354095
  { telemetryMessage: "r2 object bulk put entry file too large" }
353873
354096
  );
353874
354097
  }
353875
- entry.size = stat11.size;
354098
+ entry.size = stat10.size;
353876
354099
  }
353877
354100
  return entries2;
353878
354101
  }
@@ -369121,15 +369344,25 @@ ${tryRunningItIn}${oneOfThese}`
369121
369344
  mayReport = false;
369122
369345
  logBuildFailure(e9.cause.errors, e9.cause.warnings);
369123
369346
  } else if (e9 instanceof Cloudflare.APIError) {
369124
- const error54 = new APIError({
369125
- text: `A request to the Cloudflare API failed.`,
369126
- notes: [...e9.errors.map((err) => ({ text: renderError(err) }))],
369127
- telemetryMessage: false
369128
- });
369129
- error54.notes.push({
369347
+ const retryAfterMs = parseRetryAfterValue(e9.headers?.["retry-after"]);
369348
+ const notes = [...e9.errors.map((err) => ({ text: renderError(err) }))];
369349
+ if (retryAfterMs !== void 0) {
369350
+ notes.push({
369351
+ text: `The API responded with a "Retry-After" header indicating you should wait ${Math.ceil(retryAfterMs / 1e3)} second(s) before retrying.`
369352
+ });
369353
+ }
369354
+ notes.push({
369130
369355
  text: "\nIf you think this is a bug, please open an issue at: https://github.com/cloudflare/workers-sdk/issues/new/choose"
369131
369356
  });
369132
- logger2.error(error54);
369357
+ logger2.error(
369358
+ new APIError({
369359
+ text: `A request to the Cloudflare API failed.`,
369360
+ notes,
369361
+ status: e9.status,
369362
+ retryAfterMs,
369363
+ telemetryMessage: false
369364
+ })
369365
+ );
369133
369366
  } else {
369134
369367
  if (
369135
369368
  // Is this a StartDevEnv error event? If so, unwrap the cause, which is usually the user-recognisable error