@cosyte/x12 0.0.3 → 0.0.4

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/index.cjs CHANGED
@@ -105,7 +105,10 @@ function detectDelimiters(raw) {
105
105
  if (raw.charAt(pos) !== element) {
106
106
  throw new X12ParseError(
107
107
  FATAL_CODES.X12_INVALID_DELIMITERS,
108
- `Element separator "${element}" was detected at ISA byte 4 but is missing at fixed ISA byte ${String(pos + 1)} - ISA element layout is not 005010-conformant.`,
108
+ // The detected separator is a single byte read out of the input, so
109
+ // it is not echoed: the diagnostic is which fixed ISA position broke,
110
+ // and the byte itself is at `raw[3]` for anyone who needs it.
111
+ `The element separator detected at ISA byte 4 is missing at fixed ISA byte ${String(pos + 1)} - ISA element layout is not 005010-conformant.`,
109
112
  fatalPosition,
110
113
  snip
111
114
  );
@@ -139,182 +142,256 @@ var WARNING_CODES = {
139
142
  X12_UNKNOWN_CLAIM_STATUS: "X12_UNKNOWN_CLAIM_STATUS",
140
143
  X12_834_UNKNOWN_MAINTENANCE_TYPE: "X12_834_UNKNOWN_MAINTENANCE_TYPE"
141
144
  };
142
- function controlNumberMismatch(position, pair, header, trailer) {
145
+ var CONTROL_NUMBER_PAIRS = {
146
+ /** ISA-13 against IEA-02. */
147
+ INTERCHANGE: "interchange",
148
+ /** GS-06 against GE-02. */
149
+ GROUP: "group",
150
+ /** ST-02 against SE-02. */
151
+ TRANSACTION: "transaction"
152
+ };
153
+ var UNEXPECTED_SEGMENT_CONTEXTS = {
154
+ /** A `TA1` (envelope-level by spec) appeared inside an open functional group. */
155
+ TA1_INSIDE_GROUP: "ta1-inside-group",
156
+ /** A `GE` appeared with no open `GS`. */
157
+ GE_WITHOUT_GS: "ge-without-gs",
158
+ /** An `ST` appeared with no open functional group. */
159
+ ST_WITHOUT_GS: "st-without-gs",
160
+ /** An `SE` appeared with no open transaction set. */
161
+ SE_WITHOUT_ST: "se-without-st",
162
+ /** A body segment appeared outside any open transaction set. */
163
+ BODY_OUTSIDE_TRANSACTION: "body-outside-transaction"
164
+ };
165
+ var BALANCE_INVARIANTS = {
166
+ /** `CLP-04 + Σ(claim CAS + line CAS) == CLP-03`. */
167
+ CLAIM: "claim",
168
+ /** `SVC-03 + Σ(line CAS) == SVC-02`. */
169
+ SERVICE_LINE: "service-line",
170
+ /** `Σ(CLP-04) - Σ(PLB amounts) == BPR-02`. */
171
+ REMIT_TOTAL: "remit-total"
172
+ };
173
+ var REQUIRED_LOOPS = {
174
+ /** Loop 2000A, Billing Provider HL. */
175
+ BILLING_PROVIDER_2000A: "2000A",
176
+ /** Loop 2000B, Subscriber HL. */
177
+ SUBSCRIBER_2000B: "2000B",
178
+ /** Loop 2010BA, Subscriber Name. */
179
+ SUBSCRIBER_NAME_2010BA: "2010BA",
180
+ /** Loop 2010BB, Payer Name. */
181
+ PAYER_NAME_2010BB: "2010BB"
182
+ };
183
+ var WARNING_MESSAGES = {
184
+ X12_CONTROL_NUMBER_MISMATCH_INTERCHANGE: "Control number mismatch: ISA-13 (header) and IEA-02 (trailer) disagree. Both values are preserved verbatim on the model; neither is echoed here.",
185
+ X12_CONTROL_NUMBER_MISMATCH_GROUP: "Control number mismatch: GS-06 (header) and GE-02 (trailer) disagree. Both values are preserved verbatim on the model; neither is echoed here.",
186
+ X12_CONTROL_NUMBER_MISMATCH_TRANSACTION: "Control number mismatch: ST-02 (header) and SE-02 (trailer) disagree. Both values are preserved verbatim on the model; neither is echoed here.",
187
+ X12_PRE_005010: 'ISA-12 declares a version other than the HIPAA baseline "00501", so the input may diverge from 005010 semantics. The declared version is preserved verbatim on the model.',
188
+ X12_GROUP_COUNT_MISMATCH: "IEA-01 does not equal the number of GS..GE groups actually present in the interchange. The declared count is preserved verbatim on the model and is NEVER silently corrected.",
189
+ X12_TRANSACTION_COUNT_MISMATCH: "GE-01 does not equal the number of ST..SE transaction sets actually present in the group. The declared count is preserved verbatim on the model and is NEVER silently corrected.",
190
+ X12_SEGMENT_COUNT_MISMATCH: "SE-01 does not equal the number of segments actually present in the transaction set it closes. The declared count is preserved verbatim and is corrected only on `serializeX12(ix, { specClean: true, recomputeCounts: true })`.",
191
+ X12_TRAILING_GARBAGE: "Bytes followed the IEA segment terminator, preserved verbatim on `trailingBytes`. Common cause: a second interchange concatenated into the same file (multi-ISA, out of v1 scope).",
192
+ X12_MISSING_IEA: "Interchange has no IEA trailer - input is truncated.",
193
+ X12_MISSING_GE: "Functional group has no GE trailer - group is truncated.",
194
+ X12_MISSING_SE: "Transaction set has no SE trailer - transaction is truncated.",
195
+ X12_DANGLING_RELEASE_CHAR: "Release character (`?`) appears at end of element/segment with no following byte to escape - preserved verbatim.",
196
+ X12_UNEXPECTED_SEGMENT_TA1_INSIDE_GROUP: "Unexpected segment: TA1 is envelope-level but appeared inside an open functional group, so it is NOT captured on `ta1Segments` and `parseTA1` will not read it. It is retained verbatim on `orphanSegments` at the matching `position.segmentIndex`.",
197
+ X12_UNEXPECTED_SEGMENT_GE_WITHOUT_GS: "Unexpected segment: a GE appeared with no open functional group, so it closes nothing and no group is recorded for it. It is retained verbatim on `orphanSegments` at the matching `position.segmentIndex`.",
198
+ X12_UNEXPECTED_SEGMENT_ST_WITHOUT_GS: "Unexpected segment: an ST appeared with no open functional group (missing GS), so no transaction set is opened and nothing that follows it is bound to one. It is retained verbatim on `orphanSegments` at the matching `position.segmentIndex`.",
199
+ X12_UNEXPECTED_SEGMENT_SE_WITHOUT_ST: "Unexpected segment: an SE appeared with no open transaction set, so it closes nothing and no transaction is recorded for it. It is retained verbatim on `orphanSegments` at the matching `position.segmentIndex`.",
200
+ X12_UNEXPECTED_SEGMENT_BODY_OUTSIDE_TRANSACTION: "Unexpected segment: a body segment appeared outside any open transaction set, so it is not bound to a transaction and no `get*` reader will see it. It is retained verbatim on `orphanSegments` at the matching `position.segmentIndex`.",
201
+ X12_835_REMIT_BALANCE_MISMATCH_CLAIM: "835 balance invariant violated [CLP-04 + \u03A3(claim CAS + line CAS) == CLP-03]: the claim does not balance. Every amount is preserved verbatim on the model as an X12Decimal and is NEVER silently rebalanced.",
202
+ X12_835_REMIT_BALANCE_MISMATCH_SERVICE_LINE: "835 balance invariant violated [SVC-03 + \u03A3(line CAS) == SVC-02]: the service line does not balance. Every amount is preserved verbatim on the model as an X12Decimal and is NEVER silently rebalanced.",
203
+ X12_835_REMIT_BALANCE_MISMATCH_REMIT_TOTAL: "835 balance invariant violated [\u03A3(CLP-04) - \u03A3(PLB amounts) == BPR-02]: the remittance total does not balance. Every amount is preserved verbatim on the model as an X12Decimal and is NEVER silently rebalanced.",
204
+ X12_UNKNOWN_CARC: "Unknown CARC: the claim adjustment reason code is outside the bundled snapshot. The verbatim code is preserved on the adjustment; only its description is unavailable.",
205
+ X12_UNKNOWN_RARC: "Unknown RARC: the remittance advice remark code is outside the bundled snapshot. The verbatim code is preserved on the remark; only its description is unavailable.",
206
+ X12_HL_PARENT_MISMATCH: "HL-02 declares a parent id that no earlier HL in this transaction set emitted as its HL-01. The declared pointer is preserved verbatim and the hierarchy is NEVER silently re-numbered.",
207
+ X12_HL_PARENT_LEVEL_INVALID: "HL-03 is inconsistent with the declared parent's HL-03 per the TR3 hierarchy. Both level codes are preserved verbatim and the hierarchy is NEVER silently re-parented.",
208
+ X12_UNKNOWN_HI_QUALIFIER: 'Unknown HI qualifier: the composite qualifier is outside the bundled HI_QUALIFIERS snapshot. The verbatim qualifier and code are preserved; codeSystem resolves to "unknown".',
209
+ X12_MISSING_REQUIRED_LOOP_2000A: 'Missing required loop "2000A" (Billing Provider HL): no Billing Provider HL precedes the CLM.',
210
+ X12_MISSING_REQUIRED_LOOP_2000B: 'Missing required loop "2000B" (Subscriber HL): no Subscriber HL precedes the CLM.',
211
+ X12_MISSING_REQUIRED_LOOP_2010BA: 'Missing required loop "2010BA" (Subscriber Name): no Subscriber Name follows the Subscriber HL.',
212
+ X12_MISSING_REQUIRED_LOOP_2010BB: 'Missing required loop "2010BB" (Payer Name): no Payer Name follows the Subscriber HL.',
213
+ X12_837_UNKNOWN_VARIANT: `837 variant could not be resolved: ST-03's implementation convention reference is not one of "005010X222A2" / "005010X223A3" / "005010X224A2", and no SVx service-line segment was present to fall back on. The verbatim reference is preserved on the model.`,
214
+ X12_UNKNOWN_CLAIM_STATUS_CATEGORY: "Unknown claim status category (CSCC): the STC composite's first component is outside the bundled snapshot. The verbatim code is preserved on the status; only its description is unavailable.",
215
+ X12_UNKNOWN_CLAIM_STATUS: "Unknown claim status code (CSC): the STC composite's second component is outside the bundled snapshot. The verbatim code is preserved on the status; only its description is unavailable.",
216
+ X12_834_UNKNOWN_MAINTENANCE_TYPE: "Unknown 834 maintenance type: the INS-03/HD-01 code is outside the bundled snapshot. The verbatim code is preserved on the enrollment and the action is NEVER inferred."
217
+ };
218
+ var ALL_WARNING_MESSAGES = new Set(
219
+ Object.values(WARNING_MESSAGES)
220
+ );
221
+ var UNEXPECTED_SEGMENT_MESSAGES = {
222
+ [UNEXPECTED_SEGMENT_CONTEXTS.TA1_INSIDE_GROUP]: WARNING_MESSAGES.X12_UNEXPECTED_SEGMENT_TA1_INSIDE_GROUP,
223
+ [UNEXPECTED_SEGMENT_CONTEXTS.GE_WITHOUT_GS]: WARNING_MESSAGES.X12_UNEXPECTED_SEGMENT_GE_WITHOUT_GS,
224
+ [UNEXPECTED_SEGMENT_CONTEXTS.ST_WITHOUT_GS]: WARNING_MESSAGES.X12_UNEXPECTED_SEGMENT_ST_WITHOUT_GS,
225
+ [UNEXPECTED_SEGMENT_CONTEXTS.SE_WITHOUT_ST]: WARNING_MESSAGES.X12_UNEXPECTED_SEGMENT_SE_WITHOUT_ST,
226
+ [UNEXPECTED_SEGMENT_CONTEXTS.BODY_OUTSIDE_TRANSACTION]: WARNING_MESSAGES.X12_UNEXPECTED_SEGMENT_BODY_OUTSIDE_TRANSACTION
227
+ };
228
+ var CONTROL_NUMBER_PAIR_MESSAGES = {
229
+ [CONTROL_NUMBER_PAIRS.INTERCHANGE]: WARNING_MESSAGES.X12_CONTROL_NUMBER_MISMATCH_INTERCHANGE,
230
+ [CONTROL_NUMBER_PAIRS.GROUP]: WARNING_MESSAGES.X12_CONTROL_NUMBER_MISMATCH_GROUP,
231
+ [CONTROL_NUMBER_PAIRS.TRANSACTION]: WARNING_MESSAGES.X12_CONTROL_NUMBER_MISMATCH_TRANSACTION
232
+ };
233
+ var BALANCE_INVARIANT_MESSAGES = {
234
+ [BALANCE_INVARIANTS.CLAIM]: WARNING_MESSAGES.X12_835_REMIT_BALANCE_MISMATCH_CLAIM,
235
+ [BALANCE_INVARIANTS.SERVICE_LINE]: WARNING_MESSAGES.X12_835_REMIT_BALANCE_MISMATCH_SERVICE_LINE,
236
+ [BALANCE_INVARIANTS.REMIT_TOTAL]: WARNING_MESSAGES.X12_835_REMIT_BALANCE_MISMATCH_REMIT_TOTAL
237
+ };
238
+ var REQUIRED_LOOP_MESSAGES = {
239
+ [REQUIRED_LOOPS.BILLING_PROVIDER_2000A]: WARNING_MESSAGES.X12_MISSING_REQUIRED_LOOP_2000A,
240
+ [REQUIRED_LOOPS.SUBSCRIBER_2000B]: WARNING_MESSAGES.X12_MISSING_REQUIRED_LOOP_2000B,
241
+ [REQUIRED_LOOPS.SUBSCRIBER_NAME_2010BA]: WARNING_MESSAGES.X12_MISSING_REQUIRED_LOOP_2010BA,
242
+ [REQUIRED_LOOPS.PAYER_NAME_2010BB]: WARNING_MESSAGES.X12_MISSING_REQUIRED_LOOP_2010BB
243
+ };
244
+ function controlNumberMismatch(position, pair) {
143
245
  return {
144
246
  code: WARNING_CODES.X12_CONTROL_NUMBER_MISMATCH,
145
- message: `Control number mismatch (${pair}): header="${header}", trailer="${trailer}".`,
247
+ message: CONTROL_NUMBER_PAIR_MESSAGES[pair],
146
248
  position
147
249
  };
148
250
  }
149
- function pre005010(position, declared) {
251
+ function pre005010(position) {
150
252
  return {
151
253
  code: WARNING_CODES.X12_PRE_005010,
152
- message: `ISA-12 declares version "${declared}", not the HIPAA baseline "00501".`,
254
+ message: WARNING_MESSAGES.X12_PRE_005010,
153
255
  position
154
256
  };
155
257
  }
156
- function groupCountMismatch(position, declared, actual) {
258
+ function groupCountMismatch(position) {
157
259
  return {
158
260
  code: WARNING_CODES.X12_GROUP_COUNT_MISMATCH,
159
- message: `IEA-01 declares ${declared} group(s); ${String(actual)} were present.`,
261
+ message: WARNING_MESSAGES.X12_GROUP_COUNT_MISMATCH,
160
262
  position
161
263
  };
162
264
  }
163
- function transactionCountMismatch(position, declared, actual) {
265
+ function transactionCountMismatch(position) {
164
266
  return {
165
267
  code: WARNING_CODES.X12_TRANSACTION_COUNT_MISMATCH,
166
- message: `GE-01 declares ${declared} transaction(s); ${String(actual)} were present.`,
268
+ message: WARNING_MESSAGES.X12_TRANSACTION_COUNT_MISMATCH,
167
269
  position
168
270
  };
169
271
  }
170
- function segmentCountMismatch(position, declared, actual) {
272
+ function segmentCountMismatch(position) {
171
273
  return {
172
274
  code: WARNING_CODES.X12_SEGMENT_COUNT_MISMATCH,
173
- message: `SE-01 declares ${declared} segment(s); ${String(actual)} were present.`,
275
+ message: WARNING_MESSAGES.X12_SEGMENT_COUNT_MISMATCH,
174
276
  position
175
277
  };
176
278
  }
177
- function trailingGarbage(position, byteCount) {
279
+ function trailingGarbage(position) {
178
280
  return {
179
281
  code: WARNING_CODES.X12_TRAILING_GARBAGE,
180
- message: `${String(byteCount)} byte(s) followed the IEA terminator - preserved verbatim on \`trailingBytes\`.`,
282
+ message: WARNING_MESSAGES.X12_TRAILING_GARBAGE,
181
283
  position
182
284
  };
183
285
  }
184
286
  function missingIea(position) {
185
287
  return {
186
288
  code: WARNING_CODES.X12_MISSING_IEA,
187
- message: "Interchange has no IEA trailer - input is truncated.",
289
+ message: WARNING_MESSAGES.X12_MISSING_IEA,
188
290
  position
189
291
  };
190
292
  }
191
293
  function missingGe(position) {
192
294
  return {
193
295
  code: WARNING_CODES.X12_MISSING_GE,
194
- message: "Functional group has no GE trailer - group is truncated.",
296
+ message: WARNING_MESSAGES.X12_MISSING_GE,
195
297
  position
196
298
  };
197
299
  }
198
300
  function missingSe(position) {
199
301
  return {
200
302
  code: WARNING_CODES.X12_MISSING_SE,
201
- message: "Transaction set has no SE trailer - transaction is truncated.",
303
+ message: WARNING_MESSAGES.X12_MISSING_SE,
202
304
  position
203
305
  };
204
306
  }
205
307
  function danglingReleaseChar(position) {
206
308
  return {
207
309
  code: WARNING_CODES.X12_DANGLING_RELEASE_CHAR,
208
- message: "Release character (`?`) appears at end of element/segment with no following byte to escape - preserved verbatim.",
310
+ message: WARNING_MESSAGES.X12_DANGLING_RELEASE_CHAR,
209
311
  position
210
312
  };
211
313
  }
212
- var SEGMENT_ID_SHAPE_RE = /^[A-Z][A-Z0-9]{1,2}$/u;
213
- function unexpectedSegment(position, segmentId, context) {
214
- const safeId = SEGMENT_ID_SHAPE_RE.test(segmentId) ? segmentId : "(non-spec)";
314
+ function unexpectedSegment(position, context) {
215
315
  return {
216
316
  code: WARNING_CODES.X12_UNEXPECTED_SEGMENT,
217
- message: `Unexpected "${safeId}" segment - ${context}; segment is preserved on the prior open container if any.`,
317
+ message: UNEXPECTED_SEGMENT_MESSAGES[context],
218
318
  position
219
319
  };
220
320
  }
221
- var CODE_LIST_VALUE_SHAPE_RE = /^[A-Z0-9]{1,5}$/u;
222
- function remitBalanceMismatch(position, invariant, spec, computed, delta) {
321
+ function remitBalanceMismatch(position, invariant) {
223
322
  return {
224
323
  code: WARNING_CODES.X12_835_REMIT_BALANCE_MISMATCH,
225
- message: `835 balance invariant violated [${invariant}]: spec="${spec}", computed="${computed}", delta="${delta}".`,
324
+ message: BALANCE_INVARIANT_MESSAGES[invariant],
226
325
  position
227
326
  };
228
327
  }
229
- function unknownCarc(position, code) {
230
- const safe = CODE_LIST_VALUE_SHAPE_RE.test(code) ? code : "(non-spec)";
328
+ function unknownCarc(position) {
231
329
  return {
232
330
  code: WARNING_CODES.X12_UNKNOWN_CARC,
233
- message: `Unknown CARC "${safe}" - code is outside the bundled snapshot; verbatim value preserved, description unavailable.`,
331
+ message: WARNING_MESSAGES.X12_UNKNOWN_CARC,
234
332
  position
235
333
  };
236
334
  }
237
- function unknownRarc(position, code) {
238
- const safe = CODE_LIST_VALUE_SHAPE_RE.test(code) ? code : "(non-spec)";
335
+ function unknownRarc(position) {
239
336
  return {
240
337
  code: WARNING_CODES.X12_UNKNOWN_RARC,
241
- message: `Unknown RARC "${safe}" - code is outside the bundled snapshot; verbatim value preserved, description unavailable.`,
338
+ message: WARNING_MESSAGES.X12_UNKNOWN_RARC,
242
339
  position
243
340
  };
244
341
  }
245
- var HL_ID_SHAPE_RE = /^[0-9]{1,4}$/u;
246
- var HL_LEVEL_CODE_SHAPE_RE = /^[0-9]{2}$/u;
247
- var HI_QUALIFIER_SHAPE_RE = /^[A-Z][A-Z0-9]{1,2}$/u;
248
- function hlParentMismatch(position, hlId, declaredParentId) {
249
- const safeHl = HL_ID_SHAPE_RE.test(hlId) ? hlId : "(non-spec)";
250
- const safeParent = HL_ID_SHAPE_RE.test(declaredParentId) ? declaredParentId : "(non-spec)";
342
+ function hlParentMismatch(position) {
251
343
  return {
252
344
  code: WARNING_CODES.X12_HL_PARENT_MISMATCH,
253
- message: `HL "${safeHl}" declares parent "${safeParent}" but no earlier HL with that id was emitted - parser preserves the declared pointer verbatim and NEVER silently re-numbers.`,
345
+ message: WARNING_MESSAGES.X12_HL_PARENT_MISMATCH,
254
346
  position
255
347
  };
256
348
  }
257
- function hlParentLevelInvalid(position, hlId, hlLevel, parentHlId, parentLevel, expectedParentLevel) {
258
- const safeHl = HL_ID_SHAPE_RE.test(hlId) ? hlId : "(non-spec)";
259
- const safeLevel = HL_LEVEL_CODE_SHAPE_RE.test(hlLevel) ? hlLevel : "(non-spec)";
260
- const safeParent = HL_ID_SHAPE_RE.test(parentHlId) ? parentHlId : "(non-spec)";
261
- const safeParentLevel = HL_LEVEL_CODE_SHAPE_RE.test(parentLevel) ? parentLevel : "(non-spec)";
262
- const safeExpected = HL_LEVEL_CODE_SHAPE_RE.test(expectedParentLevel) ? expectedParentLevel : "(non-spec)";
349
+ function hlParentLevelInvalid(position) {
263
350
  return {
264
351
  code: WARNING_CODES.X12_HL_PARENT_LEVEL_INVALID,
265
- message: `HL "${safeHl}" (level "${safeLevel}") declares parent "${safeParent}" with level "${safeParentLevel}" but TR3 requires parent level "${safeExpected}".`,
352
+ message: WARNING_MESSAGES.X12_HL_PARENT_LEVEL_INVALID,
266
353
  position
267
354
  };
268
355
  }
269
- function unknownHiQualifier(position, qualifier) {
270
- const safe = HI_QUALIFIER_SHAPE_RE.test(qualifier) ? qualifier : "(non-spec)";
356
+ function unknownHiQualifier(position) {
271
357
  return {
272
358
  code: WARNING_CODES.X12_UNKNOWN_HI_QUALIFIER,
273
- message: `Unknown HI qualifier "${safe}" - qualifier is outside the bundled HI_QUALIFIERS snapshot; verbatim qualifier + code preserved, codeSystem resolves to "unknown".`,
359
+ message: WARNING_MESSAGES.X12_UNKNOWN_HI_QUALIFIER,
274
360
  position
275
361
  };
276
362
  }
277
- var LOOP_ID_SHAPE_RE = /^[0-9A-Z]{3,6}$/u;
278
- function missingRequiredLoop(position, loopId, rationale) {
279
- const safe = LOOP_ID_SHAPE_RE.test(loopId) ? loopId : "(non-spec)";
363
+ function missingRequiredLoop(position, loop) {
280
364
  return {
281
365
  code: WARNING_CODES.X12_MISSING_REQUIRED_LOOP,
282
- message: `Missing required loop "${safe}": ${rationale}`,
366
+ message: REQUIRED_LOOP_MESSAGES[loop],
283
367
  position
284
368
  };
285
369
  }
286
- var ICR_SHAPE_RE = /^[0-9A-Z]{3,16}$/u;
287
- function unknown837Variant(position, implementationConventionReference) {
288
- const safe = implementationConventionReference !== void 0 && ICR_SHAPE_RE.test(implementationConventionReference) ? implementationConventionReference : "(non-spec)";
370
+ function unknown837Variant(position) {
289
371
  return {
290
372
  code: WARNING_CODES.X12_837_UNKNOWN_VARIANT,
291
- message: `837 variant could not be resolved - ST-03 implementation convention reference "${safe}" is not one of "005010X222A2" / "X223A3" / "X224A2"; no SVx service-line segment was seen to fall back on.`,
373
+ message: WARNING_MESSAGES.X12_837_UNKNOWN_VARIANT,
292
374
  position
293
375
  };
294
376
  }
295
- var CLAIM_STATUS_CATEGORY_SHAPE_RE = /^[A-Z][0-9A-Z]{1,2}$/u;
296
- function unknownClaimStatusCategory(position, code) {
297
- const safe = CLAIM_STATUS_CATEGORY_SHAPE_RE.test(code) ? code : "(non-spec)";
377
+ function unknownClaimStatusCategory(position) {
298
378
  return {
299
379
  code: WARNING_CODES.X12_UNKNOWN_CLAIM_STATUS_CATEGORY,
300
- message: `Unknown claim status category (CSCC) "${safe}" - code is outside the bundled snapshot; verbatim value preserved, description unavailable.`,
380
+ message: WARNING_MESSAGES.X12_UNKNOWN_CLAIM_STATUS_CATEGORY,
301
381
  position
302
382
  };
303
383
  }
304
- function unknownClaimStatus(position, code) {
305
- const safe = CODE_LIST_VALUE_SHAPE_RE.test(code) ? code : "(non-spec)";
384
+ function unknownClaimStatus(position) {
306
385
  return {
307
386
  code: WARNING_CODES.X12_UNKNOWN_CLAIM_STATUS,
308
- message: `Unknown claim status code (CSC) "${safe}" - code is outside the bundled snapshot; verbatim value preserved, description unavailable.`,
387
+ message: WARNING_MESSAGES.X12_UNKNOWN_CLAIM_STATUS,
309
388
  position
310
389
  };
311
390
  }
312
- var MAINTENANCE_TYPE_SHAPE_RE = /^[0-9]{3}$/u;
313
- function unknownMaintenanceType(position, code) {
314
- const safe = MAINTENANCE_TYPE_SHAPE_RE.test(code) ? code : "(non-spec)";
391
+ function unknownMaintenanceType(position) {
315
392
  return {
316
393
  code: WARNING_CODES.X12_834_UNKNOWN_MAINTENANCE_TYPE,
317
- message: `Unknown 834 maintenance type "${safe}" - INS-03/HD-01 code is outside the bundled snapshot; verbatim value preserved, action NOT inferred.`,
394
+ message: WARNING_MESSAGES.X12_834_UNKNOWN_MAINTENANCE_TYPE,
318
395
  position
319
396
  };
320
397
  }
@@ -675,6 +752,12 @@ function renderCanonical(signum, magnitude, scale) {
675
752
  }
676
753
 
677
754
  // src/parser/segment.ts
755
+ var SEGMENT_ID_SHAPE_RE = /^[A-Z][A-Z0-9]{1,2}$/u;
756
+ var NON_SPEC_SEGMENT_ID = "(non-spec)";
757
+ function boundSegmentId(first) {
758
+ if (first.length === 0) return "";
759
+ return SEGMENT_ID_SHAPE_RE.test(first) ? first : NON_SPEC_SEGMENT_ID;
760
+ }
678
761
  function decodeSegment(raw, delimiters, emit, position) {
679
762
  const elements = Object.freeze(splitWithRelease(raw, delimiters.element));
680
763
  if (raw.length > 0 && raw.endsWith(RELEASE_CHAR)) {
@@ -684,8 +767,7 @@ function decodeSegment(raw, delimiters, emit, position) {
684
767
  emit(danglingReleaseChar({ ...position, elementIndex: elements.length - 1 }));
685
768
  }
686
769
  }
687
- const id = elements[0] ?? "";
688
- return Object.freeze({ id, raw, elements });
770
+ return Object.freeze({ id: boundSegmentId(elements[0] ?? ""), raw, elements });
689
771
  }
690
772
  function parseSegmentPath(path) {
691
773
  if (path.length === 0) {
@@ -849,8 +931,11 @@ function decodeIsa(raw, delimiters) {
849
931
  }
850
932
  function stripLeadingNewlines(text, start) {
851
933
  let i = start;
852
- if (text.charCodeAt(i) === 13) i++;
853
- if (text.charCodeAt(i) === 10) i++;
934
+ while (i < text.length) {
935
+ const code = text.charCodeAt(i);
936
+ if (code !== 13 && code !== 10) break;
937
+ i++;
938
+ }
854
939
  return i;
855
940
  }
856
941
  function findUnescapedTerminator(text, from, term) {
@@ -903,15 +988,45 @@ function decodeEnvelope(raw, delimiters) {
903
988
  const isa = decodeIsa(raw, delimiters);
904
989
  const isa12 = el(isa.elements, 12);
905
990
  if (isa12 !== "00501") {
906
- warnings.push(pre005010({ segmentIndex: 0, interchangeIndex: 0, elementIndex: 12 }, isa12));
991
+ warnings.push(pre005010({ segmentIndex: 0, interchangeIndex: 0, elementIndex: 12 }));
907
992
  }
908
993
  const { segments } = splitSegments(raw, ISA_MIN_LENGTH, delimiters);
909
994
  const groups = [];
910
995
  const ta1Segments = [];
996
+ const orphanSegments = [];
911
997
  let iea;
912
998
  let trailingBytes;
913
999
  let currentGroup;
914
1000
  let currentTx;
1001
+ const currentAnchor = () => {
1002
+ if (currentGroup === void 0) {
1003
+ return { kind: "interchange", groupIndex: groups.length };
1004
+ }
1005
+ if (currentTx === void 0) {
1006
+ return {
1007
+ kind: "group",
1008
+ groupIndex: groups.length,
1009
+ transactionIndex: currentGroup.transactions.length
1010
+ };
1011
+ }
1012
+ return {
1013
+ kind: "transaction",
1014
+ groupIndex: groups.length,
1015
+ transactionIndex: currentGroup.transactions.length,
1016
+ segmentOffset: currentTx.rawSegments.length
1017
+ };
1018
+ };
1019
+ const recordOrphan = (segmentText, position, context) => {
1020
+ const anchor = currentAnchor();
1021
+ warnings.push(unexpectedSegment(position, context));
1022
+ orphanSegments.push({
1023
+ raw: segmentText,
1024
+ segment: decodeSegment(segmentText, delimiters, collectWarning, position),
1025
+ segmentIndex: position.segmentIndex,
1026
+ context,
1027
+ anchor
1028
+ });
1029
+ };
915
1030
  const finalizeTx = (tx, group, se) => {
916
1031
  if (se === void 0) {
917
1032
  warnings.push(
@@ -944,16 +1059,12 @@ function decodeEnvelope(raw, delimiters) {
944
1059
  const actual = group.transactions.length;
945
1060
  if (declared !== String(actual)) {
946
1061
  warnings.push(
947
- transactionCountMismatch(
948
- {
949
- segmentIndex: group.startSegIdx,
950
- interchangeIndex: 0,
951
- groupIndex: groups.length,
952
- elementIndex: 1
953
- },
954
- declared,
955
- actual
956
- )
1062
+ transactionCountMismatch({
1063
+ segmentIndex: group.startSegIdx,
1064
+ interchangeIndex: 0,
1065
+ groupIndex: groups.length,
1066
+ elementIndex: 1
1067
+ })
957
1068
  );
958
1069
  }
959
1070
  const gsControl = el(group.gs.elements, 6);
@@ -967,9 +1078,7 @@ function decodeEnvelope(raw, delimiters) {
967
1078
  groupIndex: groups.length,
968
1079
  elementIndex: 2
969
1080
  },
970
- "GS-06/GE-02",
971
- gsControl,
972
- geControl
1081
+ CONTROL_NUMBER_PAIRS.GROUP
973
1082
  )
974
1083
  );
975
1084
  }
@@ -991,16 +1100,14 @@ function decodeEnvelope(raw, delimiters) {
991
1100
  ta1Segments.push({ raw: segmentText, elements });
992
1101
  break;
993
1102
  }
994
- warnings.push(
995
- unexpectedSegment(
996
- {
997
- segmentIndex: segIdx,
998
- interchangeIndex: 0,
999
- groupIndex: groups.length
1000
- },
1001
- "TA1",
1002
- "TA1 segment is envelope-level - appeared inside an open functional group"
1003
- )
1103
+ recordOrphan(
1104
+ segmentText,
1105
+ {
1106
+ segmentIndex: segIdx,
1107
+ interchangeIndex: 0,
1108
+ groupIndex: groups.length
1109
+ },
1110
+ UNEXPECTED_SEGMENT_CONTEXTS.TA1_INSIDE_GROUP
1004
1111
  );
1005
1112
  break;
1006
1113
  }
@@ -1021,12 +1128,10 @@ function decodeEnvelope(raw, delimiters) {
1021
1128
  }
1022
1129
  case "GE": {
1023
1130
  if (currentGroup === void 0) {
1024
- warnings.push(
1025
- unexpectedSegment(
1026
- { segmentIndex: segIdx, interchangeIndex: 0 },
1027
- "GE",
1028
- "no open functional group"
1029
- )
1131
+ recordOrphan(
1132
+ segmentText,
1133
+ { segmentIndex: segIdx, interchangeIndex: 0 },
1134
+ UNEXPECTED_SEGMENT_CONTEXTS.GE_WITHOUT_GS
1030
1135
  );
1031
1136
  break;
1032
1137
  }
@@ -1040,12 +1145,10 @@ function decodeEnvelope(raw, delimiters) {
1040
1145
  }
1041
1146
  case "ST": {
1042
1147
  if (currentGroup === void 0) {
1043
- warnings.push(
1044
- unexpectedSegment(
1045
- { segmentIndex: segIdx, interchangeIndex: 0 },
1046
- "ST",
1047
- "no open functional group (missing GS)"
1048
- )
1148
+ recordOrphan(
1149
+ segmentText,
1150
+ { segmentIndex: segIdx, interchangeIndex: 0 },
1151
+ UNEXPECTED_SEGMENT_CONTEXTS.ST_WITHOUT_GS
1049
1152
  );
1050
1153
  break;
1051
1154
  }
@@ -1068,12 +1171,10 @@ function decodeEnvelope(raw, delimiters) {
1068
1171
  }
1069
1172
  case "SE": {
1070
1173
  if (currentTx === void 0 || currentGroup === void 0) {
1071
- warnings.push(
1072
- unexpectedSegment(
1073
- { segmentIndex: segIdx, interchangeIndex: 0 },
1074
- "SE",
1075
- "no open transaction set"
1076
- )
1174
+ recordOrphan(
1175
+ segmentText,
1176
+ { segmentIndex: segIdx, interchangeIndex: 0 },
1177
+ UNEXPECTED_SEGMENT_CONTEXTS.SE_WITHOUT_ST
1077
1178
  );
1078
1179
  break;
1079
1180
  }
@@ -1098,9 +1199,7 @@ function decodeEnvelope(raw, delimiters) {
1098
1199
  transactionIndex: currentGroup.transactions.length,
1099
1200
  elementIndex: 2
1100
1201
  },
1101
- "ST-02/SE-02",
1102
- stControl,
1103
- seControl
1202
+ CONTROL_NUMBER_PAIRS.TRANSACTION
1104
1203
  )
1105
1204
  );
1106
1205
  }
@@ -1119,11 +1218,7 @@ function decodeEnvelope(raw, delimiters) {
1119
1218
  const declared = el(elements, 1);
1120
1219
  if (declared !== String(groups.length)) {
1121
1220
  warnings.push(
1122
- groupCountMismatch(
1123
- { segmentIndex: segIdx, interchangeIndex: 0, elementIndex: 1 },
1124
- declared,
1125
- groups.length
1126
- )
1221
+ groupCountMismatch({ segmentIndex: segIdx, interchangeIndex: 0, elementIndex: 1 })
1127
1222
  );
1128
1223
  }
1129
1224
  const isaControl = el(isa.elements, 13);
@@ -1132,9 +1227,7 @@ function decodeEnvelope(raw, delimiters) {
1132
1227
  warnings.push(
1133
1228
  controlNumberMismatch(
1134
1229
  { segmentIndex: segIdx, interchangeIndex: 0, elementIndex: 2 },
1135
- "ISA-13/IEA-02",
1136
- isaControl,
1137
- ieaControl
1230
+ CONTROL_NUMBER_PAIRS.INTERCHANGE
1138
1231
  )
1139
1232
  );
1140
1233
  }
@@ -1142,15 +1235,14 @@ function decodeEnvelope(raw, delimiters) {
1142
1235
  if (tail.length > 0) {
1143
1236
  const joined = tail + delimiters.segment;
1144
1237
  trailingBytes = joined;
1145
- warnings.push(
1146
- trailingGarbage({ segmentIndex: segIdx + 1, interchangeIndex: 0 }, joined.length)
1147
- );
1238
+ warnings.push(trailingGarbage({ segmentIndex: segIdx + 1, interchangeIndex: 0 }));
1148
1239
  }
1149
1240
  return {
1150
1241
  isa,
1151
1242
  groups: Object.freeze(groups.slice()),
1152
1243
  iea,
1153
1244
  ta1Segments: Object.freeze(ta1Segments.slice()),
1245
+ orphanSegments: Object.freeze(orphanSegments.slice()),
1154
1246
  trailingBytes,
1155
1247
  warnings: Object.freeze(warnings.slice())
1156
1248
  };
@@ -1166,12 +1258,10 @@ function decodeEnvelope(raw, delimiters) {
1166
1258
  currentTx.segments.push(decoded);
1167
1259
  currentTx.rawSegments.push(segmentText);
1168
1260
  } else if (name.length > 0) {
1169
- warnings.push(
1170
- unexpectedSegment(
1171
- { segmentIndex: segIdx, interchangeIndex: 0 },
1172
- name,
1173
- "body segment outside any open transaction set"
1174
- )
1261
+ recordOrphan(
1262
+ segmentText,
1263
+ { segmentIndex: segIdx, interchangeIndex: 0 },
1264
+ UNEXPECTED_SEGMENT_CONTEXTS.BODY_OUTSIDE_TRANSACTION
1175
1265
  );
1176
1266
  }
1177
1267
  break;
@@ -1190,6 +1280,7 @@ function decodeEnvelope(raw, delimiters) {
1190
1280
  groups: Object.freeze(groups.slice()),
1191
1281
  iea,
1192
1282
  ta1Segments: Object.freeze(ta1Segments.slice()),
1283
+ orphanSegments: Object.freeze(orphanSegments.slice()),
1193
1284
  trailingBytes,
1194
1285
  warnings: Object.freeze(warnings.slice())
1195
1286
  };
@@ -1215,7 +1306,7 @@ function parseX12(raw, options = {}) {
1215
1306
  first.code,
1216
1307
  first.message,
1217
1308
  first.position,
1218
- snippet(text)
1309
+ ""
1219
1310
  );
1220
1311
  }
1221
1312
  }
@@ -1235,6 +1326,7 @@ function parseX12(raw, options = {}) {
1235
1326
  delimiters,
1236
1327
  groups: decoded.groups,
1237
1328
  ta1Segments: decoded.ta1Segments,
1329
+ orphanSegments: decoded.orphanSegments,
1238
1330
  warnings: decoded.warnings,
1239
1331
  ...decoded.trailingBytes !== void 0 ? { trailingBytes: decoded.trailingBytes } : {},
1240
1332
  ...profile !== void 0 ? { profile } : {}
@@ -1751,14 +1843,7 @@ function checkClaimBalance(claim, position) {
1751
1843
  );
1752
1844
  const computed = claim.totalPaymentAmount.add(claimCasSum).add(lineCasSum);
1753
1845
  if (computed.equals(claim.totalChargeAmount)) return void 0;
1754
- const delta = computed.subtract(claim.totalChargeAmount);
1755
- return remitBalanceMismatch(
1756
- position,
1757
- "CLP-04 + \u03A3(claim CAS + line CAS) == CLP-03",
1758
- claim.totalChargeAmount.toString(),
1759
- computed.toString(),
1760
- delta.toString()
1761
- );
1846
+ return remitBalanceMismatch(position, BALANCE_INVARIANTS.CLAIM);
1762
1847
  }
1763
1848
  function checkServiceLineBalance(claim, position) {
1764
1849
  const out = [];
@@ -1768,14 +1853,10 @@ function checkServiceLineBalance(claim, position) {
1768
1853
  const lineCasSum = sumAmounts(line.adjustments);
1769
1854
  const computed = line.paymentAmount.add(lineCasSum);
1770
1855
  if (computed.equals(line.chargeAmount)) continue;
1771
- const delta = computed.subtract(line.chargeAmount);
1772
1856
  out.push(
1773
1857
  remitBalanceMismatch(
1774
1858
  { ...position, segmentIndex: position.segmentIndex + i + 1 },
1775
- "SVC-03 + \u03A3(line CAS) == SVC-02",
1776
- line.chargeAmount.toString(),
1777
- computed.toString(),
1778
- delta.toString()
1859
+ BALANCE_INVARIANTS.SERVICE_LINE
1779
1860
  )
1780
1861
  );
1781
1862
  }
@@ -1792,14 +1873,7 @@ function checkRemitTotalBalance(bpr02, claims, providerAdjustments, position) {
1792
1873
  );
1793
1874
  const computed = claimSum.subtract(plbSum);
1794
1875
  if (computed.equals(bpr02)) return void 0;
1795
- const delta = computed.subtract(bpr02);
1796
- return remitBalanceMismatch(
1797
- position,
1798
- "\u03A3(CLP-04) - \u03A3(PLB amounts) == BPR-02",
1799
- bpr02.toString(),
1800
- computed.toString(),
1801
- delta.toString()
1802
- );
1876
+ return remitBalanceMismatch(position, BALANCE_INVARIANTS.REMIT_TOTAL);
1803
1877
  }
1804
1878
  function sumAmounts(adjustments) {
1805
1879
  return adjustments.reduce(
@@ -1915,7 +1989,7 @@ function get835(delimiters, tx) {
1915
1989
  case "CLP": {
1916
1990
  flushClaim();
1917
1991
  lastParty = void 0;
1918
- currentClaim = openClaim(seg, delimiters);
1992
+ currentClaim = openClaim(seg, delimiters, position.segmentIndex);
1919
1993
  break;
1920
1994
  }
1921
1995
  case "CAS": {
@@ -1961,7 +2035,7 @@ function get835(delimiters, tx) {
1961
2035
  const remarks = seg.id === "MIA" ? collectMiaRemarks(seg, delimiters) : collectMoaRemarks(seg, delimiters);
1962
2036
  for (const code of remarks) {
1963
2037
  const entry = lookupRarc(code);
1964
- if (entry === void 0) warnings.push(unknownRarc(position, code));
2038
+ if (entry === void 0) warnings.push(unknownRarc(position));
1965
2039
  currentClaim.remarks.push({ system: "HE", code, description: entry?.description });
1966
2040
  }
1967
2041
  break;
@@ -2099,7 +2173,7 @@ function decodeLq(seg, delimiters, warnings, position) {
2099
2173
  let description;
2100
2174
  if (system === "HE") {
2101
2175
  const entry = lookupRarc(code);
2102
- if (entry === void 0) warnings.push(unknownRarc(position, code));
2176
+ if (entry === void 0) warnings.push(unknownRarc(position));
2103
2177
  description = entry?.description;
2104
2178
  }
2105
2179
  return Object.freeze({ system, code, description });
@@ -2131,7 +2205,7 @@ function decodeCasAdjustments(seg, delimiters, warnings, position) {
2131
2205
  if (reasonCode === void 0 && amount === void 0) continue;
2132
2206
  const code = reasonCode ?? "";
2133
2207
  const entry = code === "" ? void 0 : lookupCarc(code);
2134
- if (entry === void 0 && code !== "") warnings.push(unknownCarc(position, code));
2208
+ if (entry === void 0 && code !== "") warnings.push(unknownCarc(position));
2135
2209
  out.push(
2136
2210
  Object.freeze({
2137
2211
  groupCode,
@@ -2171,14 +2245,13 @@ function decodeNm1(seg, delimiters) {
2171
2245
  })
2172
2246
  };
2173
2247
  }
2174
- function openClaim(seg, delimiters) {
2248
+ function openClaim(seg, delimiters, clpSegmentIndex) {
2175
2249
  const claimStatusCode = elementValue(seg, 2, delimiters);
2176
2250
  const claimStatusDescription = lookupClpStatus(claimStatusCode)?.description;
2177
2251
  const facilityTypeCode = componentOptional(seg, 8, 1, delimiters) ?? elementOptional(seg, 8, delimiters);
2178
2252
  const claimFrequencyCode = componentOptional(seg, 8, 3, delimiters);
2179
2253
  return {
2180
- clpSegmentIndex: 0,
2181
- // populated in the future when we surface positions
2254
+ clpSegmentIndex,
2182
2255
  patientControlNumber: elementValue(seg, 1, delimiters),
2183
2256
  claimStatusCode,
2184
2257
  claimStatusDescription,
@@ -2984,12 +3057,7 @@ function get837Claims(delimiters, tx, opts) {
2984
3057
  }
2985
3058
  const variant = explicitType ?? variantFromIcr ?? variantFromSegment ?? "unknown";
2986
3059
  if (variant === "unknown") {
2987
- warnings.push(
2988
- unknown837Variant(
2989
- { segmentIndex: 1, transactionIndex: 0 },
2990
- implementationConventionReference
2991
- )
2992
- );
3060
+ warnings.push(unknown837Variant({ segmentIndex: 1, transactionIndex: 0 }));
2993
3061
  }
2994
3062
  const hierarchies = [];
2995
3063
  const hlIndex = /* @__PURE__ */ new Map();
@@ -3230,28 +3298,16 @@ function get837Claims(delimiters, tx, opts) {
3230
3298
  flushClaim();
3231
3299
  if (currentBillingHl === void 0 || currentSubscriberHl === void 0 || currentSubscriberMember === void 0 || currentPayer === void 0) {
3232
3300
  if (currentBillingHl === void 0) {
3233
- warnings.push(
3234
- missingRequiredLoop(position, "2000A", "no Billing Provider HL precedes the CLM")
3235
- );
3301
+ warnings.push(missingRequiredLoop(position, REQUIRED_LOOPS.BILLING_PROVIDER_2000A));
3236
3302
  }
3237
3303
  if (currentSubscriberHl === void 0) {
3238
- warnings.push(
3239
- missingRequiredLoop(position, "2000B", "no Subscriber HL precedes the CLM")
3240
- );
3304
+ warnings.push(missingRequiredLoop(position, REQUIRED_LOOPS.SUBSCRIBER_2000B));
3241
3305
  }
3242
3306
  if (currentSubscriberMember === void 0 && currentSubscriberHl !== void 0) {
3243
- warnings.push(
3244
- missingRequiredLoop(
3245
- position,
3246
- "2010BA",
3247
- "no Subscriber Name follows the Subscriber HL"
3248
- )
3249
- );
3307
+ warnings.push(missingRequiredLoop(position, REQUIRED_LOOPS.SUBSCRIBER_NAME_2010BA));
3250
3308
  }
3251
3309
  if (currentPayer === void 0 && currentSubscriberHl !== void 0) {
3252
- warnings.push(
3253
- missingRequiredLoop(position, "2010BB", "no Payer Name follows the Subscriber HL")
3254
- );
3310
+ warnings.push(missingRequiredLoop(position, REQUIRED_LOOPS.PAYER_NAME_2010BB));
3255
3311
  }
3256
3312
  }
3257
3313
  currentClaim = openClaim2(seg, delimiters, {
@@ -3396,30 +3452,21 @@ function validateHl(hl, index, position, warnings) {
3396
3452
  const expectedParent = EXPECTED_PARENT_LEVEL[hl.levelCode];
3397
3453
  if (expectedParent === void 0) {
3398
3454
  if (hl.levelCode === HL_LEVEL_CODES.INFORMATION_SOURCE && hl.parentHlId !== void 0) {
3399
- warnings.push(hlParentMismatch(position, hl.hlId, hl.parentHlId));
3455
+ warnings.push(hlParentMismatch(position));
3400
3456
  }
3401
3457
  return;
3402
3458
  }
3403
3459
  if (hl.parentHlId === void 0) {
3404
- warnings.push(hlParentMismatch(position, hl.hlId, ""));
3460
+ warnings.push(hlParentMismatch(position));
3405
3461
  return;
3406
3462
  }
3407
3463
  const parent = index.get(hl.parentHlId);
3408
3464
  if (parent === void 0) {
3409
- warnings.push(hlParentMismatch(position, hl.hlId, hl.parentHlId));
3465
+ warnings.push(hlParentMismatch(position));
3410
3466
  return;
3411
3467
  }
3412
3468
  if (parent.levelCode !== expectedParent) {
3413
- warnings.push(
3414
- hlParentLevelInvalid(
3415
- position,
3416
- hl.hlId,
3417
- hl.levelCode,
3418
- parent.hlId,
3419
- parent.levelCode,
3420
- expectedParent
3421
- )
3422
- );
3469
+ warnings.push(hlParentLevelInvalid(position));
3423
3470
  }
3424
3471
  }
3425
3472
  function decodeSbr(seg, delimiters) {
@@ -3520,7 +3567,7 @@ function decodeHi(seg, delimiters, warnings, position) {
3520
3567
  const codeSystem = resolved?.system ?? "unknown";
3521
3568
  const category = resolved?.category ?? "unknown";
3522
3569
  if (qualifier !== void 0 && resolved === void 0) {
3523
- warnings.push(unknownHiQualifier(position, qualifier));
3570
+ warnings.push(unknownHiQualifier(position));
3524
3571
  }
3525
3572
  out.push(
3526
3573
  Object.freeze({
@@ -3563,7 +3610,7 @@ function decodeCas(seg, delimiters, warnings, position) {
3563
3610
  if (reasonCode === void 0 && amount === void 0) continue;
3564
3611
  const code = reasonCode ?? "";
3565
3612
  const entry = code === "" ? void 0 : lookupCarc(code);
3566
- if (entry === void 0 && code !== "") warnings.push(unknownCarc(position, code));
3613
+ if (entry === void 0 && code !== "") warnings.push(unknownCarc(position));
3567
3614
  out.push(
3568
3615
  Object.freeze({
3569
3616
  groupCode,
@@ -4805,30 +4852,21 @@ function validateHl2(hl, index, expectedParentLevel, position, warnings) {
4805
4852
  const expectedParent = hasExpectation ? expectedParentLevel[hl.levelCode] : void 0;
4806
4853
  if (expectedParent === void 0) {
4807
4854
  if (hasExpectation && hl.parentHlId !== void 0) {
4808
- warnings.push(hlParentMismatch(position, hl.hlId, hl.parentHlId));
4855
+ warnings.push(hlParentMismatch(position));
4809
4856
  }
4810
4857
  return;
4811
4858
  }
4812
4859
  if (hl.parentHlId === void 0) {
4813
- warnings.push(hlParentMismatch(position, hl.hlId, ""));
4860
+ warnings.push(hlParentMismatch(position));
4814
4861
  return;
4815
4862
  }
4816
4863
  const parent = index.get(hl.parentHlId);
4817
4864
  if (parent === void 0) {
4818
- warnings.push(hlParentMismatch(position, hl.hlId, hl.parentHlId));
4865
+ warnings.push(hlParentMismatch(position));
4819
4866
  return;
4820
4867
  }
4821
4868
  if (parent.levelCode !== expectedParent) {
4822
- warnings.push(
4823
- hlParentLevelInvalid(
4824
- position,
4825
- hl.hlId,
4826
- hl.levelCode,
4827
- parent.hlId,
4828
- parent.levelCode,
4829
- expectedParent
4830
- )
4831
- );
4869
+ warnings.push(hlParentLevelInvalid(position));
4832
4870
  }
4833
4871
  }
4834
4872
 
@@ -5781,11 +5819,11 @@ function decodeStatusComposite(seg, n, delimiters, warnings, position) {
5781
5819
  if (categoryCode === void 0 && statusCode === void 0) return void 0;
5782
5820
  const category = categoryCode === void 0 ? void 0 : lookupClaimStatusCategory(categoryCode);
5783
5821
  if (categoryCode !== void 0 && category === void 0) {
5784
- warnings.push(unknownClaimStatusCategory(position, categoryCode));
5822
+ warnings.push(unknownClaimStatusCategory(position));
5785
5823
  }
5786
5824
  const status = statusCode === void 0 ? void 0 : lookupClaimStatus(statusCode);
5787
5825
  if (statusCode !== void 0 && status === void 0) {
5788
- warnings.push(unknownClaimStatus(position, statusCode));
5826
+ warnings.push(unknownClaimStatus(position));
5789
5827
  }
5790
5828
  return Object.freeze({
5791
5829
  categoryCode: categoryCode ?? "",
@@ -7109,7 +7147,7 @@ function openEnrollment(seg, delimiters, position) {
7109
7147
  const entry = maintenanceTypeCode === "" ? void 0 : lookupMaintenanceType(maintenanceTypeCode);
7110
7148
  const warnings = [];
7111
7149
  if (maintenanceTypeCode !== "" && entry === void 0) {
7112
- warnings.push(unknownMaintenanceType(position, maintenanceTypeCode));
7150
+ warnings.push(unknownMaintenanceType(position));
7113
7151
  }
7114
7152
  return {
7115
7153
  subscriberIndicator: elementOptional(seg, 1, delimiters),
@@ -7149,7 +7187,7 @@ function openCoverage(seg, delimiters, position, warnings) {
7149
7187
  let maintenanceTypeDescription;
7150
7188
  if (maintenanceTypeCode !== void 0) {
7151
7189
  const entry = lookupMaintenanceType(maintenanceTypeCode);
7152
- if (entry === void 0) warnings.push(unknownMaintenanceType(position, maintenanceTypeCode));
7190
+ if (entry === void 0) warnings.push(unknownMaintenanceType(position));
7153
7191
  maintenanceTypeDescription = entry?.description;
7154
7192
  }
7155
7193
  return {
@@ -7862,7 +7900,7 @@ function decodeHiDiagnoses(seg, delimiters, warnings, position) {
7862
7900
  const resolved = qualifier === void 0 ? void 0 : resolveHiQualifier(qualifier);
7863
7901
  const codeSystem = resolved?.system ?? "unknown";
7864
7902
  if (qualifier !== void 0 && resolved === void 0) {
7865
- warnings.push(unknownHiQualifier(position, qualifier));
7903
+ warnings.push(unknownHiQualifier(position));
7866
7904
  }
7867
7905
  out.push(Object.freeze({ qualifier: qualifier ?? "", code: code ?? "", codeSystem }));
7868
7906
  }
@@ -9010,18 +9048,39 @@ function serializeX12(interchange, opts = {}) {
9010
9048
  };
9011
9049
  let out = interchange.isa.raw;
9012
9050
  let segIdx = 0;
9051
+ const orphans = interchange.orphanSegments ?? [];
9052
+ const placed = /* @__PURE__ */ new Set();
9053
+ const flushOrphans = (slot) => {
9054
+ let written = 0;
9055
+ for (const [i, orphan] of orphans.entries()) {
9056
+ if (placed.has(i)) continue;
9057
+ if (!slot(orphan.anchor)) continue;
9058
+ placed.add(i);
9059
+ out += orphan.raw + term;
9060
+ segIdx++;
9061
+ written++;
9062
+ }
9063
+ return written;
9064
+ };
9013
9065
  for (const ta1 of interchange.ta1Segments) {
9014
9066
  out += ta1.raw + term;
9015
9067
  segIdx++;
9016
9068
  }
9017
9069
  for (const [g, group] of interchange.groups.entries()) {
9070
+ flushOrphans((a) => a?.kind === "interchange" && a.groupIndex === g);
9018
9071
  const gsSegIdx = ++segIdx;
9019
9072
  out += group.gs.raw + term;
9020
9073
  for (const [t, tx] of group.transactions.entries()) {
9021
- const stSegIdx = segIdx + 1;
9022
- const segCount = tx.rawSegments.length;
9074
+ flushOrphans((a) => a?.kind === "group" && a.groupIndex === g && a.transactionIndex === t);
9023
9075
  const lastIdx = tx.rawSegments.length - 1;
9076
+ let segCount = tx.rawSegments.length;
9077
+ let stSegIdx = segIdx + 1;
9024
9078
  for (const [k, raw] of tx.rawSegments.entries()) {
9079
+ const inside = flushOrphans(
9080
+ (a) => a?.kind === "transaction" && a.groupIndex === g && a.transactionIndex === t && a.segmentOffset === k
9081
+ );
9082
+ if (k === 0) stSegIdx = segIdx + 1;
9083
+ else segCount += inside;
9025
9084
  segIdx++;
9026
9085
  if (recompute && tx.se !== void 0 && k === lastIdx) {
9027
9086
  out += substituteElement(tx.se.elements, 1, String(segCount), elementSep) + term;
@@ -9029,21 +9088,20 @@ function serializeX12(interchange, opts = {}) {
9029
9088
  out += raw + term;
9030
9089
  }
9031
9090
  }
9091
+ flushOrphans(
9092
+ (a) => a?.kind === "transaction" && a.groupIndex === g && a.transactionIndex === t && a.segmentOffset === tx.rawSegments.length
9093
+ );
9032
9094
  if (specClean && tx.se !== void 0) {
9033
9095
  const declaredSe = elementAt(tx.se.elements, 1);
9034
9096
  if (declaredSe !== String(segCount)) {
9035
9097
  emit(
9036
- segmentCountMismatch(
9037
- {
9038
- segmentIndex: stSegIdx,
9039
- interchangeIndex: 0,
9040
- groupIndex: g,
9041
- transactionIndex: t,
9042
- elementIndex: 1
9043
- },
9044
- declaredSe,
9045
- segCount
9046
- )
9098
+ segmentCountMismatch({
9099
+ segmentIndex: stSegIdx,
9100
+ interchangeIndex: 0,
9101
+ groupIndex: g,
9102
+ transactionIndex: t,
9103
+ elementIndex: 1
9104
+ })
9047
9105
  );
9048
9106
  }
9049
9107
  const st02 = elementAt(tx.st.elements, 2);
@@ -9058,14 +9116,15 @@ function serializeX12(interchange, opts = {}) {
9058
9116
  transactionIndex: t,
9059
9117
  elementIndex: 2
9060
9118
  },
9061
- "ST-02/SE-02",
9062
- st02,
9063
- se02
9119
+ CONTROL_NUMBER_PAIRS.TRANSACTION
9064
9120
  )
9065
9121
  );
9066
9122
  }
9067
9123
  }
9068
9124
  }
9125
+ flushOrphans(
9126
+ (a) => a?.kind === "group" && a.groupIndex === g && a.transactionIndex === group.transactions.length
9127
+ );
9069
9128
  if (group.ge !== void 0) {
9070
9129
  const txCount = group.transactions.length;
9071
9130
  segIdx++;
@@ -9078,11 +9137,12 @@ function serializeX12(interchange, opts = {}) {
9078
9137
  const declaredGe = elementAt(group.ge.elements, 1);
9079
9138
  if (declaredGe !== String(txCount)) {
9080
9139
  emit(
9081
- transactionCountMismatch(
9082
- { segmentIndex: gsSegIdx, interchangeIndex: 0, groupIndex: g, elementIndex: 1 },
9083
- declaredGe,
9084
- txCount
9085
- )
9140
+ transactionCountMismatch({
9141
+ segmentIndex: gsSegIdx,
9142
+ interchangeIndex: 0,
9143
+ groupIndex: g,
9144
+ elementIndex: 1
9145
+ })
9086
9146
  );
9087
9147
  }
9088
9148
  const gs06 = elementAt(group.gs.elements, 6);
@@ -9091,15 +9151,15 @@ function serializeX12(interchange, opts = {}) {
9091
9151
  emit(
9092
9152
  controlNumberMismatch(
9093
9153
  { segmentIndex: gsSegIdx, interchangeIndex: 0, groupIndex: g, elementIndex: 2 },
9094
- "GS-06/GE-02",
9095
- gs06,
9096
- ge02
9154
+ CONTROL_NUMBER_PAIRS.GROUP
9097
9155
  )
9098
9156
  );
9099
9157
  }
9100
9158
  }
9101
9159
  }
9102
9160
  }
9161
+ flushOrphans((a) => a?.kind === "interchange" && a.groupIndex === interchange.groups.length);
9162
+ flushOrphans(() => true);
9103
9163
  if (interchange.iea !== void 0) {
9104
9164
  const groupCount = interchange.groups.length;
9105
9165
  segIdx++;
@@ -9111,13 +9171,7 @@ function serializeX12(interchange, opts = {}) {
9111
9171
  if (specClean) {
9112
9172
  const declaredIea = elementAt(interchange.iea.elements, 1);
9113
9173
  if (declaredIea !== String(groupCount)) {
9114
- emit(
9115
- groupCountMismatch(
9116
- { segmentIndex: segIdx, interchangeIndex: 0, elementIndex: 1 },
9117
- declaredIea,
9118
- groupCount
9119
- )
9120
- );
9174
+ emit(groupCountMismatch({ segmentIndex: segIdx, interchangeIndex: 0, elementIndex: 1 }));
9121
9175
  }
9122
9176
  const isa13 = elementAt(interchange.isa.elements, 13);
9123
9177
  const iea02 = elementAt(interchange.iea.elements, 2);
@@ -9125,9 +9179,7 @@ function serializeX12(interchange, opts = {}) {
9125
9179
  emit(
9126
9180
  controlNumberMismatch(
9127
9181
  { segmentIndex: segIdx, interchangeIndex: 0, elementIndex: 2 },
9128
- "ISA-13/IEA-02",
9129
- isa13,
9130
- iea02
9182
+ CONTROL_NUMBER_PAIRS.INTERCHANGE
9131
9183
  )
9132
9184
  );
9133
9185
  }
@@ -9590,9 +9642,10 @@ var profiles = Object.freeze({
9590
9642
  });
9591
9643
 
9592
9644
  // src/index.ts
9593
- var VERSION = "0.0.3";
9645
+ var VERSION = "0.0.4";
9594
9646
 
9595
9647
  exports.ACK_BUILD_ERROR_CODES = ACK_BUILD_ERROR_CODES;
9648
+ exports.ALL_WARNING_MESSAGES = ALL_WARNING_MESSAGES;
9596
9649
  exports.AUTH_278_BUILD_ERROR_CODES = AUTH_278_BUILD_ERROR_CODES;
9597
9650
  exports.AUTH_278_LOOP_2000A = AUTH_278_LOOP_2000A;
9598
9651
  exports.AUTH_278_LOOP_2000B = AUTH_278_LOOP_2000B;
@@ -9601,6 +9654,7 @@ exports.AUTH_278_LOOP_2000D = AUTH_278_LOOP_2000D;
9601
9654
  exports.AUTH_278_LOOP_2000E = AUTH_278_LOOP_2000E;
9602
9655
  exports.AUTH_278_LOOP_2000F = AUTH_278_LOOP_2000F;
9603
9656
  exports.AckBuildError = AckBuildError;
9657
+ exports.BALANCE_INVARIANTS = BALANCE_INVARIANTS;
9604
9658
  exports.CARC = CARC;
9605
9659
  exports.CLAIM_837D_LOOP_2000A = CLAIM_837D_LOOP_2000A;
9606
9660
  exports.CLAIM_837D_LOOP_2300 = CLAIM_837D_LOOP_2300;
@@ -9625,6 +9679,7 @@ exports.CLAIM_STATUS_277_BUILD_ERROR_CODES = CLAIM_STATUS_277_BUILD_ERROR_CODES;
9625
9679
  exports.CLAIM_STATUS_CATEGORY_CODES = CLAIM_STATUS_CATEGORY_CODES;
9626
9680
  exports.CLAIM_STATUS_CODES = CLAIM_STATUS_CODES;
9627
9681
  exports.CLP_STATUS = CLP_STATUS;
9682
+ exports.CONTROL_NUMBER_PAIRS = CONTROL_NUMBER_PAIRS;
9628
9683
  exports.Claim837BuildError = Claim837BuildError;
9629
9684
  exports.ClaimStatus277BuildError = ClaimStatus277BuildError;
9630
9685
  exports.DELIMITER_POSITIONS = DELIMITER_POSITIONS;
@@ -9654,6 +9709,7 @@ exports.ISA_MIN_LENGTH = ISA_MIN_LENGTH;
9654
9709
  exports.LoopSpecDefinitionError = LoopSpecDefinitionError;
9655
9710
  exports.MAINTENANCE_TYPE_CODES = MAINTENANCE_TYPE_CODES;
9656
9711
  exports.NM1_QUALIFIERS = NM1_QUALIFIERS;
9712
+ exports.NON_SPEC_SEGMENT_ID = NON_SPEC_SEGMENT_ID;
9657
9713
  exports.PREMIUM_820_BUILD_ERROR_CODES = PREMIUM_820_BUILD_ERROR_CODES;
9658
9714
  exports.PREMIUM_820_LOOP_1000A = PREMIUM_820_LOOP_1000A;
9659
9715
  exports.PREMIUM_820_LOOP_1000B = PREMIUM_820_LOOP_1000B;
@@ -9670,6 +9726,7 @@ exports.REMIT_835_LOOP_1000B = REMIT_835_LOOP_1000B;
9670
9726
  exports.REMIT_835_LOOP_2000 = REMIT_835_LOOP_2000;
9671
9727
  exports.REMIT_835_LOOP_2100 = REMIT_835_LOOP_2100;
9672
9728
  exports.REMIT_835_LOOP_2110 = REMIT_835_LOOP_2110;
9729
+ exports.REQUIRED_LOOPS = REQUIRED_LOOPS;
9673
9730
  exports.Remit835BuildError = Remit835BuildError;
9674
9731
  exports.SERVICE_TYPE_CODES = SERVICE_TYPE_CODES;
9675
9732
  exports.STATUS_277_LOOP_2000A = STATUS_277_LOOP_2000A;
@@ -9682,6 +9739,7 @@ exports.STATUS_277_LOOP_2220 = STATUS_277_LOOP_2220;
9682
9739
  exports.ServicesReview278BuildError = ServicesReview278BuildError;
9683
9740
  exports.TA1_ACK_CODES = TA1_ACK_CODES;
9684
9741
  exports.TA1_NOTE_CODES = TA1_NOTE_CODES;
9742
+ exports.UNEXPECTED_SEGMENT_CONTEXTS = UNEXPECTED_SEGMENT_CONTEXTS;
9685
9743
  exports.VERSION = VERSION;
9686
9744
  exports.WARNING_CODES = WARNING_CODES;
9687
9745
  exports.X12BuildError = X12BuildError;