@intellectual-frontiers/integrations 0.0.0-stage → 0.1.1

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.
Files changed (60) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +8 -2
  3. package/dist/governance/exchange.d.ts +224 -0
  4. package/dist/governance/exchange.js +86 -0
  5. package/dist/governance/ids.d.ts +61 -0
  6. package/dist/governance/ids.js +53 -0
  7. package/dist/governance/mod.d.ts +11 -0
  8. package/dist/governance/mod.js +12 -0
  9. package/dist/governance/observe.d.ts +172 -0
  10. package/dist/governance/observe.js +139 -0
  11. package/dist/logical/conformance.d.ts +44 -0
  12. package/dist/logical/conformance.js +108 -0
  13. package/dist/logical/constraints.d.ts +86 -0
  14. package/dist/logical/constraints.js +112 -0
  15. package/dist/logical/exchange.d.ts +98 -0
  16. package/dist/logical/exchange.js +135 -0
  17. package/dist/logical/ledger.d.ts +94 -0
  18. package/dist/logical/ledger.js +90 -0
  19. package/dist/logical/mapping.d.ts +64 -0
  20. package/dist/logical/mapping.js +99 -0
  21. package/dist/logical/mod.d.ts +18 -0
  22. package/dist/logical/mod.js +19 -0
  23. package/dist/logical/observe.d.ts +222 -0
  24. package/dist/logical/observe.js +156 -0
  25. package/dist/logical/plugin.d.ts +91 -0
  26. package/dist/logical/plugin.js +53 -0
  27. package/dist/logical/ports.d.ts +102 -0
  28. package/dist/logical/ports.js +31 -0
  29. package/dist/logical/registry.d.ts +72 -0
  30. package/dist/logical/registry.js +81 -0
  31. package/dist/logical/tree.d.ts +91 -0
  32. package/dist/logical/tree.js +114 -0
  33. package/dist/mod.d.ts +15 -0
  34. package/dist/mod.js +16 -0
  35. package/dist/physical/http/mod.d.ts +54 -0
  36. package/dist/physical/http/mod.js +114 -0
  37. package/dist/physical/transport/mod.d.ts +79 -0
  38. package/dist/physical/transport/mod.js +61 -0
  39. package/dist/surfaces/headless/mod.d.ts +46 -0
  40. package/dist/surfaces/headless/mod.js +258 -0
  41. package/package.json +67 -4
  42. package/src/governance/exchange.ts +220 -0
  43. package/src/governance/ids.ts +92 -0
  44. package/src/governance/mod.ts +12 -0
  45. package/src/governance/observe.ts +226 -0
  46. package/src/logical/conformance.ts +113 -0
  47. package/src/logical/constraints.ts +154 -0
  48. package/src/logical/exchange.ts +184 -0
  49. package/src/logical/ledger.ts +123 -0
  50. package/src/logical/mapping.ts +114 -0
  51. package/src/logical/mod.ts +19 -0
  52. package/src/logical/observe.ts +314 -0
  53. package/src/logical/plugin.ts +102 -0
  54. package/src/logical/ports.ts +89 -0
  55. package/src/logical/registry.ts +93 -0
  56. package/src/logical/tree.ts +153 -0
  57. package/src/mod.ts +16 -0
  58. package/src/physical/http/mod.ts +134 -0
  59. package/src/physical/transport/mod.ts +85 -0
  60. package/src/surfaces/headless/mod.ts +293 -0
@@ -0,0 +1,139 @@
1
+ // Spec: 0002-integrations-governance FR-004, FR-005, FR-006, FR-007, FR-008, FR-009
2
+ /**
3
+ * The governance of observation (commons integrations 0002-integrations-governance): what a connector is allowed to be and to read, as data that names no
4
+ * vendor, no HTTP and no file path. A connector has a class, one read-only contract, a credential reference with its least-privilege scope, a cadence, the
5
+ * kinds of entity it may produce and the fields that are never kept, labels in the world's terms, and a policy for the trust it places in the system it reads.
6
+ *
7
+ * @remarks
8
+ * Every list is a closed union with an exhaustive `switch` where it is read; the policy data of a consumer (a fleet's paths, an estate's labels, a catalogue of
9
+ * controls) is attached by the consumer and is not in this module.
10
+ *
11
+ * @module
12
+ */
13
+ import { absurd, err, ok } from "@intellectual-frontiers/core";
14
+ import { brand, durationMs, parseDuration, msOf } from "./ids.js";
15
+ export const CONNECTOR_CLASSES = ["cloud", "identity", "code-host", "hr", "endpoint", "ticketing", "network-device", "vulnerability"];
16
+ export const ENTITY_KINDS = ["person", "account", "device", "repository"];
17
+ /** The generic denylist: personal, compensation and secret fields. A connector may add to it and never remove from it. */
18
+ export const GENERIC_DENYLIST = {
19
+ patterns: [
20
+ { kind: "contains", text: "salary", why: "compensation" },
21
+ { kind: "contains", text: "compensation", why: "compensation" },
22
+ { kind: "contains", text: "bonus", why: "compensation" },
23
+ { kind: "contains", text: "ssn", why: "government identifier" },
24
+ { kind: "contains", text: "social_security", why: "government identifier" },
25
+ { kind: "contains", text: "passport", why: "government identifier" },
26
+ { kind: "contains", text: "national_id", why: "government identifier" },
27
+ { kind: "contains", text: "birth", why: "birth date" },
28
+ { kind: "contains", text: "dob", why: "birth date" },
29
+ { kind: "contains", text: "address", why: "home address" },
30
+ { kind: "contains", text: "phone", why: "personal contact" },
31
+ { kind: "contains", text: "password", why: "secret" },
32
+ { kind: "contains", text: "secret", why: "secret" },
33
+ { kind: "contains", text: "token", why: "secret" },
34
+ { kind: "contains", text: "private_key", why: "secret" },
35
+ { kind: "contains", text: "api_key", why: "secret" },
36
+ ],
37
+ };
38
+ /** Whether a field name is denied by a denylist. */
39
+ export function isDenied(list, field) {
40
+ const f = field.toLowerCase();
41
+ return list.patterns.some((p) => {
42
+ switch (p.kind) {
43
+ case "exact":
44
+ return f === p.text.toLowerCase();
45
+ case "contains":
46
+ return f.includes(p.text.toLowerCase());
47
+ default:
48
+ return absurd(p);
49
+ }
50
+ });
51
+ }
52
+ /** The denylist of a connector: the generic one and what the connector adds. */
53
+ export const denylistWith = (extra) => ({ patterns: [...GENERIC_DENYLIST.patterns, ...extra] });
54
+ /** An observation is never held fresh for longer than seven days. */
55
+ export const MAX_STALE_MS = 7 * 86_400_000;
56
+ /** A cadence from `every` (`15m`, `6h`, `1d`) and, where given, `staleAfter`: by default twice `every`, never more than seven days, never less than `every`. */
57
+ export function cadence(every, staleAfter) {
58
+ const e = parseDuration(every);
59
+ if (e.kind === "err")
60
+ return err({ kind: "cadence-text", error: e.error });
61
+ let s;
62
+ if (staleAfter === undefined) {
63
+ s = brand(Math.min(durationMs(e.value) * 2, MAX_STALE_MS));
64
+ }
65
+ else {
66
+ const parsed = parseDuration(staleAfter);
67
+ if (parsed.kind === "err")
68
+ return err({ kind: "cadence-text", error: parsed.error });
69
+ s = parsed.value;
70
+ }
71
+ if (durationMs(s) > MAX_STALE_MS)
72
+ return err({ kind: "stale-beyond-cap", staleAfter: s });
73
+ if (durationMs(s) < durationMs(e.value))
74
+ return err({ kind: "stale-before-every", every: e.value, staleAfter: s });
75
+ return ok({ every: e.value, staleAfter: s });
76
+ }
77
+ /** Whether an observation made at `at` is stale at `now`. */
78
+ export const isStale = (c, at, now) => msOf(now) - msOf(at) > durationMs(c.staleAfter);
79
+ /** A credential spec that has at least one secret field, a hint on each field and no field twice. */
80
+ export function credentialSpec(ref, fields) {
81
+ if (!fields.some((f) => f.secret))
82
+ return err({ kind: "no-secret-field" });
83
+ const seen = new Set();
84
+ for (const f of fields) {
85
+ if (f.hint.trim() === "")
86
+ return err({ kind: "field-without-hint", name: f.name });
87
+ if (seen.has(f.name))
88
+ return err({ kind: "duplicate-field", name: f.name });
89
+ seen.add(f.name);
90
+ }
91
+ return ok({ ref, fields });
92
+ }
93
+ /** Every problem of a connector's governance; none where it may be used. */
94
+ export function governanceProblems(g) {
95
+ const out = [];
96
+ if (g.scope.grants.length === 0)
97
+ out.push({ kind: "no-scope" });
98
+ if (g.transport.kind === "https") {
99
+ if (g.transport.hosts.length === 0)
100
+ out.push({ kind: "no-host" });
101
+ if (g.transport.tls.kind === "pinned" && g.transport.tls.origin === "preconfigured" && g.transport.tls.sha256 === undefined)
102
+ out.push({ kind: "pin-without-digest", origin: "preconfigured" });
103
+ }
104
+ for (const p of GENERIC_DENYLIST.patterns) {
105
+ if (!g.denylist.patterns.some((q) => q.kind === p.kind && q.text === p.text))
106
+ out.push({ kind: "denylist-weaker", missing: p.text });
107
+ }
108
+ if (g.labels.serviceModels.length === 0 && g.class === "cloud")
109
+ out.push({ kind: "no-service-model" });
110
+ const seen = new Set();
111
+ for (const e of g.entities) {
112
+ if (seen.has(e))
113
+ out.push({ kind: "entity-twice", entity: e });
114
+ seen.add(e);
115
+ }
116
+ return out;
117
+ }
118
+ /** What a pinned policy does with the digest the system shows and the one remembered (or none): a total function of the policy, the shown digest and what is remembered. */
119
+ export function decidePin(policy, shown, remembered) {
120
+ switch (policy.kind) {
121
+ case "system-roots":
122
+ return { kind: "refuse", why: "not-pinned-policy" };
123
+ case "pinned": {
124
+ const expected = policy.sha256 ?? remembered;
125
+ if (expected !== undefined)
126
+ return expected === shown ? { kind: "accept" } : { kind: "refuse", why: "mismatch" };
127
+ switch (policy.origin) {
128
+ case "trust-on-first-use":
129
+ return { kind: "remember", sha256: shown };
130
+ case "preconfigured":
131
+ return { kind: "refuse", why: "no-pin-and-not-first-use" };
132
+ default:
133
+ return absurd(policy.origin);
134
+ }
135
+ }
136
+ default:
137
+ return absurd(policy);
138
+ }
139
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * The conformance suites of the extension points (commons integrations 0008-integrations-plugins): what every connector and every standards plugin must satisfy,
3
+ * as pure functions from the extension and its fixtures to findings. A plugin package runs them in its own tests and asserts that the findings are empty.
4
+ *
5
+ * @remarks
6
+ * The suites use no test framework: a finding is data (`ConformanceFinding`) with the extension's id, so that a registry can refuse an extension that does not conform.
7
+ *
8
+ * @module
9
+ */
10
+ import { type Instant } from "@intellectual-frontiers/integrations/governance";
11
+ import type { Finding } from "./constraints.js";
12
+ import type { Connector, PostureStatus } from "./observe.js";
13
+ import type { StandardsPlugin } from "./plugin.js";
14
+ import type { ReadPort } from "./ports.js";
15
+ import { type Interchange } from "./tree.js";
16
+ /** What a suite found wrong. */
17
+ export type ConformanceFinding = {
18
+ readonly extension: string;
19
+ readonly rule: string;
20
+ readonly message: string;
21
+ };
22
+ /** A recorded run of a connector: the port it reads, the moment, and what is expected of the result. */
23
+ export type ConnectorFixture = {
24
+ readonly name: string;
25
+ readonly port: ReadPort;
26
+ readonly now: Instant;
27
+ readonly expect: {
28
+ readonly account?: string;
29
+ readonly posture?: Readonly<Record<string, string | number | boolean>>;
30
+ readonly labels?: Readonly<Record<string, number>>;
31
+ readonly policies?: Readonly<Record<string, PostureStatus>>;
32
+ };
33
+ };
34
+ /** The conformance of a connector over its fixtures: sound governance, a description that agrees with it, at least one fixture, a probe that answers, an observation that names the connector, keeps no denied field, is the same when observed twice, and meets each fixture's expectations. */
35
+ export declare function conformConnector(c: Connector, fixtures: readonly ConnectorFixture[]): Promise<readonly ConformanceFinding[]>;
36
+ /** What a plugin is checked with: texts of its syntax that parse, from the issuer's published examples or generated, never real data. */
37
+ export type PluginSamples = {
38
+ readonly valid: readonly string[];
39
+ readonly garbage: readonly string[];
40
+ };
41
+ /** The conformance of a standards plugin: its codec parses each valid sample, serializes it and reads the result back to the same tree (round trip); it fails each garbage text as a syntax error that holds no part of the text; and its standards are registered with a licence that has terms. */
42
+ export declare function conformPlugin(p: StandardsPlugin, samples: PluginSamples): readonly ConformanceFinding[];
43
+ /** The findings of a validation, with none of their messages holding a value of the payload: the check a plugin's validation must pass. */
44
+ export declare function findingsHoldNoValue(fs: readonly Finding[], tree: Interchange): boolean;
@@ -0,0 +1,108 @@
1
+ // Spec: 0008-integrations-plugins FR-005, FR-006, FR-007, FR-008
2
+ /**
3
+ * The conformance suites of the extension points (commons integrations 0008-integrations-plugins): what every connector and every standards plugin must satisfy,
4
+ * as pure functions from the extension and its fixtures to findings. A plugin package runs them in its own tests and asserts that the findings are empty.
5
+ *
6
+ * @remarks
7
+ * The suites use no test framework: a finding is data (`ConformanceFinding`) with the extension's id, so that a registry can refuse an extension that does not conform.
8
+ *
9
+ * @module
10
+ */
11
+ import { isDenied } from "@intellectual-frontiers/integrations/governance";
12
+ import { governanceProblems } from "@intellectual-frontiers/integrations/governance";
13
+ import { valuesOf } from "./tree.js";
14
+ const bad = (extension, rule, message) => ({ extension, rule, message });
15
+ function deniedProps(c, o) {
16
+ const out = [];
17
+ for (const r of o.records ?? [])
18
+ for (const k of Object.keys(r.props))
19
+ if (isDenied(c.governance.denylist, k))
20
+ out.push(`${r.label}.${k}`);
21
+ return out;
22
+ }
23
+ /** The conformance of a connector over its fixtures: sound governance, a description that agrees with it, at least one fixture, a probe that answers, an observation that names the connector, keeps no denied field, is the same when observed twice, and meets each fixture's expectations. */
24
+ export async function conformConnector(c, fixtures) {
25
+ const id = c.governance.id;
26
+ const out = [];
27
+ for (const p of governanceProblems(c.governance))
28
+ out.push(bad(id, `governance/${p.kind}`, "the governance of the connector has a problem"));
29
+ const d = c.describe();
30
+ if (d.id !== id || d.class !== c.governance.class || !d.readOnly)
31
+ out.push(bad(id, "describe/disagrees", "describe does not say what the governance says"));
32
+ if (c.governance.contract.writes !== "never")
33
+ out.push(bad(id, "contract/writes", "the contract does not say never"));
34
+ if (fixtures.length === 0)
35
+ out.push(bad(id, "fixtures/none", "a connector has at least one fixture"));
36
+ for (const f of fixtures) {
37
+ const where = `${id}:${f.name}`;
38
+ const probe = await c.probe({ port: f.port, now: f.now });
39
+ if (probe.kind === "err")
40
+ out.push(bad(where, "probe/fails", `the probe failed: ${probe.error.kind}`));
41
+ const first = await c.observe({ port: f.port, now: f.now });
42
+ if (first.kind === "err") {
43
+ out.push(bad(where, "observe/fails", `observe failed: ${first.error.kind}`));
44
+ continue;
45
+ }
46
+ const o = first.value;
47
+ if (o.provider !== id)
48
+ out.push(bad(where, "observe/provider", "the observation does not name the connector as its provider"));
49
+ for (const k of deniedProps(c, o))
50
+ out.push(bad(where, "observe/denied-field", `a denied field was kept: ${k}`));
51
+ const second = await c.observe({ port: f.port, now: f.now });
52
+ if (second.kind === "err" || JSON.stringify(second.value) !== JSON.stringify(o))
53
+ out.push(bad(where, "observe/not-repeatable", "observing twice over the same answers gives two observations"));
54
+ if (f.expect.account !== undefined && o.account !== f.expect.account)
55
+ out.push(bad(where, "expect/account", "the account is not the expected one"));
56
+ for (const [k, v] of Object.entries(f.expect.posture ?? {}))
57
+ if (o.posture[k] !== v)
58
+ out.push(bad(where, "expect/posture", `the fact ${k} is not as expected`));
59
+ for (const [label, n] of Object.entries(f.expect.labels ?? {}))
60
+ if ((o.records ?? []).filter((r) => r.label === label).length !== n)
61
+ out.push(bad(where, "expect/labels", `the number of records labelled ${label} is not ${n}`));
62
+ const results = c.check(o, f.now);
63
+ for (const [pid, status] of Object.entries(f.expect.policies ?? {}))
64
+ if (results.find((r) => r.id === pid)?.status !== status)
65
+ out.push(bad(where, "expect/policy", `the policy ${pid} is not ${status}`));
66
+ }
67
+ return out;
68
+ }
69
+ /** The values of a tree that a text must not hold. */
70
+ const leaks = (text, tree) => valuesOf(tree).some((v) => v.length >= 4 && text.includes(v));
71
+ /** The conformance of a standards plugin: its codec parses each valid sample, serializes it and reads the result back to the same tree (round trip); it fails each garbage text as a syntax error that holds no part of the text; and its standards are registered with a licence that has terms. */
72
+ export function conformPlugin(p, samples) {
73
+ const out = [];
74
+ if (samples.valid.length === 0)
75
+ out.push(bad(p.id, "samples/none", "a plugin has at least one valid sample"));
76
+ for (const [i, text] of samples.valid.entries()) {
77
+ const where = `${p.id}:valid[${i}]`;
78
+ const parsed = p.codec.parse(text);
79
+ if (parsed.kind === "err") {
80
+ out.push(bad(where, "codec/parse", `a valid sample does not parse: ${parsed.error.code}`));
81
+ continue;
82
+ }
83
+ const written = p.codec.serialize(parsed.value);
84
+ if (written.kind === "err") {
85
+ out.push(bad(where, "codec/serialize", `the tree does not serialize: ${written.error.code}`));
86
+ continue;
87
+ }
88
+ const again = p.codec.parse(written.value);
89
+ if (again.kind === "err" || JSON.stringify(again.value) !== JSON.stringify(parsed.value))
90
+ out.push(bad(where, "codec/round-trip", "parse, serialize and parse again gives another tree"));
91
+ }
92
+ for (const [i, text] of samples.garbage.entries()) {
93
+ const where = `${p.id}:garbage[${i}]`;
94
+ const parsed = p.codec.parse(text);
95
+ if (parsed.kind === "ok")
96
+ out.push(bad(where, "codec/accepts-garbage", "a text that is not of the syntax parses"));
97
+ else if (text.length >= 4 && JSON.stringify(parsed.error).includes(text))
98
+ out.push(bad(where, "codec/echoes-input", "the error repeats the text it refused"));
99
+ }
100
+ for (const s of p.standards)
101
+ if (s.license.terms.trim() === "")
102
+ out.push(bad(`${p.id}:${s.urn}`, "standard/no-terms", "a standard has the terms of its licence"));
103
+ return out;
104
+ }
105
+ /** The findings of a validation, with none of their messages holding a value of the payload: the check a plugin's validation must pass. */
106
+ export function findingsHoldNoValue(fs, tree) {
107
+ return fs.every((f) => !leaks(`${f.message} ${f.path}`, tree));
108
+ }
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Schema and Profile as typed constraints over the abstract tree, and validation (commons integrations 0006-integrations-exchange): a schema says which paths a
3
+ * transaction has and how many times, a profile adds constraints to a schema, a terminology says which codes a binding allows, and validation gives findings at the level
4
+ * where each was found (syntax, schema, profile, terminology, business rule).
5
+ *
6
+ * @remarks
7
+ * A finding has a level, a severity, a path, a code and a message made of the code and the path: it never holds a value of the payload, so that findings may be logged
8
+ * (commons integrations 0003-integrations-logical FR-003). A business rule is a function of the tree that returns findings, supplied by an agreement.
9
+ *
10
+ * @module
11
+ */
12
+ import { type Result } from "@intellectual-frontiers/core";
13
+ import type { BindingStrength, Ref, StandardUrn } from "@intellectual-frontiers/integrations/governance";
14
+ import { type Transaction } from "./tree.js";
15
+ /** Where a finding was found. */
16
+ export type FindingLevel = "syntax" | "schema" | "profile" | "terminology" | "business-rule";
17
+ /** How bad a finding is. */
18
+ export type Severity = "error" | "warning" | "information";
19
+ /** What a finding says. */
20
+ export type FindingCode = "syntax-error" | "unknown-path" | "cardinality-min" | "cardinality-max" | "value-pattern" | "value-fixed" | "code-not-in-terminology" | "terminology-unavailable" | "business-rule" | "unmapped-source-field" | "lossy-mapping" | "mapping-target-conflict";
21
+ /** Every finding code, as a closed list of strings a consumer may carry as data; the compiler holds it complete against `FindingCode`. */
22
+ export declare const FINDING_CODES: readonly FindingCode[];
23
+ /** Every level of a finding. */
24
+ export declare const FINDING_LEVELS: readonly FindingLevel[];
25
+ /** A finding: never a value of the payload. */
26
+ export type Finding = {
27
+ readonly level: FindingLevel;
28
+ readonly severity: Severity;
29
+ readonly code: FindingCode;
30
+ readonly path: string;
31
+ readonly message: string;
32
+ };
33
+ /** A finding from its parts, its message made of the code and the path. */
34
+ export declare const finding: (level: FindingLevel, severity: Severity, code: FindingCode, path: string, note?: string) => Finding;
35
+ /** What a path of a schema must be. */
36
+ export type Constraint = {
37
+ readonly kind: "cardinality";
38
+ readonly path: string;
39
+ readonly min: number;
40
+ readonly max: number | "*";
41
+ } | {
42
+ readonly kind: "pattern";
43
+ readonly path: string;
44
+ readonly regex: string;
45
+ } | {
46
+ readonly kind: "fixed";
47
+ readonly path: string;
48
+ readonly value: string;
49
+ } | {
50
+ readonly kind: "binding";
51
+ readonly path: string;
52
+ readonly terminology: Ref<"terminology">;
53
+ readonly strength: BindingStrength;
54
+ };
55
+ /** A schema: the paths a kind of transaction has, with their constraints. A path with no constraint is allowed; a path not listed (and not below a listed one) is unknown. */
56
+ export type Schema = {
57
+ readonly id: Ref<"schema">;
58
+ readonly transaction: string;
59
+ readonly paths: readonly string[];
60
+ readonly constraints: readonly Constraint[];
61
+ };
62
+ /** A profile: more constraints on a schema. */
63
+ export type Profile = {
64
+ readonly id: Ref<"profile">;
65
+ readonly schema: Ref<"schema">;
66
+ readonly constraints: readonly Constraint[];
67
+ };
68
+ /** A code system or value set, as the codes it holds. Loaded from data the user supplies or the issuer publishes; the library embeds none. */
69
+ export type Terminology = {
70
+ readonly id: Ref<"terminology">;
71
+ readonly codes: ReadonlySet<string>;
72
+ };
73
+ /** Terminologies by urn. */
74
+ export type Terminologies = ReadonlyMap<StandardUrn, Terminology>;
75
+ /** A rule of business: a function of a transaction that gives findings (never of values). */
76
+ export type BusinessRule = (t: Transaction) => readonly Finding[];
77
+ /** Every finding of a transaction against a schema, a profile where given, the terminologies loaded, and the rules of business supplied, in that order of level. Total and pure. */
78
+ export declare function validate(t: Transaction, schema: Schema, options?: {
79
+ readonly profile?: Profile;
80
+ readonly terminologies?: Terminologies;
81
+ readonly rules?: readonly BusinessRule[];
82
+ }): readonly Finding[];
83
+ /** Whether the findings hold an error. */
84
+ export declare const hasErrors: (fs: readonly Finding[]) => boolean;
85
+ /** A result of a step that may give findings: the value, or the findings that stopped it. */
86
+ export type Checked<T> = Result<T, readonly Finding[]>;
@@ -0,0 +1,112 @@
1
+ // Spec: 0006-integrations-exchange FR-004, FR-005, FR-006, FR-007
2
+ /**
3
+ * Schema and Profile as typed constraints over the abstract tree, and validation (commons integrations 0006-integrations-exchange): a schema says which paths a
4
+ * transaction has and how many times, a profile adds constraints to a schema, a terminology says which codes a binding allows, and validation gives findings at the level
5
+ * where each was found (syntax, schema, profile, terminology, business rule).
6
+ *
7
+ * @remarks
8
+ * A finding has a level, a severity, a path, a code and a message made of the code and the path: it never holds a value of the payload, so that findings may be logged
9
+ * (commons integrations 0003-integrations-logical FR-003). A business rule is a function of the tree that returns findings, supplied by an agreement.
10
+ *
11
+ * @module
12
+ */
13
+ import { absurd } from "@intellectual-frontiers/core";
14
+ import { entries, occurrences, pathsOf } from "./tree.js";
15
+ const FINDING_CODE_TABLE = {
16
+ "syntax-error": true,
17
+ "unknown-path": true,
18
+ "cardinality-min": true,
19
+ "cardinality-max": true,
20
+ "value-pattern": true,
21
+ "value-fixed": true,
22
+ "code-not-in-terminology": true,
23
+ "terminology-unavailable": true,
24
+ "business-rule": true,
25
+ "unmapped-source-field": true,
26
+ "lossy-mapping": true,
27
+ "mapping-target-conflict": true,
28
+ };
29
+ /** Every finding code, as a closed list of strings a consumer may carry as data; the compiler holds it complete against `FindingCode`. */
30
+ export const FINDING_CODES = Object.keys(FINDING_CODE_TABLE).filter((k) => Object.hasOwn(FINDING_CODE_TABLE, k));
31
+ /** Every level of a finding. */
32
+ export const FINDING_LEVELS = ["syntax", "schema", "profile", "terminology", "business-rule"];
33
+ /** A finding from its parts, its message made of the code and the path. */
34
+ export const finding = (level, severity, code, path, note = "") => ({ level, severity, code, path, message: `${code} at ${path}${note === "" ? "" : `: ${note}`}` });
35
+ function severityOf(strength) {
36
+ switch (strength) {
37
+ case "required":
38
+ return "error";
39
+ case "extensible":
40
+ return "warning";
41
+ case "preferred":
42
+ return "information";
43
+ case "example":
44
+ return undefined;
45
+ default:
46
+ return absurd(strength);
47
+ }
48
+ }
49
+ function checkConstraint(c, level, t, terms) {
50
+ const out = [];
51
+ switch (c.kind) {
52
+ case "cardinality":
53
+ for (const [parent, n] of occurrences(t, c.path)) {
54
+ if (n < c.min)
55
+ out.push(finding(level, "error", "cardinality-min", parent === t.id ? c.path : `${parent}.${c.path.slice(c.path.lastIndexOf(".") + 1)}`, `${n} of at least ${c.min}`));
56
+ if (c.max !== "*" && n > c.max)
57
+ out.push(finding(level, "error", "cardinality-max", parent === t.id ? c.path : `${parent}.${c.path.slice(c.path.lastIndexOf(".") + 1)}`, `${n} of at most ${c.max}`));
58
+ }
59
+ return out;
60
+ case "pattern": {
61
+ const re = new RegExp(c.regex);
62
+ for (const e of entries(t))
63
+ if (e.path === c.path && !re.test(e.value))
64
+ out.push(finding(level, "error", "value-pattern", e.at, "does not match the pattern"));
65
+ return out;
66
+ }
67
+ case "fixed":
68
+ for (const e of entries(t))
69
+ if (e.path === c.path && e.value !== c.value)
70
+ out.push(finding(level, "error", "value-fixed", e.at, "is not the fixed value"));
71
+ return out;
72
+ case "binding": {
73
+ const severity = severityOf(c.strength);
74
+ if (severity === undefined)
75
+ return out;
76
+ const terminology = terms.get(c.terminology.urn);
77
+ for (const e of entries(t)) {
78
+ if (e.path !== c.path)
79
+ continue;
80
+ if (terminology === undefined)
81
+ out.push(finding("terminology", "warning", "terminology-unavailable", e.at, "the terminology was not loaded"));
82
+ else if (!terminology.codes.has(e.value))
83
+ out.push(finding("terminology", severity, "code-not-in-terminology", e.at, "the code is not in the bound terminology"));
84
+ }
85
+ return out;
86
+ }
87
+ default:
88
+ return absurd(c);
89
+ }
90
+ }
91
+ /** Every finding of a transaction against a schema, a profile where given, the terminologies loaded, and the rules of business supplied, in that order of level. Total and pure. */
92
+ export function validate(t, schema, options = {}) {
93
+ const terms = options.terminologies ?? new Map();
94
+ const out = [];
95
+ if (t.id !== schema.transaction)
96
+ out.push(finding("schema", "error", "unknown-path", t.id, "the transaction is not the schema's"));
97
+ const known = new Set(schema.paths);
98
+ for (const p of pathsOf(t)) {
99
+ if (!known.has(p) && ![...known].some((k) => k !== t.id && p.startsWith(`${k}.`)))
100
+ out.push(finding("schema", "error", "unknown-path", p));
101
+ }
102
+ for (const c of schema.constraints)
103
+ out.push(...checkConstraint(c, "schema", t, terms));
104
+ if (options.profile !== undefined)
105
+ for (const c of options.profile.constraints)
106
+ out.push(...checkConstraint(c, "profile", t, terms));
107
+ for (const r of options.rules ?? [])
108
+ out.push(...r(t));
109
+ return out;
110
+ }
111
+ /** Whether the findings hold an error. */
112
+ export const hasErrors = (fs) => fs.some((f) => f.severity === "error");
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Acknowledgements, outcomes and the exchange state machine (commons integrations 0006-integrations-exchange): the typed acknowledgements of the standards
3
+ * (X12 TA1 and 999, HL7 ACK, FHIR OperationOutcome) reduced to one status, and the life of a message as a total transition function of a state and an event.
4
+ *
5
+ * @module
6
+ */
7
+ import { type Result } from "@intellectual-frontiers/core";
8
+ import type { Instant } from "@intellectual-frontiers/integrations/governance";
9
+ import type { Finding } from "./constraints.js";
10
+ /** What an acknowledgement says of what it acknowledges. */
11
+ export type AckStatus = "accepted" | "accepted-with-errors" | "rejected";
12
+ /** The codes of an HL7 v2 acknowledgement: application (AA, AE, AR) and commit (CA, CE, CR). */
13
+ export type Hl7AckCode = "AA" | "AE" | "AR" | "CA" | "CE" | "CR";
14
+ /** An acknowledgement or an outcome, by standard. It carries codes and counts and the findings (which hold no value), never a payload. */
15
+ export type Acknowledgement = {
16
+ readonly kind: "x12-ta1";
17
+ readonly control: string;
18
+ readonly status: AckStatus;
19
+ readonly note: string;
20
+ } | {
21
+ readonly kind: "x12-999";
22
+ readonly control: string;
23
+ readonly groupControl: string;
24
+ readonly status: AckStatus;
25
+ readonly errors: number;
26
+ } | {
27
+ readonly kind: "hl7-ack";
28
+ readonly control: string;
29
+ readonly code: Hl7AckCode;
30
+ } | {
31
+ readonly kind: "fhir-operation-outcome";
32
+ readonly issues: readonly Finding[];
33
+ };
34
+ /** What an acknowledgement comes to. */
35
+ export declare function statusOf(a: Acknowledgement): AckStatus;
36
+ /** Every kind of acknowledgement, as a closed list of strings a consumer may carry as data. */
37
+ export declare const ACK_KINDS: readonly Acknowledgement["kind"][];
38
+ /** Every acknowledgement status. */
39
+ export declare const ACK_STATUSES: readonly AckStatus[];
40
+ /** Every reason a message is rejected: the partner said no (`nack`), or it was invalid on receipt (`invalid`). */
41
+ export declare const REJECTION_KINDS: readonly (Extract<ExchangeState, {
42
+ kind: "rejected";
43
+ }>["reason"])[];
44
+ /** Where a message is in its life. */
45
+ export type ExchangeState = {
46
+ readonly kind: "pending";
47
+ } | {
48
+ readonly kind: "sent";
49
+ readonly attempt: number;
50
+ readonly at: Instant;
51
+ } | {
52
+ readonly kind: "received";
53
+ readonly at: Instant;
54
+ } | {
55
+ readonly kind: "retrying";
56
+ readonly attempt: number;
57
+ } | {
58
+ readonly kind: "acknowledged";
59
+ readonly status: "accepted" | "accepted-with-errors";
60
+ } | {
61
+ readonly kind: "rejected";
62
+ readonly reason: "nack" | "invalid";
63
+ } | {
64
+ readonly kind: "abandoned";
65
+ readonly attempts: number;
66
+ };
67
+ /** What happens to a message. */
68
+ export type ExchangeEvent = {
69
+ readonly kind: "send";
70
+ readonly at: Instant;
71
+ } | {
72
+ readonly kind: "receive";
73
+ readonly at: Instant;
74
+ } | {
75
+ readonly kind: "ack";
76
+ readonly status: AckStatus;
77
+ } | {
78
+ readonly kind: "timeout";
79
+ } | {
80
+ readonly kind: "retry";
81
+ readonly at: Instant;
82
+ } | {
83
+ readonly kind: "invalid";
84
+ };
85
+ /** What the agreement allows. */
86
+ export type TransitionPolicy = {
87
+ readonly maxAttempts: number;
88
+ };
89
+ /** An event that does not fit the state it came in. */
90
+ export type TransitionError = {
91
+ readonly kind: "illegal";
92
+ readonly from: ExchangeState["kind"];
93
+ readonly event: ExchangeEvent["kind"];
94
+ };
95
+ /** The next state: total over every state and every event, an illegal pair giving an error and never throwing. */
96
+ export declare function transition(state: ExchangeState, event: ExchangeEvent, policy: TransitionPolicy): Result<ExchangeState, TransitionError>;
97
+ /** Whether a state is final: nothing follows it. */
98
+ export declare function isFinal(s: ExchangeState): boolean;