wrangler 4.114.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.
- package/config-schema.json +62 -5
- package/package.json +12 -11
- package/wrangler-dist/cli.d.ts +15 -0
- package/wrangler-dist/cli.js +317 -113
- package/wrangler-dist/experimental-config.d.mts.map +1 -1
- package/wrangler-dist/metafile-cjs.json +1 -1
package/wrangler-dist/cli.js
CHANGED
|
@@ -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
|
|
3303
|
-
"../workers-utils/dist/chunk-
|
|
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
|
-
|
|
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;
|
|
@@ -37704,6 +37714,7 @@ async function fetchInternalBase(complianceConfig, resource, init4 = {}, userAge
|
|
|
37704
37714
|
logHeaders(response.headers, logger6);
|
|
37705
37715
|
logger6.debugWithSanitization?.("RESPONSE:", jsonText);
|
|
37706
37716
|
logger6.debug("-- END CF API RESPONSE");
|
|
37717
|
+
const retryAfterMs = parseRetryAfterMs(response.headers);
|
|
37707
37718
|
if (!jsonText && (response.status === 204 || response.status === 205)) {
|
|
37708
37719
|
return {
|
|
37709
37720
|
response: {
|
|
@@ -37712,7 +37723,8 @@ async function fetchInternalBase(complianceConfig, resource, init4 = {}, userAge
|
|
|
37712
37723
|
errors: [],
|
|
37713
37724
|
messages: []
|
|
37714
37725
|
},
|
|
37715
|
-
status: response.status
|
|
37726
|
+
status: response.status,
|
|
37727
|
+
retryAfterMs
|
|
37716
37728
|
};
|
|
37717
37729
|
}
|
|
37718
37730
|
if (isWAFBlockResponse(response.headers)) {
|
|
@@ -37721,12 +37733,13 @@ async function fetchInternalBase(complianceConfig, resource, init4 = {}, userAge
|
|
|
37721
37733
|
method,
|
|
37722
37734
|
resource,
|
|
37723
37735
|
response.status,
|
|
37724
|
-
response.statusText
|
|
37736
|
+
response.statusText,
|
|
37737
|
+
retryAfterMs
|
|
37725
37738
|
);
|
|
37726
37739
|
}
|
|
37727
37740
|
try {
|
|
37728
37741
|
const json22 = parseJSON(jsonText);
|
|
37729
|
-
return { response: json22, status: response.status };
|
|
37742
|
+
return { response: json22, status: response.status, retryAfterMs };
|
|
37730
37743
|
} catch {
|
|
37731
37744
|
const rayId = extractWAFBlockRayId(response.headers);
|
|
37732
37745
|
throw new APIError({
|
|
@@ -37741,12 +37754,17 @@ async function fetchInternalBase(complianceConfig, resource, init4 = {}, userAge
|
|
|
37741
37754
|
...rayId ? [{ text: `Cloudflare Ray ID: ${rayId}` }] : []
|
|
37742
37755
|
],
|
|
37743
37756
|
status: response.status,
|
|
37757
|
+
retryAfterMs,
|
|
37744
37758
|
telemetryMessage: false
|
|
37745
37759
|
});
|
|
37746
37760
|
}
|
|
37747
37761
|
}
|
|
37748
37762
|
async function fetchResultBase(complianceConfig, resource, init4 = {}, userAgent, logger6, queryParams, abortSignal, credentials) {
|
|
37749
|
-
const {
|
|
37763
|
+
const {
|
|
37764
|
+
response: json22,
|
|
37765
|
+
status: status2,
|
|
37766
|
+
retryAfterMs
|
|
37767
|
+
} = await fetchInternalBase(
|
|
37750
37768
|
complianceConfig,
|
|
37751
37769
|
resource,
|
|
37752
37770
|
init4,
|
|
@@ -37759,7 +37777,7 @@ async function fetchResultBase(complianceConfig, resource, init4 = {}, userAgent
|
|
|
37759
37777
|
if (json22.success) {
|
|
37760
37778
|
return json22.result;
|
|
37761
37779
|
} else {
|
|
37762
|
-
throwFetchError(resource, json22, status2);
|
|
37780
|
+
throwFetchError(resource, json22, status2, retryAfterMs);
|
|
37763
37781
|
}
|
|
37764
37782
|
}
|
|
37765
37783
|
async function fetchListResultBase(complianceConfig, resource, init4 = {}, userAgent, logger6, queryParams, credentials) {
|
|
@@ -37771,7 +37789,11 @@ async function fetchListResultBase(complianceConfig, resource, init4 = {}, userA
|
|
|
37771
37789
|
queryParams = new Url.URLSearchParams(queryParams);
|
|
37772
37790
|
queryParams.set("cursor", cursor);
|
|
37773
37791
|
}
|
|
37774
|
-
const {
|
|
37792
|
+
const {
|
|
37793
|
+
response: json22,
|
|
37794
|
+
status: status2,
|
|
37795
|
+
retryAfterMs
|
|
37796
|
+
} = await fetchInternalBase(
|
|
37775
37797
|
complianceConfig,
|
|
37776
37798
|
resource,
|
|
37777
37799
|
init4,
|
|
@@ -37789,7 +37811,7 @@ async function fetchListResultBase(complianceConfig, resource, init4 = {}, userA
|
|
|
37789
37811
|
getMoreResults = false;
|
|
37790
37812
|
}
|
|
37791
37813
|
} else {
|
|
37792
|
-
throwFetchError(resource, json22, status2);
|
|
37814
|
+
throwFetchError(resource, json22, status2, retryAfterMs);
|
|
37793
37815
|
}
|
|
37794
37816
|
}
|
|
37795
37817
|
return results;
|
|
@@ -37804,6 +37826,22 @@ function truncate(text, maxLength) {
|
|
|
37804
37826
|
function isWAFBlockResponse(headers) {
|
|
37805
37827
|
return headers.get("cf-mitigated") === "challenge";
|
|
37806
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
|
+
}
|
|
37807
37845
|
function extractWAFBlockRayId(headers) {
|
|
37808
37846
|
return headers.get("cf-ray") ?? void 0;
|
|
37809
37847
|
}
|
|
@@ -37874,7 +37912,7 @@ function escapeCharacter(character) {
|
|
|
37874
37912
|
return codePoint <= 65535 ? `\\u${codePoint.toString(16).toUpperCase().padStart(4, "0")}` : `\\u{${codePoint.toString(16).toUpperCase()}}`;
|
|
37875
37913
|
}).join("");
|
|
37876
37914
|
}
|
|
37877
|
-
function throwFetchError(resource, response, status2) {
|
|
37915
|
+
function throwFetchError(resource, response, status2, retryAfterMs) {
|
|
37878
37916
|
const errors = response.errors ?? [];
|
|
37879
37917
|
for (const error522 of errors) {
|
|
37880
37918
|
maybeThrowFriendlyError(error522);
|
|
@@ -37892,10 +37930,19 @@ function throwFetchError(resource, response, status2) {
|
|
|
37892
37930
|
notes.push({ text: fallbackMessage });
|
|
37893
37931
|
}
|
|
37894
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
|
+
}
|
|
37895
37938
|
const error512 = new APIError({
|
|
37896
37939
|
text: `A request to the Cloudflare API (${resource}) failed.`,
|
|
37897
37940
|
notes,
|
|
37898
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,
|
|
37899
37946
|
telemetryMessage: false
|
|
37900
37947
|
});
|
|
37901
37948
|
const code = errors[0]?.code;
|
|
@@ -37909,7 +37956,7 @@ function throwFetchError(resource, response, status2) {
|
|
|
37909
37956
|
error512.accountTag = extractAccountTag(resource);
|
|
37910
37957
|
throw error512;
|
|
37911
37958
|
}
|
|
37912
|
-
function throwWAFBlockError(headers, method, resource, status2, statusText) {
|
|
37959
|
+
function throwWAFBlockError(headers, method, resource, status2, statusText, retryAfterMs) {
|
|
37913
37960
|
const rayId = extractWAFBlockRayId(headers);
|
|
37914
37961
|
throw new APIError({
|
|
37915
37962
|
text: "The Cloudflare API responded with a WAF block page instead of the expected JSON response",
|
|
@@ -37926,6 +37973,7 @@ function throwWAFBlockError(headers, method, resource, status2, statusText) {
|
|
|
37926
37973
|
}
|
|
37927
37974
|
],
|
|
37928
37975
|
status: status2,
|
|
37976
|
+
retryAfterMs,
|
|
37929
37977
|
telemetryMessage: false
|
|
37930
37978
|
});
|
|
37931
37979
|
}
|
|
@@ -38017,19 +38065,36 @@ async function retryOnAPIFailure(action, logger6, backoff = 0, attempts = MAX_AT
|
|
|
38017
38065
|
return await action();
|
|
38018
38066
|
} catch (err) {
|
|
38019
38067
|
if (err instanceof APIError) {
|
|
38020
|
-
if (!err.isRetryable()) {
|
|
38068
|
+
if (!err.isRetryable() && err.status !== 429) {
|
|
38021
38069
|
throw err;
|
|
38022
38070
|
}
|
|
38023
38071
|
} else if (err instanceof DOMException && err.name === "TimeoutError") ;
|
|
38024
38072
|
else if (!(err instanceof TypeError)) {
|
|
38025
38073
|
throw err;
|
|
38026
38074
|
}
|
|
38027
|
-
|
|
38028
|
-
|
|
38075
|
+
const retryAfterMs = err instanceof APIError ? err.retryAfterMs : void 0;
|
|
38076
|
+
if (retryAfterMs !== void 0 && retryAfterMs > MAX_RETRY_AFTER_MS) {
|
|
38077
|
+
throw err;
|
|
38078
|
+
}
|
|
38029
38079
|
if (attempts <= 1) {
|
|
38030
38080
|
throw err;
|
|
38031
38081
|
}
|
|
38032
|
-
|
|
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 });
|
|
38033
38098
|
return retryOnAPIFailure(
|
|
38034
38099
|
action,
|
|
38035
38100
|
logger6,
|
|
@@ -38128,15 +38193,15 @@ function getWorkerNameFromProject(projectPath) {
|
|
|
38128
38193
|
}
|
|
38129
38194
|
return getWorkerName(packageJsonName, projectPath);
|
|
38130
38195
|
}
|
|
38131
|
-
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, 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;
|
|
38132
38197
|
var init_dist = __esm({
|
|
38133
38198
|
"../workers-utils/dist/index.mjs"() {
|
|
38134
38199
|
init_import_meta_url();
|
|
38135
38200
|
init_chunk_J6JRMPLM();
|
|
38136
38201
|
init_chunk_34VZWBGB();
|
|
38137
38202
|
init_chunk_34VZWBGB();
|
|
38138
|
-
|
|
38139
|
-
|
|
38203
|
+
init_chunk_3K53PSCY();
|
|
38204
|
+
init_chunk_3K53PSCY();
|
|
38140
38205
|
init_chunk_53IMCORZ();
|
|
38141
38206
|
init_chunk_53IMCORZ();
|
|
38142
38207
|
init_chunk_Q72B4Q5Z();
|
|
@@ -53126,12 +53191,47 @@ Please add a binding for "${configBindingName}" to "env.${envName}.${field}.bind
|
|
|
53126
53191
|
if (!isRemoteValid(value, field, diagnostics)) {
|
|
53127
53192
|
isValid3 = false;
|
|
53128
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
|
+
}
|
|
53129
53228
|
validateAdditionalProperties(diagnostics, field, Object.keys(value), [
|
|
53130
53229
|
"binding",
|
|
53131
53230
|
"bucket_name",
|
|
53132
53231
|
"preview_bucket_name",
|
|
53133
53232
|
"jurisdiction",
|
|
53134
|
-
"remote"
|
|
53233
|
+
"remote",
|
|
53234
|
+
"local_dev"
|
|
53135
53235
|
]);
|
|
53136
53236
|
return isValid3;
|
|
53137
53237
|
}, "validateR2Binding");
|
|
@@ -55171,6 +55271,10 @@ ${resolution}`);
|
|
|
55171
55271
|
__name2(truncate, "truncate");
|
|
55172
55272
|
__name(isWAFBlockResponse, "isWAFBlockResponse");
|
|
55173
55273
|
__name2(isWAFBlockResponse, "isWAFBlockResponse");
|
|
55274
|
+
__name(parseRetryAfterValue, "parseRetryAfterValue");
|
|
55275
|
+
__name2(parseRetryAfterValue, "parseRetryAfterValue");
|
|
55276
|
+
__name(parseRetryAfterMs, "parseRetryAfterMs");
|
|
55277
|
+
__name2(parseRetryAfterMs, "parseRetryAfterMs");
|
|
55174
55278
|
__name(extractWAFBlockRayId, "extractWAFBlockRayId");
|
|
55175
55279
|
__name2(extractWAFBlockRayId, "extractWAFBlockRayId");
|
|
55176
55280
|
__name(extractAccountTag, "extractAccountTag");
|
|
@@ -55219,6 +55323,7 @@ ${resolution}`);
|
|
|
55219
55323
|
__name(handleBrowserOpenError, "handleBrowserOpenError");
|
|
55220
55324
|
__name2(handleBrowserOpenError, "handleBrowserOpenError");
|
|
55221
55325
|
MAX_ATTEMPTS = 3;
|
|
55326
|
+
MAX_RETRY_AFTER_MS = 6e4;
|
|
55222
55327
|
__name(retryOnAPIFailure, "retryOnAPIFailure");
|
|
55223
55328
|
__name2(retryOnAPIFailure, "retryOnAPIFailure");
|
|
55224
55329
|
__name(formatTime, "formatTime");
|
|
@@ -57117,7 +57222,7 @@ var name, version2;
|
|
|
57117
57222
|
var init_package = __esm({
|
|
57118
57223
|
"package.json"() {
|
|
57119
57224
|
name = "wrangler";
|
|
57120
|
-
version2 = "4.
|
|
57225
|
+
version2 = "4.115.0";
|
|
57121
57226
|
}
|
|
57122
57227
|
});
|
|
57123
57228
|
|
|
@@ -59835,6 +59940,19 @@ function getDebugFilepath() {
|
|
|
59835
59940
|
const filepath = dir4.endsWith(".log") ? dir4 : path2__default__namespace.default.join(dir4, `wrangler-${date7}.log`);
|
|
59836
59941
|
return path2__default__namespace.default.resolve(filepath);
|
|
59837
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
|
+
}
|
|
59838
59956
|
async function cleanupOldLogFiles(logsDir) {
|
|
59839
59957
|
if (!fs6.existsSync(logsDir)) {
|
|
59840
59958
|
return;
|
|
@@ -59844,15 +59962,13 @@ async function cleanupOldLogFiles(logsDir) {
|
|
|
59844
59962
|
try {
|
|
59845
59963
|
const files = await fs$1.readdir(logsDir);
|
|
59846
59964
|
const now = Date.now();
|
|
59847
|
-
for (const f7 of files
|
|
59848
|
-
|
|
59849
|
-
|
|
59850
|
-
|
|
59965
|
+
for (const f7 of files) {
|
|
59966
|
+
const timestamp = parseLogFileTimestamp(f7);
|
|
59967
|
+
if (timestamp === void 0 || now - timestamp <= cutoffMs) {
|
|
59968
|
+
continue;
|
|
59969
|
+
}
|
|
59851
59970
|
try {
|
|
59852
|
-
|
|
59853
|
-
if (now - fileStat.mtimeMs > cutoffMs) {
|
|
59854
|
-
await fs$1.unlink(filePath);
|
|
59855
|
-
}
|
|
59971
|
+
await fs$1.unlink(path2__default__namespace.default.join(logsDir, f7));
|
|
59856
59972
|
} catch {
|
|
59857
59973
|
}
|
|
59858
59974
|
}
|
|
@@ -59918,6 +60034,7 @@ var init_log_file = __esm({
|
|
|
59918
60034
|
}
|
|
59919
60035
|
});
|
|
59920
60036
|
__name(getDebugFilepath, "getDebugFilepath");
|
|
60037
|
+
__name(parseLogFileTimestamp, "parseLogFileTimestamp");
|
|
59921
60038
|
__name(cleanupOldLogFiles, "cleanupOldLogFiles");
|
|
59922
60039
|
debugLogFilepath = getDebugFilepath();
|
|
59923
60040
|
mutex = new miniflare.Mutex();
|
|
@@ -130277,6 +130394,7 @@ async function fetchR2Objects(complianceConfig, resource, bodyInit = {}) {
|
|
|
130277
130394
|
text: `Failed to fetch ${resource} - ${response.status}: ${response.statusText};`,
|
|
130278
130395
|
status: response.status,
|
|
130279
130396
|
notes,
|
|
130397
|
+
retryAfterMs: parseRetryAfterMs(response.headers),
|
|
130280
130398
|
telemetryMessage: false
|
|
130281
130399
|
});
|
|
130282
130400
|
if (errorCode !== void 0) {
|
|
@@ -130404,7 +130522,16 @@ async function fetchPagedListResult2(complianceConfig, resource, init4 = {}, que
|
|
|
130404
130522
|
while (getMoreResults) {
|
|
130405
130523
|
queryParams = new Url.URLSearchParams(queryParams);
|
|
130406
130524
|
queryParams.set("page", String(page));
|
|
130407
|
-
const {
|
|
130525
|
+
const {
|
|
130526
|
+
response: json3,
|
|
130527
|
+
status: status2,
|
|
130528
|
+
retryAfterMs
|
|
130529
|
+
} = await fetchInternal(
|
|
130530
|
+
complianceConfig,
|
|
130531
|
+
resource,
|
|
130532
|
+
init4,
|
|
130533
|
+
queryParams
|
|
130534
|
+
);
|
|
130408
130535
|
if (json3.success) {
|
|
130409
130536
|
results.push(...json3.result);
|
|
130410
130537
|
if (hasMorePages(json3.result_info)) {
|
|
@@ -130413,7 +130540,7 @@ async function fetchPagedListResult2(complianceConfig, resource, init4 = {}, que
|
|
|
130413
130540
|
getMoreResults = false;
|
|
130414
130541
|
}
|
|
130415
130542
|
} else {
|
|
130416
|
-
throwFetchError(resource, json3, status2);
|
|
130543
|
+
throwFetchError(resource, json3, status2, retryAfterMs);
|
|
130417
130544
|
}
|
|
130418
130545
|
}
|
|
130419
130546
|
return results;
|
|
@@ -130428,7 +130555,16 @@ async function fetchCursorPage(complianceConfig, resource, init4 = {}, queryPara
|
|
|
130428
130555
|
if (cursor) {
|
|
130429
130556
|
pageQueryParams.set("cursor", cursor);
|
|
130430
130557
|
}
|
|
130431
|
-
const {
|
|
130558
|
+
const {
|
|
130559
|
+
response: json3,
|
|
130560
|
+
status: status2,
|
|
130561
|
+
retryAfterMs
|
|
130562
|
+
} = await fetchInternal(
|
|
130563
|
+
complianceConfig,
|
|
130564
|
+
resource,
|
|
130565
|
+
init4,
|
|
130566
|
+
pageQueryParams
|
|
130567
|
+
);
|
|
130432
130568
|
if (json3.success) {
|
|
130433
130569
|
if (currentPage === page) {
|
|
130434
130570
|
results = json3.result;
|
|
@@ -130442,7 +130578,7 @@ async function fetchCursorPage(complianceConfig, resource, init4 = {}, queryPara
|
|
|
130442
130578
|
break;
|
|
130443
130579
|
}
|
|
130444
130580
|
} else {
|
|
130445
|
-
throwFetchError(resource, json3, status2);
|
|
130581
|
+
throwFetchError(resource, json3, status2, retryAfterMs);
|
|
130446
130582
|
}
|
|
130447
130583
|
}
|
|
130448
130584
|
return results;
|
|
@@ -139422,7 +139558,7 @@ function renderEmailRoutingPlan(plan, workerName) {
|
|
|
139422
139558
|
lines.push(zone.zone_name ?? zone.zone_id);
|
|
139423
139559
|
for (const change of zone.changes) {
|
|
139424
139560
|
counts[change.type]++;
|
|
139425
|
-
const marker = CHANGE_MARKERS[change.type];
|
|
139561
|
+
const marker = CHANGE_MARKERS[change.type]();
|
|
139426
139562
|
switch (change.type) {
|
|
139427
139563
|
case "added":
|
|
139428
139564
|
case "updated":
|
|
@@ -139646,37 +139782,47 @@ async function applyEmailRoutingAddresses({
|
|
|
139646
139782
|
);
|
|
139647
139783
|
}
|
|
139648
139784
|
}
|
|
139649
|
-
const failures = [];
|
|
139650
139785
|
const totalChanges = plan.zones.reduce(
|
|
139651
139786
|
(total, zone) => total + zone.changes.length,
|
|
139652
139787
|
0
|
|
139653
139788
|
);
|
|
139654
139789
|
const progress = startApplyProgress(totalChanges);
|
|
139655
139790
|
let completedChanges = 0;
|
|
139791
|
+
const queue = new PQueue({ concurrency: APPLY_ZONE_CONCURRENCY });
|
|
139792
|
+
const failuresByZone = [];
|
|
139793
|
+
const zonePromises = [];
|
|
139656
139794
|
try {
|
|
139657
139795
|
for (const zone of plan.zones) {
|
|
139658
|
-
|
|
139659
|
-
|
|
139660
|
-
|
|
139661
|
-
|
|
139662
|
-
|
|
139663
|
-
|
|
139664
|
-
|
|
139665
|
-
|
|
139666
|
-
|
|
139667
|
-
|
|
139668
|
-
|
|
139669
|
-
|
|
139670
|
-
|
|
139671
|
-
|
|
139672
|
-
|
|
139673
|
-
|
|
139674
|
-
|
|
139675
|
-
|
|
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
|
+
);
|
|
139676
139820
|
}
|
|
139821
|
+
await Promise.all(zonePromises);
|
|
139677
139822
|
} finally {
|
|
139678
139823
|
progress.stop();
|
|
139679
139824
|
}
|
|
139825
|
+
const failures = failuresByZone.flat();
|
|
139680
139826
|
if (failures.length > 0) {
|
|
139681
139827
|
for (const failure of failures) {
|
|
139682
139828
|
logger.error(`Email Routing change failed: ${failure}`);
|
|
@@ -146393,7 +146539,7 @@ async function previewSettingsUpdate(accountId, args, config3) {
|
|
|
146393
146539
|
);
|
|
146394
146540
|
logger.log(formatPreviewsSettings(workerName, updatedPreviewDefaults));
|
|
146395
146541
|
}
|
|
146396
|
-
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;
|
|
146397
146543
|
var init_dist8 = __esm({
|
|
146398
146544
|
"../deploy-helpers/dist/index.mjs"() {
|
|
146399
146545
|
init_import_meta_url();
|
|
@@ -149345,10 +149491,10 @@ var init_dist8 = __esm({
|
|
|
149345
149491
|
__name(planHasDestructiveChanges, "planHasDestructiveChanges");
|
|
149346
149492
|
__name3(planHasDestructiveChanges, "planHasDestructiveChanges");
|
|
149347
149493
|
CHANGE_MARKERS = {
|
|
149348
|
-
added: "+",
|
|
149349
|
-
updated: "~",
|
|
149350
|
-
deleted: "-",
|
|
149351
|
-
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")
|
|
149352
149498
|
};
|
|
149353
149499
|
__name(describeRemoteAction, "describeRemoteAction");
|
|
149354
149500
|
__name3(describeRemoteAction, "describeRemoteAction");
|
|
@@ -149360,6 +149506,7 @@ var init_dist8 = __esm({
|
|
|
149360
149506
|
PLAN_RETRY_TIMEOUT_MS = 3e4;
|
|
149361
149507
|
PLAN_RETRY_DELAY_MS = 3e3;
|
|
149362
149508
|
NON_INTERACTIVE_PROGRESS_INTERVAL = 10;
|
|
149509
|
+
APPLY_ZONE_CONCURRENCY = 10;
|
|
149363
149510
|
__name(applyProgressMessage, "applyProgressMessage");
|
|
149364
149511
|
__name3(applyProgressMessage, "applyProgressMessage");
|
|
149365
149512
|
__name(startApplyProgress, "startApplyProgress");
|
|
@@ -156921,18 +157068,18 @@ var require_async = __commonJS({
|
|
|
156921
157068
|
];
|
|
156922
157069
|
}, "defaultPaths");
|
|
156923
157070
|
var defaultIsFile = /* @__PURE__ */ __name(function isFile3(file5, cb2) {
|
|
156924
|
-
fs34.stat(file5, function(err,
|
|
157071
|
+
fs34.stat(file5, function(err, stat10) {
|
|
156925
157072
|
if (!err) {
|
|
156926
|
-
return cb2(null,
|
|
157073
|
+
return cb2(null, stat10.isFile() || stat10.isFIFO());
|
|
156927
157074
|
}
|
|
156928
157075
|
if (err.code === "ENOENT" || err.code === "ENOTDIR") return cb2(null, false);
|
|
156929
157076
|
return cb2(err);
|
|
156930
157077
|
});
|
|
156931
157078
|
}, "isFile");
|
|
156932
157079
|
var defaultIsDir = /* @__PURE__ */ __name(function isDirectory4(dir4, cb2) {
|
|
156933
|
-
fs34.stat(dir4, function(err,
|
|
157080
|
+
fs34.stat(dir4, function(err, stat10) {
|
|
156934
157081
|
if (!err) {
|
|
156935
|
-
return cb2(null,
|
|
157082
|
+
return cb2(null, stat10.isDirectory());
|
|
156936
157083
|
}
|
|
156937
157084
|
if (err.code === "ENOENT" || err.code === "ENOTDIR") return cb2(null, false);
|
|
156938
157085
|
return cb2(err);
|
|
@@ -157423,21 +157570,21 @@ var require_sync = __commonJS({
|
|
|
157423
157570
|
}, "defaultPaths");
|
|
157424
157571
|
var defaultIsFile = /* @__PURE__ */ __name(function isFile3(file5) {
|
|
157425
157572
|
try {
|
|
157426
|
-
var
|
|
157573
|
+
var stat10 = fs34.statSync(file5, { throwIfNoEntry: false });
|
|
157427
157574
|
} catch (e9) {
|
|
157428
157575
|
if (e9 && (e9.code === "ENOENT" || e9.code === "ENOTDIR")) return false;
|
|
157429
157576
|
throw e9;
|
|
157430
157577
|
}
|
|
157431
|
-
return !!
|
|
157578
|
+
return !!stat10 && (stat10.isFile() || stat10.isFIFO());
|
|
157432
157579
|
}, "isFile");
|
|
157433
157580
|
var defaultIsDir = /* @__PURE__ */ __name(function isDirectory4(dir4) {
|
|
157434
157581
|
try {
|
|
157435
|
-
var
|
|
157582
|
+
var stat10 = fs34.statSync(dir4, { throwIfNoEntry: false });
|
|
157436
157583
|
} catch (e9) {
|
|
157437
157584
|
if (e9 && (e9.code === "ENOENT" || e9.code === "ENOTDIR")) return false;
|
|
157438
157585
|
throw e9;
|
|
157439
157586
|
}
|
|
157440
|
-
return !!
|
|
157587
|
+
return !!stat10 && stat10.isDirectory();
|
|
157441
157588
|
}, "isDirectory");
|
|
157442
157589
|
var defaultRealpathSync = /* @__PURE__ */ __name(function realpathSync5(x6) {
|
|
157443
157590
|
try {
|
|
@@ -160042,9 +160189,9 @@ var init_fs = __esm({
|
|
|
160042
160189
|
if (dirPath === (await destDirPromise).symbolic) return;
|
|
160043
160190
|
await prepareDirectory(path2__default__namespace.dirname(dirPath));
|
|
160044
160191
|
try {
|
|
160045
|
-
const
|
|
160046
|
-
if (
|
|
160047
|
-
if (
|
|
160192
|
+
const stat10 = await fs$1__namespace.lstat(dirPath);
|
|
160193
|
+
if (stat10.isDirectory()) return;
|
|
160194
|
+
if (stat10.isSymbolicLink()) try {
|
|
160048
160195
|
const realPath = await getRealDir(dirPath, `Symlink "${dirPath}" points outside the extraction directory.`);
|
|
160049
160196
|
if ((await fs$1__namespace.stat(realPath)).isDirectory()) return;
|
|
160050
160197
|
} catch (err) {
|
|
@@ -163409,16 +163556,16 @@ var require_windows = __commonJS({
|
|
|
163409
163556
|
return false;
|
|
163410
163557
|
}
|
|
163411
163558
|
__name(checkPathExt, "checkPathExt");
|
|
163412
|
-
function checkStat(
|
|
163413
|
-
if (!
|
|
163559
|
+
function checkStat(stat10, path89, options) {
|
|
163560
|
+
if (!stat10.isSymbolicLink() && !stat10.isFile()) {
|
|
163414
163561
|
return false;
|
|
163415
163562
|
}
|
|
163416
163563
|
return checkPathExt(path89, options);
|
|
163417
163564
|
}
|
|
163418
163565
|
__name(checkStat, "checkStat");
|
|
163419
163566
|
function isexe(path89, options, cb2) {
|
|
163420
|
-
fs34.stat(path89, function(er2,
|
|
163421
|
-
cb2(er2, er2 ? false : checkStat(
|
|
163567
|
+
fs34.stat(path89, function(er2, stat10) {
|
|
163568
|
+
cb2(er2, er2 ? false : checkStat(stat10, path89, options));
|
|
163422
163569
|
});
|
|
163423
163570
|
}
|
|
163424
163571
|
__name(isexe, "isexe");
|
|
@@ -163437,8 +163584,8 @@ var require_mode = __commonJS({
|
|
|
163437
163584
|
isexe.sync = sync2;
|
|
163438
163585
|
var fs34 = __require("fs");
|
|
163439
163586
|
function isexe(path89, options, cb2) {
|
|
163440
|
-
fs34.stat(path89, function(er2,
|
|
163441
|
-
cb2(er2, er2 ? false : checkStat(
|
|
163587
|
+
fs34.stat(path89, function(er2, stat10) {
|
|
163588
|
+
cb2(er2, er2 ? false : checkStat(stat10, options));
|
|
163442
163589
|
});
|
|
163443
163590
|
}
|
|
163444
163591
|
__name(isexe, "isexe");
|
|
@@ -163446,14 +163593,14 @@ var require_mode = __commonJS({
|
|
|
163446
163593
|
return checkStat(fs34.statSync(path89), options);
|
|
163447
163594
|
}
|
|
163448
163595
|
__name(sync2, "sync");
|
|
163449
|
-
function checkStat(
|
|
163450
|
-
return
|
|
163596
|
+
function checkStat(stat10, options) {
|
|
163597
|
+
return stat10.isFile() && checkMode(stat10, options);
|
|
163451
163598
|
}
|
|
163452
163599
|
__name(checkStat, "checkStat");
|
|
163453
|
-
function checkMode(
|
|
163454
|
-
var mod2 =
|
|
163455
|
-
var uid =
|
|
163456
|
-
var gid =
|
|
163600
|
+
function checkMode(stat10, options) {
|
|
163601
|
+
var mod2 = stat10.mode;
|
|
163602
|
+
var uid = stat10.uid;
|
|
163603
|
+
var gid = stat10.gid;
|
|
163457
163604
|
var myUid = options.uid !== void 0 ? options.uid : process.getuid && process.getuid();
|
|
163458
163605
|
var myGid = options.gid !== void 0 ? options.gid : process.getgid && process.getgid();
|
|
163459
163606
|
var u8 = parseInt("100", 8);
|
|
@@ -165793,10 +165940,13 @@ function kvNamespaceEntry({ binding, id: originalId, remote }, remoteProxyConnec
|
|
|
165793
165940
|
}
|
|
165794
165941
|
return [binding, { id, remoteProxyConnectionString }];
|
|
165795
165942
|
}
|
|
165796
|
-
function r2BucketEntry({ binding, bucket_name, remote }, remoteProxyConnectionString) {
|
|
165943
|
+
function r2BucketEntry({ binding, bucket_name, remote, local_dev }, remoteProxyConnectionString) {
|
|
165797
165944
|
const id = getRemoteId(bucket_name) ?? binding;
|
|
165798
165945
|
if (!remoteProxyConnectionString || !remote) {
|
|
165799
|
-
return [
|
|
165946
|
+
return [
|
|
165947
|
+
binding,
|
|
165948
|
+
{ id, s3Credentials: local_dev?.experimental_s3_credentials }
|
|
165949
|
+
];
|
|
165800
165950
|
}
|
|
165801
165951
|
return [binding, { id, remoteProxyConnectionString }];
|
|
165802
165952
|
}
|
|
@@ -171116,6 +171266,7 @@ function handleUserFriendlyError(error54, accountId) {
|
|
|
171116
171266
|
if (error54 instanceof APIError) switch (error54.code) {
|
|
171117
171267
|
case 9106:
|
|
171118
171268
|
case 1e4:
|
|
171269
|
+
case 10405:
|
|
171119
171270
|
throw new RemoteSessionAuthenticationError(error54);
|
|
171120
171271
|
case 10063: {
|
|
171121
171272
|
const onboardingLink = accountId ? `https://dash.cloudflare.com/${accountId}/workers/onboarding` : "https://dash.cloudflare.com/?to=/:account/workers/onboarding";
|
|
@@ -171303,7 +171454,7 @@ var init_dist12 = __esm({
|
|
|
171303
171454
|
init_wrapper();
|
|
171304
171455
|
init_create_worker_upload_form();
|
|
171305
171456
|
import_undici8 = __toESM(require_undici(), 1);
|
|
171306
|
-
version3 = "0.0.
|
|
171457
|
+
version3 = "0.0.3";
|
|
171307
171458
|
NoDefaultValueProvided2 = class extends UserError {
|
|
171308
171459
|
static {
|
|
171309
171460
|
__name(this, "NoDefaultValueProvided");
|
|
@@ -171314,7 +171465,7 @@ var init_dist12 = __esm({
|
|
|
171314
171465
|
};
|
|
171315
171466
|
__name(createRemoteBindingsAuth, "createRemoteBindingsAuth");
|
|
171316
171467
|
__name(getRemoteBindingsAuthHook, "getRemoteBindingsAuthHook");
|
|
171317
|
-
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';
|
|
171318
171469
|
__name(initLogger, "initLogger");
|
|
171319
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';
|
|
171320
171471
|
__name(castLogLevel2, "castLogLevel");
|
|
@@ -171499,11 +171650,11 @@ var init_dist12 = __esm({
|
|
|
171499
171650
|
}
|
|
171500
171651
|
/**
|
|
171501
171652
|
* @param cause - The original error that triggered the authentication
|
|
171502
|
-
* failure (e.g. an {@link APIError} with code 9106 or
|
|
171653
|
+
* failure (e.g. an {@link APIError} with code 9106, 10000, or 10405).
|
|
171503
171654
|
*/
|
|
171504
171655
|
constructor(cause) {
|
|
171505
171656
|
const envAuth = getAuthFromEnv();
|
|
171506
|
-
let errorMessage = "
|
|
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";
|
|
171507
171658
|
if (envAuth !== void 0) {
|
|
171508
171659
|
const method = "apiToken" in envAuth ? "a custom API token (`CLOUDFLARE_API_TOKEN`)" : "a Global API Key (`CLOUDFLARE_API_KEY`)";
|
|
171509
171660
|
errorMessage += `It looks like you are authenticating via ${method} set in an environment variable.
|
|
@@ -180689,10 +180840,16 @@ ${codeblock}`, options);
|
|
|
180689
180840
|
* endpoint-specific structured error payloads.
|
|
180690
180841
|
*/
|
|
180691
180842
|
meta;
|
|
180692
|
-
|
|
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 }) {
|
|
180693
180849
|
super(rest);
|
|
180694
180850
|
this.name = this.constructor.name;
|
|
180695
180851
|
this.#status = status2;
|
|
180852
|
+
this.retryAfterMs = retryAfterMs;
|
|
180696
180853
|
}
|
|
180697
180854
|
get status() {
|
|
180698
180855
|
return this.#status;
|
|
@@ -183704,8 +183861,8 @@ var init_esm6 = __esm({
|
|
|
183704
183861
|
}
|
|
183705
183862
|
return this._userIgnored(path89, stats);
|
|
183706
183863
|
}
|
|
183707
|
-
_isntIgnored(path89,
|
|
183708
|
-
return !this._isIgnored(path89,
|
|
183864
|
+
_isntIgnored(path89, stat10) {
|
|
183865
|
+
return !this._isIgnored(path89, stat10);
|
|
183709
183866
|
}
|
|
183710
183867
|
/**
|
|
183711
183868
|
* Provides a set of common helpers and properties relating to symlink handling.
|
|
@@ -220275,6 +220432,7 @@ async function fetchBrowserRendering(config3, resource, options = {}) {
|
|
|
220275
220432
|
text: `Browser Run API error: ${errorMessage}`,
|
|
220276
220433
|
notes: [{ text: `${method} ${url5} -> ${response.status}` }],
|
|
220277
220434
|
status: response.status,
|
|
220435
|
+
retryAfterMs: parseRetryAfterMs(response.headers),
|
|
220278
220436
|
telemetryMessage: false
|
|
220279
220437
|
});
|
|
220280
220438
|
}
|
|
@@ -220288,6 +220446,7 @@ async function fetchBrowserRendering(config3, resource, options = {}) {
|
|
|
220288
220446
|
{ text: `${method} ${url5} -> ${response.status}` }
|
|
220289
220447
|
],
|
|
220290
220448
|
status: response.status,
|
|
220449
|
+
retryAfterMs: parseRetryAfterMs(response.headers),
|
|
220291
220450
|
telemetryMessage: false
|
|
220292
220451
|
});
|
|
220293
220452
|
}
|
|
@@ -224888,14 +225047,24 @@ async function requestFromCmd(args, _config) {
|
|
|
224888
225047
|
if (args.useStdin) {
|
|
224889
225048
|
args.data = await read(process.stdin);
|
|
224890
225049
|
}
|
|
224891
|
-
|
|
224892
|
-
|
|
224893
|
-
|
|
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 {
|
|
224894
225061
|
...prev,
|
|
224895
|
-
[
|
|
224896
|
-
}
|
|
224897
|
-
|
|
224898
|
-
|
|
225062
|
+
[header.slice(0, separatorIndex).trim()]: header.slice(separatorIndex + 1).trim()
|
|
225063
|
+
};
|
|
225064
|
+
},
|
|
225065
|
+
{ "coordinator-request-id": requestId }
|
|
225066
|
+
);
|
|
225067
|
+
try {
|
|
224899
225068
|
const data = args.data ?? args.dataDeprecated;
|
|
224900
225069
|
const res = await request(OpenAPI, {
|
|
224901
225070
|
url: args.path,
|
|
@@ -224957,6 +225126,7 @@ var init_curl = __esm({
|
|
|
224957
225126
|
init_colors();
|
|
224958
225127
|
init_containers_shared();
|
|
224959
225128
|
init_request();
|
|
225129
|
+
init_dist();
|
|
224960
225130
|
init_create_command();
|
|
224961
225131
|
init_render_labelled_values();
|
|
224962
225132
|
init_common();
|
|
@@ -238102,13 +238272,25 @@ function createHandler2(def, argv) {
|
|
|
238102
238272
|
type: "command-failed",
|
|
238103
238273
|
version: 1,
|
|
238104
238274
|
code,
|
|
238105
|
-
message: outputErr.message
|
|
238275
|
+
message: outputErr.message,
|
|
238276
|
+
retry_after_ms: getRetryAfterMs(outputErr)
|
|
238106
238277
|
});
|
|
238107
238278
|
}
|
|
238108
238279
|
throw err;
|
|
238109
238280
|
}
|
|
238110
238281
|
}, "handler");
|
|
238111
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
|
+
}
|
|
238112
238294
|
var init_register_yargs_command = __esm({
|
|
238113
238295
|
"src/core/register-yargs-command.ts"() {
|
|
238114
238296
|
init_import_meta_url();
|
|
@@ -238138,6 +238320,7 @@ var init_register_yargs_command = __esm({
|
|
|
238138
238320
|
init_temporary_commands();
|
|
238139
238321
|
__name(createRegisterYargsCommand, "createRegisterYargsCommand");
|
|
238140
238322
|
__name(createHandler2, "createHandler");
|
|
238323
|
+
__name(getRetryAfterMs, "getRetryAfterMs");
|
|
238141
238324
|
}
|
|
238142
238325
|
});
|
|
238143
238326
|
|
|
@@ -303234,6 +303417,12 @@ var init_kv2 = __esm({
|
|
|
303234
303417
|
type: "boolean",
|
|
303235
303418
|
describe: "Interact with a preview namespace"
|
|
303236
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
|
+
},
|
|
303237
303426
|
...sharedResourceCreationArgs
|
|
303238
303427
|
},
|
|
303239
303428
|
positionalArgs: ["namespace"],
|
|
@@ -303242,15 +303431,20 @@ var init_kv2 = __esm({
|
|
|
303242
303431
|
const environment = args.env ? `${args.env}-` : "";
|
|
303243
303432
|
const preview2 = args.preview ? "_preview" : "";
|
|
303244
303433
|
const title = `${environment}${args.namespace}${preview2}`;
|
|
303434
|
+
const { jurisdiction } = args;
|
|
303245
303435
|
const accountId = await requireAuth(config3);
|
|
303246
303436
|
printResourceLocation("remote");
|
|
303247
|
-
logger2.log(
|
|
303437
|
+
logger2.log(
|
|
303438
|
+
`\u{1F300} Creating namespace with title "${title}"${jurisdiction ? ` (jurisdiction: ${jurisdiction})` : ""}`
|
|
303439
|
+
);
|
|
303248
303440
|
let namespaceId;
|
|
303249
303441
|
try {
|
|
303250
|
-
const
|
|
303442
|
+
const createParams = {
|
|
303251
303443
|
account_id: accountId,
|
|
303252
|
-
title
|
|
303253
|
-
|
|
303444
|
+
title,
|
|
303445
|
+
jurisdiction
|
|
303446
|
+
};
|
|
303447
|
+
const result = await sdk.kv.namespaces.create(createParams);
|
|
303254
303448
|
namespaceId = result.id;
|
|
303255
303449
|
} catch (e9) {
|
|
303256
303450
|
if (e9 instanceof Cloudflare.APIError && e9.errors.some((err) => err.code === 10014)) {
|
|
@@ -353886,13 +354080,13 @@ function validateBulkPutFile(filename) {
|
|
|
353886
354080
|
telemetryMessage: "r2 object bulk put entry file not found"
|
|
353887
354081
|
});
|
|
353888
354082
|
}
|
|
353889
|
-
const
|
|
353890
|
-
if (!
|
|
354083
|
+
const stat10 = fs6__namespace.default.statSync(entry.file, { throwIfNoEntry: false });
|
|
354084
|
+
if (!stat10?.isFile()) {
|
|
353891
354085
|
throw new UserError(`The path "${entry.file}" is not a file.`, {
|
|
353892
354086
|
telemetryMessage: "r2 object bulk put entry path not file"
|
|
353893
354087
|
});
|
|
353894
354088
|
}
|
|
353895
|
-
if (
|
|
354089
|
+
if (stat10.size > MAX_UPLOAD_SIZE_BYTES) {
|
|
353896
354090
|
throw new UserError(
|
|
353897
354091
|
`The file "${entry.file}" exceeds the maximum upload size of ${prettyBytes(
|
|
353898
354092
|
MAX_UPLOAD_SIZE_BYTES,
|
|
@@ -353901,7 +354095,7 @@ function validateBulkPutFile(filename) {
|
|
|
353901
354095
|
{ telemetryMessage: "r2 object bulk put entry file too large" }
|
|
353902
354096
|
);
|
|
353903
354097
|
}
|
|
353904
|
-
entry.size =
|
|
354098
|
+
entry.size = stat10.size;
|
|
353905
354099
|
}
|
|
353906
354100
|
return entries2;
|
|
353907
354101
|
}
|
|
@@ -369150,15 +369344,25 @@ ${tryRunningItIn}${oneOfThese}`
|
|
|
369150
369344
|
mayReport = false;
|
|
369151
369345
|
logBuildFailure(e9.cause.errors, e9.cause.warnings);
|
|
369152
369346
|
} else if (e9 instanceof Cloudflare.APIError) {
|
|
369153
|
-
const
|
|
369154
|
-
|
|
369155
|
-
|
|
369156
|
-
|
|
369157
|
-
|
|
369158
|
-
|
|
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({
|
|
369159
369355
|
text: "\nIf you think this is a bug, please open an issue at: https://github.com/cloudflare/workers-sdk/issues/new/choose"
|
|
369160
369356
|
});
|
|
369161
|
-
logger2.error(
|
|
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
|
+
);
|
|
369162
369366
|
} else {
|
|
369163
369367
|
if (
|
|
369164
369368
|
// Is this a StartDevEnv error event? If so, unwrap the cause, which is usually the user-recognisable error
|