@intellectual-frontiers/integrations-x12 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Intellectual Frontiers
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,9 @@
1
- # Temporary Holding Version
1
+ # @intellectual-frontiers/integrations-x12
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The X12 envelope and acknowledgement skeleton of Integrations: the entries of X12 and of the HIPAA 5010 and purchasing transaction sets with their licence as data, a codec for the fixed-width ISA envelope and its ISA, GS and ST levels, control counts checked as findings, TA1 and 999 made and read, and a loader of a schema from the user's own transcription of a licensed guide. It embeds no standard.
4
+
5
+ ```sh
6
+ bun add @intellectual-frontiers/integrations-x12 # or: npm install @intellectual-frontiers/integrations-x12
7
+ ```
8
+
9
+ Sources and specifications: https://github.com/intellectual-frontiers/.github/tree/main/commons/integrations-x12
package/dist/mod.d.ts ADDED
@@ -0,0 +1,28 @@
1
+ import { type EmbeddedContent, type Standard, type StandardUrn } from "@intellectual-frontiers/integrations/governance";
2
+ import { type AckPort, type AckStatus, type Codec, type Finding, type Interchange, type Loader, type StandardsPlugin } from "@intellectual-frontiers/integrations/logical";
3
+ /** The X12 syntax, version 005010. */
4
+ export declare const X12_SYNTAX: StandardUrn;
5
+ /** The transaction sets of the plugin: the HIPAA 5010 set and the purchasing documents. */
6
+ export declare const TRANSACTION_SETS: readonly ["837", "835", "270", "271", "834", "850", "810", "856"];
7
+ /** A transaction set the plugin lists. */
8
+ export type TransactionSet = (typeof TRANSACTION_SETS)[number];
9
+ /** The urn of a transaction set's schema. */
10
+ export declare const setUrn: (set: TransactionSet) => StandardUrn;
11
+ /** The standards the plugin registers. */
12
+ export declare const STANDARDS: readonly Standard[];
13
+ /** The files of standards content the package embeds: none. */
14
+ export declare const EMBEDDED: readonly EmbeddedContent[];
15
+ /** The X12 codec. */
16
+ export declare const codec: Codec;
17
+ /** The findings of the control counts of an interchange: IEA against the groups and the ISA, GE against its transactions and the GS, SE against its segments and the ST. Paths and codes only. */
18
+ export declare function envelopeFindings(i: Interchange): readonly Finding[];
19
+ /** A TA1: the acknowledgement of an interchange envelope: its control number, date and time, the status and a note code (`000` where there is no error, `001` otherwise; the detailed codes are Planned). */
20
+ export declare function ta1(received: Interchange, status: AckStatus): Interchange;
21
+ /** A 999: the acknowledgement of each group of an interchange, AK1 for the group, AK9 for its status and counts. */
22
+ export declare function ack999(received: Interchange, status: AckStatus): Interchange;
23
+ /** The acknowledgement port of X12: a 999 where the interchange has groups, a TA1 where it has none; TA1 and 999 read back. */
24
+ export declare const acks: AckPort;
25
+ /** The loaders of the transaction sets: each reads the user's own transcription of the segments of a set from a licensed guide (`{transaction, segments: [{id, min, max}]}`); nothing of a guide is in the package. */
26
+ export declare const loaders: readonly Loader[];
27
+ /** The plugin of X12. */
28
+ export declare const x12Plugin: StandardsPlugin;
package/dist/mod.js ADDED
@@ -0,0 +1,246 @@
1
+ // Spec: 0001-integrations-x12-skeleton FR-001, FR-002, FR-003, FR-004, FR-005, FR-006
2
+ /**
3
+ * The X12 envelope and acknowledgement skeleton of Integrations (commons integrations-x12 0001-integrations-x12-skeleton): the entries of X12 and of the HIPAA 5010 and
4
+ * purchasing transaction sets with their licence as data, a codec for the fixed-width ISA envelope and the ISA, GS and ST levels, the control counts checked as findings, TA1
5
+ * and 999 made and read, and a loader of a schema from the user's own transcription of a licensed guide. It embeds no transaction set, guide or companion guide of X12.
6
+ *
7
+ * @remarks
8
+ * The skeleton supports the delimiters `*` between elements and `~` ending a segment, which the fixed width of the ISA fixes by position; any other is a syntax failure with the offset of the
9
+ * delimiter. Elements are not split into components. A transaction's children are its segments between ST and SE, flat: loops (the HL loops of the 837) are the schema's, Planned.
10
+ *
11
+ * @module
12
+ */
13
+ import { err, ok } from "@intellectual-frontiers/core";
14
+ import { parseStandardUrn, ref } from "@intellectual-frontiers/integrations/governance";
15
+ import { element, finding, segment, textOf, member, } from "@intellectual-frontiers/integrations/logical";
16
+ function urn(text) {
17
+ const r = parseStandardUrn(text);
18
+ if (r.kind === "err")
19
+ throw new Error(`a constant of the plugin is not a standard urn: ${text}`);
20
+ return r.value;
21
+ }
22
+ /** The X12 syntax, version 005010. */
23
+ export const X12_SYNTAX = urn("urn:standard:x12:edi:005010");
24
+ /** The transaction sets of the plugin: the HIPAA 5010 set and the purchasing documents. */
25
+ export const TRANSACTION_SETS = ["837", "835", "270", "271", "834", "850", "810", "856"];
26
+ /** The urn of a transaction set's schema. */
27
+ export const setUrn = (set) => urn(`urn:standard:x12:${set}:005010`);
28
+ const TERMS = "X12 sells its transaction set standards, implementation guides and companion guides (https://x12.org). They are licensed to their buyer, so this library never embeds them: a schema is read from the user's own copy.";
29
+ const base = { issuer: "x12", version: "005010", location: "https://x12.org/", license: { spdx: "LicenseRef-X12-licensed", embedding: "user-supplied", terms: TERMS }, sha256: undefined };
30
+ /** The standards the plugin registers. */
31
+ export const STANDARDS = [
32
+ { ...base, urn: X12_SYNTAX, level: "syntax", family: "message", title: "X12 interchange syntax", basis: { kind: "unaligned", reason: "the standard itself" } },
33
+ ...TRANSACTION_SETS.map((s) => ({ ...base, urn: setUrn(s), level: "schema", family: "message", title: `X12 ${s} transaction set`, basis: { kind: "unaligned", reason: "the standard itself" } })),
34
+ ];
35
+ /** The files of standards content the package embeds: none. */
36
+ export const EMBEDDED = [];
37
+ const failure = (code, offset = 0) => ({ kind: "syntax", code, offset });
38
+ /** The widths of the sixteen elements of the ISA. */
39
+ const ISA_WIDTHS = [2, 10, 2, 10, 2, 15, 2, 15, 6, 4, 1, 5, 9, 1, 1, 1];
40
+ const pad = (n) => String(n).padStart(2, "0");
41
+ const seg = (id, ...values) => segment(id, ...values.map((v, i) => element(pad(i + 1), v)));
42
+ const valueAt = (s, n) => s?.elements[n - 1]?.value ?? "";
43
+ function parseSegments(text) {
44
+ return text.split("~").map((s) => s.trim()).filter((s) => s !== "").map((s) => {
45
+ const [id = "", ...values] = s.split("*");
46
+ return seg(id, ...values);
47
+ });
48
+ }
49
+ /** The X12 codec. */
50
+ export const codec = {
51
+ syntax: ref("syntax", X12_SYNTAX),
52
+ parse: (text) => {
53
+ if (text.trim() === "")
54
+ return err(failure("empty"));
55
+ if (text.length < 106 || !text.startsWith("ISA"))
56
+ return err(failure("bad-envelope"));
57
+ if (text[3] !== "*")
58
+ return err(failure("bad-delimiter", 3));
59
+ if (text[105] !== "~")
60
+ return err(failure("bad-delimiter", 105));
61
+ const segs = parseSegments(text);
62
+ const isa = segs[0];
63
+ if (isa === undefined || isa.id !== "ISA" || isa.elements.length !== 16)
64
+ return err(failure("bad-envelope"));
65
+ for (const [i, w] of ISA_WIDTHS.entries())
66
+ if ((isa.elements[i]?.value.length ?? -1) !== w)
67
+ return err(failure("bad-envelope", i + 1));
68
+ const header = [isa];
69
+ const trailer = [];
70
+ const groups = [];
71
+ let group;
72
+ let tx;
73
+ for (const s of segs.slice(1)) {
74
+ switch (s.id) {
75
+ case "GS":
76
+ if (group !== undefined || tx !== undefined)
77
+ return err(failure("unbalanced"));
78
+ group = { id: valueAt(s, 1), control: valueAt(s, 6), header: [s], transactions: [] };
79
+ break;
80
+ case "ST":
81
+ if (group === undefined || tx !== undefined)
82
+ return err(failure("unbalanced"));
83
+ tx = { id: valueAt(s, 1), control: valueAt(s, 2), header: [s], children: [] };
84
+ break;
85
+ case "SE":
86
+ if (group === undefined || tx === undefined)
87
+ return err(failure("unbalanced"));
88
+ group.transactions.push({ kind: "transaction", id: tx.id, control: tx.control, children: tx.children, envelope: { header: tx.header, trailer: [s] } });
89
+ tx = undefined;
90
+ break;
91
+ case "GE":
92
+ if (group === undefined || tx !== undefined)
93
+ return err(failure("unbalanced"));
94
+ groups.push({ kind: "group", id: group.id, control: group.control, transactions: group.transactions, envelope: { header: group.header, trailer: [s] } });
95
+ group = undefined;
96
+ break;
97
+ case "IEA":
98
+ if (group !== undefined || tx !== undefined)
99
+ return err(failure("unbalanced"));
100
+ trailer.push(s);
101
+ break;
102
+ default:
103
+ if (tx !== undefined)
104
+ tx.children.push(s);
105
+ else if (group !== undefined)
106
+ return err(failure("bad-structure"));
107
+ else if (groups.length === 0 && trailer.length === 0)
108
+ header.push(s);
109
+ else
110
+ trailer.splice(trailer.length, 0, s);
111
+ }
112
+ }
113
+ if (group !== undefined || tx !== undefined || trailer.at(-1)?.id !== "IEA")
114
+ return err(failure("unexpected-end"));
115
+ return ok({ kind: "interchange", syntax: ref("syntax", X12_SYNTAX), control: valueAt(isa, 13), groups, envelope: { header, trailer } });
116
+ },
117
+ serialize: (i) => {
118
+ const out = [];
119
+ const line = (s) => `${[s.id, ...s.elements.map((e) => e.value)].join("*")}~`;
120
+ const put = (env, side) => void out.push(...(env?.[side] ?? []).map(line));
121
+ if (i.envelope === undefined || i.envelope.header[0]?.id !== "ISA")
122
+ return err(failure("bad-envelope"));
123
+ put(i.envelope, "header");
124
+ for (const g of i.groups) {
125
+ put(g.envelope, "header");
126
+ for (const t of g.transactions) {
127
+ put(t.envelope, "header");
128
+ for (const p of t.children) {
129
+ if (p.kind !== "segment")
130
+ return err(failure("bad-structure"));
131
+ out.push(line(p));
132
+ }
133
+ put(t.envelope, "trailer");
134
+ }
135
+ put(g.envelope, "trailer");
136
+ }
137
+ put(i.envelope, "trailer");
138
+ return ok(`${out.join("\n")}\n`);
139
+ },
140
+ };
141
+ /** The findings of the control counts of an interchange: IEA against the groups and the ISA, GE against its transactions and the GS, SE against its segments and the ST. Paths and codes only. */
142
+ export function envelopeFindings(i) {
143
+ const out = [];
144
+ const bad = (path) => void out.push(finding("syntax", "error", "syntax-error", path, "control count or number does not agree"));
145
+ const iea = i.envelope?.trailer.find((s) => s.id === "IEA");
146
+ if (valueAt(iea, 1) !== String(i.groups.length))
147
+ bad("IEA.01");
148
+ if (valueAt(iea, 2) !== valueAt(i.envelope?.header[0], 13))
149
+ bad("IEA.02");
150
+ for (const g of i.groups) {
151
+ const ge = g.envelope?.trailer[0];
152
+ if (valueAt(ge, 1) !== String(g.transactions.length))
153
+ bad("GE.01");
154
+ if (valueAt(ge, 2) !== valueAt(g.envelope?.header[0], 6))
155
+ bad("GE.02");
156
+ for (const t of g.transactions) {
157
+ const se = t.envelope?.trailer[0];
158
+ if (valueAt(se, 1) !== String(t.children.length + 2))
159
+ bad("SE.01");
160
+ if (valueAt(se, 2) !== valueAt(t.envelope?.header[0], 2))
161
+ bad("SE.02");
162
+ }
163
+ }
164
+ return out;
165
+ }
166
+ const STATUS_CODE = { accepted: "A", "accepted-with-errors": "E", rejected: "R" };
167
+ function isaFor(received) {
168
+ const isa = received.envelope?.header[0];
169
+ const v = (n) => valueAt(isa, n);
170
+ // the answer goes back: the receiver's identifier is the sender's, and the other way round
171
+ return seg("ISA", v(1), v(2), v(3), v(4), v(7), v(8), v(5), v(6), v(9), v(10), v(11), v(12), v(13), "0", v(15), v(16));
172
+ }
173
+ function interchangeOf(isa, header, groups, control) {
174
+ return { kind: "interchange", syntax: ref("syntax", X12_SYNTAX), control, groups, envelope: { header: [isa, ...header], trailer: [seg("IEA", String(groups.length), valueAt(isa, 13))] } };
175
+ }
176
+ /** A TA1: the acknowledgement of an interchange envelope: its control number, date and time, the status and a note code (`000` where there is no error, `001` otherwise; the detailed codes are Planned). */
177
+ export function ta1(received, status) {
178
+ const isa = received.envelope?.header[0];
179
+ const note = status === "accepted" ? "000" : "001";
180
+ return interchangeOf(isaFor(received), [seg("TA1", valueAt(isa, 13), valueAt(isa, 9), valueAt(isa, 10), STATUS_CODE[status], note)], [], valueAt(isa, 13));
181
+ }
182
+ /** A 999: the acknowledgement of each group of an interchange, AK1 for the group, AK9 for its status and counts. */
183
+ export function ack999(received, status) {
184
+ const groups = received.groups.map((g, n) => {
185
+ const count = String(g.transactions.length);
186
+ const accepted = status === "rejected" ? "0" : count;
187
+ const children = [seg("AK1", g.id, g.control), seg("AK9", STATUS_CODE[status], count, count, accepted)];
188
+ const tx = { kind: "transaction", id: "999", control: pad(n + 1).padStart(4, "0"), children, envelope: { header: [seg("ST", "999", pad(n + 1).padStart(4, "0"))], trailer: [seg("SE", String(children.length + 2), pad(n + 1).padStart(4, "0"))] } };
189
+ return { kind: "group", id: "FA", control: String(n + 1), transactions: [tx], envelope: { header: [seg("GS", "FA", "SENDER", "RECEIVER", "20260101", "1200", String(n + 1), "X", "005010X231A1")], trailer: [seg("GE", "1", String(n + 1))] } };
190
+ });
191
+ return interchangeOf(isaFor(received), [], groups, valueAt(received.envelope?.header[0], 13));
192
+ }
193
+ const statusOfCode = (c) => (c === "A" ? "accepted" : c === "E" ? "accepted-with-errors" : "rejected");
194
+ /** The acknowledgement port of X12: a 999 where the interchange has groups, a TA1 where it has none; TA1 and 999 read back. */
195
+ export const acks = {
196
+ acknowledge: (received, status) => ok(received.groups.length > 0 ? ack999(received, status) : ta1(received, status)),
197
+ read: (i) => {
198
+ const out = [];
199
+ const t = i.envelope?.header.find((s) => s.id === "TA1");
200
+ if (t !== undefined)
201
+ out.push({ kind: "x12-ta1", control: valueAt(t, 1), status: statusOfCode(valueAt(t, 4)), note: valueAt(t, 5) });
202
+ for (const g of i.groups) {
203
+ for (const tx of g.transactions) {
204
+ if (tx.id !== "999")
205
+ continue;
206
+ const ak1 = tx.children.find((c) => c.kind === "segment" && c.id === "AK1");
207
+ const ak9 = tx.children.find((c) => c.kind === "segment" && c.id === "AK9");
208
+ if (ak1?.kind !== "segment" || ak9?.kind !== "segment")
209
+ return err(failure("bad-structure"));
210
+ out.push({ kind: "x12-999", control: tx.control, groupControl: valueAt(ak1, 2), status: statusOfCode(valueAt(ak9, 1)), errors: Math.max(0, Number(valueAt(ak9, 2)) - Number(valueAt(ak9, 4))) });
211
+ }
212
+ }
213
+ return out.length === 0 ? err(failure("bad-structure")) : ok(out);
214
+ },
215
+ };
216
+ function loadSchema(standard, set, text) {
217
+ const bad = (code) => err({ kind: "malformed", standard, code });
218
+ let j;
219
+ try {
220
+ j = JSON.parse(text);
221
+ }
222
+ catch {
223
+ return bad("not-json");
224
+ }
225
+ const list = member(j, "segments");
226
+ if (textOf(j, "transaction") !== set)
227
+ return bad("wrong-resource");
228
+ if (!Array.isArray(list) || list.length === 0)
229
+ return bad("no-elements");
230
+ const paths = [set];
231
+ const constraints = [];
232
+ for (const s of list) {
233
+ const id = textOf(s, "id");
234
+ const min = member(s, "min");
235
+ const max = member(s, "max");
236
+ if (id === undefined || typeof min !== "number")
237
+ return bad("no-elements");
238
+ paths.push(`${set}.${id}`);
239
+ constraints.push({ kind: "cardinality", path: `${set}.${id}`, min, max: max === ">1" || max === "*" ? "*" : typeof max === "number" ? max : 1 });
240
+ }
241
+ return ok({ schemas: [{ id: ref("schema", standard), transaction: set, paths, constraints }], profiles: [], terminologies: [] });
242
+ }
243
+ /** The loaders of the transaction sets: each reads the user's own transcription of the segments of a set from a licensed guide (`{transaction, segments: [{id, min, max}]}`); nothing of a guide is in the package. */
244
+ export const loaders = TRANSACTION_SETS.map((set) => ({ standard: setUrn(set), load: (s) => loadSchema(s.standard, set, s.text) }));
245
+ /** The plugin of X12. */
246
+ export const x12Plugin = { id: "x12", standards: STANDARDS, codec, loaders, acks };
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "@intellectual-frontiers/integrations-x12",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "The X12 envelope and acknowledgement skeleton of Integrations: the entries of X12 and of the HIPAA 5010 and purchasing transaction sets with their licence as data, a codec for the fixed-width ISA envelope and its ISA, GS and ST levels, control counts checked as findings, TA1 and 999 made and read, and a loader of a schema from the user's own transcription of a licensed guide. It embeds no standard.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "engines": {
8
+ "node": ">=26"
9
+ },
10
+ "sideEffects": false,
11
+ "types": "./dist/mod.d.ts",
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/mod.d.ts",
15
+ "bun": "./src/mod.ts",
16
+ "default": "./dist/mod.js"
17
+ }
18
+ },
19
+ "dependencies": {
20
+ "@intellectual-frontiers/core": "0.1.4",
21
+ "@intellectual-frontiers/integrations": "0.1.1"
22
+ },
23
+ "files": [
24
+ "dist",
25
+ "src",
26
+ "README.md",
27
+ "LICENSE"
28
+ ],
29
+ "repository": {
30
+ "type": "git",
31
+ "url": "git+https://github.com/intellectual-frontiers/.github.git",
32
+ "directory": "commons/integrations-x12"
33
+ },
34
+ "homepage": "https://github.com/intellectual-frontiers/.github/tree/main/commons/integrations-x12",
35
+ "bugs": {
36
+ "url": "https://github.com/intellectual-frontiers/.github/issues"
37
+ },
38
+ "publishConfig": {
39
+ "access": "public"
40
+ }
41
+ }
package/src/mod.ts ADDED
@@ -0,0 +1,261 @@
1
+ // Spec: 0001-integrations-x12-skeleton FR-001, FR-002, FR-003, FR-004, FR-005, FR-006
2
+ /**
3
+ * The X12 envelope and acknowledgement skeleton of Integrations (commons integrations-x12 0001-integrations-x12-skeleton): the entries of X12 and of the HIPAA 5010 and
4
+ * purchasing transaction sets with their licence as data, a codec for the fixed-width ISA envelope and the ISA, GS and ST levels, the control counts checked as findings, TA1
5
+ * and 999 made and read, and a loader of a schema from the user's own transcription of a licensed guide. It embeds no transaction set, guide or companion guide of X12.
6
+ *
7
+ * @remarks
8
+ * The skeleton supports the delimiters `*` between elements and `~` ending a segment, which the fixed width of the ISA fixes by position; any other is a syntax failure with the offset of the
9
+ * delimiter. Elements are not split into components. A transaction's children are its segments between ST and SE, flat: loops (the HL loops of the 837) are the schema's, Planned.
10
+ *
11
+ * @module
12
+ */
13
+ import { err, ok, type Result } from "@intellectual-frontiers/core";
14
+ import { parseStandardUrn, ref, type EmbeddedContent, type Standard, type StandardUrn } from "@intellectual-frontiers/integrations/governance";
15
+ import {
16
+ element,
17
+ finding,
18
+ segment,
19
+ textOf,
20
+ member,
21
+ type AckPort,
22
+ type Acknowledgement,
23
+ type AckStatus,
24
+ type Codec,
25
+ type Constraint,
26
+ type Envelope,
27
+ type Finding,
28
+ type Group,
29
+ type Interchange,
30
+ type Json,
31
+ type Loader,
32
+ type Part,
33
+ type Schema,
34
+ type Segment,
35
+ type StandardsPlugin,
36
+ type SyntaxProblem,
37
+ type Transaction,
38
+ } from "@intellectual-frontiers/integrations/logical";
39
+
40
+ function urn(text: string): StandardUrn {
41
+ const r = parseStandardUrn(text);
42
+ if (r.kind === "err") throw new Error(`a constant of the plugin is not a standard urn: ${text}`);
43
+ return r.value;
44
+ }
45
+
46
+ /** The X12 syntax, version 005010. */
47
+ export const X12_SYNTAX = urn("urn:standard:x12:edi:005010");
48
+
49
+ /** The transaction sets of the plugin: the HIPAA 5010 set and the purchasing documents. */
50
+ export const TRANSACTION_SETS = ["837", "835", "270", "271", "834", "850", "810", "856"] as const;
51
+ /** A transaction set the plugin lists. */
52
+ export type TransactionSet = (typeof TRANSACTION_SETS)[number];
53
+
54
+ /** The urn of a transaction set's schema. */
55
+ export const setUrn = (set: TransactionSet): StandardUrn => urn(`urn:standard:x12:${set}:005010`);
56
+
57
+ const TERMS = "X12 sells its transaction set standards, implementation guides and companion guides (https://x12.org). They are licensed to their buyer, so this library never embeds them: a schema is read from the user's own copy.";
58
+ const base = { issuer: "x12", version: "005010", location: "https://x12.org/", license: { spdx: "LicenseRef-X12-licensed", embedding: "user-supplied", terms: TERMS }, sha256: undefined } as const;
59
+
60
+ /** The standards the plugin registers. */
61
+ export const STANDARDS: readonly Standard[] = [
62
+ { ...base, urn: X12_SYNTAX, level: "syntax", family: "message", title: "X12 interchange syntax", basis: { kind: "unaligned", reason: "the standard itself" } },
63
+ ...TRANSACTION_SETS.map((s): Standard => ({ ...base, urn: setUrn(s), level: "schema", family: "message", title: `X12 ${s} transaction set`, basis: { kind: "unaligned", reason: "the standard itself" } })),
64
+ ];
65
+
66
+ /** The files of standards content the package embeds: none. */
67
+ export const EMBEDDED: readonly EmbeddedContent[] = [];
68
+
69
+ const failure = (code: SyntaxProblem["code"], offset = 0): SyntaxProblem => ({ kind: "syntax", code, offset });
70
+
71
+ /** The widths of the sixteen elements of the ISA. */
72
+ const ISA_WIDTHS = [2, 10, 2, 10, 2, 15, 2, 15, 6, 4, 1, 5, 9, 1, 1, 1] as const;
73
+
74
+ const pad = (n: number): string => String(n).padStart(2, "0");
75
+ const seg = (id: string, ...values: readonly string[]): Segment => segment(id, ...values.map((v, i) => element(pad(i + 1), v)));
76
+ const valueAt = (s: Segment | undefined, n: number): string => s?.elements[n - 1]?.value ?? "";
77
+
78
+ function parseSegments(text: string): readonly Segment[] {
79
+ return text.split("~").map((s) => s.trim()).filter((s) => s !== "").map((s) => {
80
+ const [id = "", ...values] = s.split("*");
81
+ return seg(id, ...values);
82
+ });
83
+ }
84
+
85
+ /** The X12 codec. */
86
+ export const codec: Codec = {
87
+ syntax: ref("syntax", X12_SYNTAX),
88
+ parse: (text) => {
89
+ if (text.trim() === "") return err(failure("empty"));
90
+ if (text.length < 106 || !text.startsWith("ISA")) return err(failure("bad-envelope"));
91
+ if (text[3] !== "*") return err(failure("bad-delimiter", 3));
92
+ if (text[105] !== "~") return err(failure("bad-delimiter", 105));
93
+ const segs = parseSegments(text);
94
+ const isa = segs[0];
95
+ if (isa === undefined || isa.id !== "ISA" || isa.elements.length !== 16) return err(failure("bad-envelope"));
96
+ for (const [i, w] of ISA_WIDTHS.entries()) if ((isa.elements[i]?.value.length ?? -1) !== w) return err(failure("bad-envelope", i + 1));
97
+ const header: Segment[] = [isa];
98
+ const trailer: Segment[] = [];
99
+ const groups: Group[] = [];
100
+ let group: { id: string; control: string; header: Segment[]; transactions: Transaction[] } | undefined;
101
+ let tx: { id: string; control: string; header: Segment[]; children: Segment[] } | undefined;
102
+ for (const s of segs.slice(1)) {
103
+ switch (s.id) {
104
+ case "GS":
105
+ if (group !== undefined || tx !== undefined) return err(failure("unbalanced"));
106
+ group = { id: valueAt(s, 1), control: valueAt(s, 6), header: [s], transactions: [] };
107
+ break;
108
+ case "ST":
109
+ if (group === undefined || tx !== undefined) return err(failure("unbalanced"));
110
+ tx = { id: valueAt(s, 1), control: valueAt(s, 2), header: [s], children: [] };
111
+ break;
112
+ case "SE":
113
+ if (group === undefined || tx === undefined) return err(failure("unbalanced"));
114
+ group.transactions.push({ kind: "transaction", id: tx.id, control: tx.control, children: tx.children, envelope: { header: tx.header, trailer: [s] } });
115
+ tx = undefined;
116
+ break;
117
+ case "GE":
118
+ if (group === undefined || tx !== undefined) return err(failure("unbalanced"));
119
+ groups.push({ kind: "group", id: group.id, control: group.control, transactions: group.transactions, envelope: { header: group.header, trailer: [s] } });
120
+ group = undefined;
121
+ break;
122
+ case "IEA":
123
+ if (group !== undefined || tx !== undefined) return err(failure("unbalanced"));
124
+ trailer.push(s);
125
+ break;
126
+ default:
127
+ if (tx !== undefined) tx.children.push(s);
128
+ else if (group !== undefined) return err(failure("bad-structure"));
129
+ else if (groups.length === 0 && trailer.length === 0) header.push(s);
130
+ else trailer.splice(trailer.length, 0, s);
131
+ }
132
+ }
133
+ if (group !== undefined || tx !== undefined || trailer.at(-1)?.id !== "IEA") return err(failure("unexpected-end"));
134
+ return ok({ kind: "interchange", syntax: ref("syntax", X12_SYNTAX), control: valueAt(isa, 13), groups, envelope: { header, trailer } });
135
+ },
136
+ serialize: (i) => {
137
+ const out: string[] = [];
138
+ const line = (s: Segment): string => `${[s.id, ...s.elements.map((e) => e.value)].join("*")}~`;
139
+ const put = (env: Envelope | undefined, side: "header" | "trailer"): void => void out.push(...(env?.[side] ?? []).map(line));
140
+ if (i.envelope === undefined || i.envelope.header[0]?.id !== "ISA") return err(failure("bad-envelope"));
141
+ put(i.envelope, "header");
142
+ for (const g of i.groups) {
143
+ put(g.envelope, "header");
144
+ for (const t of g.transactions) {
145
+ put(t.envelope, "header");
146
+ for (const p of t.children) {
147
+ if (p.kind !== "segment") return err(failure("bad-structure"));
148
+ out.push(line(p));
149
+ }
150
+ put(t.envelope, "trailer");
151
+ }
152
+ put(g.envelope, "trailer");
153
+ }
154
+ put(i.envelope, "trailer");
155
+ return ok(`${out.join("\n")}\n`);
156
+ },
157
+ };
158
+
159
+ /** The findings of the control counts of an interchange: IEA against the groups and the ISA, GE against its transactions and the GS, SE against its segments and the ST. Paths and codes only. */
160
+ export function envelopeFindings(i: Interchange): readonly Finding[] {
161
+ const out: Finding[] = [];
162
+ const bad = (path: string): void => void out.push(finding("syntax", "error", "syntax-error", path, "control count or number does not agree"));
163
+ const iea = i.envelope?.trailer.find((s) => s.id === "IEA");
164
+ if (valueAt(iea, 1) !== String(i.groups.length)) bad("IEA.01");
165
+ if (valueAt(iea, 2) !== valueAt(i.envelope?.header[0], 13)) bad("IEA.02");
166
+ for (const g of i.groups) {
167
+ const ge = g.envelope?.trailer[0];
168
+ if (valueAt(ge, 1) !== String(g.transactions.length)) bad("GE.01");
169
+ if (valueAt(ge, 2) !== valueAt(g.envelope?.header[0], 6)) bad("GE.02");
170
+ for (const t of g.transactions) {
171
+ const se = t.envelope?.trailer[0];
172
+ if (valueAt(se, 1) !== String(t.children.length + 2)) bad("SE.01");
173
+ if (valueAt(se, 2) !== valueAt(t.envelope?.header[0], 2)) bad("SE.02");
174
+ }
175
+ }
176
+ return out;
177
+ }
178
+
179
+ const STATUS_CODE = { accepted: "A", "accepted-with-errors": "E", rejected: "R" } as const;
180
+
181
+ function isaFor(received: Interchange): Segment {
182
+ const isa = received.envelope?.header[0];
183
+ const v = (n: number): string => valueAt(isa, n);
184
+ // the answer goes back: the receiver's identifier is the sender's, and the other way round
185
+ return seg("ISA", v(1), v(2), v(3), v(4), v(7), v(8), v(5), v(6), v(9), v(10), v(11), v(12), v(13), "0", v(15), v(16));
186
+ }
187
+
188
+ function interchangeOf(isa: Segment, header: readonly Segment[], groups: readonly Group[], control: string): Interchange {
189
+ return { kind: "interchange", syntax: ref("syntax", X12_SYNTAX), control, groups, envelope: { header: [isa, ...header], trailer: [seg("IEA", String(groups.length), valueAt(isa, 13))] } };
190
+ }
191
+
192
+ /** A TA1: the acknowledgement of an interchange envelope: its control number, date and time, the status and a note code (`000` where there is no error, `001` otherwise; the detailed codes are Planned). */
193
+ export function ta1(received: Interchange, status: AckStatus): Interchange {
194
+ const isa = received.envelope?.header[0];
195
+ const note = status === "accepted" ? "000" : "001";
196
+ return interchangeOf(isaFor(received), [seg("TA1", valueAt(isa, 13), valueAt(isa, 9), valueAt(isa, 10), STATUS_CODE[status], note)], [], valueAt(isa, 13));
197
+ }
198
+
199
+ /** A 999: the acknowledgement of each group of an interchange, AK1 for the group, AK9 for its status and counts. */
200
+ export function ack999(received: Interchange, status: AckStatus): Interchange {
201
+ const groups = received.groups.map((g, n): Group => {
202
+ const count = String(g.transactions.length);
203
+ const accepted = status === "rejected" ? "0" : count;
204
+ const children: Part[] = [seg("AK1", g.id, g.control), seg("AK9", STATUS_CODE[status], count, count, accepted)];
205
+ const tx: Transaction = { kind: "transaction", id: "999", control: pad(n + 1).padStart(4, "0"), children, envelope: { header: [seg("ST", "999", pad(n + 1).padStart(4, "0"))], trailer: [seg("SE", String(children.length + 2), pad(n + 1).padStart(4, "0"))] } };
206
+ return { kind: "group", id: "FA", control: String(n + 1), transactions: [tx], envelope: { header: [seg("GS", "FA", "SENDER", "RECEIVER", "20260101", "1200", String(n + 1), "X", "005010X231A1")], trailer: [seg("GE", "1", String(n + 1))] } };
207
+ });
208
+ return interchangeOf(isaFor(received), [], groups, valueAt(received.envelope?.header[0], 13));
209
+ }
210
+
211
+ const statusOfCode = (c: string): AckStatus => (c === "A" ? "accepted" : c === "E" ? "accepted-with-errors" : "rejected");
212
+
213
+ /** The acknowledgement port of X12: a 999 where the interchange has groups, a TA1 where it has none; TA1 and 999 read back. */
214
+ export const acks: AckPort = {
215
+ acknowledge: (received, status) => ok(received.groups.length > 0 ? ack999(received, status) : ta1(received, status)),
216
+ read: (i) => {
217
+ const out: Acknowledgement[] = [];
218
+ const t = i.envelope?.header.find((s) => s.id === "TA1");
219
+ if (t !== undefined) out.push({ kind: "x12-ta1", control: valueAt(t, 1), status: statusOfCode(valueAt(t, 4)), note: valueAt(t, 5) });
220
+ for (const g of i.groups) {
221
+ for (const tx of g.transactions) {
222
+ if (tx.id !== "999") continue;
223
+ const ak1 = tx.children.find((c) => c.kind === "segment" && c.id === "AK1");
224
+ const ak9 = tx.children.find((c) => c.kind === "segment" && c.id === "AK9");
225
+ if (ak1?.kind !== "segment" || ak9?.kind !== "segment") return err(failure("bad-structure"));
226
+ out.push({ kind: "x12-999", control: tx.control, groupControl: valueAt(ak1, 2), status: statusOfCode(valueAt(ak9, 1)), errors: Math.max(0, Number(valueAt(ak9, 2)) - Number(valueAt(ak9, 4))) });
227
+ }
228
+ }
229
+ return out.length === 0 ? err(failure("bad-structure")) : ok(out);
230
+ },
231
+ };
232
+
233
+ function loadSchema(standard: StandardUrn, set: TransactionSet, text: string): Result<{ readonly schemas: readonly Schema[]; readonly profiles: readonly []; readonly terminologies: readonly [] }, { readonly kind: "malformed"; readonly standard: StandardUrn; readonly code: "not-json" | "wrong-resource" | "no-elements" }> {
234
+ const bad = (code: "not-json" | "wrong-resource" | "no-elements") => err({ kind: "malformed" as const, standard, code });
235
+ let j: Json;
236
+ try {
237
+ j = JSON.parse(text) as Json;
238
+ } catch {
239
+ return bad("not-json");
240
+ }
241
+ const list = member(j, "segments");
242
+ if (textOf(j, "transaction") !== set) return bad("wrong-resource");
243
+ if (!Array.isArray(list) || list.length === 0) return bad("no-elements");
244
+ const paths: string[] = [set];
245
+ const constraints: Constraint[] = [];
246
+ for (const s of list) {
247
+ const id = textOf(s, "id");
248
+ const min = member(s, "min");
249
+ const max = member(s, "max");
250
+ if (id === undefined || typeof min !== "number") return bad("no-elements");
251
+ paths.push(`${set}.${id}`);
252
+ constraints.push({ kind: "cardinality", path: `${set}.${id}`, min, max: max === ">1" || max === "*" ? "*" : typeof max === "number" ? max : 1 });
253
+ }
254
+ return ok({ schemas: [{ id: ref("schema", standard), transaction: set, paths, constraints }], profiles: [], terminologies: [] });
255
+ }
256
+
257
+ /** The loaders of the transaction sets: each reads the user's own transcription of the segments of a set from a licensed guide (`{transaction, segments: [{id, min, max}]}`); nothing of a guide is in the package. */
258
+ export const loaders: readonly Loader[] = TRANSACTION_SETS.map((set): Loader => ({ standard: setUrn(set), load: (s) => loadSchema(s.standard, set, s.text) }));
259
+
260
+ /** The plugin of X12. */
261
+ export const x12Plugin: StandardsPlugin = { id: "x12", standards: STANDARDS, codec, loaders, acks };