@cavelon/cli 0.2.16 → 0.2.17

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.
@@ -40,7 +40,8 @@ export const AGENTS_BLOCK = [
40
40
  "",
41
41
  "This folder is a Cavelon solution (`cavelon.yaml`): edit `package/`, `tests/` and `env/`, then run `cavelon validate` and `cavelon apply`.",
42
42
  "Use the Cavelon skills (cavelon-loop, cavelon-authoring, cavelon-testing, cavelon-long-running); without them, `cavelon --help` and `cavelon docs search <query>` lead on.",
43
- "`cavelon apply` only previews; show a preview that reaches an active solution or `env/prod` to a person before `cavelon apply --confirm <id>`.",
43
+ "Before instance work, discover this session's Cavelon tools and call `whoami`. If unavailable, tell the person with a repair step; announce CLI fallback and check `cavelon whoami --json` before using it. An intentionally CLI-only client starts with that CLI check directly. Loaded skills alone do not prove a connection. Local authoring may continue.",
44
+ "`cavelon apply` normally previews: follow `show_to_person`, `needs_person` and its exact confirmation instructions. Review routine previews yourself; critical changes need one native approval or the person's own terminal. Person-enabled YOLO may execute eligible routine changes in one call.",
44
45
  "`cavelon status` shows the instance, tenant and open previews, and `.cavelon/inventory.md` the tenant's solutions, knowledge bases and tools. A person runs `cavelon login`; never handle a token.",
45
46
  ].join("\n");
46
47
  const GITIGNORE_BLOCK = ["# Local cavelon state (inventory, previews); never committed.", `${STATE_DIR}/`].join("\n");
@@ -699,7 +700,7 @@ async function runInit(ctx, input) {
699
700
  result = await importPackage(ctx, project, from, imported, boolOption(input, "force"));
700
701
  if (packageHarness && !project.harness && !stringOption(input, "harness"))
701
702
  await setProjectKey(project, "harness", packageHarness);
702
- next.unshift(`Check it offline: ${folderCommand("validate")}`, `Preview it on the instance: ${harness ? folderCommand("apply", "--env", "test") : folderCommand("apply", "--harness", fill("name or slug"))}`);
703
+ next.unshift(`Check the package: ${folderCommand("validate")}`, `Preview it on the instance: ${harness ? folderCommand("apply", "--env", "test") : folderCommand("apply", "--harness", fill("name or slug"))}`);
703
704
  }
704
705
  else if (!(await hasPackageFiles(root, project.layout.package))) {
705
706
  const choices = chosenHarness?.choices ?? [];
@@ -420,6 +420,7 @@ async function runCheck(ctx, input) {
420
420
  for (const probe of probes) {
421
421
  lines.push(`${mark(probe.ok)}The Cavelon tools start: ${probe.command}${probe.ok ? (probe.server ? ` (${probe.server})` : "") : ` (${probe.error})`}`);
422
422
  }
423
+ lines.push("This checks a separately started server, not the current coding-agent session. In Claude Code, open /mcp and call Cavelon's whoami tool to verify that session.");
423
424
  lines.push(loginCheck.ok
424
425
  ? `${mark(true)}Logged in to ${loginCheck.instance}${loginCheck.who ? ` as ${loginCheck.who}` : ""}${loginCheck.tenant ? `, tenant ${loginCheck.tenant}` : ""}`
425
426
  : `${mark(false)}Login: ${loginCheck.problem}`);
@@ -428,6 +429,7 @@ async function runCheck(ctx, input) {
428
429
  return {
429
430
  data: {
430
431
  ok,
432
+ session_connection: "not_checked",
431
433
  agents: checks.map(({ servers: _servers, ...c }) => c),
432
434
  server: probes,
433
435
  login: loginCheck,
@@ -502,7 +504,8 @@ export const setup = {
502
504
  "and the skills in their user skills folder. It touches nothing else in those files and\n" +
503
505
  "records what it did, so --remove undoes exactly that. Then it logs in if needed, choosing the tenant by name as `login` does.\n" +
504
506
  "The server starts as `cavelon mcp` when cavelon is installed, otherwise through npx. --check reports what is set up and\n" +
505
- "working: each agent's entry, the MCP server starting, and the login. An agent found but never set up for Cavelon is\n" +
507
+ "working: each agent's entry, a separately started MCP server, and the login. It does not verify the current agent session's connection.\n" +
508
+ "An agent found but never set up for Cavelon is\n" +
506
509
  "reported and skipped (exit 0 when the rest works); --strict, or naming it with --agents, counts it.\n" +
507
510
  "--update refreshes plugins and owned skills, including the current solution's generated setup, and keeps your login.\n" +
508
511
  "--mcp-mode saves a personal startup choice; restart your coding agent to apply it. Critical changes still need approval.\n" +
@@ -409,7 +409,7 @@ function schemaUsedLine(used, ttlSeconds) {
409
409
  }
410
410
  export const validate = {
411
411
  name: "validate",
412
- summary: "Check the package files against the instance's package schema, offline.",
412
+ summary: "Check the package files against the instance's published package schema.",
413
413
  description: "Uses the schema and error catalog cached by init, pull or apply; fetches them only when none is cached or a development\n" +
414
414
  "build's copy is past its time-to-live, and never with --offline. A development build keeps one version while its schema\n" +
415
415
  "changes, so its copy is read again after a minute (CAVELON_CONTRACT_TTL_SECONDS), or checked with the ETag the instance\n" +
@@ -1051,8 +1051,8 @@ export const apply = {
1051
1051
  "secrets (`cavelon secrets set <name>`, or in the Admin where the instance lets no token set one), never the agent.\n" +
1052
1052
  "Where the instance says this credential cannot import (needs_a_person), it still previews but prints no confirm\n" +
1053
1053
  "command: a person imports in the Admin or with their own personal access token. --confirm refuses before sending (exit 5).\n" +
1054
- "Show a preview that reaches an active solution or env/prod to a person before confirming. Such a preview (show_to_person:\n" +
1055
- "tenant-wide sections, an active solution, deletions, env/prod, or database query writes) a coding agent cannot confirm.\n" +
1054
+ "Follow the preview's show_to_person and needs_person requirements. Routine isolated-draft previews may be confirmed within the requested work.\n" +
1055
+ "Tenant-wide changes, active effects without explicit draft isolation, deletions, env/prod and database query writes need a person.\n" +
1056
1056
  "Over MCP the client asks the person; from an agent's shell the person runs the confirm in their own terminal. A stale preview exits 4 and\n" +
1057
1057
  "imports nothing: one whose target changed on the instance since, one whose package files changed since (what they\n" +
1058
1058
  "hold, not their formatting; --allow-stale imports what the preview showed anyway), and one older than a day. So does\n" +
@@ -9,7 +9,7 @@ import { confirmation } from "../confirm-token.js";
9
9
  import { confinedPath } from "../paths.js";
10
10
  import { clip, keyValues, moreHint, table } from "../format.js";
11
11
  import { callOperation, callStable, workflowOperation } from "../invoke.js";
12
- import { deref } from "../openapi.js";
12
+ import { deref, jsonBodySchema } from "../openapi.js";
13
13
  import { bindsNow, changedBy, limitError, limitsOrWarn, readLimits } from "../limits.js";
14
14
  import { getOperation } from "../operations.js";
15
15
  import { caseCounts, caseLabel, countsText, failedCase, caseKnowledgeOutcomes, NOT_PASSED, runVerdict } from "../results.js";
@@ -653,16 +653,45 @@ function votesNot(suite) {
653
653
  const tags = Array.isArray(suite.tags) ? suite.tags : [];
654
654
  return tags.includes(ENGAGEMENT_TAG) && tags.some((t) => typeof t === "string" && t.startsWith(RULE_TAG_PREFIX) && t.length > RULE_TAG_PREFIX.length);
655
655
  }
656
- function skippedView(suite) {
657
- return { suite: suite.name, suite_id: suite.id, ...(suite.purpose ? { purpose: suite.purpose } : {}), reason: "not_in_readiness" };
656
+ function isQuestionCheck(suite) {
657
+ if (suite.purpose)
658
+ return suite.purpose === "engagement_check";
659
+ const tags = Array.isArray(suite.tags) ? suite.tags : [];
660
+ return tags.includes(ENGAGEMENT_TAG);
661
+ }
662
+ function skippedView(suite, reason = "not_in_readiness") {
663
+ return { suite: suite.name, suite_id: suite.id, ...(suite.purpose ? { purpose: suite.purpose } : {}), reason };
658
664
  }
659
665
  function skippedText(skipped) {
660
666
  if (!skipped.length)
661
667
  return "";
662
668
  const names = skipped.map((s) => `"${s.name}"`).join(", ");
663
- return (`Skipped ${skipped.length === 1 ? "1 suite that does" : `${skipped.length} suites that do`} not vote in readiness (campaign question checks): ${names}. ` +
669
+ const why = skipped.every(isQuestionCheck) ? " (campaign question checks)" : "";
670
+ return (`Skipped ${skipped.length === 1 ? "1 suite that does" : `${skipped.length} suites that do`} not vote in readiness${why}: ${names}. ` +
664
671
  `Run one with: ${cavelonCommand("test", "run", "--suite", skipped[0].name)}`);
665
672
  }
673
+ function withoutProfileText(skipped, profile) {
674
+ if (!skipped.length)
675
+ return "";
676
+ const names = skipped.map((s) => `"${s.name}"`).join(", ");
677
+ return `Skipped ${skipped.length === 1 ? "1 suite" : `${skipped.length} suites`} without the run profile "${profile}": ${names}.`;
678
+ }
679
+ function hasProfile(suite, profile) {
680
+ return Array.isArray(suite.profiles) ? suite.profiles.includes(profile) : undefined;
681
+ }
682
+ async function requireRunField(ctx, field) {
683
+ const { doc, op } = await workflowOperation(ctx, "POST", "/api/v1/test-suites/{suite_id}/runs", "test runs");
684
+ const schema = doc ? jsonBodySchema(op) : undefined;
685
+ const properties = doc && schema ? deref(doc, schema)?.properties : undefined;
686
+ if (properties && field in properties)
687
+ return;
688
+ throw new CavelonError(ExitCode.failure, {
689
+ code: "operation_unavailable",
690
+ message: `This instance's OpenAPI does not establish support for ${field} in test runs (POST /api/v1/test-suites/{suite_id}/runs), so nothing was sent.`,
691
+ hint: `The instance may be older than run profiles or its request schema unavailable. Restore its published contract, or run the whole suite instead. \`${cavelonCommand("status")}\` shows its version.`,
692
+ details: { sent: false },
693
+ });
694
+ }
666
695
  function summaryText(summary) {
667
696
  const verdict = runVerdict(summary);
668
697
  const shown = ["passed", "failed", "errors"].filter((k) => k in summary).map((k) => k + " " + String(summary[k]));
@@ -676,6 +705,10 @@ function summaryText(summary) {
676
705
  }
677
706
  return shown.join(" ");
678
707
  }
708
+ function skippedData(skipped, withoutProfile) {
709
+ const all = [...skipped.map((s) => skippedView(s)), ...withoutProfile.map((s) => skippedView(s, "no_profile"))];
710
+ return all.length ? { skipped: all } : {};
711
+ }
679
712
  function resumeCommand(pending, timeout) {
680
713
  return cavelonCommand("wait", ...pending, ...(timeout ? ["--timeout", timeout] : []));
681
714
  }
@@ -684,6 +717,10 @@ export const testRun = {
684
717
  summary: "Start test-suite runs; returns operation ids.",
685
718
  description: "Without --suite, runs every suite of the solution (--harness, or cavelon.yaml's harness), except suites that never\n" +
686
719
  "vote in readiness, such as a campaign's question checks: they are listed as skipped, and --suite runs one.\n" +
720
+ "--profile runs one of each suite's run profiles, by its key, in place of the whole suite: without --suite, every\n" +
721
+ "suite that has it, the others listed as skipped. Where a suite's gate names a profile, only a run of that profile\n" +
722
+ "counts for publishing. --tags runs the cases carrying one of the tags. An instance older than run profiles refuses\n" +
723
+ "both before anything is sent. An unavailable request schema also refuses both; whole-suite runs keep their fallback.\n" +
687
724
  "With --wait, exits 1 when a case failed or a run measured nothing comparable (cases not run, technical errors),\n" +
688
725
  "5 when answers wait for a manual verdict or a value a case needs.\n" +
689
726
  "--as-chat-user chooses a Chat User reader for these runs only, for knowledge and identity-bound database queries;\n" +
@@ -699,13 +736,27 @@ export const testRun = {
699
736
  suite: { type: "string", multiple: true, value: "<suite>", description: "Suite name or id." },
700
737
  harness: { type: "string", value: "<harness>", description: "The solution to run against: its name, slug or id." },
701
738
  "as-chat-user": AS_CHAT_USER_OPTION,
739
+ profile: { type: "string", value: "<profile>", description: "Run this run profile of each suite (its key), in place of the whole suite." },
740
+ tags: { type: "string", multiple: true, value: "<tag>", description: "Run only the cases carrying one of these tags." },
702
741
  wait: WAIT_OPTION,
703
742
  timeout: TIMEOUT_OPTION,
704
743
  "idempotency-key": { type: "string", value: "<key>", description: "Send an Idempotency-Key with each start." },
705
744
  },
706
- examples: ["cavelon test run --suite smoke --wait --timeout 10m", "cavelon test run --harness support --json"],
745
+ examples: [
746
+ "cavelon test run --suite smoke --wait --timeout 10m",
747
+ "cavelon test run --harness support --json",
748
+ "cavelon test run --profile s0 --wait",
749
+ ],
707
750
  async run(ctx, input) {
708
751
  const session = await ctx.session();
752
+ const profile = stringOption(input, "profile");
753
+ const tags = listOption(input, "tags");
754
+ if (profile !== undefined && tags.length)
755
+ throw usageError("Give --profile or --tags, not both.");
756
+ if (profile !== undefined)
757
+ await requireRunField(ctx, "profile");
758
+ if (tags.length)
759
+ await requireRunField(ctx, "tags");
709
760
  const reader = await chatUserReader(ctx, input, "/api/v1/test-suites/{suite_id}/runs");
710
761
  const harnessRef = stringOption(input, "harness") ?? session.project?.harness;
711
762
  const harnessId = harnessRef ? await resolveHarnessId(ctx, harnessRef) : undefined;
@@ -715,6 +766,7 @@ export const testRun = {
715
766
  const wanted = listOption(input, "suite");
716
767
  let chosen;
717
768
  let skipped = [];
769
+ let withoutProfile = [];
718
770
  if (wanted.length) {
719
771
  chosen = wanted.map((ref) => {
720
772
  const hit = suites.find((s) => s.id === ref) ?? suites.filter((s) => s.name.toLowerCase() === ref.toLowerCase());
@@ -729,11 +781,30 @@ export const testRun = {
729
781
  }
730
782
  return hit;
731
783
  });
784
+ const lacking = profile === undefined ? undefined : chosen.find((s) => hasProfile(s, profile) === false);
785
+ if (lacking) {
786
+ throw new CavelonError(ExitCode.failure, {
787
+ code: "profile_unknown",
788
+ message: `The suite "${lacking.name}" has no run profile "${profile}", so nothing was sent.`,
789
+ hint: `\`${cavelonCommand("api", "list_suites")}\` lists each suite's profiles.`,
790
+ details: { sent: false },
791
+ });
792
+ }
732
793
  }
733
794
  else {
734
795
  const current = suites.filter((s) => !s.archived_at);
735
796
  skipped = current.filter(votesNot);
736
797
  chosen = current.filter((s) => !votesNot(s));
798
+ if (profile !== undefined) {
799
+ withoutProfile = chosen.filter((s) => hasProfile(s, profile) === false);
800
+ chosen = chosen.filter((s) => hasProfile(s, profile) !== false);
801
+ }
802
+ if (chosen.length === 0 && withoutProfile.length) {
803
+ throw new CavelonError(ExitCode.failure, {
804
+ code: "no_suites",
805
+ message: `${harnessRef ? `${harnessRef} has no test suites` : "This tenant has no test suites"} with the run profile "${profile}". ${withoutProfileText(withoutProfile, profile)}`,
806
+ });
807
+ }
737
808
  if (chosen.length === 0) {
738
809
  throw new CavelonError(ExitCode.failure, {
739
810
  code: "no_suites",
@@ -748,6 +819,10 @@ export const testRun = {
748
819
  const body = { ...reader };
749
820
  if (harnessId)
750
821
  body.harness_id = harnessId;
822
+ if (profile !== undefined)
823
+ body.profile = profile;
824
+ if (tags.length)
825
+ body.tags = tags;
751
826
  runs.push(await callStable(ctx, "POST", "/api/v1/test-suites/{suite_id}/runs", "test runs", {
752
827
  params: { suite_id: [suite.id] },
753
828
  body,
@@ -782,19 +857,21 @@ export const testRun = {
782
857
  "",
783
858
  ...results.map((r) => `${r.suite}: ${r.status} ${summaryText(r.summary)}`),
784
859
  ...(skipped.length ? ["", skippedText(skipped)] : []),
860
+ ...(withoutProfile.length ? ["", withoutProfileText(withoutProfile, profile)] : []),
785
861
  ...(resume ? ["", `${waited.why} after the timeout; the runs go on. Resume: ${resume}`] : []),
786
862
  ].join("\n");
787
863
  return {
788
- data: { runs: results, failed_cases: failedCases, ...waited.data, ...reader, ...(skipped.length ? { skipped: skipped.map(skippedView) } : {}), ...(resume ? { resume } : {}) },
864
+ data: { runs: results, failed_cases: failedCases, ...waited.data, ...reader, ...skippedData(skipped, withoutProfile), ...(resume ? { resume } : {}) },
789
865
  text: reader ? `Reading as Chat User ${reader.reader_chat_user_id} for these runs only.\n${text}` : text,
790
866
  exitCode,
791
867
  };
792
868
  }
793
869
  return {
794
- data: { runs: started, operation_ids: operationIds, ...reader, ...(skipped.length ? { skipped: skipped.map(skippedView) } : {}) },
870
+ data: { runs: started, operation_ids: operationIds, ...reader, ...skippedData(skipped, withoutProfile) },
795
871
  text: (reader ? `Reading as Chat User ${reader.reader_chat_user_id} for these runs only.\n` : "") +
796
872
  table(started, ["suite", "run_id", "status", "operation_id"]) +
797
873
  (skipped.length ? `\n\n${skippedText(skipped)}` : "") +
874
+ (withoutProfile.length ? `\n\n${withoutProfileText(withoutProfile, profile)}` : "") +
798
875
  (operationIds.length ? `\n\nWait with: ${cavelonCommand("wait", ...operationIds)}` : ""),
799
876
  };
800
877
  },
package/dist/kit-codes.js CHANGED
@@ -87,6 +87,7 @@ export const KIT_ERROR_CODES = [
87
87
  { code: "model_not_found", area: "cli", message: "The tenant's Model Registry has no row by that name or id.", hint: "`cavelon models list` shows its rows by model_id and id." },
88
88
  { code: "variable_not_set", area: "cli", message: "The tenant has no variable by that name.", hint: "`cavelon variables list` shows them; `cavelon variables set <name> <value>` sets one." },
89
89
  { code: "no_suites", area: "cli", message: "The solution (or tenant) has no test suites.", hint: "Write one in tests/ and apply it; the cavelon-testing skill shows how." },
90
+ { code: "profile_unknown", area: "cli", message: "A suite named with --suite has no run profile of that key; nothing was sent.", hint: "`cavelon api list_suites` lists each suite's profiles; a suite defines them under settings.profiles." },
90
91
  { code: "no_result", area: "cli", message: "The operation has no result yet.", hint: "`cavelon wait <op_id>` waits for it." },
91
92
  { code: "no_trace", area: "cli", message: "The operation's result has no trace.", hint: "Trace a run, test run or conversation id instead." },
92
93
  { code: "run_not_found", area: "cli", message: "No run, test run or conversation with that id in this tenant.", hint: "Check the id and the tenant (`cavelon whoami`); --kind names what the id is." },
package/dist/mcp.js CHANGED
@@ -33,8 +33,8 @@ const INSTRUCTIONS = "Tools for one Cavelon instance, acting with the token a pe
33
33
  "kb_upload names files that match an active document of the knowledge base; with replace it replaces them, and where the " +
34
34
  "instance's upload cannot, it returns what it would deactivate and uploads nothing without its confirm_token. " +
35
35
  "init, pull and fmt change nothing on the instance (pull only reads it); they write files in the solution folder without confirm " +
36
- "(pull refuses to replace a package file that changed since the last pull or apply and is not committed, unless force), " +
37
- "and the other changing tools act at once. api refuses, even with confirm, an operation the instance marks for a person " +
36
+ "(pull refuses to replace a package file that changed since the last pull or apply and is not committed, unless force). " +
37
+ "Other changing tools follow their declared preview and confirmation rules. api refuses, even with confirm, an operation the instance marks for a person " +
38
38
  "(x-cavelon-person-only; its reason is in the error), or on an instance that marks none, one that changes a secret, " +
39
39
  "creates or revokes a credential (tokens, API keys, sign-in) or decides an approval; it also refuses a body that sets a field " +
40
40
  "the instance marks as a secret value (x-cavelon-secret): leave the field out and let a person enter the value. " +
@@ -1,4 +1,4 @@
1
- @modelcontextprotocol/sdk 1.32.1
1
+ @modelcontextprotocol/sdk 1.32.2
2
2
  MIT License
3
3
 
4
4
  Copyright (c) 2024 Anthropic, PBC
@@ -129,7 +129,7 @@ SOFTWARE.
129
129
 
130
130
  ---
131
131
 
132
- fast-uri 3.1.8
132
+ fast-uri 3.1.9
133
133
  Copyright (c) 2011-2021, Gary Court until https://github.com/garycourt/uri-js/commit/a1acf730b4bba3f1097c9f52e7d9d3aba8cdcaae
134
134
  Copyright (c) 2021-present The Fastify team <https://github.com/fastify/fastify#team>
135
135
  All rights reserved.
@@ -277,7 +277,7 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI
277
277
 
278
278
  ---
279
279
 
280
- typebox 1.4.2
280
+ typebox 1.4.3
281
281
  TypeBox
282
282
 
283
283
  The MIT License (MIT)
@@ -3343,6 +3343,37 @@ var require_utils = __commonJS({
3343
3343
  }
3344
3344
  return output2.join("");
3345
3345
  }
3346
+ function removeDotSegmentsRelative(path4) {
3347
+ if (path4 === "" || path4[0] === "/") {
3348
+ return removeDotSegments(path4);
3349
+ }
3350
+ const segments = path4.split("/");
3351
+ const last = segments.length - 1;
3352
+ const output2 = [];
3353
+ let trailingDirectory = false;
3354
+ for (let i = 0; i <= last; i++) {
3355
+ const segment = segments[i];
3356
+ if (segment === "." || segment === "..") {
3357
+ if (segment === "..") {
3358
+ if (output2.length !== 0 && output2[output2.length - 1] !== "..") {
3359
+ output2.pop();
3360
+ } else {
3361
+ output2.push("..");
3362
+ }
3363
+ }
3364
+ trailingDirectory = i === last;
3365
+ } else {
3366
+ output2.push(segment);
3367
+ }
3368
+ }
3369
+ if (trailingDirectory && output2[output2.length - 1] !== "..") {
3370
+ output2.push("");
3371
+ }
3372
+ if (output2.length === 0 || output2[0] === "" || output2[0].includes(":")) {
3373
+ output2.unshift(".");
3374
+ }
3375
+ return output2.join("/");
3376
+ }
3346
3377
  var HOST_DELIMS = { "@": "%40", "/": "%2F", "?": "%3F", "#": "%23", ":": "%3A" };
3347
3378
  var HOST_DELIM_RE = /[@/?#:]/g;
3348
3379
  var HOST_DELIM_NO_COLON_RE = /[@/?#]/g;
@@ -3603,6 +3634,7 @@ var require_utils = __commonJS({
3603
3634
  encodeFragment,
3604
3635
  escapePreservingEscapes,
3605
3636
  removeDotSegments,
3637
+ removeDotSegmentsRelative,
3606
3638
  isIPv4,
3607
3639
  isUUID,
3608
3640
  normalizeIPv6,
@@ -3826,16 +3858,18 @@ var require_schemes = __commonJS({
3826
3858
  var require_fast_uri = __commonJS({
3827
3859
  "node_modules/fast-uri/index.js"(exports, module) {
3828
3860
  "use strict";
3829
- var { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizePercentEncoding, normalizePathEncoding, serializePathEncoding, normalizeQueryFragmentEncoding, encodeQuery, encodeFragment, reescapeHostDelimiters, isIPv4, nonSimpleDomain } = require_utils();
3861
+ var { normalizeIPv6, removeDotSegments, removeDotSegmentsRelative, recomposeAuthority, normalizePercentEncoding, normalizePathEncoding, serializePathEncoding, normalizeQueryFragmentEncoding, encodeQuery, encodeFragment, reescapeHostDelimiters, isIPv4, nonSimpleDomain } = require_utils();
3830
3862
  var { SCHEMES, getSchemeHandler } = require_schemes();
3831
3863
  var VALID_SCHEME = /^[A-Za-z][A-Za-z0-9+.-]*$/u;
3832
3864
  var MALFORMED_SCHEME_ERROR = "URI scheme is malformed.";
3833
- function decodeValidScheme(scheme) {
3834
- const decodedScheme = unescape(String(scheme));
3835
- if (!VALID_SCHEME.test(decodedScheme)) {
3865
+ var MALFORMED_HOST_ERROR = "URI host is malformed.";
3866
+ var FORBIDDEN_DOMAIN_HOST_CHARACTER = /[\0-\x20"#/:<>?@[\\\]^`{|}\x7F]/u;
3867
+ function validateScheme(scheme) {
3868
+ const stringScheme = String(scheme);
3869
+ if (!VALID_SCHEME.test(stringScheme)) {
3836
3870
  throw new TypeError(MALFORMED_SCHEME_ERROR);
3837
3871
  }
3838
- return decodedScheme;
3872
+ return stringScheme;
3839
3873
  }
3840
3874
  function normalize(uri, options) {
3841
3875
  if (typeof uri === "string") {
@@ -3872,6 +3906,9 @@ var require_fast_uri = __commonJS({
3872
3906
  const resolvedSchemeHandler = getSchemeHandler(options && options.scheme || resolved.scheme);
3873
3907
  const resolvedHost = resolved.host;
3874
3908
  const resolvedHostIsIP = resolvedHost !== void 0 && resolvedHost !== "" && (isIPv4(resolvedHost) || normalizeIPv6(resolvedHost).isIPV6);
3909
+ if (hasForbiddenDomainHost(resolved, options || {}, resolvedSchemeHandler, resolvedHostIsIP)) {
3910
+ throw new Error(MALFORMED_HOST_ERROR);
3911
+ }
3875
3912
  canonicalizeHost(resolved, options || {}, resolvedSchemeHandler, resolvedHostIsIP);
3876
3913
  const encodedASCIIHost = resolvedHost && resolvedHost.indexOf("%") !== -1 && !new RegExp("\\P{ASCII}", "u").test(resolvedHost);
3877
3914
  if (resolved.error && !encodedASCIIHost) {
@@ -3913,14 +3950,15 @@ var require_fast_uri = __commonJS({
3913
3950
  if (relative.path[0] === "/") {
3914
3951
  target.path = removeDotSegments(relative.path);
3915
3952
  } else {
3916
- if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) {
3953
+ const baseHasAuthority = base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0;
3954
+ if (baseHasAuthority && !base.path) {
3917
3955
  target.path = "/" + relative.path;
3918
3956
  } else if (!base.path) {
3919
3957
  target.path = relative.path;
3920
3958
  } else {
3921
3959
  target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path;
3922
3960
  }
3923
- target.path = removeDotSegments(target.path);
3961
+ target.path = base.scheme === void 0 && !baseHasAuthority && target.path[0] !== "/" ? removeDotSegmentsRelative(target.path) : removeDotSegments(target.path);
3924
3962
  }
3925
3963
  target.query = relative.query;
3926
3964
  }
@@ -3958,12 +3996,13 @@ var require_fast_uri = __commonJS({
3958
3996
  const options = Object.assign({}, opts);
3959
3997
  const uriTokens = [];
3960
3998
  if (component.scheme) {
3961
- component.scheme = decodeValidScheme(component.scheme);
3999
+ component.scheme = validateScheme(component.scheme);
3962
4000
  }
3963
4001
  const schemeHandler = getSchemeHandler(options.scheme || component.scheme);
3964
4002
  if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options);
3965
4003
  const hasAuthority = component.userinfo !== void 0 || component.host !== void 0 || component.port !== void 0;
3966
- const pathNoScheme = !options.skipEscape && component.scheme === void 0 && !hasAuthority;
4004
+ const schemelessReference = (component.scheme === void 0 || options.reference === "suffix") && !hasAuthority;
4005
+ const pathNoScheme = !options.skipEscape && schemelessReference;
3967
4006
  if (component.path !== void 0) {
3968
4007
  if (!options.skipEscape) {
3969
4008
  component.path = serializePathEncoding(component.path, pathNoScheme);
@@ -3972,7 +4011,7 @@ var require_fast_uri = __commonJS({
3972
4011
  }
3973
4012
  }
3974
4013
  if (options.reference !== "suffix" && component.scheme) {
3975
- component.scheme = decodeValidScheme(component.scheme);
4014
+ component.scheme = validateScheme(component.scheme);
3976
4015
  uriTokens.push(component.scheme, ":");
3977
4016
  }
3978
4017
  const authority = recomposeAuthority(component);
@@ -3988,9 +4027,9 @@ var require_fast_uri = __commonJS({
3988
4027
  if (component.path !== void 0) {
3989
4028
  let s = component.path;
3990
4029
  if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {
3991
- s = removeDotSegments(s);
4030
+ s = schemelessReference && s[0] !== "/" ? removeDotSegmentsRelative(s) : removeDotSegments(s);
3992
4031
  }
3993
- if (pathNoScheme) {
4032
+ if (schemelessReference) {
3994
4033
  s = serializePathEncoding(s, true);
3995
4034
  }
3996
4035
  if (authority === void 0 && s[0] === "/" && s[1] === "/") {
@@ -4037,16 +4076,34 @@ var require_fast_uri = __commonJS({
4037
4076
  return hasMalformedPercentEncoding(matches[3]) || host !== void 0 && !isIPLiteral(host) && hasMalformedPercentEncoding(host) || hasMalformedPercentEncoding(matches[6]) || hasMalformedPercentEncoding(matches[7]) || hasMalformedPercentEncoding(matches[8]);
4038
4077
  }
4039
4078
  function canonicalizeHost(parsed, options, schemeHandler, isIP) {
4079
+ if (hasForbiddenDomainHost(parsed, options, schemeHandler, isIP)) {
4080
+ parsed.error = parsed.error || MALFORMED_HOST_ERROR;
4081
+ return true;
4082
+ }
4040
4083
  if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport) && parsed.host && !isIPLiteral(parsed.host) && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) {
4084
+ let url2;
4041
4085
  try {
4042
- parsed.host = new URL("http://" + parsed.host).hostname;
4086
+ url2 = new URL("http://" + parsed.host);
4043
4087
  } catch (e) {
4044
4088
  parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e;
4045
4089
  return true;
4046
4090
  }
4091
+ if (!isHostOnlyURL(url2)) {
4092
+ parsed.error = parsed.error || MALFORMED_HOST_ERROR;
4093
+ return true;
4094
+ }
4095
+ parsed.host = url2.hostname;
4047
4096
  }
4048
4097
  return false;
4049
4098
  }
4099
+ function hasForbiddenDomainHost(parsed, options, schemeHandler, isIP) {
4100
+ return Boolean(
4101
+ parsed.host && isIP === false && !isIPLiteral(parsed.host) && (options.domainHost || schemeHandler && schemeHandler.domainHost) && FORBIDDEN_DOMAIN_HOST_CHARACTER.test(parsed.host)
4102
+ );
4103
+ }
4104
+ function isHostOnlyURL(url2) {
4105
+ return url2.username === "" && url2.password === "" && url2.port === "" && url2.pathname === "/" && url2.search === "" && url2.hash === "" && url2.hostname !== "";
4106
+ }
4050
4107
  function parseWithStatus(uri, opts) {
4051
4108
  const options = Object.assign({}, opts);
4052
4109
  const parsed = {
@@ -4101,9 +4158,8 @@ var require_fast_uri = __commonJS({
4101
4158
  parsed.query = matches[7];
4102
4159
  parsed.fragment = matches[8];
4103
4160
  if (parsed.scheme !== void 0) {
4104
- const decodedScheme = unescape(parsed.scheme);
4105
- if (VALID_SCHEME.test(decodedScheme)) {
4106
- parsed.scheme = decodedScheme.toLowerCase();
4161
+ if (VALID_SCHEME.test(parsed.scheme)) {
4162
+ parsed.scheme = parsed.scheme.toLowerCase();
4107
4163
  } else {
4108
4164
  parsed.error = parsed.error || MALFORMED_SCHEME_ERROR;
4109
4165
  malformedScheme = true;
@@ -4131,7 +4187,7 @@ var require_fast_uri = __commonJS({
4131
4187
  malformedIPLiteral = hasIPLiteralBracket && (!bracketedIPLiteral || ipv6result.error === true);
4132
4188
  parsed.host = isIP ? ipv6result.host : ipv6result.host.toLowerCase();
4133
4189
  if (malformedIPLiteral) {
4134
- parsed.error = parsed.error || "URI host is malformed.";
4190
+ parsed.error = parsed.error || MALFORMED_HOST_ERROR;
4135
4191
  malformedAuthorityOrPort = true;
4136
4192
  }
4137
4193
  } else {
@@ -4159,7 +4215,7 @@ var require_fast_uri = __commonJS({
4159
4215
  if (!isIP) {
4160
4216
  host = normalizePercentEncoding(host.toLowerCase());
4161
4217
  }
4162
- parsed.host = reescapeHostDelimiters(host, isIP);
4218
+ parsed.host = isIP || options.scheme !== "null" ? reescapeHostDelimiters(host, isIP) : host;
4163
4219
  }
4164
4220
  if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) {
4165
4221
  if (parsed.path) {