@rockcarver/frodo-cli 5.0.0-19 → 5.0.0-20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/app.cjs CHANGED
@@ -11,15 +11,12 @@ let util = require("util");
11
11
  util = require_rolldown_runtime.__toESM(util, 1);
12
12
  let crypto$1 = require("crypto");
13
13
  crypto$1 = require_rolldown_runtime.__toESM(crypto$1, 1);
14
- let stream = require("stream");
15
14
  let path = require("path");
16
15
  path = require_rolldown_runtime.__toESM(path, 1);
17
- require("http");
18
16
  let fs = require("fs");
19
17
  fs = require_rolldown_runtime.__toESM(fs, 1);
20
18
  let os = require("os");
21
19
  os = require_rolldown_runtime.__toESM(os, 1);
22
- let http2 = require("http2");
23
20
  let node_crypto = require("node:crypto");
24
21
  let fs_promises = require("fs/promises");
25
22
  let node_child_process = require("node:child_process");
@@ -31,8 +28,10 @@ let node_process = require("node:process");
31
28
  node_process = require_rolldown_runtime.__toESM(node_process, 1);
32
29
  let node_os = require("node:os");
33
30
  node_os = require_rolldown_runtime.__toESM(node_os, 1);
31
+ let node_stream = require("node:stream");
34
32
  let node_http = require("node:http");
35
33
  let node_net = require("node:net");
34
+ let node_http2 = require("node:http2");
36
35
  let node_repl = require("node:repl");
37
36
  node_repl = require_rolldown_runtime.__toESM(node_repl, 1);
38
37
  let vm = require("vm");
@@ -6715,7 +6714,7 @@ async function lockTenants() {
6715
6714
  const lockStatus = await lockEnvironment(true);
6716
6715
  require_Console.printMessage({
6717
6716
  status: lockStatus.result,
6718
- Promotionid: lockStatus.promotionId
6717
+ promotionId: lockStatus.promotionId
6719
6718
  }, "data");
6720
6719
  return true;
6721
6720
  } catch (error) {
@@ -6725,7 +6724,7 @@ async function lockTenants() {
6725
6724
  }
6726
6725
  /**
6727
6726
  * Unlock tenants and wait until they are unlocked.
6728
- * @param {string} promotionId Promotion ID associated with the lock.
6727
+ * @param {string} promotionId Optional promotion ID associated with the lock. If not specified, it is read from the environment lock status.
6729
6728
  * @returns {Promise<boolean>} True if tenants were successfully unlocked, false otherwise.
6730
6729
  */
6731
6730
  async function unlockTenants(promotionId) {
@@ -6945,7 +6944,7 @@ const { CLOUD_DEPLOYMENT_TYPE_KEY: CLOUD_DEPLOYMENT_TYPE_KEY$160 } = require_Con
6945
6944
  const deploymentTypes$171 = [CLOUD_DEPLOYMENT_TYPE_KEY$160];
6946
6945
  function setup$326() {
6947
6946
  const program = new require_FrodoCommand.FrodoCommand("frodo config-manager promote unlock-tenants", [], deploymentTypes$171);
6948
- program.description("Unlock tenants and wait until they are unlocked.").requiredOption("-i, --id <id>", "Promotion ID associated with the lock.").addHelpText("after", "Usage Examples:\n Unlock the environments after a promotion and wait until they are unlocked (the ID is the promotion ID that lock-tenants printed):\n" + require_Console.theme.command(` $ frodo config-manager promote unlock-tenants --id 1d9ac1b3-b9a0-46d5-8d8c-0f3f2a1f8a21 ${connId}\n`)).action(async (host, realm, user, password, options, command) => {
6947
+ program.description("Unlock tenants and wait until they are unlocked.").option("-i, --id <id>", "Promotion ID associated with the lock. If not specified, it is read from the lock status of the environment.").addHelpText("after", "Usage Examples:\n Unlock the environments after a promotion and wait until they are unlocked (the promotion ID is read from the lock status):\n" + require_Console.theme.command(` $ frodo config-manager promote unlock-tenants ${connId}\n`) + ` Unlock the environments of a specific promotion (the ID is the promotion ID that lock-tenants printed):\n` + require_Console.theme.command(` $ frodo config-manager promote unlock-tenants --id 1d9ac1b3-b9a0-46d5-8d8c-0f3f2a1f8a21 ${connId}\n`)).action(async (host, realm, user, password, options, command) => {
6949
6948
  command.handleDefaultArgsAndOpts(host, realm, user, password, options, command);
6950
6949
  if (!await require_FrodoCommand.getTokens(false, true, deploymentTypes$171)) {
6951
6950
  process.exitCode = 1;
@@ -9585,7 +9584,7 @@ async function configManagerImportTermsAndConditions() {
9585
9584
  }
9586
9585
  //#endregion
9587
9586
  //#region src/configManagerOps/FrConfigThemeOps.ts
9588
- const { saveJsonToFile: saveJsonToFile$16, getFilePath: getFilePath$17, constants: constants$3 } = require_Console.frodo.utils;
9587
+ const { saveJsonToFile: saveJsonToFile$16, getFilePath: getFilePath$17, constants: constants$4 } = require_Console.frodo.utils;
9589
9588
  const { readRealms, readRealmByName } = require_Console.frodo.realm;
9590
9589
  const { readThemes, importThemes } = require_Console.frodo.theme;
9591
9590
  const THEME_HTML_FIELDS = [
@@ -9642,7 +9641,7 @@ function extractHtmlFields(theme, themePath) {
9642
9641
  }
9643
9642
  async function configManagerExportThemes(realm) {
9644
9643
  try {
9645
- const realmNames = realm && realm !== constants$3.DEFAULT_REALM_KEY ? [realm] : await realmList();
9644
+ const realmNames = realm && realm !== constants$4.DEFAULT_REALM_KEY ? [realm] : await realmList();
9646
9645
  for (const realm of realmNames) {
9647
9646
  if (realm === "/") continue;
9648
9647
  require_Console.state.setRealm(realm);
@@ -9664,7 +9663,7 @@ async function configManagerExportThemes(realm) {
9664
9663
  }
9665
9664
  async function configManagerImportThemes(realm) {
9666
9665
  try {
9667
- const realms = realm && realm !== constants$3.DEFAULT_REALM_KEY ? [await readRealmByName(realm)] : await readRealms();
9666
+ const realms = realm && realm !== constants$4.DEFAULT_REALM_KEY ? [await readRealmByName(realm)] : await readRealms();
9668
9667
  for (const realm of realms) {
9669
9668
  if (realm.name === "/") continue;
9670
9669
  require_Console.state.setRealm(realm.name);
@@ -10542,14 +10541,14 @@ function setup$301() {
10542
10541
  //#region src/cli/config-manager/config-manager-pull/config-manager-pull-org-privileges.ts
10543
10542
  const { CLOUD_DEPLOYMENT_TYPE_KEY: CLOUD_DEPLOYMENT_TYPE_KEY$134, FORGEOPS_DEPLOYMENT_TYPE_KEY: FORGEOPS_DEPLOYMENT_TYPE_KEY$91 } = require_Console.frodo.utils.constants;
10544
10543
  const deploymentTypes$149 = [CLOUD_DEPLOYMENT_TYPE_KEY$134, FORGEOPS_DEPLOYMENT_TYPE_KEY$91];
10545
- const { constants: constants$2 } = require_Console.frodo.utils;
10544
+ const { constants: constants$3 } = require_Console.frodo.utils;
10546
10545
  function setup$300() {
10547
10546
  const program = new require_FrodoCommand.FrodoCommand("frodo config-manager pull org-privileges", [], deploymentTypes$149);
10548
10547
  program.description("Export organization privileges config.").action(async (host, realm, user, password, options, command) => {
10549
10548
  command.handleDefaultArgsAndOpts(host, realm, user, password, options, command);
10550
10549
  if (await require_FrodoCommand.getTokens(false, true, deploymentTypes$149)) {
10551
10550
  let outcome;
10552
- if (realm !== constants$2.DEFAULT_REALM_KEY) {
10551
+ if (realm !== constants$3.DEFAULT_REALM_KEY) {
10553
10552
  require_Console.printMessage(`Exporting organization privileges config from the realm: "${realm}"`);
10554
10553
  outcome = await configManagerExportOrgPrivileges() && await configManagerExportOrgPrivilegesRealm(realm);
10555
10554
  } else {
@@ -12020,7 +12019,7 @@ async function importEntityfromFile(file, global = false, options = {
12020
12019
  //#region src/cli/config/config-export.ts
12021
12020
  function setup$238() {
12022
12021
  const program = new require_FrodoCommand.FrodoCommand("frodo config export");
12023
- program.description("Export full cloud configuration.\nBy default, it only exports importable config (i.e. config that is not read-only) for the current deployment (e.g. if exporting from cloud, realm config would NOT be exported since it can't be imported back into cloud even though it can be imported into classic deployments). There is a flag to export all config including read only config.\nAdditionally, there is a flag to export config for only the specified realm, a flag to export only global config, and many other flags to customize the export. Use the -h or --help to see them all and to also see usage examples.").addOption(new require_FrodoCommand.Option("-f, --file <file>", "Name of the export file. Cannot be used with -A.").conflicts(["allSeparate"])).addOption(new require_FrodoCommand.Option("-a, --all", "Export everything to a single file. Cannot be used with -A.").conflicts(["allSeparate"])).addOption(new require_FrodoCommand.Option("-A, --all-separate", "Export everything to separate files in the -D directory. Cannot be used with -f or -a.").conflicts(["file", "all"])).addOption(new require_FrodoCommand.Option("--use-string-arrays", "Where applicable, use string arrays to store multi-line text (e.g. scripts).").default(false, "off")).addOption(new require_FrodoCommand.Option("--no-decode", "Do not include decoded variable value in variable export").default(false, "false")).addOption(new require_FrodoCommand.Option("-x, --no-extract", "Do not extract scripts and server properties from the exported file to a separate file.").default(true, "true")).addOption(new require_FrodoCommand.Option("-N, --no-metadata", "Does not include metadata in the export file.")).addOption(new require_FrodoCommand.Option("-M, --modified-properties", "Include modified properties in export (e.g. lastModifiedDate, lastModifiedBy, createdBy, creationDate, etc.)").default(false, "false")).addOption(new require_FrodoCommand.Option("--no-coords", "Do not include the x and y coordinate positions of the journey/tree nodes.")).addOption(new require_FrodoCommand.Option("-d, --default", "Export all scripts including the default scripts.")).addOption(new require_FrodoCommand.Option("-R, --read-only", "Export read-only config (with the exception of default scripts) in addition to the importable config. On Identity Cloud this adds a root realm, which holds read-only authorization config.")).addOption(new require_FrodoCommand.Option("-r, --realm-only", "Export only the config for the active realm (on Identity Cloud alpha, unless you name another realm after the host). If -g, --global-only is also active, then the global config will also be exported.")).addOption(new require_FrodoCommand.Option("-g, --global-only", "Export only the global config. If -r, --realm-only is also active, then the corresponding active realm config will also be exported.")).addOption(new require_FrodoCommand.Option("-s, --separate-mappings", "Export sync.idm.json mappings separately in their own directory. Cannot be used with -a.").conflicts(["all"])).addOption(new require_FrodoCommand.Option("-o, --separate-objects", "Export managed.idm.json objects separately in their own directory. Cannot be used with -a.").conflicts(["all"])).addOption(new require_FrodoCommand.Option("--include-active-values", "Include the currently active (and loaded) secret value in the export. By default, secret values are encrypted server-side in the environment they are exported from. Use --target <host url> to have another environment perform the encryption.")).addOption(new require_FrodoCommand.Option("--target <host url>", "Host URL of the environment to perform secret value encryption. The URL must resolve to an existing connection profile. Use this option to generate an export that can be imported into the target environment without requiring admin access to the source environment.")).addOption(new require_FrodoCommand.Option("-c, --only-custom", "Only export custom request types (IGA cloud deployments only).")).addOption(new require_FrodoCommand.Option("--static", "Export only static configuration: what an environment promotion carries (journeys, scripts, themes and the like). With --dynamic it exports both, which is also what happens without either.")).addOption(new require_FrodoCommand.Option("--dynamic", "Export only dynamic configuration: what changes at run time (OAuth2 clients, agents, policies, SAML providers, ESVs and the like). With --static it exports both, which is also what happens without either.")).addHelpText("after", require_Console.theme.positive(`How Frodo handles secrets:\n`) + require_Console.theme.positive(` Frodo supports exporting and importing of ESV secret values. To leave stuartship of secret values with the cloud environment where they belong, frodo always encrypts values using either encryption keys from the source environment (default) or the target environment (--target parameter). Frodo never exports secrets in the clear.\n\n`) + require_Console.theme.positive(`Realms on Identity Cloud:\n`) + " A default export holds the global config and the alpha and bravo realms. Identity Cloud denies access to most root realm config, so the root realm is only exported with -R, --read-only, and then only as read-only authorization config (policies, policy sets, resource types and the like).\n Use -r to limit the export to the active realm and -g to limit it to the global config. Use both for the global config plus the active realm.\n\nUsage Examples:\n Export global and realm configuration for version control (e.g. Git) into the current directory.\n Note that -A exports everything to separate files in the -D directory and, unless you add -x (--no-extract), scripts and server properties are extracted into files of their own, which makes changes to them easier to track, and -N removes metadata since it changes every export (you may consider using --no-coords as well if you don't care to track node positions in journeys):\n" + require_Console.theme.command(` $ frodo config export -AND . ${connId}\n`) + ` Export the global config and only the active realm for version control (on Identity Cloud the active realm is alpha unless you name another one after the connection profile, for example bravo):\n` + require_Console.theme.command(` $ frodo config export -rgAND . ${connId}\n`) + " Export global and realm configuration from cloud to be later imported into a classic, on-prem deployment.\n Note -dR is used for exporting all read-only config from cloud since certain cloud read-only config (like the realm config) can be imported into a classic on-prem deployment:\n" + require_Console.theme.command(` $ frodo config export -adR ${connId}\n`) + ` Export only the bravo realm configuration:\n` + require_Console.theme.command(` $ frodo config export -ar ${connId} bravo\n`) + ` Export only the static configuration, the part an environment promotion carries, to a single file:\n` + require_Console.theme.command(` $ frodo config export -a --static ${connId}\n`) + ` Export only the dynamic configuration, the part that changes at run time:\n` + require_Console.theme.command(` $ frodo config export -a --dynamic ${connId}\n`) + ` Backup global and realm configuration including active secret values to a single file (Note: only values of active and loaded secrets can be exported):\n` + require_Console.theme.command(` $ frodo config export -a --include-active-values ${connId}\n`) + ` Backup global and realm configuration including active secret values to individual files in a directory structure (Note: only values of active and loaded secrets can be exported):\n` + require_Console.theme.command(` $ frodo config export -A -D ${connId}-backup --include-active-values ${connId}\n`) + " Export global and realm configuration including active secret values for import into another environment.\n The --target parameter instructs frodo to encrypt the exported secret values using the target environment so they can be imported into that target environment without requiring the source environment they were exported from.\n Using the --target parameter, the target environment must be available at the time of export and the person performing the export must have a connection profile for the target environment.\n Without the --target parameter, the source environment must be available at the time of import and the person performing the import must have a connection profile for the source environment.\n" + require_Console.theme.command(` $ frodo config export -a --include-active-values --target ${connId2} ${connId}\n`)).requireOneOf({
12022
+ program.description("Export full cloud configuration.\nBy default, it only exports importable config (i.e. config that is not read-only) for the current deployment (e.g. if exporting from cloud, realm config would NOT be exported since it can't be imported back into cloud even though it can be imported into classic deployments). There is a flag to export all config including read only config.\nAdditionally, there is a flag to export config for only the specified realm, a flag to export only global config, and many other flags to customize the export. Use the -h or --help to see them all and to also see usage examples.").addOption(new require_FrodoCommand.Option("-f, --file <file>", "Name of the export file. Cannot be used with -A.").conflicts(["allSeparate"])).addOption(new require_FrodoCommand.Option("-a, --all", "Export everything to a single file. Cannot be used with -A.").conflicts(["allSeparate"])).addOption(new require_FrodoCommand.Option("-A, --all-separate", "Export everything to separate files in the -D directory. Cannot be used with -f or -a.").conflicts(["file", "all"])).addOption(new require_FrodoCommand.Option("--use-string-arrays", "Where applicable, use string arrays to store multi-line text (e.g. scripts).").default(false, "off")).addOption(new require_FrodoCommand.Option("--no-decode", "Do not include decoded variable value in variable export").default(false, "false")).addOption(new require_FrodoCommand.Option("-x, --no-extract", "Do not extract scripts and server properties from the exported file to a separate file.").default(true, "true")).addOption(new require_FrodoCommand.Option("-N, --no-metadata", "Does not include metadata in the export file.")).addOption(new require_FrodoCommand.Option("-M, --modified-properties", "Include modified properties in export (e.g. lastModifiedDate, lastModifiedBy, createdBy, creationDate, etc.)").default(false, "false")).addOption(new require_FrodoCommand.Option("--no-coords", "Do not include the x and y coordinate positions of the journey/tree nodes.")).addOption(new require_FrodoCommand.Option("-d, --default", "Export all scripts including the default scripts.")).addOption(new require_FrodoCommand.Option("-R, --read-only", "Export read-only config (with the exception of default scripts) in addition to the importable config. On Identity Cloud this adds a root realm, which holds read-only authorization config.")).addOption(new require_FrodoCommand.Option("-r, --realm-only", "Export only the config for the active realm (on Identity Cloud alpha, unless you name another realm after the host). If -g, --global-only is also active, then the global config will also be exported.")).addOption(new require_FrodoCommand.Option("-g, --global-only", "Export only the global config. If -r, --realm-only is also active, then the corresponding active realm config will also be exported.")).addOption(new require_FrodoCommand.Option("-s, --separate-mappings", "Export sync.idm.json mappings separately in their own directory. Cannot be used with -a.").conflicts(["all"])).addOption(new require_FrodoCommand.Option("-o, --separate-objects", "Export managed.idm.json objects separately in their own directory. Cannot be used with -a.").conflicts(["all"])).addOption(new require_FrodoCommand.Option("--include-active-values", "Include the currently active (and loaded) secret value in the export. By default, secret values are encrypted server-side in the environment they are exported from. Use --target <host url> to have another environment perform the encryption.")).addOption(new require_FrodoCommand.Option("--target <host url>", "Host URL of the environment to perform secret value encryption. The URL must resolve to an existing connection profile. Use this option to generate an export that can be imported into the target environment without requiring admin access to the source environment.")).addOption(new require_FrodoCommand.Option("-c, --only-custom", "Only export custom request types (IGA cloud deployments only).")).addOption(new require_FrodoCommand.Option("--static", "Export only static configuration: what an environment promotion carries (journeys, scripts, themes and the like). With --dynamic it exports both, which is also what happens without either.")).addOption(new require_FrodoCommand.Option("--dynamic", "Export only dynamic configuration: everything that is not static, which is what an environment promotion does not carry (OAuth2 clients, agents, policies, SAML providers, ESVs and the like). With --static it exports both, which is also what happens without either.")).addHelpText("after", require_Console.theme.positive(`How Frodo handles secrets:\n`) + require_Console.theme.positive(` Frodo supports exporting and importing of ESV secret values. To leave stuartship of secret values with the cloud environment where they belong, frodo always encrypts values using either encryption keys from the source environment (default) or the target environment (--target parameter). Frodo never exports secrets in the clear.\n\n`) + require_Console.theme.positive(`Realms on Identity Cloud:\n`) + " A default export holds the global config and the alpha and bravo realms. Identity Cloud denies access to most root realm config, so the root realm is only exported with -R, --read-only, and then only as read-only authorization config (policies, policy sets, resource types and the like).\n Use -r to limit the export to the active realm and -g to limit it to the global config. Use both for the global config plus the active realm.\n\nUsage Examples:\n Export global and realm configuration for version control (e.g. Git) into the current directory.\n Note that -A exports everything to separate files in the -D directory and, unless you add -x (--no-extract), scripts and server properties are extracted into files of their own, which makes changes to them easier to track, and -N removes metadata since it changes every export (you may consider using --no-coords as well if you don't care to track node positions in journeys):\n" + require_Console.theme.command(` $ frodo config export -AND . ${connId}\n`) + ` Export the global config and only the active realm for version control (on Identity Cloud the active realm is alpha unless you name another one after the connection profile, for example bravo):\n` + require_Console.theme.command(` $ frodo config export -rgAND . ${connId}\n`) + " Export global and realm configuration from cloud to be later imported into a classic, on-prem deployment.\n Note -dR is used for exporting all read-only config from cloud since certain cloud read-only config (like the realm config) can be imported into a classic on-prem deployment:\n" + require_Console.theme.command(` $ frodo config export -adR ${connId}\n`) + ` Export only the bravo realm configuration:\n` + require_Console.theme.command(` $ frodo config export -ar ${connId} bravo\n`) + ` Export only the static configuration, the part an environment promotion carries, to a single file:\n` + require_Console.theme.command(` $ frodo config export -a --static ${connId}\n`) + ` Export only the dynamic configuration, everything a promotion does not carry:\n` + require_Console.theme.command(` $ frodo config export -a --dynamic ${connId}\n`) + ` Backup global and realm configuration including active secret values to a single file (Note: only values of active and loaded secrets can be exported):\n` + require_Console.theme.command(` $ frodo config export -a --include-active-values ${connId}\n`) + ` Backup global and realm configuration including active secret values to individual files in a directory structure (Note: only values of active and loaded secrets can be exported):\n` + require_Console.theme.command(` $ frodo config export -A -D ${connId}-backup --include-active-values ${connId}\n`) + " Export global and realm configuration including active secret values for import into another environment.\n The --target parameter instructs frodo to encrypt the exported secret values using the target environment so they can be imported into that target environment without requiring the source environment they were exported from.\n Using the --target parameter, the target environment must be available at the time of export and the person performing the export must have a connection profile for the target environment.\n Without the --target parameter, the source environment must be available at the time of import and the person performing the import must have a connection profile for the source environment.\n" + require_Console.theme.command(` $ frodo config export -a --include-active-values --target ${connId2} ${connId}\n`)).requireOneOf({
12024
12023
  options: ["all", "allSeparate"],
12025
12024
  purpose: "what to export"
12026
12025
  }).action(async (host, realm, user, password, options, command) => {
@@ -12069,7 +12068,7 @@ function setup$238() {
12069
12068
  //#region src/cli/config/config-import.ts
12070
12069
  function setup$237() {
12071
12070
  const program = new require_FrodoCommand.FrodoCommand("frodo config import");
12072
- program.description("Import full cloud configuration.").addOption(new require_FrodoCommand.Option("-f, --file <file>", "Name of the file to import. Cannot be used with -A. If included without -a, it will import the single entity within the file.").conflicts(["allSeparate"])).addOption(new require_FrodoCommand.Option("-a, --all", "Import all configuration from the single file -f. Cannot be used with -A.").conflicts(["allSeparate"])).addOption(new require_FrodoCommand.Option("-A, --all-separate", "Import all configuration from separate (.json) files in the (working) directory -D. Cannot be used with -f or -a.").conflicts(["file", "all"])).addOption(new require_FrodoCommand.Option("-C, --clean", "Remove existing service(s) before importing.")).addOption(new require_FrodoCommand.Option("--re-uuid-journeys", "Generate new UUIDs for all journey nodes during import.").default(false, "off")).addOption(new require_FrodoCommand.Option("--re-uuid-scripts", "Create new UUIDs for the scripts upon import. Use this to duplicate scripts or create a new versions of the same scripts.").default(false, "off")).addOption(new require_FrodoCommand.Option("--re-uuid-custom-nodes", "Create new UUIDs for the custom nodes upon import. Use this to duplicate custom nodes or create a new versions of the same custom nodes.").default(false, "off")).addOption(new require_FrodoCommand.Option("-d, --default", "Import all scripts including the default scripts.")).addOption(new require_FrodoCommand.Option("-c, --only-custom", "Only import custom request types (IGA cloud deployments only).")).addOption(new require_FrodoCommand.Option("--include-active-values", "Import any secret values contained in the import file. By default, secret values are encrypted server-side in the environment they are exported from. Use --source <host url> to import a file exported from another environment than the one you are importing to.")).addOption(new require_FrodoCommand.Option("--no-validate", "Do not validate journeys during import.")).addOption(new require_FrodoCommand.Option("--source <host url>", "Host URL of the environment which performed secret value encryption. The URL must resolve to an existing connection profile. Use this option to import a file that was exported from a different source environment than the one you are importing to.")).addOption(new require_FrodoCommand.Option("-g, --global", "Import global entity. Cannot be used with -a or -A.").conflicts(["all", "allSeparate"])).addOption(new require_FrodoCommand.Option("--static", "Import only static configuration: what an environment promotion carries (journeys, scripts, themes and the like). With --dynamic it imports both, which is also what happens without either.")).addOption(new require_FrodoCommand.Option("--dynamic", "Import only dynamic configuration: what changes at run time (OAuth2 clients, agents, policies, SAML providers, ESVs and the like). With --static it imports both, which is also what happens without either.")).addHelpText("after", require_Console.theme.positive(`How Frodo handles secrets:\n`) + require_Console.theme.positive(` Frodo supports exporting and importing of ESV secret values. To leave stuartship of secret values with the cloud environment where they belong, frodo always encrypts values using either encryption keys from the source environment (default) or the target environment (--target parameter). Frodo never exports secrets in the clear.\n\n`) + require_Console.theme.positive(`Realms on Identity Cloud:\n`) + " Frodo imports every realm it finds in the export. An export made with -R, --read-only contains a root realm, and importing it makes Frodo attempt the root realm of the target. Identity Cloud denies access to most root realm config.\n To leave the root realm out, import an export made without -R (on Identity Cloud that holds the global config and the alpha and bravo realms) or remove the realm/root directory.\n\nUsage Examples:\n Restore global and active realm configuration including active secret values from a single file (Note: config export must have been performed using the --include-active-values option):\n" + require_Console.theme.command(` $ frodo config import -a -f Alpha.everything.json --include-active-values ${connId}\n`) + ` Restore global and active realm configuration including active secret values from separate files in a directory structure (Note: config export must have been performed using the --include-active-values option):\n` + require_Console.theme.command(` $ frodo config import -A -D ${connId}-backup --include-active-values ${connId}\n`) + ` Import the global config and the realm from a directory that was exported for version control, for example with frodo config export -rgAND (see the examples of that command):\n` + require_Console.theme.command(` $ frodo config import -A -D . ${connId}\n`) + ` Import only the static configuration, the part an environment promotion carries, from a single file:\n` + require_Console.theme.command(` $ frodo config import -a -f Alpha.everything.json --static ${connId}\n`) + ` Import only the dynamic configuration, the part that changes at run time:\n` + require_Console.theme.command(` $ frodo config import -a -f Alpha.everything.json --dynamic ${connId}\n`) + " Import global and active realm configuration including active secret values, wich were exported from another environment using the --include-active-values option but without using the --target parameter, therefore requiring the --source parameter on import:\n The --source parameter instructs frodo to decrypt the secret values during import using the source environment, which was used to encrypt them.\n Using the --source parameter, the source environment must be available at the time of import and the person performing the import must have a connection profile for the source environment.\n" + require_Console.theme.command(` $ frodo config import -a -f Alpha.everything.json --include-active-values --source ${connId} ${connId2}\n`)).requireOneOf({
12071
+ program.description("Import full cloud configuration.").addOption(new require_FrodoCommand.Option("-f, --file <file>", "Name of the file to import. Cannot be used with -A. If included without -a, it will import the single entity within the file.").conflicts(["allSeparate"])).addOption(new require_FrodoCommand.Option("-a, --all", "Import all configuration from the single file -f. Cannot be used with -A.").conflicts(["allSeparate"])).addOption(new require_FrodoCommand.Option("-A, --all-separate", "Import all configuration from separate (.json) files in the (working) directory -D. Cannot be used with -f or -a.").conflicts(["file", "all"])).addOption(new require_FrodoCommand.Option("-C, --clean", "Remove existing service(s) before importing.")).addOption(new require_FrodoCommand.Option("--re-uuid-journeys", "Generate new UUIDs for all journey nodes during import.").default(false, "off")).addOption(new require_FrodoCommand.Option("--re-uuid-scripts", "Create new UUIDs for the scripts upon import. Use this to duplicate scripts or create a new versions of the same scripts.").default(false, "off")).addOption(new require_FrodoCommand.Option("--re-uuid-custom-nodes", "Create new UUIDs for the custom nodes upon import. Use this to duplicate custom nodes or create a new versions of the same custom nodes.").default(false, "off")).addOption(new require_FrodoCommand.Option("-d, --default", "Import all scripts including the default scripts.")).addOption(new require_FrodoCommand.Option("-c, --only-custom", "Only import custom request types (IGA cloud deployments only).")).addOption(new require_FrodoCommand.Option("--include-active-values", "Import any secret values contained in the import file. By default, secret values are encrypted server-side in the environment they are exported from. Use --source <host url> to import a file exported from another environment than the one you are importing to.")).addOption(new require_FrodoCommand.Option("--no-validate", "Do not validate journeys during import.")).addOption(new require_FrodoCommand.Option("--source <host url>", "Host URL of the environment which performed secret value encryption. The URL must resolve to an existing connection profile. Use this option to import a file that was exported from a different source environment than the one you are importing to.")).addOption(new require_FrodoCommand.Option("-g, --global", "Import global entity. Cannot be used with -a or -A.").conflicts(["all", "allSeparate"])).addOption(new require_FrodoCommand.Option("--static", "Import only static configuration: what an environment promotion carries (journeys, scripts, themes and the like). With --dynamic it imports both, which is also what happens without either.")).addOption(new require_FrodoCommand.Option("--dynamic", "Import only dynamic configuration: everything that is not static, which is what an environment promotion does not carry (OAuth2 clients, agents, policies, SAML providers, ESVs and the like). With --static it imports both, which is also what happens without either.")).addHelpText("after", require_Console.theme.positive(`How Frodo handles secrets:\n`) + require_Console.theme.positive(` Frodo supports exporting and importing of ESV secret values. To leave stuartship of secret values with the cloud environment where they belong, frodo always encrypts values using either encryption keys from the source environment (default) or the target environment (--target parameter). Frodo never exports secrets in the clear.\n\n`) + require_Console.theme.positive(`Realms on Identity Cloud:\n`) + " Frodo imports every realm it finds in the export. An export made with -R, --read-only contains a root realm, and importing it makes Frodo attempt the root realm of the target. Identity Cloud denies access to most root realm config.\n To leave the root realm out, import an export made without -R (on Identity Cloud that holds the global config and the alpha and bravo realms) or remove the realm/root directory.\n\nUsage Examples:\n Restore global and active realm configuration including active secret values from a single file (Note: config export must have been performed using the --include-active-values option):\n" + require_Console.theme.command(` $ frodo config import -a -f Alpha.everything.json --include-active-values ${connId}\n`) + ` Restore global and active realm configuration including active secret values from separate files in a directory structure (Note: config export must have been performed using the --include-active-values option):\n` + require_Console.theme.command(` $ frodo config import -A -D ${connId}-backup --include-active-values ${connId}\n`) + ` Import the global config and the realm from a directory that was exported for version control, for example with frodo config export -rgAND (see the examples of that command):\n` + require_Console.theme.command(` $ frodo config import -A -D . ${connId}\n`) + ` Import only the static configuration, the part an environment promotion carries, from a single file:\n` + require_Console.theme.command(` $ frodo config import -a -f Alpha.everything.json --static ${connId}\n`) + ` Import only the dynamic configuration, everything a promotion does not carry:\n` + require_Console.theme.command(` $ frodo config import -a -f Alpha.everything.json --dynamic ${connId}\n`) + " Import global and active realm configuration including active secret values, wich were exported from another environment using the --include-active-values option but without using the --target parameter, therefore requiring the --source parameter on import:\n The --source parameter instructs frodo to decrypt the secret values during import using the source environment, which was used to encrypt them.\n Using the --source parameter, the source environment must be available at the time of import and the person performing the import must have a connection profile for the source environment.\n" + require_Console.theme.command(` $ frodo config import -a -f Alpha.everything.json --include-active-values --source ${connId} ${connId2}\n`)).requireOneOf({
12073
12072
  options: [
12074
12073
  "all",
12075
12074
  "allSeparate",
@@ -20468,7 +20467,7 @@ function setup$110() {
20468
20467
  }
20469
20468
  //#endregion
20470
20469
  //#region src/ops/LoginSetupOps.ts
20471
- const constants$1 = require_Console.frodo.utils.constants;
20470
+ const constants$2 = require_Console.frodo.utils.constants;
20472
20471
  const { client: { readOAuth2Client, createOAuth2Client, updateOAuth2Client } } = require_Console.frodo.oauth2oidc;
20473
20472
  const { readScript, createScript, updateScript } = require_Console.frodo.script;
20474
20473
  const { getInfo } = require_Console.frodo.info;
@@ -20652,7 +20651,7 @@ function buildDesiredClient(existing, options, resolved) {
20652
20651
  */
20653
20652
  async function setupBrowserLogin(options) {
20654
20653
  const deploymentType = require_Console.state.getDeploymentType();
20655
- if (deploymentType === constants$1.CLOUD_DEPLOYMENT_TYPE_KEY) {
20654
+ if (deploymentType === constants$2.CLOUD_DEPLOYMENT_TYPE_KEY) {
20656
20655
  require_Console.printMessage("Cloud needs no setup — it uses a fixed, built-in OAuth2 client. `login setup` only applies to forgeops and classic.", "warn");
20657
20656
  return false;
20658
20657
  }
@@ -20704,11 +20703,11 @@ async function setupBrowserLogin(options) {
20704
20703
  }
20705
20704
  //#endregion
20706
20705
  //#region src/cli/login/login-setup.ts
20707
- const constants = require_Console.frodo.utils.constants;
20706
+ const constants$1 = require_Console.frodo.utils.constants;
20708
20707
  /** Used when --login-client-id is omitted. */
20709
20708
  const DEFAULT_LOGIN_CLIENT_ID = "frodo-browser-login";
20710
20709
  function setup$109() {
20711
- const program = new require_FrodoCommand.FrodoCommand("frodo login setup", ["realm"], [constants.FORGEOPS_DEPLOYMENT_TYPE_KEY, constants.CLASSIC_DEPLOYMENT_TYPE_KEY]);
20710
+ const program = new require_FrodoCommand.FrodoCommand("frodo login setup", ["realm"], [constants$1.FORGEOPS_DEPLOYMENT_TYPE_KEY, constants$1.CLASSIC_DEPLOYMENT_TYPE_KEY]);
20712
20711
  program.mergeHeadingIntoOptions(require_FrodoCommand.AUTHENTICATION_OPTIONS_HEADING);
20713
20712
  const shortSummary = "Setup a forgeops or classic deployment with an OAuth2 client and session-capture script for --browser/--device login.";
20714
20713
  program.summary(shortSummary).description(`${shortSummary}\n\nCloud needs no setup. --login-client-id defaults to "${DEFAULT_LOGIN_CLIENT_ID}" if omitted; --login-redirect-uri defaults to a wildcard loopback pattern matching any local port (if the target AM's version supports it) or a fixed URI otherwise — pass --login-redirect-uri explicitly to force a specific value. This is an ordinary (non-interactive) admin login, not a --browser login itself — a host with a saved connection profile (identified by its full URL, a unique substring, or a saved alias) works with no extra arguments; a brand-new host with no saved profile yet needs a username/password (or service account) on the command line. See docs/BROWSER_LOGIN.md.`).addOption(new require_FrodoCommand.Option("--login-scope <scope>", "OAuth2 scope for the client. Defaults per deployment type: \nforgeops: \"openid fr:idm:*\" \nclassic: \"openid\"")).addOption(new require_FrodoCommand.Option("--script-id <script-id>", "Script id for the session-capture script. Defaults to \"<login-client-id>-session-capture\".")).addOption(new require_FrodoCommand.Option("--script-name <script-name>", "Display name for the session-capture script.").default("Frodo Browser Login Session Capture")).addOption(new require_FrodoCommand.Option("--yes", "Skip the confirmation prompt and apply changes immediately.").default(false)).addHelpText("after", `Usage Examples:\n Shortest form — a host with an already-saved connection profile (identified by a unique substring or alias), which already remembers its own deployment type, so --type isn't needed either; also picks up the default client id "${DEFAULT_LOGIN_CLIENT_ID}" and a wildcard loopback redirect URI if the target AM supports it:\n` + require_Console.theme.command(` $ frodo login setup ${connId}\n`) + ` Same, spelled out with the full host URL and an explicit --type (equivalent when a saved profile already exists for it):\n` + require_Console.theme.command(` $ frodo login setup --type forgeops ${amBaseUrl}\n`) + ` A brand-new host with no saved connection profile yet — needs a username/password (or service account) and --type, since there's no saved profile to infer either from:\n` + require_Console.theme.command(` $ frodo login setup --type forgeops ${amBaseUrl} ${username} '${password}'\n`) + ` Pick your own client id, and also enable the device authorization grant on it:\n` + require_Console.theme.command(` $ frodo login setup --device --login-client-id ${loginClientId} ${connId}\n`) + ` Force a fixed, exact redirect URI instead of the auto-detected wildcard loopback pattern:\n` + require_Console.theme.command(` $ frodo login setup --login-redirect-uri http://127.0.0.1:8080/callback ${connId}\n`) + ` Then log in (omit --login-redirect-uri too, if the wildcard pattern was used):\n` + require_Console.theme.command(` $ frodo login --browser --login-client-id ${DEFAULT_LOGIN_CLIENT_ID} --type forgeops ${connId}\n`)).action(async (host, user, password, options, command) => {
@@ -20718,7 +20717,7 @@ function setup$109() {
20718
20717
  return;
20719
20718
  }
20720
20719
  const clientId = options.loginClientId || DEFAULT_LOGIN_CLIENT_ID;
20721
- const defaultScope = require_Console.state.getDeploymentType() === constants.CLASSIC_DEPLOYMENT_TYPE_KEY ? "openid" : "openid fr:idm:*";
20720
+ const defaultScope = require_Console.state.getDeploymentType() === constants$1.CLASSIC_DEPLOYMENT_TYPE_KEY ? "openid" : "openid fr:idm:*";
20722
20721
  if (!await setupBrowserLogin({
20723
20722
  clientId,
20724
20723
  scriptId: options.scriptId || `${clientId}-session-capture`,
@@ -21041,9 +21040,9 @@ function setup$101() {
21041
21040
  }
21042
21041
  //#endregion
21043
21042
  //#region package.json
21044
- var version$1 = "5.0.0-19";
21043
+ var version$1 = "5.0.0-20";
21045
21044
  //#endregion
21046
- //#region node_modules/@modelcontextprotocol/server/dist/chunk-Br0eD_fh.mjs
21045
+ //#region node_modules/@modelcontextprotocol/server/dist/chunk-vYduTEsO.mjs
21047
21046
  var __create = Object.create;
21048
21047
  var __defProp = Object.defineProperty;
21049
21048
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -21075,7 +21074,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
21075
21074
  enumerable: true
21076
21075
  }) : target, mod));
21077
21076
  //#endregion
21078
- //#region node_modules/@modelcontextprotocol/server/dist/dialects-DoSzNhcb.mjs
21077
+ //#region node_modules/@modelcontextprotocol/server/dist/dialects-CDpMbily.mjs
21079
21078
  /**
21080
21079
  * Canonical `$schema` URIs per supported dialect (http + https variants, trailing-`#` stripped).
21081
21080
  */
@@ -28475,6 +28474,8 @@ const ServerResultSchema = union([
28475
28474
  ListToolsResultSchema,
28476
28475
  SubscriptionsListenResultSchema
28477
28476
  ]);
28477
+ //#endregion
28478
+ //#region node_modules/@modelcontextprotocol/core/dist/auth-UMQCo-ad.mjs
28478
28479
  /**
28479
28480
  * Reusable URL validation that disallows `javascript:` scheme
28480
28481
  */
@@ -28678,7 +28679,7 @@ const OAuthTokenRevocationRequestSchema = object({
28678
28679
  token_type_hint: string().optional()
28679
28680
  }).strip();
28680
28681
  //#endregion
28681
- //#region node_modules/@modelcontextprotocol/server/dist/src-Cqbh3MYc.mjs
28682
+ //#region node_modules/@modelcontextprotocol/server/dist/src-DdvbAHrR.mjs
28682
28683
  /**
28683
28684
  * Cross-bundle `instanceof` support for the SDK error classes.
28684
28685
  *
@@ -33035,25 +33036,22 @@ const X_MCP_HEADER_KEY = "x-mcp-header";
33035
33036
  */
33036
33037
  const RFC9110_TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
33037
33038
  /**
33038
- * JSON Schema `type` values the spec admits on an `x-mcp-header` property.
33039
- *
33040
- * The spec text names `integer`, `string`, `boolean` and explicitly excludes
33041
- * `number`. The published conformance referee at the pinned release ships its
33042
- * `http-custom-headers` scenario with two `type: "number"` `x-mcp-header`
33043
- * parameters and expects the client to mirror them, so `number` is accepted
33044
- * here so that the conformance gate passes; the discrepancy is tracked
33045
- * upstream. Everything else (`object`, `array`, `null`, absent) is rejected.
33039
+ * JSON Schema `type` values the spec admits on an `x-mcp-header` property:
33040
+ * `integer`, `string` and `boolean`. `number` is explicitly not permitted
33041
+ * (2026-07-28 Streamable HTTP, "Schema Extension"), so a tool that annotates a
33042
+ * `number`-typed property is invalid (the server still checks its headers).
33043
+ * Everything else (`object`, `array`, `null`, absent) is rejected too.
33046
33044
  */
33047
33045
  const PERMITTED_X_MCP_HEADER_TYPES = /* @__PURE__ */ new Set([
33048
33046
  "string",
33049
33047
  "integer",
33050
- "boolean",
33051
- "number"
33048
+ "boolean"
33052
33049
  ]);
33053
33050
  /**
33054
33051
  * Scan a tool's JSON-serialized `inputSchema` for `x-mcp-header` declarations
33055
33052
  * and validate every constraint the spec places on them. Returns either the
33056
- * collected declarations (possibly empty) or the first violated constraint.
33053
+ * collected declarations (possibly empty) or the first violated constraint
33054
+ * (with the declarations too, when `number`-typed declarations are the only fault).
33057
33055
  *
33058
33056
  * The walk descends through `properties` at any depth (the spec's "any nesting
33059
33057
  * depth" clause). The static-reachability MUST is enforced as a structural
@@ -33066,6 +33064,7 @@ const PERMITTED_X_MCP_HEADER_TYPES = /* @__PURE__ */ new Set([
33066
33064
  function scanXMcpHeaderDeclarations(inputSchema) {
33067
33065
  const declarations = [];
33068
33066
  const seenLower = /* @__PURE__ */ new Map();
33067
+ let numberFault;
33069
33068
  const visit = (node, path, reachable) => {
33070
33069
  if (node === null || typeof node !== "object") return void 0;
33071
33070
  const schema = node;
@@ -33075,7 +33074,11 @@ function scanXMcpHeaderDeclarations(inputSchema) {
33075
33074
  if (typeof raw !== "string" || raw.length === 0) return `${pathName(path)}: x-mcp-header MUST be a non-empty string`;
33076
33075
  if (!RFC9110_TOKEN.test(raw)) return `${pathName(path)}: x-mcp-header '${raw}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;
33077
33076
  const type = typeof schema.type === "string" ? schema.type : void 0;
33078
- if (type === void 0 || !PERMITTED_X_MCP_HEADER_TYPES.has(type)) return `${pathName(path)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${type ?? "<none>"}`;
33077
+ if (type === void 0 || !PERMITTED_X_MCP_HEADER_TYPES.has(type)) {
33078
+ const fault$1 = `${pathName(path)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${type ?? "<none>"}`;
33079
+ if (type !== "number") return fault$1;
33080
+ numberFault ??= fault$1;
33081
+ }
33079
33082
  const lower = raw.toLowerCase();
33080
33083
  const prior = seenLower.get(lower);
33081
33084
  if (prior !== void 0) return `x-mcp-header '${raw}' is not case-insensitively unique (also declared as '${prior}')`;
@@ -33102,12 +33105,17 @@ function scanXMcpHeaderDeclarations(inputSchema) {
33102
33105
  }
33103
33106
  };
33104
33107
  const fault = visit(inputSchema, [], true);
33105
- return fault === void 0 ? {
33108
+ if (fault !== void 0) return {
33109
+ valid: false,
33110
+ reason: numberFault ?? fault
33111
+ };
33112
+ return numberFault === void 0 ? {
33106
33113
  valid: true,
33107
33114
  declarations
33108
33115
  } : {
33109
33116
  valid: false,
33110
- reason: fault
33117
+ reason: numberFault,
33118
+ declarations
33111
33119
  };
33112
33120
  }
33113
33121
  /**
@@ -33149,8 +33157,115 @@ const OBJECT_VALUED_SUBSCHEMA_KEYWORDS = /* @__PURE__ */ new Set([
33149
33157
  function pathName(path) {
33150
33158
  return path.length === 0 ? "<root>" : path.join(".");
33151
33159
  }
33160
+ /**
33161
+ * Inbound HTTP request classification and the inbound validation ladder
33162
+ * (protocol revision 2026-07-28).
33163
+ *
33164
+ * `classifyInboundRequest` is the body-primary era predicate for an HTTP
33165
+ * entry that serves both protocol eras on one endpoint. It is evaluated
33166
+ * exactly once, at the entry boundary, on the already-parsed request body:
33167
+ *
33168
+ * - `initialize` is a legacy-era request by definition (the modern era has no
33169
+ * `initialize` handshake) — unless it carries a valid envelope claim naming
33170
+ * a modern revision, in which case the claim wins and the request is
33171
+ * classified like any other enveloped request (the modern era then answers
33172
+ * it with method-not-found, exactly like every other method it does not
33173
+ * define).
33174
+ * - A request whose `params._meta` carries the reserved protocol-version key
33175
+ * claims the per-request envelope mechanism and classifies into the era the
33176
+ * named revision belongs to (a malformed envelope behind a present claim is
33177
+ * a validation error, never a silent fall back to legacy handling).
33178
+ * - A request without a claim is legacy-era traffic.
33179
+ * - The `MCP-Protocol-Version` header is a cross-check only *for
33180
+ * classification*: it never upgrades or downgrades a body-derived
33181
+ * classification, and a disagreement between header and body is an explicit
33182
+ * ladder outcome. Its absence likewise never changes the era — but the spec
33183
+ * requires the header on every modern *request* POST, so a
33184
+ * modern-classified request that omits it is refused one rung later, by
33185
+ * {@linkcode validateStandardRequestHeaders}, not here. Notification POSTs
33186
+ * are exempt (see the next bullet), and that rung enforces presence on
33187
+ * requests only.
33188
+ * - Notifications carry no envelope claim of their own under the current
33189
+ * spec, so for notification POSTs without a body claim the modern header is
33190
+ * determinative; the `Mcp-Method` header is validated against the body when
33191
+ * the message classifies modern and is never enforced on legacy traffic.
33192
+ * A notification that does carry a claim is treated body-primary like a
33193
+ * request, and a malformed claim is rejected the same way a request's
33194
+ * malformed claim is — never silently resolved against the header.
33195
+ * The notification-POST header cross-checks here are an SDK-defensive
33196
+ * posture, not a spec requirement: the spec leaves header rules for posted
33197
+ * notifications undefined (core client notifications do not occur over
33198
+ * Streamable HTTP); applying the request rules symmetrically is what an
33199
+ * ecosystem custom-notification POST expects, and the −32020 cells stay
33200
+ * passing for them.
33201
+ * - `GET`/`DELETE` (and any other non-`POST` method) are body-less 2025-era
33202
+ * session operations: the modern era is `POST`-only, so they are routed to
33203
+ * legacy serving when it is configured and rejected otherwise.
33204
+ * - Array (batch) bodies are classified element-wise: an array containing a
33205
+ * modern-claiming or invalid element is rejected, an all-legacy array is
33206
+ * legacy traffic unchanged, and a single-element array is still an array.
33207
+ *
33208
+ * The classifier returns plain values (it never throws and never touches a
33209
+ * transport): a routing outcome (`legacy`/`modern`) or a ladder rejection
33210
+ * carrying the JSON-RPC error to emit and the HTTP status to emit it with.
33211
+ * Legacy routing outcomes deliberately carry NO `MessageClassification` —
33212
+ * legacy and hand-wired traffic is never classified, which keeps its
33213
+ * dispatch behavior byte-identical to today's.
33214
+ *
33215
+ * Error codes for the modern-path rejection cells follow the published
33216
+ * conformance suite (and the spec text it asserts):
33217
+ *
33218
+ * - A header/body cross-check mismatch (the `MCP-Protocol-Version` header
33219
+ * disagreeing with the body, or the `Mcp-Method` header disagreeing with the
33220
+ * body method) is rejected with `-32020` (`HeaderMismatch`) on HTTP 400.
33221
+ * - A request whose protocol-version header names a modern revision but whose
33222
+ * body carries no `_meta` envelope claim — including an envelope present but
33223
+ * missing the required protocol-version key — is rejected with `-32602`
33224
+ * (invalid params) naming the missing key(s), on HTTP 400.
33225
+ *
33226
+ * Should a future spec revision or conformance release change these
33227
+ * assignments, the affected cells are re-derived against that release; the
33228
+ * `settled` flag on {@linkcode InboundLadderRejection} stays available to mark
33229
+ * a cell provisional again while such a change is in flight.
33230
+ */
33231
+ /**
33232
+ * The error code emitted for header/body cross-check mismatches: the
33233
+ * `MCP-Protocol-Version` header disagreeing with the body's envelope claim (or
33234
+ * with the body's classification), and the `Mcp-Method` header disagreeing
33235
+ * with the body method.
33236
+ *
33237
+ * `-32020` is the draft schema's `HEADER_MISMATCH` constant (the SEP-2243
33238
+ * `HeaderMismatch` code; the spec requires HTTP 400 for it), as also asserted
33239
+ * by the published conformance suite for header-validation failures. It has no
33240
+ * {@linkcode ProtocolErrorCode} member because it is not part of the 2025-era
33241
+ * wire vocabulary; the validation ladder is its only emitter.
33242
+ */
33243
+ const HEADER_MISMATCH_ERROR_CODE$1 = -32020;
33152
33244
  ProtocolErrorCode.InvalidRequest, ProtocolErrorCode.UnsupportedProtocolVersion, ProtocolErrorCode.InvalidParams, ProtocolErrorCode.MethodNotFound, ProtocolErrorCode.InvalidParams, ProtocolErrorCode.MissingRequiredClientCapability;
33153
- ProtocolErrorCode.ParseError, ProtocolErrorCode.InvalidRequest, ProtocolErrorCode.MethodNotFound, ProtocolErrorCode.UnsupportedProtocolVersion, ProtocolErrorCode.MissingRequiredClientCapability;
33245
+ /**
33246
+ * HTTP status for ladder-originated JSON-RPC error codes.
33247
+ *
33248
+ * Keyed on origin, not on the bare code: this table only applies to errors
33249
+ * the ladder (or a pre-handler protocol gate) produced. Errors produced by
33250
+ * request handlers — whatever their code — stay in-band on HTTP 200, and are
33251
+ * never mapped to an HTTP status by this table; in particular `-32603` and
33252
+ * domain-specific codes never become a blanket 500. The single exception is
33253
+ * `MissingRequiredClientCapability` (-32021) — see
33254
+ * {@linkcode httpStatusForErrorCode}.
33255
+ *
33256
+ * `-32602` (invalid params) deliberately has NO entry: the only invalid-params
33257
+ * rejection that maps to HTTP 400 is the classifier's own envelope rung
33258
+ * short-circuit, which carries its HTTP status directly. A dispatch- or
33259
+ * handler-produced invalid-params error is always in-band.
33260
+ */
33261
+ const LADDER_ERROR_HTTP_STATUS = {
33262
+ [ProtocolErrorCode.ParseError]: 400,
33263
+ [ProtocolErrorCode.InvalidRequest]: 400,
33264
+ [ProtocolErrorCode.MethodNotFound]: 404,
33265
+ [ProtocolErrorCode.UnsupportedProtocolVersion]: 400,
33266
+ [ProtocolErrorCode.MissingRequiredClientCapability]: 400,
33267
+ [HEADER_MISMATCH_ERROR_CODE$1]: 400
33268
+ };
33154
33269
  function rejection(rung, cell, httpStatus, error, settled) {
33155
33270
  return {
33156
33271
  kind: "reject",
@@ -33287,22 +33402,26 @@ function standardSchemaToJsonSchema(schema, io = "input") {
33287
33402
  ...result
33288
33403
  };
33289
33404
  }
33405
+ const LOCAL_DEFINITION_REF = /^#\/(\$defs|definitions)\/([^/~%]+)$/;
33290
33406
  /**
33291
33407
  * A typeless JSON Schema root is "provably object-shaped" when either it carries object keywords
33292
33408
  * directly (`properties`/`patternProperties`/`additionalProperties`/`required`), or it is a
33293
33409
  * composition (`oneOf`/`anyOf`/`allOf`) whose every member is itself `type:'object'` or recursively
33294
- * provably object-shaped (e.g. a nested `discriminatedUnion`). `$ref` is not followed. Used to
33410
+ * provably object-shaped (e.g. a nested `discriminatedUnion`). A `$ref` is followed one hop, to an
33411
+ * entry of the root's `$defs`/`definitions` that is itself `type:'object'`. Used to
33295
33412
  * decide whether stamping `type:'object'` is safe (redundant-but-valid) versus self-contradictory.
33296
33413
  */
33297
- function isProvablyObjectShapedRoot(schema) {
33414
+ function isProvablyObjectShapedRoot(schema, root = schema) {
33298
33415
  if ("properties" in schema || "patternProperties" in schema || "additionalProperties" in schema || "required" in schema) return true;
33416
+ const ref = typeof schema.$ref === "string" && LOCAL_DEFINITION_REF.exec(schema.$ref);
33417
+ if (ref && root[ref[1]]?.[ref[2]]?.type === "object") return true;
33299
33418
  for (const key of [
33300
33419
  "oneOf",
33301
33420
  "anyOf",
33302
33421
  "allOf"
33303
33422
  ]) {
33304
33423
  const members = schema[key];
33305
- if (Array.isArray(members) && members.length > 0) return members.every((m) => m !== null && typeof m === "object" && (m.type === "object" || isProvablyObjectShapedRoot(m)));
33424
+ if (Array.isArray(members) && members.length > 0) return members.every((m) => m !== null && typeof m === "object" && (m.type === "object" || isProvablyObjectShapedRoot(m, "$id" in m ? {} : root)));
33306
33425
  }
33307
33426
  return false;
33308
33427
  }
@@ -35011,7 +35130,7 @@ function normalizeRawShapeSchema(schema) {
35011
35130
  return schema;
35012
35131
  }
35013
35132
  //#endregion
35014
- //#region node_modules/@modelcontextprotocol/server/dist/ajvProvider-CEoC__sr.mjs
35133
+ //#region node_modules/@modelcontextprotocol/server/dist/ajvProvider-DyjnscPj.mjs
35015
35134
  var require_code$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
35016
35135
  Object.defineProperty(exports, "__esModule", { value: true });
35017
35136
  exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0;
@@ -37689,6 +37808,28 @@ var require_utils = /* @__PURE__ */ __commonJSMin(((exports, module) => {
37689
37808
  const isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu);
37690
37809
  /** @type {(value: string) => boolean} */
37691
37810
  const isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);
37811
+ /** @type {(value: string) => boolean} */
37812
+ const isPort = RegExp.prototype.test.bind(/^\d*$/u);
37813
+ /** @type {(value: string) => boolean} */
37814
+ const isHexPair = RegExp.prototype.test.bind(/^[\da-f]{2}$/iu);
37815
+ /** @type {(value: string) => boolean} */
37816
+ const isUnreserved = RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu);
37817
+ /** @type {(value: string) => boolean} */
37818
+ const isPathCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u);
37819
+ /** @type {(value: string) => boolean} */
37820
+ const isQueryFragmentCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u);
37821
+ /** @type {(value: string) => boolean} */
37822
+ const isUserinfoCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u);
37823
+ const BYTE_HEX = new Array(256);
37824
+ {
37825
+ const HEX_DIGITS = "0123456789ABCDEF";
37826
+ for (let i = 0; i < 256; i++) BYTE_HEX[i] = "%" + HEX_DIGITS[i >> 4] + HEX_DIGITS[i & 15];
37827
+ }
37828
+ function percentEncodeNonAscii(cp) {
37829
+ if (cp < 2048) return BYTE_HEX[192 | cp >> 6] + BYTE_HEX[128 | cp & 63];
37830
+ if (cp < 65536) return BYTE_HEX[224 | cp >> 12] + BYTE_HEX[128 | cp >> 6 & 63] + BYTE_HEX[128 | cp & 63];
37831
+ return BYTE_HEX[240 | cp >> 18] + BYTE_HEX[128 | cp >> 12 & 63] + BYTE_HEX[128 | cp >> 6 & 63] + BYTE_HEX[128 | cp & 63];
37832
+ }
37692
37833
  /**
37693
37834
  * @param {Array<string>} input
37694
37835
  * @returns {string}
@@ -37711,119 +37852,162 @@ var require_utils = /* @__PURE__ */ __commonJSMin(((exports, module) => {
37711
37852
  }
37712
37853
  return acc;
37713
37854
  }
37714
- /**
37715
- * @typedef {Object} GetIPV6Result
37716
- * @property {boolean} error - Indicates if there was an error parsing the IPv6 address.
37717
- * @property {string} address - The parsed IPv6 address.
37718
- * @property {string} [zone] - The zone identifier, if present.
37719
- */
37855
+ /** @type {(value: string) => boolean} */
37856
+ const isHextet = RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/);
37857
+ /** @type {(value: string) => boolean} */
37858
+ const isIPvFuture = RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/);
37859
+ /** @type {(value: string) => boolean} */
37860
+ const isZoneCharacter = RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/);
37720
37861
  /**
37721
37862
  * @param {string} value
37722
37863
  * @returns {boolean}
37723
37864
  */
37724
37865
  const nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);
37725
37866
  /**
37726
- * @param {Array<string>} buffer
37867
+ * @param {string} zone
37727
37868
  * @returns {boolean}
37728
37869
  */
37729
- function consumeIsZone(buffer) {
37730
- buffer.length = 0;
37870
+ function isZoneIdentifier(zone) {
37871
+ if (zone.length === 0) return false;
37872
+ for (let i = 0; i < zone.length; i++) {
37873
+ if (isZoneCharacter(zone[i])) continue;
37874
+ if (zone[i] === "%" && i + 2 < zone.length && isHexPair(zone.slice(i + 1, i + 3))) {
37875
+ i += 2;
37876
+ continue;
37877
+ }
37878
+ return false;
37879
+ }
37731
37880
  return true;
37732
37881
  }
37733
37882
  /**
37734
- * @param {Array<string>} buffer
37735
- * @param {Array<string>} address
37736
- * @param {GetIPV6Result} output
37737
- * @returns {boolean}
37883
+ * Compresses the longest run of zero hextets to "::" per RFC 5952. A run of a
37884
+ * single zero hextet is left uncompressed. On ties the leftmost run wins.
37885
+ *
37886
+ * @param {string[]} hextets
37887
+ * @returns {string}
37738
37888
  */
37739
- function consumeHextets(buffer, address, output) {
37740
- if (buffer.length) {
37741
- const hex = stringArrayToHexStripped(buffer);
37742
- if (hex !== "") address.push(hex);
37743
- else {
37744
- output.error = true;
37745
- return false;
37889
+ function compressIPv6ZeroRun(hextets) {
37890
+ let bestStart = -1;
37891
+ let bestLength = 0;
37892
+ let runStart = -1;
37893
+ let runLength = 0;
37894
+ for (let i = 0; i < hextets.length; i++) if (hextets[i] === "0") {
37895
+ if (runStart === -1) runStart = i;
37896
+ runLength++;
37897
+ if (runLength > bestLength) {
37898
+ bestLength = runLength;
37899
+ bestStart = runStart;
37746
37900
  }
37747
- buffer.length = 0;
37901
+ } else {
37902
+ runStart = -1;
37903
+ runLength = 0;
37748
37904
  }
37749
- return true;
37905
+ if (bestLength < 2) return hextets.join(":");
37906
+ const head = hextets.slice(0, bestStart).join(":");
37907
+ const tail = hextets.slice(bestStart + bestLength).join(":");
37908
+ return head + "::" + tail;
37750
37909
  }
37751
37910
  /**
37911
+ * Validates an IPv6 address against the alternatives in RFC 3986 section
37912
+ * 3.2.2 and returns the same address with leading hextet zeroes removed.
37913
+ * An embedded IPv4 address counts as two hextets and is only valid at the end.
37914
+ *
37752
37915
  * @param {string} input
37753
- * @returns {GetIPV6Result}
37916
+ * @returns {string|undefined}
37754
37917
  */
37755
- function getIPV6(input) {
37756
- let tokenCount = 0;
37757
- const output = {
37758
- error: false,
37759
- address: "",
37760
- zone: ""
37761
- };
37762
- /** @type {Array<string>} */
37763
- const address = [];
37764
- /** @type {Array<string>} */
37765
- const buffer = [];
37766
- let endipv6Encountered = false;
37767
- let endIpv6 = false;
37768
- let consume = consumeHextets;
37769
- for (let i = 0; i < input.length; i++) {
37770
- const cursor = input[i];
37771
- if (cursor === "[" || cursor === "]") continue;
37772
- if (cursor === ":") {
37773
- if (endipv6Encountered === true) endIpv6 = true;
37774
- if (!consume(buffer, address, output)) break;
37775
- if (++tokenCount > 7) {
37776
- output.error = true;
37777
- break;
37778
- }
37779
- if (i > 0 && input[i - 1] === ":") endipv6Encountered = true;
37780
- address.push(":");
37781
- continue;
37782
- } else if (cursor === "%") {
37783
- if (!consume(buffer, address, output)) break;
37784
- consume = consumeIsZone;
37785
- } else {
37786
- buffer.push(cursor);
37918
+ function normalizeIPv6Address(input) {
37919
+ const compression = input.indexOf("::");
37920
+ if (compression !== -1 && input.indexOf("::", compression + 1) !== -1) return void 0;
37921
+ const left = compression === -1 ? input.split(":") : input.slice(0, compression).split(":");
37922
+ const right = compression === -1 ? [] : input.slice(compression + 2).split(":");
37923
+ if (compression !== -1) {
37924
+ if (left.length === 1 && left[0] === "") left.length = 0;
37925
+ if (right.length === 1 && right[0] === "") right.length = 0;
37926
+ }
37927
+ const parts = left.concat(right);
37928
+ let hextetCount = 0;
37929
+ for (let i = 0; i < parts.length; i++) {
37930
+ const part = parts[i];
37931
+ if (part === "") return void 0;
37932
+ if (part.indexOf(".") !== -1) {
37933
+ if (i !== parts.length - 1 || compression !== -1 && right.length === 0 || !isIPv4(part)) return void 0;
37934
+ hextetCount += 2;
37787
37935
  continue;
37788
37936
  }
37937
+ if (!isHextet(part)) return void 0;
37938
+ parts[i] = parseInt(part, 16).toString(16);
37939
+ hextetCount++;
37789
37940
  }
37790
- if (buffer.length) if (consume === consumeIsZone) output.zone = buffer.join("");
37791
- else if (endIpv6) address.push(buffer.join(""));
37792
- else address.push(stringArrayToHexStripped(buffer));
37793
- output.address = address.join("");
37794
- return output;
37941
+ if (compression === -1) {
37942
+ if (hextetCount !== 8) return void 0;
37943
+ return compressIPv6ZeroRun(parts);
37944
+ }
37945
+ if (hextetCount >= 8) return void 0;
37946
+ const expanded = parts.slice(0, left.length);
37947
+ for (let i = hextetCount; i < 8; i++) expanded.push("0");
37948
+ for (let i = left.length; i < parts.length; i++) expanded.push(parts[i]);
37949
+ return compressIPv6ZeroRun(expanded);
37795
37950
  }
37796
37951
  /**
37797
37952
  * @typedef {Object} NormalizeIPv6Result
37798
37953
  * @property {string} host - The normalized host.
37799
37954
  * @property {string} [escapedHost] - The escaped host.
37800
37955
  * @property {boolean} isIPV6 - Indicates if the host is an IPv6 address.
37956
+ * @property {boolean} [isIPVFuture] - Indicates if the host is an IPvFuture literal.
37957
+ * @property {boolean} [error] - Indicates if a bracketed IP literal is malformed.
37801
37958
  */
37802
37959
  /**
37960
+ * Validates and normalizes a bracketed IP literal. Raw zone separators remain
37961
+ * accepted for backwards compatibility, while encoded separators and zone
37962
+ * contents follow RFC 6874.
37963
+ *
37803
37964
  * @param {string} host
37804
37965
  * @returns {NormalizeIPv6Result}
37805
37966
  */
37806
37967
  function normalizeIPv6(host) {
37807
- if (findToken(host, ":") < 2) return {
37968
+ const bracketed = host[0] === "[" && host[host.length - 1] === "]";
37969
+ if ((host[0] === "[" || host[host.length - 1] === "]") && !bracketed) return {
37808
37970
  host,
37809
- isIPV6: false
37971
+ isIPV6: false,
37972
+ error: true
37810
37973
  };
37811
- const ipv6 = getIPV6(host);
37812
- if (!ipv6.error) {
37813
- let newHost = ipv6.address;
37814
- let escapedHost = ipv6.address;
37815
- if (ipv6.zone) {
37816
- newHost += "%" + ipv6.zone;
37817
- escapedHost += "%25" + ipv6.zone;
37818
- }
37974
+ let input = bracketed ? host.slice(1, -1) : host;
37975
+ if (bracketed && isIPvFuture(input)) {
37976
+ input = input.toLowerCase();
37819
37977
  return {
37820
- host: newHost,
37821
- isIPV6: true,
37822
- escapedHost
37978
+ host: `[${input}]`,
37979
+ escapedHost: input,
37980
+ isIPV6: false,
37981
+ isIPVFuture: true
37982
+ };
37983
+ }
37984
+ if (findToken(input, ":") < 2) return {
37985
+ host,
37986
+ isIPV6: false,
37987
+ error: bracketed
37988
+ };
37989
+ let zoneIdentifier = "";
37990
+ const zoneSeparator = input.indexOf("%");
37991
+ if (zoneSeparator !== -1) {
37992
+ const separatorLength = input.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1;
37993
+ zoneIdentifier = input.slice(zoneSeparator + separatorLength);
37994
+ if (!isZoneIdentifier(zoneIdentifier)) return {
37995
+ host,
37996
+ isIPV6: false,
37997
+ error: true
37823
37998
  };
37824
- } else return {
37999
+ input = input.slice(0, zoneSeparator);
38000
+ }
38001
+ const address = normalizeIPv6Address(input);
38002
+ if (address === void 0) return {
37825
38003
  host,
37826
- isIPV6: false
38004
+ isIPV6: false,
38005
+ error: true
38006
+ };
38007
+ return {
38008
+ host: address + (zoneIdentifier ? "%" + zoneIdentifier : ""),
38009
+ escapedHost: address + (zoneIdentifier ? "%25" + zoneIdentifier : ""),
38010
+ isIPV6: true
37827
38011
  };
37828
38012
  }
37829
38013
  /**
@@ -37911,19 +38095,264 @@ var require_utils = /* @__PURE__ */ __commonJSMin(((exports, module) => {
37911
38095
  return output.join("");
37912
38096
  }
37913
38097
  /**
37914
- * @param {import('../types/index').URIComponent} component
37915
- * @param {boolean} esc
37916
- * @returns {import('../types/index').URIComponent}
38098
+ * Re-escape RFC 3986 gen-delims that must not appear literally in the host.
38099
+ * After the URI regex parses, these characters cannot be literal in the host
38100
+ * field, so any that appear after decoding came from percent-encoding and
38101
+ * must be restored to prevent authority structure changes.
38102
+ *
38103
+ * @param {string} host
38104
+ * @param {boolean} isIP - true for IPv4/IPv6 hosts (skip colon re-escaping)
38105
+ * @returns {string}
37917
38106
  */
37918
- function normalizeComponentEncoding(component, esc) {
37919
- const func = esc !== true ? escape : unescape;
37920
- if (component.scheme !== void 0) component.scheme = func(component.scheme);
37921
- if (component.userinfo !== void 0) component.userinfo = func(component.userinfo);
37922
- if (component.host !== void 0) component.host = func(component.host);
37923
- if (component.path !== void 0) component.path = func(component.path);
37924
- if (component.query !== void 0) component.query = func(component.query);
37925
- if (component.fragment !== void 0) component.fragment = func(component.fragment);
37926
- return component;
38107
+ const HOST_DELIMS = {
38108
+ "@": "%40",
38109
+ "/": "%2F",
38110
+ "?": "%3F",
38111
+ "#": "%23",
38112
+ ":": "%3A"
38113
+ };
38114
+ const HOST_DELIM_RE = /[@/?#:]/g;
38115
+ const HOST_DELIM_NO_COLON_RE = /[@/?#]/g;
38116
+ function reescapeHostDelimiters(host, isIP) {
38117
+ const re = isIP ? HOST_DELIM_NO_COLON_RE : HOST_DELIM_RE;
38118
+ re.lastIndex = 0;
38119
+ return host.replace(re, (ch) => HOST_DELIMS[ch]);
38120
+ }
38121
+ /**
38122
+ * Normalizes percent escapes and optionally decodes only unreserved ASCII bytes.
38123
+ * Reserved delimiters such as `%2F` stay escaped; `%2E` is unreserved.
38124
+ *
38125
+ * @param {string} input
38126
+ * @param {boolean} [decodeUnreserved=false]
38127
+ * @returns {string}
38128
+ */
38129
+ function normalizePercentEncoding(input, decodeUnreserved = false) {
38130
+ if (input.indexOf("%") === -1) return input;
38131
+ let output = "";
38132
+ for (let i = 0; i < input.length; i++) {
38133
+ if (input[i] === "%" && i + 2 < input.length) {
38134
+ const hex = input.slice(i + 1, i + 3);
38135
+ if (isHexPair(hex)) {
38136
+ const normalizedHex = hex.toUpperCase();
38137
+ const decoded = String.fromCharCode(parseInt(normalizedHex, 16));
38138
+ if (decodeUnreserved && isUnreserved(decoded)) output += decoded;
38139
+ else output += "%" + normalizedHex;
38140
+ i += 2;
38141
+ continue;
38142
+ }
38143
+ }
38144
+ output += input[i];
38145
+ }
38146
+ return output;
38147
+ }
38148
+ /**
38149
+ * Normalizes path data without turning reserved escapes into live path syntax.
38150
+ * Valid escapes are uppercased, raw unsafe characters are escaped, and only
38151
+ * unreserved bytes that are not `.` are decoded.
38152
+ *
38153
+ * @param {string} input
38154
+ * @returns {string}
38155
+ */
38156
+ function normalizePathEncoding(input) {
38157
+ let output = "";
38158
+ for (let i = 0; i < input.length; i++) {
38159
+ const ch = input[i];
38160
+ if (ch === "%" && i + 2 < input.length) {
38161
+ const hex = input.slice(i + 1, i + 3);
38162
+ if (isHexPair(hex)) {
38163
+ const normalizedHex = hex.toUpperCase();
38164
+ const decoded = String.fromCharCode(parseInt(normalizedHex, 16));
38165
+ if (decoded !== "." && isUnreserved(decoded)) output += decoded;
38166
+ else output += "%" + normalizedHex;
38167
+ i += 2;
38168
+ continue;
38169
+ }
38170
+ }
38171
+ if (isPathCharacter(ch)) output += ch;
38172
+ else {
38173
+ const code = input.charCodeAt(i);
38174
+ if (code < 128) output += isEscapeSafe(code) ? ch : BYTE_HEX[code];
38175
+ else if (code < 55296 || code > 57343) output += percentEncodeNonAscii(code);
38176
+ else if (code <= 56319 && i + 1 < input.length) {
38177
+ const low = input.charCodeAt(i + 1);
38178
+ if (low >= 56320 && low <= 57343) {
38179
+ output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320));
38180
+ i++;
38181
+ } else output += percentEncodeNonAscii(65533);
38182
+ } else output += percentEncodeNonAscii(65533);
38183
+ }
38184
+ }
38185
+ return output;
38186
+ }
38187
+ /**
38188
+ * Serializes a path without rewriting reserved data. Raw RFC 3986 path
38189
+ * characters remain literal, valid escapes are preserved and uppercased, and
38190
+ * everything else is UTF-8 percent-encoded. In a path-noscheme, a colon in the
38191
+ * first segment must be escaped so the result cannot be parsed as a scheme.
38192
+ *
38193
+ * @param {string} input
38194
+ * @param {boolean} [pathNoScheme=false]
38195
+ * @returns {string}
38196
+ */
38197
+ function serializePathEncoding(input, pathNoScheme = false) {
38198
+ let output = "";
38199
+ let firstSegment = pathNoScheme && input[0] !== "/";
38200
+ for (let i = 0; i < input.length; i++) {
38201
+ const ch = input[i];
38202
+ if (ch === "%" && i + 2 < input.length) {
38203
+ const hex = input.slice(i + 1, i + 3);
38204
+ if (isHexPair(hex)) {
38205
+ output += "%" + hex.toUpperCase();
38206
+ i += 2;
38207
+ continue;
38208
+ }
38209
+ }
38210
+ if (ch === "/") firstSegment = false;
38211
+ if (isPathCharacter(ch) && (ch !== ":" || !firstSegment)) output += ch;
38212
+ else {
38213
+ const code = input.charCodeAt(i);
38214
+ if (code < 128) output += BYTE_HEX[code];
38215
+ else if (code < 55296 || code > 57343) output += percentEncodeNonAscii(code);
38216
+ else if (code <= 56319 && i + 1 < input.length) {
38217
+ const low = input.charCodeAt(i + 1);
38218
+ if (low >= 56320 && low <= 57343) {
38219
+ output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320));
38220
+ i++;
38221
+ } else output += percentEncodeNonAscii(65533);
38222
+ } else output += percentEncodeNonAscii(65533);
38223
+ }
38224
+ }
38225
+ return output;
38226
+ }
38227
+ /**
38228
+ * Percent-encodes a URI component using its RFC 3986 literal character set.
38229
+ * Existing valid escapes are preserved and normalized to uppercase hex.
38230
+ *
38231
+ * @param {string} input
38232
+ * @param {(value: string) => boolean} isAllowed
38233
+ * @returns {string}
38234
+ */
38235
+ function encodeComponent(input, isAllowed) {
38236
+ let output = "";
38237
+ for (let i = 0; i < input.length; i++) {
38238
+ const ch = input[i];
38239
+ if (ch === "%" && i + 2 < input.length) {
38240
+ const hex = input.slice(i + 1, i + 3);
38241
+ if (isHexPair(hex)) {
38242
+ output += "%" + hex.toUpperCase();
38243
+ i += 2;
38244
+ continue;
38245
+ }
38246
+ }
38247
+ if (isAllowed(ch)) output += ch;
38248
+ else {
38249
+ const code = input.charCodeAt(i);
38250
+ if (code < 128) output += BYTE_HEX[code];
38251
+ else if (code < 55296 || code > 57343) output += percentEncodeNonAscii(code);
38252
+ else if (code <= 56319 && i + 1 < input.length) {
38253
+ const low = input.charCodeAt(i + 1);
38254
+ if (low >= 56320 && low <= 57343) {
38255
+ output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320));
38256
+ i++;
38257
+ } else output += percentEncodeNonAscii(65533);
38258
+ } else output += percentEncodeNonAscii(65533);
38259
+ }
38260
+ }
38261
+ return output;
38262
+ }
38263
+ /**
38264
+ * Encodes userinfo while preserving its RFC 3986 §3.2.1 literal characters.
38265
+ * In particular, authority delimiters such as `@`, `/`, `?`, and `#` are data.
38266
+ *
38267
+ * @param {string} input
38268
+ * @returns {string}
38269
+ */
38270
+ function encodeUserinfo(input) {
38271
+ return encodeComponent(input, isUserinfoCharacter);
38272
+ }
38273
+ /**
38274
+ * Encodes query data using the RFC 3986 §3.4 grammar. A literal `#` must be
38275
+ * escaped because it would otherwise begin the fragment component.
38276
+ *
38277
+ * @param {string} input
38278
+ * @returns {string}
38279
+ */
38280
+ function encodeQuery(input) {
38281
+ return encodeComponent(input, isQueryFragmentCharacter);
38282
+ }
38283
+ /**
38284
+ * Encodes fragment data using the RFC 3986 §3.5 grammar.
38285
+ *
38286
+ * @param {string} input
38287
+ * @returns {string}
38288
+ */
38289
+ function encodeFragment(input) {
38290
+ return encodeComponent(input, isQueryFragmentCharacter);
38291
+ }
38292
+ function isEscapeSafe(cp) {
38293
+ return cp >= 48 && cp <= 57 || cp >= 65 && cp <= 90 || cp >= 97 && cp <= 122 || cp === 42 || cp === 43 || cp === 45 || cp === 46 || cp === 47 || cp === 64 || cp === 95;
38294
+ }
38295
+ /**
38296
+ * Normalizes the percent-encoding of a query or fragment component.
38297
+ *
38298
+ * Like `normalizePathEncoding`, but uses the query/fragment character set
38299
+ * (which additionally allows `?`) and decodes `.` since it has no dot-segment
38300
+ * meaning outside of a path.
38301
+ *
38302
+ * @param {string} input
38303
+ * @returns {string}
38304
+ */
38305
+ function normalizeQueryFragmentEncoding(input) {
38306
+ let output = "";
38307
+ for (let i = 0; i < input.length; i++) {
38308
+ const ch = input[i];
38309
+ if (ch === "%" && i + 2 < input.length) {
38310
+ const hex = input.slice(i + 1, i + 3);
38311
+ if (isHexPair(hex)) {
38312
+ const normalizedHex = hex.toUpperCase();
38313
+ const decoded = String.fromCharCode(parseInt(normalizedHex, 16));
38314
+ if (isUnreserved(decoded)) output += decoded;
38315
+ else output += "%" + normalizedHex;
38316
+ i += 2;
38317
+ continue;
38318
+ }
38319
+ }
38320
+ if (isQueryFragmentCharacter(ch)) output += ch;
38321
+ else {
38322
+ const code = input.charCodeAt(i);
38323
+ if (code < 128) output += isEscapeSafe(code) ? ch : BYTE_HEX[code];
38324
+ else if (code < 55296 || code > 57343) output += percentEncodeNonAscii(code);
38325
+ else if (code <= 56319 && i + 1 < input.length) {
38326
+ const low = input.charCodeAt(i + 1);
38327
+ if (low >= 56320 && low <= 57343) {
38328
+ output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320));
38329
+ i++;
38330
+ } else output += percentEncodeNonAscii(65533);
38331
+ } else output += percentEncodeNonAscii(65533);
38332
+ }
38333
+ }
38334
+ return output;
38335
+ }
38336
+ /**
38337
+ * Escapes a component while preserving existing valid percent escapes.
38338
+ *
38339
+ * @param {string} input
38340
+ * @returns {string}
38341
+ */
38342
+ function escapePreservingEscapes(input) {
38343
+ let output = "";
38344
+ for (let i = 0; i < input.length; i++) {
38345
+ if (input[i] === "%" && i + 2 < input.length) {
38346
+ const hex = input.slice(i + 1, i + 3);
38347
+ if (isHexPair(hex)) {
38348
+ output += "%" + hex.toUpperCase();
38349
+ i += 2;
38350
+ continue;
38351
+ }
38352
+ }
38353
+ output += escape(input[i]);
38354
+ }
38355
+ return output;
37927
38356
  }
37928
38357
  /**
37929
38358
  * @param {import('../types/index').URIComponent} component
@@ -37932,28 +38361,42 @@ var require_utils = /* @__PURE__ */ __commonJSMin(((exports, module) => {
37932
38361
  function recomposeAuthority(component) {
37933
38362
  const uriTokens = [];
37934
38363
  if (component.userinfo !== void 0) {
37935
- uriTokens.push(component.userinfo);
38364
+ uriTokens.push(encodeUserinfo(component.userinfo));
37936
38365
  uriTokens.push("@");
37937
38366
  }
37938
38367
  if (component.host !== void 0) {
37939
- let host = unescape(component.host);
38368
+ let host = component.host;
37940
38369
  if (!isIPv4(host)) {
37941
- const ipV6res = normalizeIPv6(host);
37942
- if (ipV6res.isIPV6 === true) host = `[${ipV6res.escapedHost}]`;
37943
- else host = component.host;
38370
+ let ipV6res = normalizeIPv6(host);
38371
+ if (ipV6res.isIPV6 !== true && ipV6res.isIPVFuture !== true) {
38372
+ host = normalizePercentEncoding(host, true);
38373
+ ipV6res = normalizeIPv6(host);
38374
+ }
38375
+ if (ipV6res.isIPV6 === true || ipV6res.isIPVFuture === true) host = `[${ipV6res.escapedHost}]`;
38376
+ else host = reescapeHostDelimiters(host, false);
37944
38377
  }
37945
38378
  uriTokens.push(host);
37946
38379
  }
37947
38380
  if (typeof component.port === "number" || typeof component.port === "string") {
38381
+ const port = String(component.port);
38382
+ if (!isPort(port)) throw new TypeError("URI port is malformed.");
37948
38383
  uriTokens.push(":");
37949
- uriTokens.push(String(component.port));
38384
+ uriTokens.push(port);
37950
38385
  }
37951
38386
  return uriTokens.length ? uriTokens.join("") : void 0;
37952
38387
  }
37953
38388
  module.exports = {
37954
38389
  nonSimpleDomain,
37955
38390
  recomposeAuthority,
37956
- normalizeComponentEncoding,
38391
+ reescapeHostDelimiters,
38392
+ normalizePercentEncoding,
38393
+ normalizePathEncoding,
38394
+ serializePathEncoding,
38395
+ normalizeQueryFragmentEncoding,
38396
+ encodeUserinfo,
38397
+ encodeQuery,
38398
+ encodeFragment,
38399
+ escapePreservingEscapes,
37957
38400
  removeDotSegments,
37958
38401
  isIPv4,
37959
38402
  isUUID,
@@ -37963,7 +38406,7 @@ var require_utils = /* @__PURE__ */ __commonJSMin(((exports, module) => {
37963
38406
  }));
37964
38407
  var require_schemes = /* @__PURE__ */ __commonJSMin(((exports, module) => {
37965
38408
  const { isUUID } = require_utils();
37966
- const URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;
38409
+ const URN_REG = /^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu;
37967
38410
  const supportedSchemeNames = [
37968
38411
  "http",
37969
38412
  "https",
@@ -38034,9 +38477,10 @@ var require_schemes = /* @__PURE__ */ __commonJSMin(((exports, module) => {
38034
38477
  wsComponent.secure = void 0;
38035
38478
  }
38036
38479
  if (wsComponent.resourceName) {
38037
- const [path, query] = wsComponent.resourceName.split("?");
38480
+ const queryIndex = wsComponent.resourceName.indexOf("?");
38481
+ const path = queryIndex === -1 ? wsComponent.resourceName : wsComponent.resourceName.slice(0, queryIndex);
38038
38482
  wsComponent.path = path && path !== "/" ? path : void 0;
38039
- wsComponent.query = query;
38483
+ wsComponent.query = queryIndex === -1 ? void 0 : wsComponent.resourceName.slice(queryIndex + 1);
38040
38484
  wsComponent.resourceName = void 0;
38041
38485
  }
38042
38486
  wsComponent.fragment = void 0;
@@ -38049,7 +38493,7 @@ var require_schemes = /* @__PURE__ */ __commonJSMin(((exports, module) => {
38049
38493
  return urnComponent;
38050
38494
  }
38051
38495
  const matches = urnComponent.path.match(URN_REG);
38052
- if (matches) {
38496
+ if (matches && matches[0] === urnComponent.path) {
38053
38497
  const scheme = options.scheme || urnComponent.scheme || "urn";
38054
38498
  urnComponent.nid = matches[1].toLowerCase();
38055
38499
  urnComponent.nss = matches[2];
@@ -38143,8 +38587,19 @@ var require_schemes = /* @__PURE__ */ __commonJSMin(((exports, module) => {
38143
38587
  };
38144
38588
  }));
38145
38589
  var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
38146
- const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require_utils();
38590
+ const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizePercentEncoding, normalizePathEncoding, serializePathEncoding, normalizeQueryFragmentEncoding, encodeQuery, encodeFragment, reescapeHostDelimiters, isIPv4, nonSimpleDomain } = require_utils();
38147
38591
  const { SCHEMES, getSchemeHandler } = require_schemes();
38592
+ const VALID_SCHEME = /^[A-Za-z][A-Za-z0-9+.-]*$/u;
38593
+ const MALFORMED_SCHEME_ERROR = "URI scheme is malformed.";
38594
+ /**
38595
+ * @param {string} scheme
38596
+ * @returns {string}
38597
+ */
38598
+ function decodeValidScheme(scheme) {
38599
+ const decodedScheme = unescape(String(scheme));
38600
+ if (!VALID_SCHEME.test(decodedScheme)) throw new TypeError(MALFORMED_SCHEME_ERROR);
38601
+ return decodedScheme;
38602
+ }
38148
38603
  /**
38149
38604
  * @template {import('./types/index').URIComponent|string} T
38150
38605
  * @param {T} uri
@@ -38152,7 +38607,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
38152
38607
  * @returns {T}
38153
38608
  */
38154
38609
  function normalize(uri, options) {
38155
- if (typeof uri === "string") uri = serialize(parse(uri, options), options);
38610
+ if (typeof uri === "string") uri = normalizeString(uri, options);
38156
38611
  else if (typeof uri === "object") uri = parse(serialize(uri, options), options);
38157
38612
  return uri;
38158
38613
  }
@@ -38164,7 +38619,16 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
38164
38619
  */
38165
38620
  function resolve(baseURI, relativeURI, options) {
38166
38621
  const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
38167
- const resolved = resolveComponent(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true);
38622
+ const { parsed: baseParsed, malformedAuthorityOrPort: baseMalformed, malformedPercentEncoding: baseMalformedPercentEncoding, malformedSchemeSpecific: baseMalformedSchemeSpecific, malformedHost: baseMalformedHost, malformedScheme: baseMalformedScheme } = parseWithStatus(baseURI, schemelessOptions);
38623
+ const { parsed: relativeParsed, malformedAuthorityOrPort: relativeMalformed, malformedPercentEncoding: relativeMalformedPercentEncoding, malformedSchemeSpecific: relativeMalformedSchemeSpecific, malformedHost: relativeMalformedHost, malformedScheme: relativeMalformedScheme } = parseWithStatus(relativeURI, schemelessOptions);
38624
+ if (baseMalformed || relativeMalformed || baseMalformedPercentEncoding || relativeMalformedPercentEncoding || baseMalformedSchemeSpecific || relativeMalformedSchemeSpecific || baseMalformedHost || relativeMalformedHost || baseMalformedScheme || relativeMalformedScheme) throw new Error(baseParsed.error || relativeParsed.error || "URI is malformed.");
38625
+ const resolved = resolveComponent(baseParsed, relativeParsed, schemelessOptions, true);
38626
+ const resolvedSchemeHandler = getSchemeHandler(options && options.scheme || resolved.scheme);
38627
+ const resolvedHost = resolved.host;
38628
+ const resolvedHostIsIP = resolvedHost !== void 0 && resolvedHost !== "" && (isIPv4(resolvedHost) || normalizeIPv6(resolvedHost).isIPV6);
38629
+ canonicalizeHost(resolved, options || {}, resolvedSchemeHandler, resolvedHostIsIP);
38630
+ const encodedASCIIHost = resolvedHost && resolvedHost.indexOf("%") !== -1 && !/\P{ASCII}/u.test(resolvedHost);
38631
+ if (resolved.error && !encodedASCIIHost) throw new Error(resolved.error);
38168
38632
  schemelessOptions.skipEscape = true;
38169
38633
  return serialize(resolved, schemelessOptions);
38170
38634
  }
@@ -38228,27 +38692,9 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
38228
38692
  * @returns {boolean}
38229
38693
  */
38230
38694
  function equal(uriA, uriB, options) {
38231
- if (typeof uriA === "string") {
38232
- uriA = unescape(uriA);
38233
- uriA = serialize(normalizeComponentEncoding(parse(uriA, options), true), {
38234
- ...options,
38235
- skipEscape: true
38236
- });
38237
- } else if (typeof uriA === "object") uriA = serialize(normalizeComponentEncoding(uriA, true), {
38238
- ...options,
38239
- skipEscape: true
38240
- });
38241
- if (typeof uriB === "string") {
38242
- uriB = unescape(uriB);
38243
- uriB = serialize(normalizeComponentEncoding(parse(uriB, options), true), {
38244
- ...options,
38245
- skipEscape: true
38246
- });
38247
- } else if (typeof uriB === "object") uriB = serialize(normalizeComponentEncoding(uriB, true), {
38248
- ...options,
38249
- skipEscape: true
38250
- });
38251
- return uriA.toLowerCase() === uriB.toLowerCase();
38695
+ const normalizedA = normalizeComparableURI(uriA, options);
38696
+ const normalizedB = normalizeComparableURI(uriB, options);
38697
+ return normalizedA !== void 0 && normalizedB !== void 0 && normalizedA === normalizedB;
38252
38698
  }
38253
38699
  /**
38254
38700
  * @param {Readonly<import('./types/index').URIComponent>} cmpts
@@ -38274,13 +38720,17 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
38274
38720
  };
38275
38721
  const options = Object.assign({}, opts);
38276
38722
  const uriTokens = [];
38723
+ if (component.scheme) component.scheme = decodeValidScheme(component.scheme);
38277
38724
  const schemeHandler = getSchemeHandler(options.scheme || component.scheme);
38278
38725
  if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options);
38279
- if (component.path !== void 0) if (!options.skipEscape) {
38280
- component.path = escape(component.path);
38281
- if (component.scheme !== void 0) component.path = component.path.split("%3A").join(":");
38282
- } else component.path = unescape(component.path);
38283
- if (options.reference !== "suffix" && component.scheme) uriTokens.push(component.scheme, ":");
38726
+ const hasAuthority = component.userinfo !== void 0 || component.host !== void 0 || component.port !== void 0;
38727
+ const pathNoScheme = !options.skipEscape && component.scheme === void 0 && !hasAuthority;
38728
+ if (component.path !== void 0) if (!options.skipEscape) component.path = serializePathEncoding(component.path, pathNoScheme);
38729
+ else component.path = normalizePercentEncoding(component.path);
38730
+ if (options.reference !== "suffix" && component.scheme) {
38731
+ component.scheme = decodeValidScheme(component.scheme);
38732
+ uriTokens.push(component.scheme, ":");
38733
+ }
38284
38734
  const authority = recomposeAuthority(component);
38285
38735
  if (authority !== void 0) {
38286
38736
  if (options.reference !== "suffix") uriTokens.push("//");
@@ -38290,20 +38740,84 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
38290
38740
  if (component.path !== void 0) {
38291
38741
  let s = component.path;
38292
38742
  if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) s = removeDotSegments(s);
38743
+ if (pathNoScheme) s = serializePathEncoding(s, true);
38293
38744
  if (authority === void 0 && s[0] === "/" && s[1] === "/") s = "/%2F" + s.slice(2);
38294
38745
  uriTokens.push(s);
38295
38746
  }
38296
- if (component.query !== void 0) uriTokens.push("?", component.query);
38297
- if (component.fragment !== void 0) uriTokens.push("#", component.fragment);
38747
+ if (component.query !== void 0) uriTokens.push("?", encodeQuery(component.query));
38748
+ if (component.fragment !== void 0) uriTokens.push("#", encodeFragment(component.fragment));
38298
38749
  return uriTokens.join("");
38299
38750
  }
38300
38751
  const URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;
38752
+ const AUTHORITY_PREFIX = /^(?:[^#/:?]+:)?\/\/([^/?#]*)/;
38753
+ const AUTHORITY_INTRODUCER_REGION = /^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;
38754
+ /**
38755
+ * @param {import('./types/index').URIComponent} parsed
38756
+ * @param {RegExpMatchArray} matches
38757
+ * @returns {string|undefined}
38758
+ */
38759
+ function getParseError(parsed, matches) {
38760
+ if (matches[2] !== void 0 && parsed.path && parsed.path[0] !== "/") return "URI path must start with \"/\" when authority is present.";
38761
+ if (typeof parsed.port === "number" && (parsed.port < 0 || parsed.port > 65535)) return "URI port is malformed.";
38762
+ }
38763
+ /**
38764
+ * Checks percent syntax without decoding the represented octets. RFC 3986
38765
+ * percent-encoding is byte-oriented, so sequences such as `%FF` are valid even
38766
+ * though they are not independently valid UTF-8.
38767
+ *
38768
+ * @param {string|undefined} component
38769
+ * @returns {boolean}
38770
+ */
38771
+ function hasMalformedPercentEncoding(component) {
38772
+ if (component === void 0) return false;
38773
+ let percent = component.indexOf("%");
38774
+ while (percent !== -1) {
38775
+ if (percent + 2 >= component.length || !/^[\da-f]{2}$/iu.test(component.slice(percent + 1, percent + 3))) return true;
38776
+ percent = component.indexOf("%", percent + 3);
38777
+ }
38778
+ return false;
38779
+ }
38780
+ /**
38781
+ * Whether the host is a bracketed IP literal (RFC 3986 `IP-literal`).
38782
+ * An unterminated `[` is not a literal, so it must still be validated as a
38783
+ * reg-name instead of being waved through as an IP.
38784
+ *
38785
+ * @param {string} host
38786
+ * @returns {boolean}
38787
+ */
38788
+ function isIPLiteral(host) {
38789
+ return host[0] === "[" && host[host.length - 1] === "]";
38790
+ }
38791
+ /**
38792
+ * @param {RegExpMatchArray} matches
38793
+ * @returns {boolean}
38794
+ */
38795
+ function hasMalformedComponentPercentEncoding(matches) {
38796
+ const host = matches[4];
38797
+ return hasMalformedPercentEncoding(matches[3]) || host !== void 0 && !isIPLiteral(host) && hasMalformedPercentEncoding(host) || hasMalformedPercentEncoding(matches[6]) || hasMalformedPercentEncoding(matches[7]) || hasMalformedPercentEncoding(matches[8]);
38798
+ }
38799
+ /**
38800
+ * @param {import('./types/index').URIComponent} parsed
38801
+ * @param {import('./types/index').Options} options
38802
+ * @param {{ domainHost?: boolean, unicodeSupport?: boolean }|undefined} schemeHandler
38803
+ * @param {boolean} isIP
38804
+ * @returns {boolean} whether host conversion failed
38805
+ */
38806
+ function canonicalizeHost(parsed, options, schemeHandler, isIP) {
38807
+ if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport) && parsed.host && !isIPLiteral(parsed.host) && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) try {
38808
+ parsed.host = new URL("http://" + parsed.host).hostname;
38809
+ } catch (e) {
38810
+ parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e;
38811
+ return true;
38812
+ }
38813
+ return false;
38814
+ }
38301
38815
  /**
38302
38816
  * @param {string} uri
38303
38817
  * @param {import('./types/index').Options} [opts]
38304
- * @returns
38818
+ * @returns {{ parsed: import('./types/index').URIComponent, malformedAuthorityOrPort: boolean, malformedPercentEncoding: boolean, malformedSchemeSpecific: boolean, malformedHost: boolean, malformedScheme: boolean }}
38305
38819
  */
38306
- function parse(uri, opts) {
38820
+ function parseWithStatus(uri, opts) {
38307
38821
  const options = Object.assign({}, opts);
38308
38822
  /** @type {import('./types/index').URIComponent} */
38309
38823
  const parsed = {
@@ -38315,9 +38829,34 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
38315
38829
  query: void 0,
38316
38830
  fragment: void 0
38317
38831
  };
38832
+ let malformedAuthorityOrPort = false;
38833
+ let malformedPercentEncoding = false;
38834
+ let malformedSchemeSpecific = false;
38835
+ let malformedHost = false;
38836
+ let malformedIPLiteral = false;
38837
+ let malformedScheme = false;
38318
38838
  let isIP = false;
38319
38839
  if (options.reference === "suffix") if (options.scheme) uri = options.scheme + ":" + uri;
38320
38840
  else uri = "//" + uri;
38841
+ const authorityMatch = uri.match(AUTHORITY_PREFIX);
38842
+ if (authorityMatch !== null && authorityMatch[1].indexOf("\\") !== -1) {
38843
+ parsed.error = "URI authority must not contain a literal backslash.";
38844
+ malformedAuthorityOrPort = true;
38845
+ }
38846
+ const introducerMatch = uri.match(AUTHORITY_INTRODUCER_REGION);
38847
+ if (introducerMatch !== null) {
38848
+ const region = introducerMatch[1];
38849
+ const normalizedRegion = region.replace(/[\t\n\r]/g, "");
38850
+ if (normalizedRegion.length >= 2) {
38851
+ if (normalizedRegion.slice(0, 2) !== "//") {
38852
+ parsed.error = parsed.error || "URI authority must not contain a literal backslash.";
38853
+ malformedAuthorityOrPort = true;
38854
+ } else if (region.length !== normalizedRegion.length) {
38855
+ parsed.error = parsed.error || "URI authority introducer must not contain whitespace.";
38856
+ malformedAuthorityOrPort = true;
38857
+ }
38858
+ }
38859
+ }
38321
38860
  const matches = uri.match(URI_PARSE);
38322
38861
  if (matches) {
38323
38862
  parsed.scheme = matches[1];
@@ -38327,11 +38866,33 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
38327
38866
  parsed.path = matches[6] || "";
38328
38867
  parsed.query = matches[7];
38329
38868
  parsed.fragment = matches[8];
38869
+ if (parsed.scheme !== void 0) {
38870
+ const decodedScheme = unescape(parsed.scheme);
38871
+ if (VALID_SCHEME.test(decodedScheme)) parsed.scheme = decodedScheme.toLowerCase();
38872
+ else {
38873
+ parsed.error = parsed.error || MALFORMED_SCHEME_ERROR;
38874
+ malformedScheme = true;
38875
+ }
38876
+ }
38877
+ malformedPercentEncoding = hasMalformedComponentPercentEncoding(matches);
38878
+ if (malformedPercentEncoding) parsed.error = parsed.error || "URI contains malformed percent-encoding.";
38330
38879
  if (isNaN(parsed.port)) parsed.port = matches[5];
38880
+ const parseError = getParseError(parsed, matches);
38881
+ if (parseError !== void 0) {
38882
+ parsed.error = parsed.error || parseError;
38883
+ malformedAuthorityOrPort = true;
38884
+ }
38331
38885
  if (parsed.host) if (isIPv4(parsed.host) === false) {
38886
+ const bracketedIPLiteral = isIPLiteral(parsed.host);
38887
+ const hasIPLiteralBracket = parsed.host.indexOf("[") !== -1 || parsed.host.indexOf("]") !== -1;
38332
38888
  const ipv6result = normalizeIPv6(parsed.host);
38333
- parsed.host = ipv6result.host.toLowerCase();
38334
- isIP = ipv6result.isIPV6;
38889
+ isIP = ipv6result.isIPV6 || ipv6result.isIPVFuture === true;
38890
+ malformedIPLiteral = hasIPLiteralBracket && (!bracketedIPLiteral || ipv6result.error === true);
38891
+ parsed.host = isIP ? ipv6result.host : ipv6result.host.toLowerCase();
38892
+ if (malformedIPLiteral) {
38893
+ parsed.error = parsed.error || "URI host is malformed.";
38894
+ malformedAuthorityOrPort = true;
38895
+ }
38335
38896
  } else isIP = true;
38336
38897
  if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) parsed.reference = "same-document";
38337
38898
  else if (parsed.scheme === void 0) parsed.reference = "relative";
@@ -38339,24 +38900,78 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
38339
38900
  else parsed.reference = "uri";
38340
38901
  if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) parsed.error = parsed.error || "URI is not a " + options.reference + " reference.";
38341
38902
  const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme);
38342
- if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {
38343
- if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) try {
38344
- parsed.host = URL.domainToASCII(parsed.host.toLowerCase());
38345
- } catch (e) {
38346
- parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e;
38347
- }
38903
+ if (!malformedIPLiteral) malformedHost = canonicalizeHost(parsed, options, schemeHandler, isIP);
38904
+ if (uri.indexOf("%") !== -1 && parsed.host !== void 0 && !malformedIPLiteral) {
38905
+ let host = isIP ? parsed.host : normalizePercentEncoding(parsed.host, true);
38906
+ if (!isIP) host = normalizePercentEncoding(host.toLowerCase());
38907
+ parsed.host = reescapeHostDelimiters(host, isIP);
38348
38908
  }
38349
38909
  if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) {
38350
- if (uri.indexOf("%") !== -1) {
38351
- if (parsed.scheme !== void 0) parsed.scheme = unescape(parsed.scheme);
38352
- if (parsed.host !== void 0) parsed.host = unescape(parsed.host);
38353
- }
38354
- if (parsed.path) parsed.path = escape(unescape(parsed.path));
38355
- if (parsed.fragment) parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment));
38910
+ if (parsed.path) parsed.path = normalizePathEncoding(parsed.path);
38911
+ if (parsed.query) parsed.query = normalizeQueryFragmentEncoding(parsed.query);
38912
+ if (parsed.fragment) parsed.fragment = normalizeQueryFragmentEncoding(parsed.fragment);
38913
+ }
38914
+ if (schemeHandler && schemeHandler.parse) {
38915
+ schemeHandler.parse(parsed, options);
38916
+ if (schemeHandler === SCHEMES.urn && parsed.nid === void 0) malformedSchemeSpecific = true;
38356
38917
  }
38357
- if (schemeHandler && schemeHandler.parse) schemeHandler.parse(parsed, options);
38358
38918
  } else parsed.error = parsed.error || "URI can not be parsed.";
38359
- return parsed;
38919
+ return {
38920
+ parsed,
38921
+ malformedAuthorityOrPort,
38922
+ malformedPercentEncoding,
38923
+ malformedSchemeSpecific,
38924
+ malformedHost,
38925
+ malformedScheme
38926
+ };
38927
+ }
38928
+ /**
38929
+ * @param {string} uri
38930
+ * @param {import('./types/index').Options} [opts]
38931
+ * @returns
38932
+ */
38933
+ function parse(uri, opts) {
38934
+ return parseWithStatus(uri, opts).parsed;
38935
+ }
38936
+ /**
38937
+ * @param {string} uri
38938
+ * @param {import('./types/index').Options} [opts]
38939
+ * @returns {string}
38940
+ */
38941
+ function normalizeString(uri, opts) {
38942
+ return normalizeStringWithStatus(uri, opts).normalized;
38943
+ }
38944
+ /**
38945
+ * @param {string} uri
38946
+ * @param {import('./types/index').Options} [opts]
38947
+ * @returns {{ normalized: string, malformedAuthorityOrPort: boolean, malformedPercentEncoding: boolean, malformedSchemeSpecific: boolean, malformedHost: boolean, malformedScheme: boolean }}
38948
+ */
38949
+ function normalizeStringWithStatus(uri, opts) {
38950
+ const { parsed, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme } = parseWithStatus(uri, opts);
38951
+ return {
38952
+ normalized: malformedAuthorityOrPort || malformedPercentEncoding || malformedSchemeSpecific || malformedHost || malformedScheme ? uri : serialize(parsed, opts),
38953
+ malformedAuthorityOrPort,
38954
+ malformedPercentEncoding,
38955
+ malformedSchemeSpecific,
38956
+ malformedHost,
38957
+ malformedScheme
38958
+ };
38959
+ }
38960
+ /**
38961
+ * @param {import ('./types/index').URIComponent|string} uri
38962
+ * @param {import('./types/index').Options} [opts]
38963
+ * @returns {string|undefined}
38964
+ */
38965
+ function normalizeComparableURI(uri, opts) {
38966
+ if (typeof uri !== "string" && typeof uri !== "object") return;
38967
+ let value;
38968
+ try {
38969
+ value = typeof uri === "string" ? uri : serialize(uri, opts);
38970
+ } catch {
38971
+ return;
38972
+ }
38973
+ const { normalized, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme } = normalizeStringWithStatus(value, opts);
38974
+ return malformedAuthorityOrPort || malformedPercentEncoding || malformedSchemeSpecific || malformedHost || malformedScheme ? void 0 : normalized;
38360
38975
  }
38361
38976
  const fastUri = {
38362
38977
  SCHEMES,
@@ -42146,7 +42761,7 @@ var AjvJsonSchemaValidator = class {
42146
42761
  };
42147
42762
  import_ajv.Ajv;
42148
42763
  //#endregion
42149
- //#region node_modules/@modelcontextprotocol/server/dist/mcp-DIH4cS6P.mjs
42764
+ //#region node_modules/@modelcontextprotocol/server/dist/mcp-oHn3ureC.mjs
42150
42765
  const COMPLETABLE_SYMBOL = Symbol.for("mcp.completable");
42151
42766
  /**
42152
42767
  * Checks if a schema is completable (has completion metadata).
@@ -42168,225 +42783,229 @@ function armSseKeepAlive(intervalMs, onTick) {
42168
42783
  timer.unref?.();
42169
42784
  return timer;
42170
42785
  }
42786
+ let readClassification;
42171
42787
  /**
42172
- * Whether a `subscriptions/listen` filter accepts a given change event.
42173
- *
42174
- * Pure: no I/O, no mutation. The filter governs ONLY the four
42175
- * subscription-gated change types — non-gated notifications never reach the
42176
- * bus and are not modeled here.
42788
+ * The per-request micro-transport: a real, connected `Transport` whose whole
42789
+ * lifetime is one HTTP exchange. See the module documentation for the
42790
+ * response shapes it produces.
42177
42791
  *
42178
- * `resource_updated` matches only when `resourceSubscriptions` is present and
42179
- * contains the event's URI exactly (per the spec: "for these resource URIs").
42180
- */
42181
- function listenFilterAccepts(filter, event) {
42182
- switch (event.kind) {
42183
- case "tools_list_changed": return filter.toolsListChanged === true;
42184
- case "prompts_list_changed": return filter.promptsListChanged === true;
42185
- case "resources_list_changed": return filter.resourcesListChanged === true;
42186
- case "resource_updated": return filter.resourceSubscriptions !== void 0 && filter.resourceSubscriptions.includes(event.uri);
42187
- }
42188
- }
42189
- /**
42190
- * The honored subset of a requested filter: keeps only the fields the client
42191
- * explicitly opted in to (drops `false` and absent fields), narrowed against
42192
- * the server's declared capabilities when supplied. The serving entry sends
42193
- * this back in `notifications/subscriptions/acknowledged` so the ack reflects
42194
- * what the server can actually deliver.
42195
- *
42196
- * - `toolsListChanged` is honored only when `capabilities.tools.listChanged`
42197
- * is advertised; likewise `promptsListChanged` / `resourcesListChanged`.
42198
- * - `resourceSubscriptions` is honored only when
42199
- * `capabilities.resources.subscribe` is advertised.
42200
- *
42201
- * `capabilities` is optional on this pure helper for test convenience only —
42202
- * both wired routers REQUIRE capabilities at the call site (the HTTP router's
42203
- * `serve()` takes a required parameter; `StdioListenRouter.serve()` throws
42204
- * before `setServerCapabilities()` was called), so the fail-open
42205
- * `undefined → honor everything` branch is never reachable on a wired entry.
42792
+ * Connecting a `Server` binds the instance to the classified modern revision
42793
+ * when its `supportedProtocolVersions` lists it and the SDK implements it.
42206
42794
  */
42207
- function honoredSubset(requested, capabilities) {
42208
- const honored = {};
42209
- const allow = (bit) => capabilities === void 0 || bit === true;
42210
- if (requested.toolsListChanged === true && allow(capabilities?.tools?.listChanged)) honored.toolsListChanged = true;
42211
- if (requested.promptsListChanged === true && allow(capabilities?.prompts?.listChanged)) honored.promptsListChanged = true;
42212
- if (requested.resourcesListChanged === true && allow(capabilities?.resources?.listChanged)) honored.resourcesListChanged = true;
42213
- if (requested.resourceSubscriptions !== void 0 && requested.resourceSubscriptions.length > 0 && allow(capabilities?.resources?.subscribe)) honored.resourceSubscriptions = [...requested.resourceSubscriptions];
42214
- return honored;
42215
- }
42216
- /** Default capacity guard: refuse a new subscription when this many are already open. */
42217
- const DEFAULT_MAX_SUBSCRIPTIONS = 1024;
42218
- /** Stamp the subscription id onto a notification's `_meta`. Non-mutating. */
42219
- function stampSubscriptionId(notification, subscriptionId) {
42220
- return {
42221
- method: notification.method,
42222
- params: {
42223
- ...notification.params,
42224
- _meta: {
42225
- ...notification.params?._meta,
42226
- [SUBSCRIPTION_ID_META_KEY]: subscriptionId
42227
- }
42228
- }
42229
- };
42230
- }
42231
- /**
42232
- * Read the requested filter off a `subscriptions/listen` request body.
42233
- * Returns the validated filter, or `undefined` when `params.notifications`
42234
- * is absent or fails the schema (the caller answers `-32602` — the spec
42235
- * marks `notifications` REQUIRED on the listen request).
42236
- */
42237
- function parseListenFilter(message) {
42238
- const outcome = codecForVersion(MODERN_WIRE_REVISION).validateRequest("subscriptions/listen", message);
42239
- return outcome.ok ? outcome.value.params?.notifications : void 0;
42240
- }
42241
- const CHANGE_NOTIFICATION_METHODS = /* @__PURE__ */ new Set([
42242
- "notifications/tools/list_changed",
42243
- "notifications/prompts/list_changed",
42244
- "notifications/resources/list_changed",
42245
- "notifications/resources/updated"
42246
- ]);
42247
- /**
42248
- * Per-connection listen state for the stdio entry. One instance is held by
42249
- * `serveStdio` for the connection lifetime; it routes inbound
42250
- * `subscriptions/listen` / `notifications/cancelled` and rewrites outbound
42251
- * change notifications onto the active subscriptions. No bus — the long-lived
42252
- * pinned instance's existing `send*ListChanged()` calls feed straight into
42253
- * `routeOutbound()`.
42254
- */
42255
- var StdioListenRouter = class {
42256
- /** Active subscriptions, keyed by the listen request's JSON-RPC id verbatim. */
42257
- _subs = /* @__PURE__ */ new Map();
42258
- /**
42259
- * The serving instance's declared capabilities. Filled in by the entry
42260
- * once the modern instance is constructed (the router is created before
42261
- * the instance exists), so the acknowledged filter is narrowed against
42262
- * what the server can actually deliver.
42263
- */
42264
- _serverCapabilities;
42265
- /**
42266
- * The serving instance's identity, stamped onto the graceful-close
42267
- * results' `_meta` (the spec's `SubscriptionsListenResultMetaObject` extends
42268
- * `ResultMetaObject`). Handed over together with the capabilities.
42269
- */
42270
- _serverInfo;
42271
- constructor(_maxSubscriptions = DEFAULT_MAX_SUBSCRIPTIONS, serverCapabilities, serverInfo) {
42272
- this._maxSubscriptions = _maxSubscriptions;
42273
- this._serverCapabilities = serverCapabilities;
42274
- this._serverInfo = serverInfo;
42795
+ var PerRequestHTTPServerTransport = class {
42796
+ static {
42797
+ readClassification = (transport) => transport._classification;
42275
42798
  }
42799
+ onclose;
42800
+ onerror;
42801
+ onmessage;
42802
+ _classification;
42803
+ _responseMode;
42804
+ _started = false;
42805
+ _used = false;
42806
+ _closed = false;
42807
+ _terminalDelivered = false;
42276
42808
  /**
42277
- * Record the serving instance's declared capabilities and identity once
42278
- * it has been constructed. Called by `serveStdio`'s connect path;
42279
- * subsequent `serve()` calls narrow the honored filter against the
42280
- * capabilities, and `teardownAll()` stamps the identity.
42809
+ * `true` only while the inbound message is being delivered synchronously
42810
+ * to the connected protocol layer. The pre-handler gates (the era
42811
+ * registry gate, the edge→instance handoff check, the missing-handler
42812
+ * rejection) answer inside this window; request handlers always run
42813
+ * after it (the protocol layer defers them to a microtask). An error
42814
+ * sent inside the window is therefore ladder-originated, and an error
42815
+ * sent after it is handler-produced.
42281
42816
  */
42282
- setServerCapabilities(capabilities, serverInfo) {
42283
- this._serverCapabilities = capabilities;
42284
- if (serverInfo !== void 0) this._serverInfo = serverInfo;
42817
+ _dispatchWindowOpen = false;
42818
+ _requestId;
42819
+ _deferredResponse;
42820
+ _sse;
42821
+ _abortCleanup;
42822
+ _keepAliveMs;
42823
+ constructor(options) {
42824
+ this._classification = options.classification;
42825
+ this._responseMode = options.responseMode ?? "auto";
42826
+ this._keepAliveMs = options.keepAliveMs ?? 15e3;
42285
42827
  }
42286
- /** Whether `id` is an active listen subscription on this connection. */
42287
- has(id) {
42288
- return this._subs.has(id);
42828
+ async start() {
42829
+ if (this._started) throw new Error("PerRequestHTTPServerTransport is already started");
42830
+ this._started = true;
42289
42831
  }
42290
42832
  /**
42291
- * Serve one inbound `subscriptions/listen` request: registers the
42292
- * subscription and returns the stamped acknowledged notification (or, on
42293
- * capacity / params rejection, the in-band JSON-RPC error response).
42833
+ * Serves the single exchange: delivers the classified message to the
42834
+ * connected server instance and resolves with the HTTP response.
42294
42835
  *
42295
- * @throws when called before {@linkcode setServerCapabilities} (or the
42296
- * constructor) has supplied the serving instance's capabilities. Honoring a
42297
- * filter without knowing the server's advertised capabilities would fail
42298
- * open (deliver unadvertised types); the entry guarantees capabilities are
42299
- * set before any listen request is routed here.
42836
+ * Throws when called a second time (the transport is strictly
42837
+ * single-use), or before a server has been connected to the transport.
42838
+ * The returned promise rejects with a connection-closed error when the
42839
+ * transport is closed before a response was produced (for example because
42840
+ * the client disconnected).
42300
42841
  */
42301
- serve(message) {
42302
- if (this._serverCapabilities === void 0) throw new Error("StdioListenRouter.serve() called before setServerCapabilities(); refusing to honor a filter without capabilities");
42303
- if (this._subs.size >= this._maxSubscriptions) return {
42304
- jsonrpc: "2.0",
42305
- id: message.id,
42306
- error: {
42307
- code: -32603,
42308
- message: "Subscription limit reached"
42309
- }
42842
+ async handleMessage(message, extra) {
42843
+ if (this._used) throw new Error("PerRequestHTTPServerTransport serves exactly one exchange; construct a new transport per request");
42844
+ if (!this._started || this.onmessage === void 0) throw new Error("PerRequestHTTPServerTransport is not connected: connect a server to this transport before handling a message");
42845
+ if (this._closed) throw new Error("PerRequestHTTPServerTransport is closed");
42846
+ this._used = true;
42847
+ const signal = extra?.request?.signal;
42848
+ if (signal?.aborted) {
42849
+ await this.close();
42850
+ throw new SdkError(SdkErrorCode.ConnectionClosed, "The request was aborted before it could be handled");
42851
+ }
42852
+ const messageExtra = {
42853
+ classification: this._classification,
42854
+ ...extra?.request !== void 0 && { request: extra.request },
42855
+ ...extra?.authInfo !== void 0 && { authInfo: extra.authInfo }
42310
42856
  };
42311
- const filter = parseListenFilter(message);
42312
- if (filter === void 0) return {
42313
- jsonrpc: "2.0",
42314
- id: message.id,
42315
- error: {
42316
- code: -32602,
42317
- message: "Invalid params: 'notifications' is required and must be a valid SubscriptionFilter"
42857
+ if (isJSONRPCRequest(message)) {
42858
+ this._requestId = message.id;
42859
+ let resolve;
42860
+ let reject;
42861
+ const promise = new Promise((promiseResolve, promiseReject) => {
42862
+ resolve = promiseResolve;
42863
+ reject = promiseReject;
42864
+ });
42865
+ this._deferredResponse = {
42866
+ promise,
42867
+ resolve,
42868
+ reject,
42869
+ settled: false
42870
+ };
42871
+ if (signal !== void 0) {
42872
+ const onAbort = () => void this.close();
42873
+ signal.addEventListener("abort", onAbort, { once: true });
42874
+ this._abortCleanup = () => signal.removeEventListener("abort", onAbort);
42318
42875
  }
42319
- };
42320
- const honored = honoredSubset(filter, this._serverCapabilities);
42321
- this._subs.set(message.id, honored);
42322
- return stampSubscriptionId({
42323
- method: "notifications/subscriptions/acknowledged",
42324
- params: { notifications: honored }
42325
- }, message.id);
42876
+ this._dispatchWindowOpen = true;
42877
+ try {
42878
+ this.onmessage(message, messageExtra);
42879
+ } finally {
42880
+ this._dispatchWindowOpen = false;
42881
+ }
42882
+ if (this._responseMode === "sse" && !this._closed && !this._deferredResponse.settled) this.upgradeToSse();
42883
+ return promise;
42884
+ }
42885
+ this.onmessage(message, messageExtra);
42886
+ return new Response(null, { status: 202 });
42326
42887
  }
42327
- /**
42328
- * Tear down one subscription (inbound `notifications/cancelled`). Returns
42329
- * `true` when a subscription was removed. After this call NOTHING further
42330
- * is delivered for that subscription id (the post-cancel hardening).
42331
- */
42332
- cancel(id) {
42333
- return this._subs.delete(id);
42888
+ async send(message, options) {
42889
+ if (this._closed) return;
42890
+ const isResponse = isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message);
42891
+ const relatedId = isResponse ? message.id : options?.relatedRequestId;
42892
+ if (this._requestId === void 0 || relatedId === void 0 || relatedId !== this._requestId) {
42893
+ if (isResponse) this.onerror?.(/* @__PURE__ */ new Error(`Received a response for an unknown request id: ${String(message.id)}`));
42894
+ return;
42895
+ }
42896
+ if (isResponse) {
42897
+ if (this._terminalDelivered) return;
42898
+ this._terminalDelivered = true;
42899
+ const errorCode = isJSONRPCErrorResponse(message) ? message.error.code : void 0;
42900
+ const ladderStatus = errorCode !== void 0 && (this._dispatchWindowOpen || errorCode === ProtocolErrorCode.MissingRequiredClientCapability) ? LADDER_ERROR_HTTP_STATUS[errorCode] : void 0;
42901
+ if (ladderStatus !== void 0 && this._sse === void 0) {
42902
+ this.settleResponse(Response.json(message, {
42903
+ status: ladderStatus,
42904
+ headers: { "Content-Type": "application/json" }
42905
+ }));
42906
+ queueMicrotask(() => void this.close());
42907
+ return;
42908
+ }
42909
+ if (this._sse !== void 0 || this._responseMode === "sse") {
42910
+ if (this._sse === void 0) this.upgradeToSse();
42911
+ this.writeMessageFrame(message);
42912
+ this.finalizeStream();
42913
+ return;
42914
+ }
42915
+ this.settleResponse(Response.json(message, {
42916
+ status: 200,
42917
+ headers: { "Content-Type": "application/json" }
42918
+ }));
42919
+ queueMicrotask(() => void this.close());
42920
+ return;
42921
+ }
42922
+ if (this._responseMode === "json") return;
42923
+ if (this._sse === void 0) this.upgradeToSse();
42924
+ this.writeMessageFrame(message);
42334
42925
  }
42335
42926
  /**
42336
- * Route an outbound notification through the active subscriptions.
42337
- *
42338
- * - For a subscription-gated change notification, returns one stamped copy
42339
- * per subscription that opted in to it (an empty array means it is
42340
- * dropped — the modern era never delivers an un-requested change type).
42341
- * - For any other outbound message, returns `'passthrough'` (the entry
42342
- * forwards it as-is).
42927
+ * Writes an SSE comment frame (a keep-alive heartbeat). Dropped when the
42928
+ * exchange is not currently streaming.
42343
42929
  */
42344
- routeOutbound(message) {
42345
- if (!CHANGE_NOTIFICATION_METHODS.has(message.method)) return "passthrough";
42346
- const uriParam = message.params?.["uri"];
42347
- const uri = typeof uriParam === "string" ? uriParam : void 0;
42348
- const event = notificationToServerEvent(message.method, uri);
42349
- const out = [];
42350
- for (const [subscriptionId, filter] of this._subs) if (listenFilterAccepts(filter, event)) out.push(stampSubscriptionId({
42351
- method: message.method,
42352
- params: message.params ?? {}
42353
- }, subscriptionId));
42354
- return out;
42930
+ writeCommentFrame(comment) {
42931
+ if (this._closed || this._sse === void 0 || this._sse.closed) return;
42932
+ const frame = comment.split("\n").map((line) => `: ${line}`).join("\n");
42933
+ this.writeFrame(`${frame}\n\n`);
42355
42934
  }
42356
- /**
42357
- * Server-side graceful teardown of every active subscription: returns the
42358
- * empty `subscriptions/listen` JSON-RPC result for each subscription id —
42359
- * the spec's graceful-close signal, `_meta` carrying the subscription id
42360
- * and the serving instance's identity — for the entry to emit before
42361
- * closing the wire. Clears the set so nothing further is delivered.
42362
- */
42363
- teardownAll() {
42364
- const out = [];
42365
- for (const id of this._subs.keys()) out.push({
42366
- jsonrpc: "2.0",
42367
- id,
42368
- result: {
42369
- resultType: "complete",
42370
- _meta: {
42371
- [SUBSCRIPTION_ID_META_KEY]: id,
42372
- ...this._serverInfo !== void 0 && { ["io.modelcontextprotocol/serverInfo"]: this._serverInfo }
42373
- }
42935
+ async close() {
42936
+ if (this._closed) return;
42937
+ this._closed = true;
42938
+ this._abortCleanup?.();
42939
+ this._abortCleanup = void 0;
42940
+ if (this._sse?.keepAliveTimer !== void 0) clearInterval(this._sse.keepAliveTimer);
42941
+ if (this._sse !== void 0 && !this._sse.closed) {
42942
+ this._sse.closed = true;
42943
+ try {
42944
+ this._sse.controller.close();
42945
+ } catch {}
42946
+ }
42947
+ if (this._deferredResponse !== void 0 && !this._deferredResponse.settled) {
42948
+ this._deferredResponse.settled = true;
42949
+ this._deferredResponse.reject(new SdkError(SdkErrorCode.ConnectionClosed, "Connection closed before a response was produced"));
42950
+ }
42951
+ this.onclose?.();
42952
+ }
42953
+ settleResponse(response) {
42954
+ if (this._deferredResponse === void 0 || this._deferredResponse.settled) return;
42955
+ this._deferredResponse.settled = true;
42956
+ this._deferredResponse.resolve(response);
42957
+ }
42958
+ upgradeToSse() {
42959
+ let controller;
42960
+ const readable = new ReadableStream({
42961
+ start: (streamController) => {
42962
+ controller = streamController;
42963
+ },
42964
+ cancel: () => {
42965
+ this.close();
42374
42966
  }
42375
42967
  });
42376
- this._subs.clear();
42377
- return out;
42378
- }
42379
- };
42380
- function notificationToServerEvent(method, uri) {
42381
- switch (method) {
42382
- case "notifications/tools/list_changed": return { kind: "tools_list_changed" };
42383
- case "notifications/prompts/list_changed": return { kind: "prompts_list_changed" };
42384
- case "notifications/resources/list_changed": return { kind: "resources_list_changed" };
42385
- default: return {
42386
- kind: "resource_updated",
42387
- uri: uri ?? ""
42968
+ this._sse = {
42969
+ controller,
42970
+ encoder: new TextEncoder(),
42971
+ closed: false
42388
42972
  };
42973
+ this._sse.keepAliveTimer = armSseKeepAlive(this._keepAliveMs, () => this.writeCommentFrame("keepalive"));
42974
+ this.settleResponse(new Response(readable, {
42975
+ status: 200,
42976
+ headers: {
42977
+ "Content-Type": "text/event-stream",
42978
+ "Cache-Control": "no-cache, no-transform",
42979
+ Connection: "keep-alive",
42980
+ "X-Accel-Buffering": "no"
42981
+ }
42982
+ }));
42983
+ }
42984
+ finalizeStream() {
42985
+ if (this._sse?.keepAliveTimer !== void 0) clearInterval(this._sse.keepAliveTimer);
42986
+ if (this._sse !== void 0 && !this._sse.closed) {
42987
+ this._sse.closed = true;
42988
+ try {
42989
+ this._sse.controller.close();
42990
+ } catch {}
42991
+ }
42992
+ queueMicrotask(() => void this.close());
42993
+ }
42994
+ writeMessageFrame(message) {
42995
+ this.writeFrame(`event: message\ndata: ${JSON.stringify(message)}\n\n`);
42996
+ }
42997
+ writeFrame(frame) {
42998
+ if (this._sse === void 0 || this._sse.closed) return;
42999
+ try {
43000
+ this._sse.controller.enqueue(this._sse.encoder.encode(frame));
43001
+ } catch (error) {
43002
+ this.onerror?.(/* @__PURE__ */ new Error(`Failed to write to the response stream: ${error}`));
43003
+ }
42389
43004
  }
43005
+ };
43006
+ /** Package-internal: the classification a per-request transport serves; `undefined` for any other transport. Not public API. */
43007
+ function perRequestClassificationOf(transport) {
43008
+ return transport instanceof PerRequestHTTPServerTransport ? readClassification(transport) : void 0;
42390
43009
  }
42391
43010
  function comparableResource(value) {
42392
43011
  const text = String(value);
@@ -42845,6 +43464,7 @@ var Server = class extends Protocol {
42845
43464
  _requestStateVerify;
42846
43465
  _inputRequiredServing;
42847
43466
  _legacyShim;
43467
+ _boundFromTransport = false;
42848
43468
  /** Lazily-built legacy shim; the loop lives in legacyInputRequiredShim.ts behind a narrow host contract. */
42849
43469
  _legacyInputRequiredShim() {
42850
43470
  return this._legacyShim ??= new LegacyInputRequiredShim({
@@ -42884,6 +43504,15 @@ var Server = class extends Protocol {
42884
43504
  /** Attaches to the given transport; rejects while this instance is connected to another one. */
42885
43505
  async connect(transport) {
42886
43506
  if (this.transport !== void 0) throw new SdkError(SdkErrorCode.AlreadyConnected, "Use a separate Server instance per connection: this instance is already connected to a transport. To connect it to a new transport, call close() first.");
43507
+ if (this._boundFromTransport) {
43508
+ this._boundFromTransport = false;
43509
+ this._negotiatedProtocolVersion = void 0;
43510
+ }
43511
+ const revision = perRequestClassificationOf(transport)?.revision;
43512
+ if (revision !== void 0 && !this._servedModernEra() && SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(revision) && modernProtocolVersions(this._supportedProtocolVersions).includes(revision)) {
43513
+ this._negotiatedProtocolVersion = revision;
43514
+ this._boundFromTransport = true;
43515
+ }
42887
43516
  await super.connect(transport);
42888
43517
  }
42889
43518
  /**
@@ -43194,8 +43823,8 @@ var Server = class extends Protocol {
43194
43823
  * @deprecated Read client identity from the per-request handler context instead: on
43195
43824
  * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` carries the client's
43196
43825
  * declared capabilities, while on 2025-era connections this accessor keeps returning the
43197
- * `initialize`-scoped value. The accessor remains functional — instances serving the
43198
- * 2026-07-28 era are backfilled per request from the validated envelope.
43826
+ * `initialize`-scoped value. The accessor remains functional where `createMcpHandler`
43827
+ * serves the 2026-07-28 era: it backfills it per request from the validated envelope.
43199
43828
  */
43200
43829
  getClientCapabilities() {
43201
43830
  return this._clientCapabilities;
@@ -43206,8 +43835,8 @@ var Server = class extends Protocol {
43206
43835
  * @deprecated Read client identity from the per-request handler context instead: on
43207
43836
  * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` carries the client's
43208
43837
  * name and version, while on 2025-era connections this accessor keeps returning the
43209
- * `initialize`-scoped value. The accessor remains functional — instances serving the
43210
- * 2026-07-28 era are backfilled per request from the validated envelope.
43838
+ * `initialize`-scoped value. The accessor remains functional where `createMcpHandler`
43839
+ * serves the 2026-07-28 era: it backfills it per request from the validated envelope.
43211
43840
  */
43212
43841
  getClientVersion() {
43213
43842
  return this._clientVersion;
@@ -43800,8 +44429,14 @@ var McpServer = class {
43800
44429
  if (updates.uri) this._registeredResources[updates.uri] = registeredResource;
43801
44430
  }
43802
44431
  if (updates.name !== void 0) registeredResource.name = updates.name;
43803
- if (updates.title !== void 0) registeredResource.title = updates.title;
43804
44432
  if (updates.metadata !== void 0) registeredResource.metadata = updates.metadata;
44433
+ if (updates.title !== void 0) {
44434
+ registeredResource.title = updates.title;
44435
+ registeredResource.metadata = {
44436
+ ...registeredResource.metadata,
44437
+ title: updates.title
44438
+ };
44439
+ }
43805
44440
  if (updates.callback !== void 0) registeredResource.readCallback = updates.callback;
43806
44441
  if (updates.scopeChallenge !== void 0) registeredResource.scopeChallenge = updates.scopeChallenge === null ? void 0 : updates.scopeChallenge;
43807
44442
  if (updates.enabled !== void 0) registeredResource.enabled = updates.enabled;
@@ -43827,9 +44462,15 @@ var McpServer = class {
43827
44462
  delete this._registeredResourceTemplates[name];
43828
44463
  if (updates.name) this._registeredResourceTemplates[updates.name] = registeredResourceTemplate;
43829
44464
  }
43830
- if (updates.title !== void 0) registeredResourceTemplate.title = updates.title;
43831
44465
  if (updates.template !== void 0) registeredResourceTemplate.resourceTemplate = updates.template;
43832
44466
  if (updates.metadata !== void 0) registeredResourceTemplate.metadata = updates.metadata;
44467
+ if (updates.title !== void 0) {
44468
+ registeredResourceTemplate.title = updates.title;
44469
+ registeredResourceTemplate.metadata = {
44470
+ ...registeredResourceTemplate.metadata,
44471
+ title: updates.title
44472
+ };
44473
+ }
43833
44474
  if (updates.callback !== void 0) registeredResourceTemplate.readCallback = updates.callback;
43834
44475
  if (updates.scopeChallenge !== void 0) registeredResourceTemplate.scopeChallenge = updates.scopeChallenge === null ? void 0 : updates.scopeChallenge;
43835
44476
  if (updates.enabled !== void 0) registeredResourceTemplate.enabled = updates.enabled;
@@ -44104,6 +44745,228 @@ function unwrapOptionalSchema(schema) {
44104
44745
  return schema.def?.innerType ?? schema;
44105
44746
  }
44106
44747
  //#endregion
44748
+ //#region node_modules/@modelcontextprotocol/server/dist/listenRouter-Bartj63y.mjs
44749
+ /**
44750
+ * Whether a `subscriptions/listen` filter accepts a given change event.
44751
+ *
44752
+ * Pure: no I/O, no mutation. The filter governs ONLY the four
44753
+ * subscription-gated change types — non-gated notifications never reach the
44754
+ * bus and are not modeled here.
44755
+ *
44756
+ * `resource_updated` matches only when `resourceSubscriptions` is present and
44757
+ * contains the event's URI exactly (per the spec: "for these resource URIs").
44758
+ */
44759
+ function listenFilterAccepts(filter, event) {
44760
+ switch (event.kind) {
44761
+ case "tools_list_changed": return filter.toolsListChanged === true;
44762
+ case "prompts_list_changed": return filter.promptsListChanged === true;
44763
+ case "resources_list_changed": return filter.resourcesListChanged === true;
44764
+ case "resource_updated": return filter.resourceSubscriptions !== void 0 && filter.resourceSubscriptions.includes(event.uri);
44765
+ }
44766
+ }
44767
+ /**
44768
+ * The honored subset of a requested filter: keeps only the fields the client
44769
+ * explicitly opted in to (drops `false` and absent fields), narrowed against
44770
+ * the server's declared capabilities when supplied. The serving entry sends
44771
+ * this back in `notifications/subscriptions/acknowledged` so the ack reflects
44772
+ * what the server can actually deliver.
44773
+ *
44774
+ * - `toolsListChanged` is honored only when `capabilities.tools.listChanged`
44775
+ * is advertised; likewise `promptsListChanged` / `resourcesListChanged`.
44776
+ * - `resourceSubscriptions` is honored only when
44777
+ * `capabilities.resources.subscribe` is advertised.
44778
+ *
44779
+ * `capabilities` is optional on this pure helper for test convenience only —
44780
+ * both wired routers REQUIRE capabilities at the call site (the HTTP router's
44781
+ * `serve()` takes a required parameter; `StdioListenRouter.serve()` throws
44782
+ * before `setServerCapabilities()` was called), so the fail-open
44783
+ * `undefined → honor everything` branch is never reachable on a wired entry.
44784
+ */
44785
+ function honoredSubset(requested, capabilities) {
44786
+ const honored = {};
44787
+ const allow = (bit) => capabilities === void 0 || bit === true;
44788
+ if (requested.toolsListChanged === true && allow(capabilities?.tools?.listChanged)) honored.toolsListChanged = true;
44789
+ if (requested.promptsListChanged === true && allow(capabilities?.prompts?.listChanged)) honored.promptsListChanged = true;
44790
+ if (requested.resourcesListChanged === true && allow(capabilities?.resources?.listChanged)) honored.resourcesListChanged = true;
44791
+ if (requested.resourceSubscriptions !== void 0 && requested.resourceSubscriptions.length > 0 && allow(capabilities?.resources?.subscribe)) honored.resourceSubscriptions = [...requested.resourceSubscriptions];
44792
+ return honored;
44793
+ }
44794
+ /** Default capacity guard: refuse a new subscription when this many are already open. */
44795
+ const DEFAULT_MAX_SUBSCRIPTIONS = 1024;
44796
+ /** Stamp the subscription id onto a notification's `_meta`. Non-mutating. */
44797
+ function stampSubscriptionId(notification, subscriptionId) {
44798
+ return {
44799
+ method: notification.method,
44800
+ params: {
44801
+ ...notification.params,
44802
+ _meta: {
44803
+ ...notification.params?._meta,
44804
+ [SUBSCRIPTION_ID_META_KEY]: subscriptionId
44805
+ }
44806
+ }
44807
+ };
44808
+ }
44809
+ /**
44810
+ * Read the requested filter off a `subscriptions/listen` request body.
44811
+ * Returns the validated filter, or `undefined` when `params.notifications`
44812
+ * is absent or fails the schema (the caller answers `-32602` — the spec
44813
+ * marks `notifications` REQUIRED on the listen request).
44814
+ */
44815
+ function parseListenFilter(message) {
44816
+ const outcome = codecForVersion(MODERN_WIRE_REVISION).validateRequest("subscriptions/listen", message);
44817
+ return outcome.ok ? outcome.value.params?.notifications : void 0;
44818
+ }
44819
+ const CHANGE_NOTIFICATION_METHODS = /* @__PURE__ */ new Set([
44820
+ "notifications/tools/list_changed",
44821
+ "notifications/prompts/list_changed",
44822
+ "notifications/resources/list_changed",
44823
+ "notifications/resources/updated"
44824
+ ]);
44825
+ /**
44826
+ * Per-connection listen state for the stdio entry. One instance is held by
44827
+ * `serveStdio` for the connection lifetime; it routes inbound
44828
+ * `subscriptions/listen` / `notifications/cancelled` and rewrites outbound
44829
+ * change notifications onto the active subscriptions. No bus — the long-lived
44830
+ * pinned instance's existing `send*ListChanged()` calls feed straight into
44831
+ * `routeOutbound()`.
44832
+ */
44833
+ var StdioListenRouter = class {
44834
+ /** Active subscriptions, keyed by the listen request's JSON-RPC id verbatim. */
44835
+ _subs = /* @__PURE__ */ new Map();
44836
+ /**
44837
+ * The serving instance's declared capabilities. Filled in by the entry
44838
+ * once the modern instance is constructed (the router is created before
44839
+ * the instance exists), so the acknowledged filter is narrowed against
44840
+ * what the server can actually deliver.
44841
+ */
44842
+ _serverCapabilities;
44843
+ /**
44844
+ * The serving instance's identity, stamped onto the graceful-close
44845
+ * results' `_meta` (the spec's `SubscriptionsListenResultMetaObject` extends
44846
+ * `ResultMetaObject`). Handed over together with the capabilities.
44847
+ */
44848
+ _serverInfo;
44849
+ constructor(_maxSubscriptions = DEFAULT_MAX_SUBSCRIPTIONS, serverCapabilities, serverInfo) {
44850
+ this._maxSubscriptions = _maxSubscriptions;
44851
+ this._serverCapabilities = serverCapabilities;
44852
+ this._serverInfo = serverInfo;
44853
+ }
44854
+ /**
44855
+ * Record the serving instance's declared capabilities and identity once
44856
+ * it has been constructed. Called by `serveStdio`'s connect path;
44857
+ * subsequent `serve()` calls narrow the honored filter against the
44858
+ * capabilities, and `teardownAll()` stamps the identity.
44859
+ */
44860
+ setServerCapabilities(capabilities, serverInfo) {
44861
+ this._serverCapabilities = capabilities;
44862
+ if (serverInfo !== void 0) this._serverInfo = serverInfo;
44863
+ }
44864
+ /** Whether `id` is an active listen subscription on this connection. */
44865
+ has(id) {
44866
+ return this._subs.has(id);
44867
+ }
44868
+ /**
44869
+ * Serve one inbound `subscriptions/listen` request: registers the
44870
+ * subscription and returns the stamped acknowledged notification (or, on
44871
+ * capacity / params rejection, the in-band JSON-RPC error response).
44872
+ *
44873
+ * @throws when called before {@linkcode setServerCapabilities} (or the
44874
+ * constructor) has supplied the serving instance's capabilities. Honoring a
44875
+ * filter without knowing the server's advertised capabilities would fail
44876
+ * open (deliver unadvertised types); the entry guarantees capabilities are
44877
+ * set before any listen request is routed here.
44878
+ */
44879
+ serve(message) {
44880
+ if (this._serverCapabilities === void 0) throw new Error("StdioListenRouter.serve() called before setServerCapabilities(); refusing to honor a filter without capabilities");
44881
+ if (this._subs.size >= this._maxSubscriptions) return {
44882
+ jsonrpc: "2.0",
44883
+ id: message.id,
44884
+ error: {
44885
+ code: -32603,
44886
+ message: "Subscription limit reached"
44887
+ }
44888
+ };
44889
+ const filter = parseListenFilter(message);
44890
+ if (filter === void 0) return {
44891
+ jsonrpc: "2.0",
44892
+ id: message.id,
44893
+ error: {
44894
+ code: -32602,
44895
+ message: "Invalid params: 'notifications' is required and must be a valid SubscriptionFilter"
44896
+ }
44897
+ };
44898
+ const honored = honoredSubset(filter, this._serverCapabilities);
44899
+ this._subs.set(message.id, honored);
44900
+ return stampSubscriptionId({
44901
+ method: "notifications/subscriptions/acknowledged",
44902
+ params: { notifications: honored }
44903
+ }, message.id);
44904
+ }
44905
+ /**
44906
+ * Tear down one subscription (inbound `notifications/cancelled`). Returns
44907
+ * `true` when a subscription was removed. After this call NOTHING further
44908
+ * is delivered for that subscription id (the post-cancel hardening).
44909
+ */
44910
+ cancel(id) {
44911
+ return this._subs.delete(id);
44912
+ }
44913
+ /**
44914
+ * Route an outbound notification through the active subscriptions.
44915
+ *
44916
+ * - For a subscription-gated change notification, returns one stamped copy
44917
+ * per subscription that opted in to it (an empty array means it is
44918
+ * dropped — the modern era never delivers an un-requested change type).
44919
+ * - For any other outbound message, returns `'passthrough'` (the entry
44920
+ * forwards it as-is).
44921
+ */
44922
+ routeOutbound(message) {
44923
+ if (!CHANGE_NOTIFICATION_METHODS.has(message.method)) return "passthrough";
44924
+ const uriParam = message.params?.["uri"];
44925
+ const uri = typeof uriParam === "string" ? uriParam : void 0;
44926
+ const event = notificationToServerEvent(message.method, uri);
44927
+ const out = [];
44928
+ for (const [subscriptionId, filter] of this._subs) if (listenFilterAccepts(filter, event)) out.push(stampSubscriptionId({
44929
+ method: message.method,
44930
+ params: message.params ?? {}
44931
+ }, subscriptionId));
44932
+ return out;
44933
+ }
44934
+ /**
44935
+ * Server-side graceful teardown of every active subscription: returns the
44936
+ * empty `subscriptions/listen` JSON-RPC result for each subscription id —
44937
+ * the spec's graceful-close signal, `_meta` carrying the subscription id
44938
+ * and the serving instance's identity — for the entry to emit before
44939
+ * closing the wire. Clears the set so nothing further is delivered.
44940
+ */
44941
+ teardownAll() {
44942
+ const out = [];
44943
+ for (const id of this._subs.keys()) out.push({
44944
+ jsonrpc: "2.0",
44945
+ id,
44946
+ result: {
44947
+ resultType: "complete",
44948
+ _meta: {
44949
+ [SUBSCRIPTION_ID_META_KEY]: id,
44950
+ ...this._serverInfo !== void 0 && { ["io.modelcontextprotocol/serverInfo"]: this._serverInfo }
44951
+ }
44952
+ }
44953
+ });
44954
+ this._subs.clear();
44955
+ return out;
44956
+ }
44957
+ };
44958
+ function notificationToServerEvent(method, uri) {
44959
+ switch (method) {
44960
+ case "notifications/tools/list_changed": return { kind: "tools_list_changed" };
44961
+ case "notifications/prompts/list_changed": return { kind: "prompts_list_changed" };
44962
+ case "notifications/resources/list_changed": return { kind: "resources_list_changed" };
44963
+ default: return {
44964
+ kind: "resource_updated",
44965
+ uri: uri ?? ""
44966
+ };
44967
+ }
44968
+ }
44969
+ //#endregion
44107
44970
  //#region node_modules/@modelcontextprotocol/server/dist/index.mjs
44108
44971
  /** Default upper bound, in bytes, on a request body read by the HTTP entry points (4 MiB). */
44109
44972
  const DEFAULT_MAX_REQUEST_BODY_SIZE = 4194304;
@@ -45900,7 +46763,7 @@ const { getVersion, getBuildTimestamp, getAllVersions } = require_Console.frodo.
45900
46763
  * rather than a tsup build, since no bundler ever substitutes the
45901
46764
  * identifier there.
45902
46765
  */
45903
- const getCliBuildTimestamp = () => "2026-10-30T16:18:20.127Z";
46766
+ const getCliBuildTimestamp = () => "2026-10-31T01:41:07.564Z";
45904
46767
  const VERSION_CACHE_FILE = `${os.default.homedir()}/.frodo/Versions.json`;
45905
46768
  const VERSION_CHECK_INTERVAL = 86400;
45906
46769
  const ENDPOINTS = [{
@@ -55229,7 +56092,7 @@ var require_file = /* @__PURE__ */ require_rolldown_runtime.__commonJSMin(((expo
55229
56092
  * MIT LICENCE
55230
56093
  */
55231
56094
  var require_http = /* @__PURE__ */ require_rolldown_runtime.__commonJSMin(((exports, module) => {
55232
- const http$1 = require("http");
56095
+ const http = require("http");
55233
56096
  const https = require("https");
55234
56097
  const { Stream } = require_readable();
55235
56098
  const TransportStream = require_winston_transport();
@@ -55402,7 +56265,7 @@ var require_http = /* @__PURE__ */ require_rolldown_runtime.__commonJSMin(((expo
55402
56265
  _doRequest(options, callback, auth, path) {
55403
56266
  const headers = Object.assign({}, this.headers);
55404
56267
  if (auth && auth.bearer) headers.Authorization = `Bearer ${auth.bearer}`;
55405
- const req = (this.ssl ? https : http$1).request({
56268
+ const req = (this.ssl ? https : http).request({
55406
56269
  ...this.options,
55407
56270
  method: "POST",
55408
56271
  host: this.host,
@@ -57430,29 +58293,236 @@ var RequestError = class extends Error {
57430
58293
  this.name = "RequestError";
57431
58294
  }
57432
58295
  };
57433
- var toRequestError = (e) => {
58296
+ const nonJoinedHeaders = /* @__PURE__ */ new Set([
58297
+ "age",
58298
+ "authorization",
58299
+ "content-length",
58300
+ "content-type",
58301
+ "etag",
58302
+ "expires",
58303
+ "from",
58304
+ "host",
58305
+ "if-modified-since",
58306
+ "if-unmodified-since",
58307
+ "last-modified",
58308
+ "location",
58309
+ "max-forwards",
58310
+ "proxy-authorization",
58311
+ "referer",
58312
+ "retry-after",
58313
+ "server",
58314
+ "user-agent"
58315
+ ]);
58316
+ const validHeaderName = /^[!#$%&'*+\-.^_`|~\dA-Za-z]+$/;
58317
+ const isHttpWhitespace = (code) => code === 9 || code === 10 || code === 13 || code === 32;
58318
+ const normalizeHeaderValue = (value) => {
58319
+ if (!isHttpWhitespace(value.charCodeAt(0)) && !isHttpWhitespace(value.charCodeAt(value.length - 1))) return value;
58320
+ let start = 0;
58321
+ let end = value.length;
58322
+ while (start < end && isHttpWhitespace(value.charCodeAt(start))) start++;
58323
+ while (end > start && isHttpWhitespace(value.charCodeAt(end - 1))) end--;
58324
+ return value.slice(start, end);
58325
+ };
58326
+ const forbiddenHeaderValue = /[\0\r\n]/;
58327
+ const GlobalHeaders = globalThis.Headers;
58328
+ const materializeHeaders = (rawHeaders, HeadersCtor = GlobalHeaders) => {
58329
+ const headers = new HeadersCtor();
58330
+ for (let i = 0; i < rawHeaders.length; i += 2) {
58331
+ const name = rawHeaders[i];
58332
+ if (!name.startsWith(":")) headers.append(name, rawHeaders[i + 1]);
58333
+ }
58334
+ return headers;
58335
+ };
58336
+ var RequestHeaders = class {
58337
+ #incoming;
58338
+ #rawHeaders;
58339
+ #headers;
58340
+ #invalidValue;
58341
+ constructor(incoming) {
58342
+ this.#incoming = incoming;
58343
+ if (incoming instanceof node_http2.Http2ServerRequest) this.#rawHeaders = incoming.rawHeaders.slice();
58344
+ }
58345
+ get #lazyRawHeaders() {
58346
+ return this.#rawHeaders ??= this.#incoming.rawHeaders.slice();
58347
+ }
58348
+ get #native() {
58349
+ if (!this.#headers) {
58350
+ this.#headers = materializeHeaders(this.#lazyRawHeaders);
58351
+ this.#rawHeaders = void 0;
58352
+ }
58353
+ return this.#headers;
58354
+ }
58355
+ #normalizedName(name) {
58356
+ if (typeof name !== "string") return;
58357
+ if (!validHeaderName.test(name)) throw new TypeError(`Invalid header name: ${name}`);
58358
+ return name.toLowerCase();
58359
+ }
58360
+ #lookupHttp1(lowerName) {
58361
+ const headers = this.#incoming instanceof node_http2.Http2ServerRequest ? void 0 : this.#incoming.headers;
58362
+ if (!headers || nonJoinedHeaders.has(lowerName) || lowerName === "set-cookie" || lowerName === "__proto__") return;
58363
+ if (!Object.hasOwn(headers, lowerName)) return null;
58364
+ const rawValue = headers[lowerName];
58365
+ if (typeof rawValue === "string") {
58366
+ const value = normalizeHeaderValue(rawValue);
58367
+ return forbiddenHeaderValue.test(value) ? void 0 : value;
58368
+ }
58369
+ }
58370
+ #lookup(rawHeaders, lowerName) {
58371
+ const separator = lowerName === "cookie" ? "; " : ", ";
58372
+ let value = null;
58373
+ for (let i = 0; i < rawHeaders.length; i += 2) {
58374
+ const rawName = rawHeaders[i];
58375
+ if (rawName.length === lowerName.length && rawName.toLowerCase() === lowerName) {
58376
+ const rawValue = normalizeHeaderValue(rawHeaders[i + 1]);
58377
+ if (forbiddenHeaderValue.test(rawValue)) {
58378
+ this.#invalidValue = true;
58379
+ return;
58380
+ }
58381
+ value = value === null ? rawValue : value + separator + rawValue;
58382
+ }
58383
+ }
58384
+ return value;
58385
+ }
58386
+ append(name, value) {
58387
+ this.#native.append(name, value);
58388
+ }
58389
+ delete(name) {
58390
+ this.#native.delete(name);
58391
+ }
58392
+ get(name) {
58393
+ const lowerName = this.#normalizedName(name);
58394
+ if (lowerName && !this.#headers && !this.#invalidValue) {
58395
+ const http1Value = this.#lookupHttp1(lowerName);
58396
+ if (http1Value !== void 0) return http1Value;
58397
+ const value = this.#lookup(this.#lazyRawHeaders, lowerName);
58398
+ if (value !== void 0) return value;
58399
+ }
58400
+ return this.#native.get(name);
58401
+ }
58402
+ has(name) {
58403
+ const lowerName = this.#normalizedName(name);
58404
+ if (lowerName && !this.#headers && !this.#invalidValue) {
58405
+ const http1Value = this.#lookupHttp1(lowerName);
58406
+ if (http1Value !== void 0) return http1Value !== null;
58407
+ const value = this.#lookup(this.#lazyRawHeaders, lowerName);
58408
+ if (value !== void 0) return value !== null;
58409
+ }
58410
+ return this.#native.has(name);
58411
+ }
58412
+ set(name, value) {
58413
+ this.#native.set(name, value);
58414
+ }
58415
+ getSetCookie() {
58416
+ return this.#native.getSetCookie();
58417
+ }
58418
+ keys() {
58419
+ return this.#native.keys();
58420
+ }
58421
+ values() {
58422
+ return this.#native.values();
58423
+ }
58424
+ entries() {
58425
+ return this.#native.entries();
58426
+ }
58427
+ forEach(callback, thisArg) {
58428
+ this.#native.forEach((value, key) => {
58429
+ callback.call(thisArg, value, key, this);
58430
+ });
58431
+ }
58432
+ [Symbol.iterator]() {
58433
+ return this.entries();
58434
+ }
58435
+ };
58436
+ Object.defineProperty(RequestHeaders.prototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
58437
+ return `Headers (lightweight) ${inspectFn(Object.fromEntries(this), {
58438
+ ...options,
58439
+ depth: depth == null ? null : depth - 1
58440
+ })}`;
58441
+ } });
58442
+ Object.setPrototypeOf(RequestHeaders.prototype, GlobalHeaders.prototype);
58443
+ const newHeadersFromIncoming = (incoming) => globalThis.Headers === GlobalHeaders ? new RequestHeaders(incoming) : materializeHeaders(incoming.rawHeaders, globalThis.Headers);
58444
+ const reValidRequestUrl = /^\/[!#$&-;=?-\[\]_a-z~]*$/;
58445
+ const reDotSegment = /\/\.\.?(?:[/?#]|$)/;
58446
+ const reValidHost = /^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/;
58447
+ const buildUrl = (scheme, host, incomingUrl) => {
58448
+ const url = `${scheme}://${host}${incomingUrl}`;
58449
+ if (!reValidHost.test(host)) {
58450
+ const urlObj = new URL(url);
58451
+ if (urlObj.hostname.length !== host.length && urlObj.hostname !== (host.includes(":") ? host.replace(/:\d+$/, "") : host).toLowerCase()) throw new RequestError("Invalid host header");
58452
+ return urlObj.href;
58453
+ } else if (incomingUrl.length === 0) return url + "/";
58454
+ else {
58455
+ if (incomingUrl.charCodeAt(0) !== 47) throw new RequestError("Invalid URL");
58456
+ if (!reValidRequestUrl.test(incomingUrl) || reDotSegment.test(incomingUrl)) return new URL(url).href;
58457
+ return url;
58458
+ }
58459
+ };
58460
+ const toRequestError = (e) => {
57434
58461
  if (e instanceof RequestError) return e;
57435
58462
  return new RequestError(e.message, { cause: e });
57436
58463
  };
57437
- var GlobalRequest = global.Request;
58464
+ const GlobalRequest = global.Request;
57438
58465
  var Request$1 = class extends GlobalRequest {
57439
58466
  constructor(input, options) {
57440
- if (typeof input === "object" && getRequestCache in input) input = input[getRequestCache]();
57441
- if (typeof options?.body?.getReader !== "undefined") options.duplex ??= "half";
58467
+ if (typeof input === "object" && getRequestCache in input) {
58468
+ const hasReplacementBody = options !== void 0 && "body" in options && options.body != null;
58469
+ if (input[bodyConsumedDirectlyKey] && !hasReplacementBody) throw new TypeError("Cannot construct a Request with a Request object that has already been used.");
58470
+ input = input[getRequestCache]();
58471
+ }
58472
+ if (typeof (options?.body)?.getReader !== "undefined") options.duplex ??= "half";
57442
58473
  super(input, options);
57443
58474
  }
57444
58475
  };
57445
- var newHeadersFromIncoming = (incoming) => {
57446
- const headerRecord = [];
57447
- const rawHeaders = incoming.rawHeaders;
57448
- for (let i = 0; i < rawHeaders.length; i += 2) {
57449
- const { [i]: key, [i + 1]: value } = rawHeaders;
57450
- if (key.charCodeAt(0) !== 58) headerRecord.push([key, value]);
58476
+ const wrapBodyStream = Symbol("wrapBodyStream");
58477
+ const byteExactEncodings = /* @__PURE__ */ new Set([
58478
+ "latin1",
58479
+ "binary",
58480
+ "hex",
58481
+ "base64",
58482
+ "base64url"
58483
+ ]);
58484
+ const isByteExactEncoding = (encoding) => encoding === null || byteExactEncodings.has(encoding);
58485
+ const bodyBufferedBeforeDisconnectKey = Symbol("bodyBufferedBeforeDisconnect");
58486
+ const bodyBufferedLengthBeforeDisconnectKey = Symbol("bodyBufferedLengthBeforeDisconnect");
58487
+ const toBufferChunk = (chunk, encoding) => Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding ?? "utf8");
58488
+ const isRecoverableDisconnectedIncoming = (incoming) => !(incoming instanceof node_http2.Http2ServerRequest) && !!incoming.complete && !!incoming.readableAborted && typeof incoming.read === "function" && isByteExactEncoding(incoming.readableEncoding);
58489
+ const recordBodyBufferedBeforeDisconnect = (incoming) => {
58490
+ if (incoming.readableDidRead || !isRecoverableDisconnectedIncoming(incoming)) return;
58491
+ const incomingWithRecovery = incoming;
58492
+ incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey] ??= incoming.readableLength;
58493
+ };
58494
+ const readBodyBufferedBeforeDisconnect = (incoming, chunks) => {
58495
+ if (incoming.readableDidRead && !chunks || !isRecoverableDisconnectedIncoming(incoming)) return;
58496
+ const incomingWithRecovery = incoming;
58497
+ if (incomingWithRecovery[bodyBufferedBeforeDisconnectKey] !== void 0) return incomingWithRecovery[bodyBufferedBeforeDisconnectKey];
58498
+ let result;
58499
+ const errored = incoming.errored;
58500
+ if (errored && errored.code !== "ECONNRESET") result = errored;
58501
+ else if (incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey] !== void 0 && incoming.readableLength !== incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey]) result = newBodyUnusableError();
58502
+ else {
58503
+ const bodyChunks = chunks ?? [];
58504
+ const chunk = incoming.read();
58505
+ if (chunk !== null) bodyChunks.push(toBufferChunk(chunk, incoming.readableEncoding));
58506
+ const buffer = bodyChunks.length === 1 ? bodyChunks[0] : Buffer.concat(bodyChunks);
58507
+ result = buffer;
58508
+ const contentLength = incoming.headers["content-length"];
58509
+ if (typeof contentLength === "string" && /^\d+$/.test(contentLength)) {
58510
+ const expectedLength = Number(contentLength);
58511
+ if (Number.isSafeInteger(expectedLength) && buffer.length !== expectedLength) result = newBodyUnusableError();
58512
+ }
58513
+ }
58514
+ incomingWithRecovery[bodyBufferedBeforeDisconnectKey] = result;
58515
+ return result;
58516
+ };
58517
+ const enqueueBufferedBody = (controller, buffered) => {
58518
+ if (buffered instanceof Error) {
58519
+ controller.error(buffered);
58520
+ return;
57451
58521
  }
57452
- return new Headers(headerRecord);
58522
+ if (buffered.length > 0) controller.enqueue(buffered);
58523
+ controller.close();
57453
58524
  };
57454
- var wrapBodyStream = Symbol("wrapBodyStream");
57455
- var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
58525
+ const newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
57456
58526
  const init = {
57457
58527
  method,
57458
58528
  headers,
@@ -57466,36 +58536,215 @@ var newRequestFromIncoming = (method, url, headers, incoming, abortController) =
57466
58536
  } });
57467
58537
  return req;
57468
58538
  }
57469
- if (!(method === "GET" || method === "HEAD")) {
57470
- if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) init.body = new ReadableStream({ start(controller) {
57471
- controller.enqueue(incoming.rawBody);
57472
- controller.close();
57473
- } });
57474
- else if (incoming[wrapBodyStream]) {
57475
- let reader;
57476
- init.body = new ReadableStream({ async pull(controller) {
57477
- try {
57478
- reader ||= stream.Readable.toWeb(incoming).getReader();
57479
- const { done, value } = await reader.read();
57480
- if (done) controller.close();
57481
- else controller.enqueue(value);
57482
- } catch (error) {
57483
- controller.error(error);
58539
+ if (!(method === "GET" || method === "HEAD")) if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) init.body = new ReadableStream({ start(controller) {
58540
+ controller.enqueue(incoming.rawBody);
58541
+ controller.close();
58542
+ } });
58543
+ else if (incoming[wrapBodyStream]) {
58544
+ let reader;
58545
+ init.body = new ReadableStream({ async pull(controller) {
58546
+ try {
58547
+ if (!reader) {
58548
+ const buffered = readBodyBufferedBeforeDisconnect(incoming);
58549
+ if (buffered !== void 0) {
58550
+ enqueueBufferedBody(controller, buffered);
58551
+ return;
58552
+ }
57484
58553
  }
57485
- } });
57486
- } else init.body = stream.Readable.toWeb(incoming);
58554
+ reader ||= node_stream.Readable.toWeb(incoming).getReader();
58555
+ const { done, value } = await reader.read();
58556
+ if (done) controller.close();
58557
+ else controller.enqueue(value);
58558
+ } catch (error) {
58559
+ controller.error(error);
58560
+ }
58561
+ } });
58562
+ } else {
58563
+ const buffered = readBodyBufferedBeforeDisconnect(incoming);
58564
+ if (buffered !== void 0) init.body = new ReadableStream({ start(controller) {
58565
+ enqueueBufferedBody(controller, buffered);
58566
+ } });
58567
+ else init.body = node_stream.Readable.toWeb(incoming);
57487
58568
  }
57488
58569
  return new Request$1(url, init);
57489
58570
  };
57490
- var getRequestCache = Symbol("getRequestCache");
57491
- var requestCache = Symbol("requestCache");
57492
- var incomingKey = Symbol("incomingKey");
57493
- var urlKey = Symbol("urlKey");
57494
- var headersKey = Symbol("headersKey");
57495
- var abortControllerKey = Symbol("abortControllerKey");
57496
- var requestPrototype = {
58571
+ const getRequestCache = Symbol("getRequestCache");
58572
+ const requestCache = Symbol("requestCache");
58573
+ const incomingKey = Symbol("incomingKey");
58574
+ const urlKey = Symbol("urlKey");
58575
+ const methodKey = Symbol("methodKey");
58576
+ const headersKey = Symbol("headersKey");
58577
+ const abortControllerKey = Symbol("abortControllerKey");
58578
+ const getAbortController = Symbol("getAbortController");
58579
+ const abortRequest = Symbol("abortRequest");
58580
+ const bodyBufferKey = Symbol("bodyBuffer");
58581
+ const bodyReadPromiseKey = Symbol("bodyReadPromise");
58582
+ const bodyConsumedDirectlyKey = Symbol("bodyConsumedDirectly");
58583
+ const bodyLockReaderKey = Symbol("bodyLockReader");
58584
+ const abortReasonKey = Symbol("abortReason");
58585
+ const newBodyUnusableError = () => {
58586
+ return /* @__PURE__ */ new TypeError("Body is unusable");
58587
+ };
58588
+ const rejectBodyUnusable = () => {
58589
+ return Promise.reject(newBodyUnusableError());
58590
+ };
58591
+ const textDecoder = new TextDecoder();
58592
+ const consumeBodyDirectOnce = (request) => {
58593
+ if (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
58594
+ request[bodyConsumedDirectlyKey] = true;
58595
+ };
58596
+ const toArrayBuffer = (buf) => {
58597
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
58598
+ };
58599
+ const contentType = (request) => {
58600
+ return (request[headersKey] ||= newHeadersFromIncoming(request[incomingKey])).get("content-type") || "";
58601
+ };
58602
+ const methodTokenRegExp = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
58603
+ const normalizeIncomingMethod = (method) => {
58604
+ if (typeof method !== "string" || method.length === 0) return "GET";
58605
+ switch (method) {
58606
+ case "DELETE":
58607
+ case "GET":
58608
+ case "HEAD":
58609
+ case "OPTIONS":
58610
+ case "PATCH":
58611
+ case "POST":
58612
+ case "PUT":
58613
+ case "QUERY": return method;
58614
+ }
58615
+ const upper = method.toUpperCase();
58616
+ switch (upper) {
58617
+ case "DELETE":
58618
+ case "GET":
58619
+ case "HEAD":
58620
+ case "OPTIONS":
58621
+ case "POST":
58622
+ case "PUT": return upper;
58623
+ default: return method;
58624
+ }
58625
+ };
58626
+ const validateDirectReadMethod = (method) => {
58627
+ if (!methodTokenRegExp.test(method)) return /* @__PURE__ */ new TypeError(`'${method}' is not a valid HTTP method.`);
58628
+ const normalized = method.toUpperCase();
58629
+ if (normalized === "CONNECT" || normalized === "TRACK" || normalized === "TRACE" && method !== "TRACE") return /* @__PURE__ */ new TypeError(`'${method}' HTTP method is unsupported.`);
58630
+ };
58631
+ const readBodyWithFastPath = (request, method, fromBuffer) => {
58632
+ if (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
58633
+ const methodName = request.method;
58634
+ if (methodName === "GET" || methodName === "HEAD") return request[getRequestCache]()[method]();
58635
+ const methodValidationError = validateDirectReadMethod(methodName);
58636
+ if (methodValidationError) return Promise.reject(methodValidationError);
58637
+ if (request[requestCache]) {
58638
+ if (methodName !== "TRACE") return request[requestCache][method]();
58639
+ }
58640
+ const alreadyUsedError = consumeBodyDirectOnce(request);
58641
+ if (alreadyUsedError) return alreadyUsedError;
58642
+ const raw = readRawBodyIfAvailable(request);
58643
+ if (raw) {
58644
+ const result = Promise.resolve(fromBuffer(raw, request));
58645
+ request[bodyBufferKey] = void 0;
58646
+ return result;
58647
+ }
58648
+ return readBodyDirect(request).then((buf) => {
58649
+ const result = fromBuffer(buf, request);
58650
+ request[bodyBufferKey] = void 0;
58651
+ return result;
58652
+ });
58653
+ };
58654
+ const readRawBodyIfAvailable = (request) => {
58655
+ const incoming = request[incomingKey];
58656
+ if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) return incoming.rawBody;
58657
+ };
58658
+ const normalizeAbortError = (request, incoming) => {
58659
+ if (incoming.errored) return incoming.errored;
58660
+ const reason = request[abortReasonKey];
58661
+ if (reason !== void 0) return reason instanceof Error ? reason : new Error(String(reason));
58662
+ return /* @__PURE__ */ new Error("Client connection prematurely closed.");
58663
+ };
58664
+ const readBodyDirect = (request) => {
58665
+ if (request[bodyBufferKey]) return Promise.resolve(request[bodyBufferKey]);
58666
+ if (request[bodyReadPromiseKey]) return request[bodyReadPromiseKey];
58667
+ const incoming = request[incomingKey];
58668
+ if (incoming.readableDidRead) return rejectBodyUnusable();
58669
+ const buffered = readBodyBufferedBeforeDisconnect(incoming);
58670
+ if (buffered !== void 0) {
58671
+ if (buffered instanceof Error) return Promise.reject(buffered);
58672
+ request[bodyBufferKey] = buffered;
58673
+ return Promise.resolve(buffered);
58674
+ }
58675
+ const promise = new Promise((resolve, reject) => {
58676
+ const chunks = [];
58677
+ let settled = false;
58678
+ const finish = (callback) => {
58679
+ if (settled) return;
58680
+ settled = true;
58681
+ cleanup();
58682
+ callback();
58683
+ };
58684
+ const recoverCompleteBodyAfterDisconnect = (error) => {
58685
+ const streamError = incoming.errored ?? error;
58686
+ if (!isRecoverableDisconnectedIncoming(incoming) || streamError && streamError.code !== "ECONNRESET") return false;
58687
+ finish(() => {
58688
+ const recovered = readBodyBufferedBeforeDisconnect(incoming, chunks);
58689
+ if (recovered instanceof Error) reject(recovered);
58690
+ else if (recovered === void 0) reject(error ?? normalizeAbortError(request, incoming));
58691
+ else {
58692
+ request[bodyBufferKey] = recovered;
58693
+ resolve(recovered);
58694
+ }
58695
+ });
58696
+ return true;
58697
+ };
58698
+ const onData = (chunk) => {
58699
+ chunks.push(toBufferChunk(chunk, incoming.readableEncoding));
58700
+ };
58701
+ const onEnd = () => {
58702
+ finish(() => {
58703
+ const buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks);
58704
+ request[bodyBufferKey] = buffer;
58705
+ resolve(buffer);
58706
+ });
58707
+ };
58708
+ const onError = (error) => {
58709
+ if (recoverCompleteBodyAfterDisconnect(error)) return;
58710
+ finish(() => {
58711
+ reject(error);
58712
+ });
58713
+ };
58714
+ const onClose = () => {
58715
+ if (incoming.readableEnded) {
58716
+ onEnd();
58717
+ return;
58718
+ }
58719
+ if (recoverCompleteBodyAfterDisconnect()) return;
58720
+ finish(() => {
58721
+ reject(normalizeAbortError(request, incoming));
58722
+ });
58723
+ };
58724
+ const cleanup = () => {
58725
+ incoming.off("data", onData);
58726
+ incoming.off("end", onEnd);
58727
+ incoming.off("error", onError);
58728
+ incoming.off("close", onClose);
58729
+ request[bodyReadPromiseKey] = void 0;
58730
+ };
58731
+ incoming.on("data", onData);
58732
+ incoming.on("end", onEnd);
58733
+ incoming.on("error", onError);
58734
+ incoming.on("close", onClose);
58735
+ queueMicrotask(() => {
58736
+ if (settled) return;
58737
+ if (incoming.readableEnded) onEnd();
58738
+ else if (incoming.errored) onError(incoming.errored);
58739
+ else if (incoming.destroyed) onClose();
58740
+ });
58741
+ });
58742
+ request[bodyReadPromiseKey] = promise;
58743
+ return promise;
58744
+ };
58745
+ const requestPrototype = {
57497
58746
  get method() {
57498
- return this[incomingKey].method || "GET";
58747
+ return this[methodKey];
57499
58748
  },
57500
58749
  get url() {
57501
58750
  return this[urlKey];
@@ -57503,18 +58752,57 @@ var requestPrototype = {
57503
58752
  get headers() {
57504
58753
  return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
57505
58754
  },
57506
- [Symbol("getAbortController")]() {
57507
- this[getRequestCache]();
58755
+ [abortRequest](reason) {
58756
+ if (this[abortReasonKey] === void 0) this[abortReasonKey] = reason;
58757
+ const abortController = this[abortControllerKey];
58758
+ if (abortController && !abortController.signal.aborted) abortController.abort(reason);
58759
+ },
58760
+ [getAbortController]() {
58761
+ this[abortControllerKey] ||= new AbortController();
58762
+ if (this[abortReasonKey] !== void 0 && !this[abortControllerKey].signal.aborted) this[abortControllerKey].abort(this[abortReasonKey]);
57508
58763
  return this[abortControllerKey];
57509
58764
  },
57510
58765
  [getRequestCache]() {
57511
- this[abortControllerKey] ||= new AbortController();
57512
- return this[requestCache] ||= newRequestFromIncoming(this.method, this[urlKey], this.headers, this[incomingKey], this[abortControllerKey]);
58766
+ const abortController = this[getAbortController]();
58767
+ if (this[requestCache]) return this[requestCache];
58768
+ const method = this.method;
58769
+ if (this[bodyConsumedDirectlyKey] && !(method === "GET" || method === "HEAD")) {
58770
+ this[bodyBufferKey] = void 0;
58771
+ const init = {
58772
+ method: method === "TRACE" ? "GET" : method,
58773
+ headers: this.headers,
58774
+ signal: abortController.signal
58775
+ };
58776
+ if (method !== "TRACE") {
58777
+ init.body = new ReadableStream({ start(c) {
58778
+ c.close();
58779
+ } });
58780
+ init.duplex = "half";
58781
+ }
58782
+ const req = new Request$1(this[urlKey], init);
58783
+ if (method === "TRACE") Object.defineProperty(req, "method", { get() {
58784
+ return "TRACE";
58785
+ } });
58786
+ return this[requestCache] = req;
58787
+ }
58788
+ return this[requestCache] = newRequestFromIncoming(this.method, this[urlKey], this.headers, this[incomingKey], abortController);
58789
+ },
58790
+ get body() {
58791
+ if (!this[bodyConsumedDirectlyKey]) return this[getRequestCache]().body;
58792
+ const request = this[getRequestCache]();
58793
+ if (!this[bodyLockReaderKey] && request.body) this[bodyLockReaderKey] = request.body.getReader();
58794
+ return request.body;
58795
+ },
58796
+ get bodyUsed() {
58797
+ if (this[bodyConsumedDirectlyKey]) return true;
58798
+ if (this[requestCache]) return this[requestCache].bodyUsed;
58799
+ return false;
57513
58800
  }
57514
58801
  };
58802
+ Object.defineProperty(requestPrototype, "signal", { get() {
58803
+ return this[getAbortController]().signal;
58804
+ } });
57515
58805
  [
57516
- "body",
57517
- "bodyUsed",
57518
58806
  "cache",
57519
58807
  "credentials",
57520
58808
  "destination",
@@ -57523,25 +58811,37 @@ var requestPrototype = {
57523
58811
  "redirect",
57524
58812
  "referrer",
57525
58813
  "referrerPolicy",
57526
- "signal",
57527
58814
  "keepalive"
57528
58815
  ].forEach((k) => {
57529
58816
  Object.defineProperty(requestPrototype, k, { get() {
57530
58817
  return this[getRequestCache]()[k];
57531
58818
  } });
57532
58819
  });
57533
- [
57534
- "arrayBuffer",
57535
- "blob",
57536
- "clone",
57537
- "formData",
57538
- "json",
57539
- "text"
57540
- ].forEach((k) => {
58820
+ ["clone", "formData"].forEach((k) => {
57541
58821
  Object.defineProperty(requestPrototype, k, { value: function() {
58822
+ if (this[bodyConsumedDirectlyKey]) {
58823
+ if (k === "clone") throw newBodyUnusableError();
58824
+ return rejectBodyUnusable();
58825
+ }
57542
58826
  return this[getRequestCache]()[k]();
57543
58827
  } });
57544
58828
  });
58829
+ Object.defineProperty(requestPrototype, "text", { value: function() {
58830
+ return readBodyWithFastPath(this, "text", (buf) => textDecoder.decode(buf));
58831
+ } });
58832
+ Object.defineProperty(requestPrototype, "arrayBuffer", { value: function() {
58833
+ return readBodyWithFastPath(this, "arrayBuffer", (buf) => toArrayBuffer(buf));
58834
+ } });
58835
+ Object.defineProperty(requestPrototype, "blob", { value: function() {
58836
+ return readBodyWithFastPath(this, "blob", (buf, request) => {
58837
+ const type = contentType(request);
58838
+ return new Response(buf, type ? { headers: { "content-type": type } } : void 0).blob();
58839
+ });
58840
+ } });
58841
+ Object.defineProperty(requestPrototype, "json", { value: function() {
58842
+ if (this[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
58843
+ return this.text().then(JSON.parse);
58844
+ } });
57545
58845
  Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
57546
58846
  return `Request (lightweight) ${inspectFn({
57547
58847
  method: this.method,
@@ -57554,12 +58854,13 @@ Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom")
57554
58854
  })}`;
57555
58855
  } });
57556
58856
  Object.setPrototypeOf(requestPrototype, Request$1.prototype);
57557
- var newRequest = (incoming, defaultHostname) => {
58857
+ const newRequest = (incoming, defaultHostname) => {
57558
58858
  const req = Object.create(requestPrototype);
57559
58859
  req[incomingKey] = incoming;
58860
+ req[methodKey] = normalizeIncomingMethod(incoming.method);
57560
58861
  const incomingUrl = incoming.url || "";
57561
58862
  if (incomingUrl[0] !== "/" && (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
57562
- if (incoming instanceof http2.Http2ServerRequest) throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
58863
+ if (incoming instanceof node_http2.Http2ServerRequest) throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
57563
58864
  try {
57564
58865
  req[urlKey] = new URL(incomingUrl).href;
57565
58866
  } catch (e) {
@@ -57567,53 +58868,62 @@ var newRequest = (incoming, defaultHostname) => {
57567
58868
  }
57568
58869
  return req;
57569
58870
  }
57570
- const host = (incoming instanceof http2.Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
58871
+ const host = (incoming instanceof node_http2.Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
57571
58872
  if (!host) throw new RequestError("Missing host header");
57572
58873
  let scheme;
57573
- if (incoming instanceof http2.Http2ServerRequest) {
58874
+ if (incoming instanceof node_http2.Http2ServerRequest) {
57574
58875
  scheme = incoming.scheme;
57575
58876
  if (!(scheme === "http" || scheme === "https")) throw new RequestError("Unsupported scheme");
57576
58877
  } else scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
57577
- const url = new URL(`${scheme}://${host}${incomingUrl}`);
57578
- if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) throw new RequestError("Invalid host header");
57579
- req[urlKey] = url.href;
58878
+ try {
58879
+ req[urlKey] = buildUrl(scheme, host, incomingUrl);
58880
+ } catch (e) {
58881
+ if (e instanceof RequestError) throw e;
58882
+ else throw new RequestError("Invalid URL", { cause: e });
58883
+ }
57580
58884
  return req;
57581
58885
  };
57582
- var responseCache = Symbol("responseCache");
57583
- var getResponseCache = Symbol("getResponseCache");
57584
- var cacheKey = Symbol("cache");
57585
- var GlobalResponse = global.Response;
57586
- var Response2 = class _Response {
58886
+ const defaultContentType = "text/plain; charset=UTF-8";
58887
+ const responseCache = Symbol("responseCache");
58888
+ const getResponseCache = Symbol("getResponseCache");
58889
+ const cacheKey = Symbol("cache");
58890
+ const GlobalResponse = global.Response;
58891
+ var Response$1 = class Response$1 {
57587
58892
  #body;
57588
58893
  #init;
57589
58894
  [getResponseCache]() {
58895
+ const cache = this[cacheKey];
58896
+ const liveHeaders = cache && cache[2] instanceof Headers ? cache[2] : void 0;
57590
58897
  delete this[cacheKey];
57591
- return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
58898
+ return this[responseCache] ||= new GlobalResponse(this.#body, liveHeaders ? {
58899
+ status: this.#init?.status,
58900
+ statusText: this.#init?.statusText,
58901
+ headers: liveHeaders
58902
+ } : this.#init);
57592
58903
  }
57593
58904
  constructor(body, init) {
57594
58905
  let headers;
57595
58906
  this.#body = body;
57596
- if (init instanceof _Response) {
58907
+ if (init instanceof GlobalResponse) {
57597
58908
  const cachedGlobalResponse = init[responseCache];
57598
58909
  if (cachedGlobalResponse) {
57599
58910
  this.#init = cachedGlobalResponse;
57600
58911
  this[getResponseCache]();
57601
58912
  return;
57602
- } else {
57603
- this.#init = init.#init;
57604
- headers = new Headers(init.#init.headers);
57605
58913
  }
58914
+ this.#init = init instanceof Response$1 ? init.#init : init;
58915
+ headers = new Headers(init.headers);
57606
58916
  } else this.#init = init;
57607
- if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) this[cacheKey] = [
58917
+ if (body == null || typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) this[cacheKey] = [
57608
58918
  init?.status || 200,
57609
- body,
58919
+ body ?? null,
57610
58920
  headers || init?.headers
57611
58921
  ];
57612
58922
  }
57613
58923
  get headers() {
57614
58924
  const cache = this[cacheKey];
57615
58925
  if (cache) {
57616
- if (!(cache[2] instanceof Headers)) cache[2] = new Headers(cache[2] || { "content-type": "text/plain; charset=UTF-8" });
58926
+ if (!(cache[2] instanceof Headers)) cache[2] = new Headers(cache[2] || (cache[1] === null ? void 0 : { "content-type": defaultContentType }));
57617
58927
  return cache[2];
57618
58928
  }
57619
58929
  return this[getResponseCache]().headers;
@@ -57635,7 +58945,7 @@ var Response2 = class _Response {
57635
58945
  "type",
57636
58946
  "url"
57637
58947
  ].forEach((k) => {
57638
- Object.defineProperty(Response2.prototype, k, { get() {
58948
+ Object.defineProperty(Response$1.prototype, k, { get() {
57639
58949
  return this[getResponseCache]()[k];
57640
58950
  } });
57641
58951
  });
@@ -57647,11 +58957,11 @@ var Response2 = class _Response {
57647
58957
  "json",
57648
58958
  "text"
57649
58959
  ].forEach((k) => {
57650
- Object.defineProperty(Response2.prototype, k, { value: function() {
58960
+ Object.defineProperty(Response$1.prototype, k, { value: function() {
57651
58961
  return this[getResponseCache]()[k]();
57652
58962
  } });
57653
58963
  });
57654
- Object.defineProperty(Response2.prototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
58964
+ Object.defineProperty(Response$1.prototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
57655
58965
  return `Response (lightweight) ${inspectFn({
57656
58966
  status: this.status,
57657
58967
  headers: this.headers,
@@ -57662,8 +58972,51 @@ Object.defineProperty(Response2.prototype, Symbol.for("nodejs.util.inspect.custo
57662
58972
  depth: depth == null ? null : depth - 1
57663
58973
  })}`;
57664
58974
  } });
57665
- Object.setPrototypeOf(Response2, GlobalResponse);
57666
- Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
58975
+ Object.setPrototypeOf(Response$1, GlobalResponse);
58976
+ Object.setPrototypeOf(Response$1.prototype, GlobalResponse.prototype);
58977
+ const validRedirectUrl = /^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/;
58978
+ const parseRedirectUrl = (url) => {
58979
+ if (url instanceof URL) return url.href;
58980
+ if (validRedirectUrl.test(url)) return url;
58981
+ return new URL(url).href;
58982
+ };
58983
+ const validRedirectStatuses = /* @__PURE__ */ new Set([
58984
+ 301,
58985
+ 302,
58986
+ 303,
58987
+ 307,
58988
+ 308
58989
+ ]);
58990
+ Object.defineProperty(Response$1, "redirect", {
58991
+ value: function redirect(url, status = 302) {
58992
+ if (!validRedirectStatuses.has(status)) throw new RangeError("Invalid status code");
58993
+ return new Response$1(null, {
58994
+ status,
58995
+ headers: { location: parseRedirectUrl(url) }
58996
+ });
58997
+ },
58998
+ writable: true,
58999
+ configurable: true
59000
+ });
59001
+ Object.defineProperty(Response$1, "json", {
59002
+ value: function json(data, init) {
59003
+ const body = JSON.stringify(data);
59004
+ if (body === void 0) throw new TypeError("The data is not JSON serializable");
59005
+ const initHeaders = init?.headers;
59006
+ let headers;
59007
+ if (initHeaders) {
59008
+ headers = new Headers(initHeaders);
59009
+ if (!headers.has("content-type")) headers.set("content-type", "application/json");
59010
+ } else headers = { "content-type": "application/json" };
59011
+ return new Response$1(body, {
59012
+ status: init?.status ?? 200,
59013
+ statusText: init?.statusText,
59014
+ headers
59015
+ });
59016
+ },
59017
+ writable: true,
59018
+ configurable: true
59019
+ });
57667
59020
  async function readWithoutBlocking(readPromise) {
57668
59021
  return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
57669
59022
  }
@@ -57694,34 +59047,34 @@ function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromi
57694
59047
  }
57695
59048
  }
57696
59049
  }
57697
- function writeFromReadableStream(stream$1, writable) {
57698
- if (stream$1.locked) throw new TypeError("ReadableStream is locked.");
59050
+ function writeFromReadableStream(stream, writable) {
59051
+ if (stream.locked) throw new TypeError("ReadableStream is locked.");
57699
59052
  else if (writable.destroyed) return;
57700
- return writeFromReadableStreamDefaultReader(stream$1.getReader(), writable);
59053
+ return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
57701
59054
  }
57702
- var buildOutgoingHttpHeaders = (headers) => {
59055
+ const buildOutgoingHttpHeaders = (headers, defaultContentType) => {
57703
59056
  const res = {};
57704
59057
  if (!(headers instanceof Headers)) headers = new Headers(headers ?? void 0);
57705
- const cookies = [];
57706
- for (const [k, v] of headers) if (k === "set-cookie") cookies.push(v);
57707
- else res[k] = v;
57708
- if (cookies.length > 0) res["set-cookie"] = cookies;
57709
- res["content-type"] ??= "text/plain; charset=UTF-8";
59058
+ if (headers.has("set-cookie")) {
59059
+ const cookies = [];
59060
+ for (const [k, v] of headers) if (k === "set-cookie") cookies.push(v);
59061
+ else res[k] = v;
59062
+ if (cookies.length > 0) res["set-cookie"] = cookies;
59063
+ } else for (const [k, v] of headers) res[k] = v;
59064
+ if (defaultContentType) res["content-type"] ??= defaultContentType;
57710
59065
  return res;
57711
59066
  };
57712
- var X_ALREADY_SENT = "x-hono-already-sent";
57713
- if (typeof global.crypto === "undefined") global.crypto = crypto$1.default;
57714
- var outgoingEnded = Symbol("outgoingEnded");
57715
- var incomingDraining = Symbol("incomingDraining");
57716
- var DRAIN_TIMEOUT_MS = 500;
57717
- var MAX_DRAIN_BYTES = 67108864;
57718
- var drainIncoming = (incoming) => {
59067
+ const outgoingEnded = Symbol("outgoingEnded");
59068
+ const incomingDraining = Symbol("incomingDraining");
59069
+ const DRAIN_TIMEOUT_MS = 500;
59070
+ const MAX_DRAIN_BYTES = 67108864;
59071
+ const drainIncoming = (incoming) => {
57719
59072
  const incomingWithDrainState = incoming;
57720
59073
  if (incoming.destroyed || incomingWithDrainState[incomingDraining]) return;
57721
59074
  incomingWithDrainState[incomingDraining] = true;
57722
- if (incoming instanceof http2.Http2ServerRequest) {
59075
+ if (incoming instanceof node_http2.Http2ServerRequest) {
57723
59076
  try {
57724
- incoming.stream?.close?.(http2.constants.NGHTTP2_NO_ERROR);
59077
+ incoming.stream?.close?.(node_http2.constants.NGHTTP2_NO_ERROR);
57725
59078
  } catch {}
57726
59079
  return;
57727
59080
  }
@@ -57735,7 +59088,10 @@ var drainIncoming = (incoming) => {
57735
59088
  const forceClose = () => {
57736
59089
  cleanup();
57737
59090
  const socket = incoming.socket;
57738
- if (socket && !socket.destroyed) socket.destroySoon();
59091
+ if (socket && !socket.destroyed) {
59092
+ if (typeof socket.destroySoon === "function") socket.destroySoon();
59093
+ else if (typeof socket.destroy === "function") socket.destroy();
59094
+ }
57739
59095
  };
57740
59096
  const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
57741
59097
  timer.unref?.();
@@ -57748,43 +59104,114 @@ var drainIncoming = (incoming) => {
57748
59104
  incoming.on("error", cleanup);
57749
59105
  incoming.resume();
57750
59106
  };
57751
- var handleRequestError = () => new Response(null, { status: 400 });
57752
- var handleFetchError = (e) => new Response(null, { status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500 });
57753
- var handleResponseError = (e, outgoing) => {
59107
+ const makeCloseHandler = (req, incoming, outgoing, needsBodyCleanup) => () => {
59108
+ if (incoming.errored) {
59109
+ recordBodyBufferedBeforeDisconnect(incoming);
59110
+ req[abortRequest](incoming.errored.toString());
59111
+ } else if (!outgoing.writableFinished || incoming instanceof node_http2.Http2ServerRequest && incoming.aborted) {
59112
+ recordBodyBufferedBeforeDisconnect(incoming);
59113
+ req[abortRequest]("Client connection prematurely closed.");
59114
+ }
59115
+ if (needsBodyCleanup && !incoming.readableEnded) setTimeout(() => {
59116
+ if (!incoming.readableEnded) setTimeout(() => {
59117
+ drainIncoming(incoming);
59118
+ });
59119
+ });
59120
+ };
59121
+ const isImmediateCacheableResponse = (res) => {
59122
+ if (!(cacheKey in res)) return false;
59123
+ const body = res[cacheKey][1];
59124
+ return body === null || typeof body === "string" || body instanceof Uint8Array;
59125
+ };
59126
+ const handleRequestError = () => new Response(null, { status: 400 });
59127
+ const handleFetchError = (e) => new Response(null, { status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500 });
59128
+ const handleResponseError = (e, outgoing) => {
57754
59129
  const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
57755
59130
  if (err.code === "ERR_STREAM_PREMATURE_CLOSE") console.info("The user aborted a request.");
57756
59131
  else {
57757
59132
  console.error(e);
57758
- if (!outgoing.headersSent) outgoing.writeHead(500, { "Content-Type": "text/plain" });
59133
+ if (!outgoing.headersSent) {
59134
+ if (outgoing instanceof node_http.ServerResponse) outgoing._contentLength = null;
59135
+ outgoing.writeHead(500, { "Content-Type": "text/plain" });
59136
+ }
57759
59137
  outgoing.end(`Error: ${err.message}`);
57760
59138
  outgoing.destroy(err);
57761
59139
  }
57762
59140
  };
57763
- var flushHeaders = (outgoing) => {
59141
+ const flushHeaders = (outgoing) => {
57764
59142
  if ("flushHeaders" in outgoing && outgoing.writable) outgoing.flushHeaders();
57765
59143
  };
57766
- var responseViaCache = async (res, outgoing) => {
59144
+ const trySetContentLength = (outgoing, status, length) => {
59145
+ const http1 = outgoing;
59146
+ if (http1._contentLength === null && http1._hasBody && http1.useChunkedEncodingByDefault && !http1._removedContLen && status >= 200 && status !== 204 && status !== 304 && !outgoing.hasHeader("content-length") && !outgoing.hasHeader("transfer-encoding") && !outgoing.hasHeader("trailer")) {
59147
+ http1._contentLength = length;
59148
+ return true;
59149
+ }
59150
+ return false;
59151
+ };
59152
+ const writeDefaultHeaders = (outgoing, status, length) => {
59153
+ if (trySetContentLength(outgoing, status, length)) outgoing.writeHead(status, { "Content-Type": defaultContentType });
59154
+ else outgoing.writeHead(status, {
59155
+ "Content-Type": defaultContentType,
59156
+ "Content-Length": length
59157
+ });
59158
+ };
59159
+ const responseViaCache = async (res, outgoing) => {
57767
59160
  let [status, body, header] = res[cacheKey];
59161
+ if (!header) {
59162
+ if (body === null) {
59163
+ outgoing.writeHead(status);
59164
+ outgoing.end();
59165
+ } else if (typeof body === "string") {
59166
+ writeDefaultHeaders(outgoing, status, Buffer.byteLength(body));
59167
+ outgoing.end(body);
59168
+ } else if (body instanceof Uint8Array) {
59169
+ writeDefaultHeaders(outgoing, status, body.byteLength);
59170
+ outgoing.end(body);
59171
+ } else if (body instanceof Blob) {
59172
+ writeDefaultHeaders(outgoing, status, body.size);
59173
+ outgoing.end(new Uint8Array(await body.arrayBuffer()));
59174
+ } else {
59175
+ outgoing.writeHead(status, { "Content-Type": defaultContentType });
59176
+ flushHeaders(outgoing);
59177
+ await writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));
59178
+ }
59179
+ outgoing[outgoingEnded]?.();
59180
+ return;
59181
+ }
57768
59182
  let hasContentLength = false;
57769
- if (!header) header = { "content-type": "text/plain; charset=UTF-8" };
57770
- else if (header instanceof Headers) {
59183
+ let plainHeaders = false;
59184
+ let canAutoLength = true;
59185
+ if (header instanceof Headers) {
57771
59186
  hasContentLength = header.has("content-length");
57772
- header = buildOutgoingHttpHeaders(header);
59187
+ header = buildOutgoingHttpHeaders(header, body === null ? void 0 : defaultContentType);
57773
59188
  } else if (Array.isArray(header)) {
57774
59189
  const headerObj = new Headers(header);
57775
59190
  hasContentLength = headerObj.has("content-length");
57776
- header = buildOutgoingHttpHeaders(headerObj);
57777
- } else for (const key in header) if (key.length === 14 && key.toLowerCase() === "content-length") {
57778
- hasContentLength = true;
57779
- break;
59191
+ header = buildOutgoingHttpHeaders(headerObj, body === null ? void 0 : defaultContentType);
59192
+ } else {
59193
+ plainHeaders = true;
59194
+ for (const key in header) {
59195
+ if (key.length === 14 && key.toLowerCase() === "content-length") {
59196
+ hasContentLength = true;
59197
+ break;
59198
+ }
59199
+ if (key.length === 17 && key.toLowerCase() === "transfer-encoding" || key.length === 7 && key.toLowerCase() === "trailer") canAutoLength = false;
59200
+ }
57780
59201
  }
57781
59202
  if (!hasContentLength) {
57782
- if (typeof body === "string") header["Content-Length"] = Buffer.byteLength(body);
57783
- else if (body instanceof Uint8Array) header["Content-Length"] = body.byteLength;
57784
- else if (body instanceof Blob) header["Content-Length"] = body.size;
59203
+ let length;
59204
+ if (typeof body === "string") length = Buffer.byteLength(body);
59205
+ else if (body instanceof Uint8Array) length = body.byteLength;
59206
+ else if (body instanceof Blob) length = body.size;
59207
+ if (length !== void 0 && (!plainHeaders || !canAutoLength || !trySetContentLength(outgoing, status, length))) {
59208
+ if (plainHeaders) header = { ...header };
59209
+ header["Content-Length"] = length;
59210
+ }
57785
59211
  }
57786
59212
  outgoing.writeHead(status, header);
57787
- if (typeof body === "string" || body instanceof Uint8Array) outgoing.end(body);
59213
+ if (body == null) outgoing.end();
59214
+ else if (typeof body === "string" || body instanceof Uint8Array) outgoing.end(body);
57788
59215
  else if (body instanceof Blob) outgoing.end(new Uint8Array(await body.arrayBuffer()));
57789
59216
  else {
57790
59217
  flushHeaders(outgoing);
@@ -57792,20 +59219,18 @@ var responseViaCache = async (res, outgoing) => {
57792
59219
  }
57793
59220
  outgoing[outgoingEnded]?.();
57794
59221
  };
57795
- var isPromise = (res) => typeof res.then === "function";
57796
- var responseViaResponseObject = async (res, outgoing, options = {}) => {
57797
- if (isPromise(res)) {
57798
- if (options.errorHandler) try {
57799
- res = await res;
57800
- } catch (err) {
57801
- const errRes = await options.errorHandler(err);
57802
- if (!errRes) return;
57803
- res = errRes;
57804
- }
57805
- else res = await res.catch(handleFetchError);
59222
+ const isPromise = (res) => typeof res.then === "function";
59223
+ const responseViaResponseObject = async (res, outgoing, options = {}) => {
59224
+ if (isPromise(res)) if (options.errorHandler) try {
59225
+ res = await res;
59226
+ } catch (err) {
59227
+ const errRes = await options.errorHandler(err);
59228
+ if (!errRes) return;
59229
+ res = errRes;
57806
59230
  }
59231
+ else res = await res.catch(handleFetchError);
57807
59232
  if (cacheKey in res) return responseViaCache(res, outgoing);
57808
- const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
59233
+ const resHeaderRecord = buildOutgoingHttpHeaders(res.headers, res.body === null ? void 0 : defaultContentType);
57809
59234
  if (res.body) {
57810
59235
  const reader = res.body.getReader();
57811
59236
  const values = [];
@@ -57845,63 +59270,60 @@ var responseViaResponseObject = async (res, outgoing, options = {}) => {
57845
59270
  if (values.length === 0) flushHeaders(outgoing);
57846
59271
  await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
57847
59272
  }
57848
- } else if (resHeaderRecord[X_ALREADY_SENT]) {} else {
59273
+ } else if (resHeaderRecord["x-hono-already-sent"]) {} else {
57849
59274
  outgoing.writeHead(res.status, resHeaderRecord);
57850
59275
  outgoing.end();
57851
59276
  }
57852
59277
  outgoing[outgoingEnded]?.();
57853
59278
  };
57854
- var getRequestListener = (fetchCallback, options = {}) => {
59279
+ const getRequestListener = (fetchCallback, options = {}) => {
57855
59280
  const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
57856
59281
  if (options.overrideGlobalObjects !== false && global.Request !== Request$1) {
57857
59282
  Object.defineProperty(global, "Request", { value: Request$1 });
57858
- Object.defineProperty(global, "Response", { value: Response2 });
59283
+ Object.defineProperty(global, "Response", { value: Response$1 });
57859
59284
  }
57860
59285
  return async (incoming, outgoing) => {
57861
59286
  let res, req;
59287
+ let needsBodyCleanup = false;
59288
+ let closeHandlerAttached = false;
59289
+ const ensureCloseHandler = () => {
59290
+ if (!req || closeHandlerAttached) return;
59291
+ closeHandlerAttached = true;
59292
+ outgoing.on("close", makeCloseHandler(req, incoming, outgoing, needsBodyCleanup));
59293
+ };
57862
59294
  try {
57863
59295
  req = newRequest(incoming, options.hostname);
57864
- let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
57865
- if (!incomingEnded) {
59296
+ needsBodyCleanup = autoCleanupIncoming && !(incoming.method === "GET" || incoming.method === "HEAD");
59297
+ if (needsBodyCleanup) {
57866
59298
  incoming[wrapBodyStream] = true;
57867
- incoming.on("end", () => {
57868
- incomingEnded = true;
57869
- });
57870
- if (incoming instanceof http2.Http2ServerRequest) outgoing[outgoingEnded] = () => {
57871
- if (!incomingEnded) setTimeout(() => {
57872
- if (!incomingEnded) setTimeout(() => {
57873
- drainIncoming(incoming);
59299
+ if (incoming instanceof node_http2.Http2ServerRequest) outgoing[outgoingEnded] = () => {
59300
+ if (!incoming.readableEnded) setTimeout(() => {
59301
+ if (!incoming.readableEnded) setTimeout(() => {
59302
+ incoming.destroy();
59303
+ outgoing.destroy();
57874
59304
  });
57875
59305
  });
57876
59306
  };
57877
- outgoing.on("finish", () => {
57878
- if (!incomingEnded) drainIncoming(incoming);
57879
- });
57880
59307
  }
57881
- outgoing.on("close", () => {
57882
- if (req[abortControllerKey]) {
57883
- if (incoming.errored) req[abortControllerKey].abort(incoming.errored.toString());
57884
- else if (!outgoing.writableFinished) req[abortControllerKey].abort("Client connection prematurely closed.");
57885
- }
57886
- if (!incomingEnded) setTimeout(() => {
57887
- if (!incomingEnded) setTimeout(() => {
57888
- drainIncoming(incoming);
57889
- });
57890
- });
57891
- });
57892
59308
  res = fetchCallback(req, {
57893
59309
  incoming,
57894
59310
  outgoing
57895
59311
  });
57896
- if (cacheKey in res) return responseViaCache(res, outgoing);
59312
+ if (!isPromise(res) && isImmediateCacheableResponse(res)) {
59313
+ if (needsBodyCleanup && !incoming.readableEnded) outgoing.once("finish", () => {
59314
+ if (!incoming.readableEnded) drainIncoming(incoming);
59315
+ });
59316
+ return responseViaCache(res, outgoing);
59317
+ }
59318
+ ensureCloseHandler();
57897
59319
  } catch (e) {
57898
- if (!res) {
57899
- if (options.errorHandler) {
57900
- res = await options.errorHandler(req ? e : toRequestError(e));
57901
- if (!res) return;
57902
- } else if (!req) res = handleRequestError();
57903
- else res = handleFetchError(e);
57904
- } else return handleResponseError(e, outgoing);
59320
+ if (!res) if (options.errorHandler) {
59321
+ ensureCloseHandler();
59322
+ res = await options.errorHandler(req ? e : toRequestError(e));
59323
+ if (!res) return;
59324
+ } else if (!req) res = handleRequestError();
59325
+ else res = handleFetchError(e);
59326
+ else return handleResponseError(e, outgoing);
57905
59327
  }
57906
59328
  try {
57907
59329
  return await responseViaResponseObject(res, outgoing, options);
@@ -57910,6 +59332,8 @@ var getRequestListener = (fetchCallback, options = {}) => {
57910
59332
  }
57911
59333
  };
57912
59334
  };
59335
+ globalThis.CloseEvent;
59336
+ globalThis.ErrorEvent;
57913
59337
  //#endregion
57914
59338
  //#region node_modules/@modelcontextprotocol/node/dist/index.mjs
57915
59339
  /**