@dudko.dev/baton-format 0.1.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/src/index.js CHANGED
@@ -1,5 +1,8 @@
1
1
  export * from "./types.js";
2
2
  export { FormatError } from "./errors.js";
3
- export { parseRequestFile, parseCollectionFile, parseEnvironmentFile, parseWorkspaceManifest, parseSchedulesFile, } from "./parse.js";
4
- export { serializeRequestFile, serializeCollectionFile, serializeEnvironmentFile, serializeWorkspaceManifest, serializeSchedulesFile, } from "./serialize.js";
3
+ export { parseRequestFile, parseCollectionFile, parseEnvironmentFile, parseWorkspaceManifest, parseSchedulesFile, parseExamplesFile, parseMockFile, parseFlowFile, } from "./parse.js";
4
+ export { serializeRequestFile, serializeCollectionFile, serializeEnvironmentFile, serializeWorkspaceManifest, serializeSchedulesFile, serializeExamplesFile, serializeMockFile, serializeFlowFile, } from "./serialize.js";
5
+ export { parseVaultRef, formatVaultRef } from "./vault.js";
6
+ export { FLOW_LOOP_LIMIT, FlowRun, FlowRunError, capture, evaluateWhen, render, } from "./flow_run.js";
7
+ export { ancestorsOf, edgeRef, loopBodies, parentsOf, portsOf } from "./flow_graph.js";
5
8
  //# sourceMappingURL=index.js.map
@@ -1,4 +1,4 @@
1
- import { CollectionFile, EnvironmentFile, RequestFile, SchedulesFile, WorkspaceManifest } from "./types.js";
1
+ import { CollectionFile, EnvironmentFile, RequestFile, SchedulesFile, WorkspaceManifest, ExamplesFile, FlowFile, MockFile } from "./types.js";
2
2
  /** Parse and validate a `*.req.yaml` file into its normalized form. */
3
3
  export declare function parseRequestFile(text: string): RequestFile;
4
4
  /** Parse and validate a `collection.yaml` / `folder.yaml` file. */
@@ -9,3 +9,9 @@ export declare function parseEnvironmentFile(text: string): EnvironmentFile;
9
9
  export declare function parseWorkspaceManifest(text: string): WorkspaceManifest;
10
10
  /** Parse and validate a `schedules.yaml` file. */
11
11
  export declare function parseSchedulesFile(text: string): SchedulesFile;
12
+ /** Parse and validate a `flows/<slug>.flow.yaml` file. */
13
+ export declare function parseFlowFile(text: string): FlowFile;
14
+ /** Parse and validate a `<slug>.examples.yaml` file. */
15
+ export declare function parseExamplesFile(text: string): ExamplesFile;
16
+ /** Parse and validate a `mocks/<name>.yaml` file. */
17
+ export declare function parseMockFile(text: string): MockFile;
package/dist/src/parse.js CHANGED
@@ -1,5 +1,7 @@
1
1
  import { parse as parseYaml } from "yaml";
2
2
  import { FormatError } from "./errors.js";
3
+ import { ancestorsOf, descendantsThrough, edgeRef, loopBodies, parentsOf, portsOf } from "./flow_graph.js";
4
+ import { parseVaultRef } from "./vault.js";
3
5
  import { DEFAULT_SETTINGS, FORMAT_VERSION, METHODS, } from "./types.js";
4
6
  const ULID_RE = /^[0-9A-HJKMNP-TV-Z]{26}$/;
5
7
  // MARK: - Primitive readers
@@ -52,6 +54,17 @@ function reqString(obj, key, path) {
52
54
  }
53
55
  return value;
54
56
  }
57
+ /** A required string that may be empty. */
58
+ function reqText(obj, key, path) {
59
+ if (!(key in obj)) {
60
+ throw new FormatError("missing-field", join(path, key), "required field is missing");
61
+ }
62
+ const value = obj[key];
63
+ if (typeof value !== "string") {
64
+ throw new FormatError("invalid-field", join(path, key), "must be a string");
65
+ }
66
+ return value;
67
+ }
55
68
  function optString(obj, key, path) {
56
69
  const value = obj[key];
57
70
  if (value === undefined)
@@ -70,6 +83,16 @@ function optBool(obj, key, path, dflt) {
70
83
  }
71
84
  return value;
72
85
  }
86
+ function reqInt(obj, key, path) {
87
+ const value = obj[key];
88
+ if (value === undefined) {
89
+ throw new FormatError("missing-field", join(path, key), "is required");
90
+ }
91
+ if (typeof value !== "number" || !Number.isInteger(value)) {
92
+ throw new FormatError("invalid-field", join(path, key), "must be an integer");
93
+ }
94
+ return value;
95
+ }
73
96
  function optInt(obj, key, path, dflt) {
74
97
  const value = obj[key];
75
98
  if (value === undefined)
@@ -118,7 +141,9 @@ function parseKvRows(obj, key, path) {
118
141
  checkKeys(row, ["name", "value", "enabled"], itemPath);
119
142
  return {
120
143
  name: reqString(row, "name", itemPath),
121
- value: reqString(row, "value", itemPath),
144
+ // Empty is a value here: `curl -H 'Name;'` sends an empty header, and
145
+ // a documented parameter may have no sample yet.
146
+ value: reqText(row, "value", itemPath),
122
147
  enabled: optBool(row, "enabled", itemPath, true),
123
148
  };
124
149
  });
@@ -400,11 +425,13 @@ export function parseRequestFile(text) {
400
425
  /** Parse and validate a `collection.yaml` / `folder.yaml` file. */
401
426
  export function parseCollectionFile(text) {
402
427
  const obj = root(text);
403
- checkKeys(obj, ["format", "id", "name", "auth", "variables", "order"], "");
428
+ checkKeys(obj, ["format", "id", "name", "spec", "auth", "variables", "order"], "");
429
+ const spec = optString(obj, "spec", "");
404
430
  return {
405
431
  format: checkFormat(obj, ""),
406
432
  id: ulid(obj, "id", ""),
407
433
  name: reqString(obj, "name", ""),
434
+ ...(spec !== undefined ? { spec } : {}),
408
435
  auth: parseAuth(obj, ""),
409
436
  variables: parseVariables(obj, "variables", ""),
410
437
  order: parseStringList(obj, "order", ""),
@@ -413,14 +440,45 @@ export function parseCollectionFile(text) {
413
440
  /** Parse and validate a `*.env.yaml` file. */
414
441
  export function parseEnvironmentFile(text) {
415
442
  const obj = root(text);
416
- checkKeys(obj, ["format", "name", "variables", "secrets"], "");
443
+ checkKeys(obj, ["format", "name", "production", "variables", "secrets"], "");
444
+ const { secrets, vault } = parseSecrets(obj, "");
445
+ const production = optBool(obj, "production", "", false);
417
446
  return {
418
447
  format: checkFormat(obj, ""),
419
448
  name: reqString(obj, "name", ""),
420
449
  variables: parseVariables(obj, "variables", ""),
421
- secrets: parseStringList(obj, "secrets", ""),
450
+ secrets,
451
+ ...(Object.keys(vault).length > 0 ? { vault } : {}),
452
+ ...(production ? { production: true } : {}),
422
453
  };
423
454
  }
455
+ /**
456
+ * `secrets:` entries: a bare name (device store), or `{name, vault}` for a
457
+ * value read from Vault. Order is the list's; the Vault map is by name.
458
+ */
459
+ function parseSecrets(obj, path) {
460
+ const secrets = [];
461
+ const vault = {};
462
+ optArray(obj, "secrets", path).forEach((item, i) => {
463
+ const itemPath = `${join(path, "secrets")}[${i}]`;
464
+ if (typeof item === "string") {
465
+ if (item === "")
466
+ throw new FormatError("invalid-field", itemPath, "must be a non-empty string");
467
+ secrets.push(item);
468
+ return;
469
+ }
470
+ const entry = itemRecord(item, itemPath);
471
+ checkKeys(entry, ["name", "vault"], itemPath);
472
+ const name = reqString(entry, "name", itemPath);
473
+ const ref = reqString(entry, "vault", itemPath);
474
+ // Validated here so a bad reference is a format error at its field, not
475
+ // a send-time failure in whichever engine reads it first.
476
+ parseVaultRef(ref, `${itemPath}.vault`);
477
+ secrets.push(name);
478
+ vault[name] = ref;
479
+ });
480
+ return { secrets, vault };
481
+ }
424
482
  /** Parse and validate the `baton.yaml` workspace manifest. */
425
483
  export function parseWorkspaceManifest(text) {
426
484
  const obj = root(text);
@@ -428,7 +486,7 @@ export function parseWorkspaceManifest(text) {
428
486
  const settingsObj = optRecord(obj, "settings", "");
429
487
  let settings = { ...DEFAULT_SETTINGS };
430
488
  if (settingsObj !== undefined) {
431
- checkKeys(settingsObj, ["followRedirects", "timeoutMs", "validateTls", "tls", "proxy"], "settings");
489
+ checkKeys(settingsObj, ["followRedirects", "timeoutMs", "validateTls", "tls", "proxy", "vault"], "settings");
432
490
  let tls = { clientCertificates: [] };
433
491
  const tlsObj = optRecord(settingsObj, "tls", "settings");
434
492
  if (tlsObj !== undefined) {
@@ -463,12 +521,24 @@ export function parseWorkspaceManifest(text) {
463
521
  ...(passwordSecret !== undefined ? { passwordSecret } : {}),
464
522
  };
465
523
  }
524
+ let vault;
525
+ const vaultObj = optRecord(settingsObj, "vault", "settings");
526
+ if (vaultObj !== undefined) {
527
+ checkKeys(vaultObj, ["address", "namespace"], "settings.vault");
528
+ const address = reqString(vaultObj, "address", "settings.vault");
529
+ if (!address.startsWith("http://") && !address.startsWith("https://")) {
530
+ throw new FormatError("invalid-field", "settings.vault.address", "must start with http:// or https://");
531
+ }
532
+ const namespace = optString(vaultObj, "namespace", "settings.vault");
533
+ vault = { address, ...(namespace !== undefined ? { namespace } : {}) };
534
+ }
466
535
  settings = {
467
536
  followRedirects: optBool(settingsObj, "followRedirects", "settings", DEFAULT_SETTINGS.followRedirects),
468
537
  timeoutMs: optInt(settingsObj, "timeoutMs", "settings", DEFAULT_SETTINGS.timeoutMs),
469
538
  validateTls: optBool(settingsObj, "validateTls", "settings", DEFAULT_SETTINGS.validateTls),
470
539
  ...(tls.caFile !== undefined || tls.clientCertificates.length > 0 ? { tls } : {}),
471
540
  ...(proxy !== undefined ? { proxy } : {}),
541
+ ...(vault !== undefined ? { vault } : {}),
472
542
  };
473
543
  }
474
544
  const description = optString(obj, "description", "");
@@ -492,11 +562,12 @@ export function parseSchedulesFile(text) {
492
562
  throw new FormatError("missing-field", join(itemPath, "run"), "required field is missing");
493
563
  }
494
564
  const runPath = join(itemPath, "run");
495
- checkKeys(runObj, ["collection", "request", "environment"], runPath);
565
+ checkKeys(runObj, ["collection", "request", "flow", "environment"], runPath);
496
566
  const collection = optString(runObj, "collection", runPath);
497
567
  const request = optString(runObj, "request", runPath);
498
- if ((collection === undefined) === (request === undefined)) {
499
- throw new FormatError("invalid-field", runPath, "exactly one of collection or request must be set");
568
+ const flow = optString(runObj, "flow", runPath);
569
+ if ([collection, request, flow].filter((target) => target !== undefined).length !== 1) {
570
+ throw new FormatError("invalid-field", runPath, "exactly one of collection, request or flow must be set");
500
571
  }
501
572
  let notify;
502
573
  const notifyObj = optRecord(sched, "notify", itemPath);
@@ -521,6 +592,7 @@ export function parseSchedulesFile(text) {
521
592
  run: {
522
593
  ...(collection !== undefined ? { collection } : {}),
523
594
  ...(request !== undefined ? { request } : {}),
595
+ ...(flow !== undefined ? { flow } : {}),
524
596
  environment: reqString(runObj, "environment", runPath),
525
597
  },
526
598
  ...(notify !== undefined ? { notify } : {}),
@@ -528,4 +600,377 @@ export function parseSchedulesFile(text) {
528
600
  });
529
601
  return { format: checkFormat(obj, ""), schedules };
530
602
  }
603
+ // MARK: - Flows (ADR-0008)
604
+ const STEP_ID_RE = /^[a-z0-9][a-z0-9_-]*$/;
605
+ const CAPTURE_NAME_RE = /^[A-Za-z_][A-Za-z0-9_-]*$/;
606
+ const CAPTURE_PATH_RE = /^[^.\s]+(\.[^.\s]+)*$/;
607
+ const STATUS_CLASS_RE = /^[1-5]xx$/;
608
+ function parseFlowExpect(step, path) {
609
+ const obj = optRecord(step, "expect", path);
610
+ if (obj === undefined)
611
+ return undefined;
612
+ const expectPath = join(path, "expect");
613
+ checkKeys(obj, ["status"], expectPath);
614
+ const value = obj["status"];
615
+ if (value === undefined)
616
+ return {};
617
+ const statusPath = join(expectPath, "status");
618
+ // A quoted "200" is the same expectation as 200; only the class form is a string.
619
+ const exact = typeof value === "number" ? value : typeof value === "string" && /^\d{3}$/.test(value) ? Number(value) : undefined;
620
+ if (exact !== undefined) {
621
+ if (!Number.isInteger(exact) || exact < 100 || exact > 599) {
622
+ throw new FormatError("invalid-field", statusPath, "must be an HTTP status (100–599) or a class like 2xx");
623
+ }
624
+ return { status: exact };
625
+ }
626
+ if (typeof value === "string" && STATUS_CLASS_RE.test(value))
627
+ return { status: value };
628
+ throw new FormatError("invalid-field", statusPath, "must be an HTTP status (100–599) or a class like 2xx");
629
+ }
630
+ /**
631
+ * Kahn's algorithm over `after`. The steps it cannot order are on a cycle or
632
+ * behind one; the first of them in file order is the one reported, which both
633
+ * implementations agree on.
634
+ */
635
+ function checkAcyclic(steps) {
636
+ const parents = new Map(steps.map((step) => [step.id, parentsOf(step)]));
637
+ const waiting = new Map(steps.map((step) => [step.id, parents.get(step.id).length]));
638
+ const ready = steps.filter((step) => step.after.length === 0).map((step) => step.id);
639
+ const done = new Set();
640
+ while (ready.length > 0) {
641
+ const id = ready.shift();
642
+ done.add(id);
643
+ for (const step of steps) {
644
+ for (const parent of parents.get(step.id)) {
645
+ if (parent !== id)
646
+ continue;
647
+ const left = waiting.get(step.id) - 1;
648
+ waiting.set(step.id, left);
649
+ if (left === 0)
650
+ ready.push(step.id);
651
+ }
652
+ }
653
+ }
654
+ const stuck = steps.findIndex((step) => !done.has(step.id));
655
+ if (stuck >= 0) {
656
+ throw new FormatError("invalid-field", `steps[${stuck}].after`, "steps form a cycle");
657
+ }
658
+ }
659
+ const FLOW_KINDS = ["request", "log", "if", "switch", "loop", "get", "set"];
660
+ /** A non-empty template or condition. */
661
+ function flowText(obj, key, path) {
662
+ const value = obj[key];
663
+ if (typeof value !== "string" || value.trim() === "") {
664
+ throw new FormatError("invalid-field", join(path, key), "must be a non-empty string");
665
+ }
666
+ return value;
667
+ }
668
+ /** A mapping with at least one entry, whose keys `keyRe` accepts and whose values are strings `valueOk` accepts. */
669
+ function flowMap(obj, key, path, keyRe, keyMessage, valueOk, valueMessage) {
670
+ const raw = obj[key];
671
+ const mapPath = join(path, key);
672
+ if (raw === null || raw === undefined || typeof raw !== "object" || Array.isArray(raw)) {
673
+ throw new FormatError("invalid-field", mapPath, "must be a mapping with at least one entry");
674
+ }
675
+ const entries = Object.entries(raw);
676
+ if (entries.length === 0) {
677
+ throw new FormatError("invalid-field", mapPath, "must be a mapping with at least one entry");
678
+ }
679
+ const out = {};
680
+ for (const [name, value] of entries) {
681
+ const entryPath = join(mapPath, name);
682
+ if (!keyRe.test(name))
683
+ throw new FormatError("invalid-field", entryPath, keyMessage);
684
+ if (typeof value !== "string" || !valueOk(value)) {
685
+ throw new FormatError("invalid-field", entryPath, valueMessage);
686
+ }
687
+ out[name] = value;
688
+ }
689
+ return out;
690
+ }
691
+ const isPath = (value) => CAPTURE_PATH_RE.test(value);
692
+ const isAny = () => true;
693
+ function parseFlowStep(step, stepPath, stepId, stepName) {
694
+ const present = FLOW_KINDS.filter((kind) => step[kind] !== undefined);
695
+ if (present.length === 0) {
696
+ throw new FormatError("missing-field", join(stepPath, "request"), "a step needs one of request, log, if, switch, loop, get or set");
697
+ }
698
+ if (present.length > 1) {
699
+ throw new FormatError("invalid-field", join(stepPath, present[1]), `a step is one kind; it is already ${present[0]}`);
700
+ }
701
+ const kind = present[0];
702
+ const only = (key, kinds) => {
703
+ if (step[key] !== undefined && !kinds.includes(kind)) {
704
+ throw new FormatError("invalid-field", join(stepPath, key), `not allowed on a ${kind} step`);
705
+ }
706
+ };
707
+ only("capture", ["request"]);
708
+ only("when", ["request"]);
709
+ only("expect", ["request"]);
710
+ only("continueOnFailure", ["request", "loop"]);
711
+ const after = parseStringList(step, "after", stepPath);
712
+ after.forEach((ref, j) => {
713
+ if (after.indexOf(ref) !== j) {
714
+ throw new FormatError("invalid-field", `${join(stepPath, "after")}[${j}]`, `"${ref}" is listed twice`);
715
+ }
716
+ });
717
+ const when = optString(step, "when", stepPath);
718
+ if (when !== undefined && when.trim() === "") {
719
+ throw new FormatError("invalid-field", join(stepPath, "when"), "must be a non-empty condition");
720
+ }
721
+ const expect = parseFlowExpect(step, stepPath);
722
+ const base = {
723
+ id: stepId,
724
+ ...(stepName !== undefined ? { name: stepName } : {}),
725
+ after,
726
+ ...(when !== undefined ? { when } : {}),
727
+ ...(expect !== undefined ? { expect } : {}),
728
+ continueOnFailure: optBool(step, "continueOnFailure", stepPath, false),
729
+ };
730
+ switch (kind) {
731
+ case "request": {
732
+ const request = reqString(step, "request", stepPath);
733
+ if (!request.endsWith(".req.yaml") || request.startsWith("/") || request.split("/").includes("..")) {
734
+ throw new FormatError("invalid-field", join(stepPath, "request"), "must be a workspace-relative path to a .req.yaml file");
735
+ }
736
+ const rawCapture = step["capture"];
737
+ const isEmpty = rawCapture === undefined ||
738
+ rawCapture === null ||
739
+ (typeof rawCapture === "object" && !Array.isArray(rawCapture) && Object.keys(rawCapture).length === 0);
740
+ const capture = isEmpty
741
+ ? {}
742
+ : flowMap(step, "capture", stepPath, CAPTURE_NAME_RE, "must be a variable name", isPath, "must be a dotted path such as data.items.0.id");
743
+ return { step: { kind, request, ...base }, capture };
744
+ }
745
+ case "log":
746
+ return { step: { kind, log: flowText(step, "log", stepPath), ...base } };
747
+ case "if":
748
+ return { step: { kind, if: flowText(step, "if", stepPath), ...base } };
749
+ case "switch": {
750
+ const obj = optRecord(step, "switch", stepPath);
751
+ const switchPath = join(stepPath, "switch");
752
+ if (obj === undefined)
753
+ throw new FormatError("invalid-field", switchPath, "must be a mapping");
754
+ checkKeys(obj, ["value", "cases"], switchPath);
755
+ const value = flowText(obj, "value", switchPath);
756
+ const cases = flowMap(obj, "cases", switchPath, STEP_ID_RE, "a case is named like a step id: lowercase letters, digits, - and _", isAny, "must be a string");
757
+ if (Object.prototype.hasOwnProperty.call(cases, "default")) {
758
+ throw new FormatError("invalid-field", join(join(switchPath, "cases"), "default"), "default is the port no case matched");
759
+ }
760
+ return { step: { kind, switch: { value, cases }, ...base } };
761
+ }
762
+ case "loop": {
763
+ const obj = optRecord(step, "loop", stepPath);
764
+ const loopPath = join(stepPath, "loop");
765
+ if (obj === undefined)
766
+ throw new FormatError("invalid-field", loopPath, "must be a mapping");
767
+ checkKeys(obj, ["items"], loopPath);
768
+ return { step: { kind, loop: { items: flowText(obj, "items", loopPath) }, ...base } };
769
+ }
770
+ case "get": {
771
+ const obj = optRecord(step, "get", stepPath);
772
+ const getPath = join(stepPath, "get");
773
+ if (obj === undefined)
774
+ throw new FormatError("invalid-field", getPath, "must be a mapping");
775
+ checkKeys(obj, ["from", "values"], getPath);
776
+ const from = reqString(obj, "from", getPath);
777
+ const values = flowMap(obj, "values", getPath, CAPTURE_NAME_RE, "must be a variable name", isPath, "must be a dotted path such as data.items.0.id");
778
+ return { step: { kind, get: { from, values }, ...base } };
779
+ }
780
+ case "set":
781
+ return {
782
+ step: {
783
+ kind,
784
+ set: flowMap(step, "set", stepPath, CAPTURE_NAME_RE, "must be a variable name", isAny, "must be a string"),
785
+ ...base,
786
+ },
787
+ };
788
+ }
789
+ }
790
+ /** Edges name steps that exist, and ports exactly where the source has them. */
791
+ function checkEdges(steps) {
792
+ const byId = new Map(steps.map((step) => [step.id, step]));
793
+ steps.forEach((step, i) => {
794
+ step.after.forEach((ref, j) => {
795
+ const path = `steps[${i}].after[${j}]`;
796
+ const { step: source, port } = edgeRef(ref);
797
+ const from = byId.get(source);
798
+ if (from === undefined)
799
+ throw new FormatError("invalid-field", path, `no step with id "${source}"`);
800
+ const ports = portsOf(from);
801
+ if (ports.length === 0 && port !== undefined) {
802
+ throw new FormatError("invalid-field", path, `a ${from.kind} step has no ports; write "${source}"`);
803
+ }
804
+ if (ports.length > 0 && port === undefined) {
805
+ throw new FormatError("invalid-field", path, `name a port of "${source}": ${ports.join(", ")}`);
806
+ }
807
+ if (port !== undefined && !ports.includes(port)) {
808
+ throw new FormatError("invalid-field", path, `"${source}" has no port "${port}"; it has ${ports.join(", ")}`);
809
+ }
810
+ });
811
+ });
812
+ }
813
+ /** A Get reads a request step it follows; loops do not nest, and a body never waits on its own `done`. */
814
+ function checkGetsAndLoops(steps) {
815
+ const byId = new Map(steps.map((step) => [step.id, step]));
816
+ const ancestors = ancestorsOf(steps);
817
+ steps.forEach((step, i) => {
818
+ if (step.kind !== "get")
819
+ return;
820
+ const path = `steps[${i}].get.from`;
821
+ const from = byId.get(step.get.from);
822
+ if (from === undefined || from.kind !== "request") {
823
+ throw new FormatError("invalid-field", path, `"${step.get.from}" is not a request step`);
824
+ }
825
+ if (!ancestors.get(step.id).has(from.id)) {
826
+ throw new FormatError("invalid-field", path, `"${from.id}" is not a step this one follows`);
827
+ }
828
+ });
829
+ const bodies = loopBodies(steps);
830
+ steps.forEach((step, i) => {
831
+ if (step.kind !== "loop")
832
+ return;
833
+ for (const [loop, body] of bodies) {
834
+ if (body.has(step.id)) {
835
+ throw new FormatError("invalid-field", `steps[${i}].loop`, `loops do not nest; this one is inside "${loop}"`);
836
+ }
837
+ }
838
+ });
839
+ for (const [loop, body] of bodies) {
840
+ const after = descendantsThrough(steps, `${loop}.done`);
841
+ const index = steps.findIndex((step) => body.has(step.id) && after.has(step.id));
842
+ if (index >= 0) {
843
+ throw new FormatError("invalid-field", `steps[${index}].after`, `a step in the body of "${loop}" cannot wait for its done port`);
844
+ }
845
+ }
846
+ }
847
+ /**
848
+ * An older file's `capture` (ADR-0009): a Get variable node right after the
849
+ * step, and the steps that waited for the request wait for it instead.
850
+ */
851
+ function rewriteCaptures(steps, captures) {
852
+ if (captures.size === 0)
853
+ return steps;
854
+ const taken = new Set(steps.map((step) => step.id));
855
+ const renamed = new Map();
856
+ for (const step of steps) {
857
+ if (!captures.has(step.id))
858
+ continue;
859
+ let id = `${step.id}-get`;
860
+ for (let n = 2; taken.has(id); n++)
861
+ id = `${step.id}-get-${n}`;
862
+ taken.add(id);
863
+ renamed.set(step.id, id);
864
+ }
865
+ const out = [];
866
+ for (const step of steps) {
867
+ out.push({ ...step, after: step.after.map((ref) => renamed.get(ref) ?? ref) });
868
+ const getId = renamed.get(step.id);
869
+ if (getId !== undefined) {
870
+ out.push({
871
+ kind: "get",
872
+ id: getId,
873
+ get: { from: step.id, values: captures.get(step.id) },
874
+ after: [step.id],
875
+ continueOnFailure: false,
876
+ });
877
+ }
878
+ }
879
+ return out;
880
+ }
881
+ /** Parse and validate a `flows/<slug>.flow.yaml` file. */
882
+ export function parseFlowFile(text) {
883
+ const obj = root(text);
884
+ checkKeys(obj, ["format", "id", "name", "description", "environment", "steps"], "");
885
+ const format = checkFormat(obj, "");
886
+ const id = ulid(obj, "id", "");
887
+ const name = reqString(obj, "name", "");
888
+ const description = optString(obj, "description", "");
889
+ const environment = obj["environment"] === undefined ? undefined : reqString(obj, "environment", "");
890
+ const ids = new Set();
891
+ const captures = new Map();
892
+ const steps = optArray(obj, "steps", "").map((item, i) => {
893
+ const stepPath = `steps[${i}]`;
894
+ const step = itemRecord(item, stepPath);
895
+ checkKeys(step, ["id", "name", ...FLOW_KINDS, "after", "when", "capture", "expect", "continueOnFailure"], stepPath);
896
+ const stepId = reqString(step, "id", stepPath);
897
+ if (!STEP_ID_RE.test(stepId)) {
898
+ throw new FormatError("invalid-field", join(stepPath, "id"), "must be lowercase letters, digits, - and _");
899
+ }
900
+ if (ids.has(stepId)) {
901
+ throw new FormatError("invalid-field", join(stepPath, "id"), `duplicate step id "${stepId}"`);
902
+ }
903
+ ids.add(stepId);
904
+ const stepName = optString(step, "name", stepPath);
905
+ if (stepName === "") {
906
+ throw new FormatError("invalid-field", join(stepPath, "name"), "must be a non-empty string");
907
+ }
908
+ const parsed = parseFlowStep(step, stepPath, stepId, stepName);
909
+ if (parsed.capture !== undefined && Object.keys(parsed.capture).length > 0) {
910
+ captures.set(stepId, parsed.capture);
911
+ }
912
+ return parsed.step;
913
+ });
914
+ checkEdges(steps);
915
+ checkAcyclic(steps);
916
+ checkGetsAndLoops(steps);
917
+ return {
918
+ format,
919
+ id,
920
+ name,
921
+ ...(description !== undefined ? { description } : {}),
922
+ ...(environment !== undefined ? { environment } : {}),
923
+ steps: rewriteCaptures(steps, captures),
924
+ };
925
+ }
926
+ /** Parse and validate a `<slug>.examples.yaml` file. */
927
+ export function parseExamplesFile(text) {
928
+ const obj = root(text);
929
+ checkKeys(obj, ["format", "examples"], "");
930
+ const seen = new Set();
931
+ const examples = optArray(obj, "examples", "").map((item, i) => {
932
+ const itemPath = `examples[${i}]`;
933
+ const entry = itemRecord(item, itemPath);
934
+ checkKeys(entry, ["name", "status", "headers", "body"], itemPath);
935
+ const name = reqString(entry, "name", itemPath);
936
+ if (seen.has(name)) {
937
+ throw new FormatError("invalid-field", `${itemPath}.name`, `duplicate example name "${name}"`);
938
+ }
939
+ seen.add(name);
940
+ const status = reqInt(entry, "status", itemPath);
941
+ if (status < 100 || status > 599) {
942
+ throw new FormatError("invalid-field", `${itemPath}.status`, "must be an HTTP status (100–599)");
943
+ }
944
+ return {
945
+ name,
946
+ status,
947
+ headers: parseKvRows(entry, "headers", itemPath),
948
+ body: optString(entry, "body", itemPath) ?? "",
949
+ };
950
+ });
951
+ return { format: checkFormat(obj, ""), examples };
952
+ }
953
+ /** Parse and validate a `mocks/<name>.yaml` file. */
954
+ export function parseMockFile(text) {
955
+ const obj = root(text);
956
+ checkKeys(obj, ["format", "name", "port", "collections", "example"], "");
957
+ const port = reqInt(obj, "port", "");
958
+ if (port < 1 || port > 65535) {
959
+ throw new FormatError("invalid-field", "port", "must be 1–65535");
960
+ }
961
+ const collections = parseStringList(obj, "collections", "");
962
+ collections.forEach((path, i) => {
963
+ if (!path.startsWith("collections/") || path.includes("..")) {
964
+ throw new FormatError("invalid-field", `collections[${i}]`, "must be a workspace-relative collection path (collections/<name>)");
965
+ }
966
+ });
967
+ const example = optString(obj, "example", "");
968
+ return {
969
+ format: checkFormat(obj, ""),
970
+ name: reqString(obj, "name", ""),
971
+ port,
972
+ collections,
973
+ ...(example === undefined ? {} : { example }),
974
+ };
975
+ }
531
976
  //# sourceMappingURL=parse.js.map
@@ -1,4 +1,4 @@
1
- import { CollectionFile, EnvironmentFile, RequestFile, SchedulesFile, WorkspaceManifest } from "./types.js";
1
+ import { CollectionFile, EnvironmentFile, RequestFile, SchedulesFile, WorkspaceManifest, ExamplesFile, FlowFile, MockFile } from "./types.js";
2
2
  /** Serialize a normalized request to canonical `*.req.yaml` bytes. */
3
3
  export declare function serializeRequestFile(req: RequestFile): string;
4
4
  /** Serialize a normalized collection/folder to canonical bytes. */
@@ -9,3 +9,9 @@ export declare function serializeEnvironmentFile(env: EnvironmentFile): string;
9
9
  export declare function serializeWorkspaceManifest(ws: WorkspaceManifest): string;
10
10
  /** Serialize normalized schedules to canonical bytes. */
11
11
  export declare function serializeSchedulesFile(file: SchedulesFile): string;
12
+ /** Serialize a request's examples to canonical bytes. */
13
+ export declare function serializeExamplesFile(file: ExamplesFile): string;
14
+ /** Serialize a mock definition to canonical bytes. */
15
+ export declare function serializeMockFile(mock: MockFile): string;
16
+ /** Serialize a normalized flow to canonical bytes (ADR-0008, ADR-0009). */
17
+ export declare function serializeFlowFile(flow: FlowFile): string;