@cobol-ts/cursor-loader-cobol 0.0.0-stage → 0.0.2

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.
@@ -0,0 +1,29 @@
1
+ # Fixed-record decoded-value integration (23 October 2026)
2
+
3
+ The production opt-in details constructors `createCobolDecodedFixedDetails` and
4
+ `createCobolDecodedProjectionDetails` use `@cobol-ts/codec`. They preserve
5
+ original bytes, compiled geometry, pooled state, nested arrays, ODO count
6
+ resolution, and the existing projection lifetime model.
7
+
8
+ During selected projection-path compilation, a field's PICTURE, effective
9
+ inherited USAGE, sign and compiled field width are used to compile a decoder
10
+ exactly once per stable compiled elementary node. On every scalar access the
11
+ existing `fieldRange()` finds the current geometry and a *pooled* fragmented
12
+ byte cursor decodes the borrowed range. This decoder does not receive a
13
+ contiguous copy and works when even individual field bytes are in different
14
+ buffers. For now, `createCobolFixedDetails` / `createCobolProjectionDetails`
15
+ keep their diagnostic-range values, for compatibility with existing detailed
16
+ geometry tests.
17
+
18
+ The decoded FB test uses actual original EBCDIC hex fixture bytes,
19
+ `createFileCursor()`, a real compiled copybook and 3-byte physical reads. Other
20
+ decoded cases exercise COMP signed negative values across buffer boundaries,
21
+ fixed OCCURS/REDEFINES and nested three-level ODO with a split scalar field.
22
+ A zero-byte phantom record at exact-buffer EOF was also corrected in the
23
+ generic record cursor; the new FB test is its regression oracle.
24
+
25
+ This is **a first decoded-value milestone, not all possible COBOL encodings**.
26
+ Only the documented subset in `@cobol-ts/codec/README.md` has production
27
+ decoders. In particular source compiler conventions, code pages and decimal
28
+ precision must be agreed before accepting real client data. ODO test fixtures
29
+ are bound completed records, not variable-record file-framing integration.
package/README.md CHANGED
@@ -1,3 +1,242 @@
1
- # Temporary Holding Version
1
+ # Quick start — Node.js fixed-block files
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
+ ```ts
4
+ import {readCobolFile} from '@cobol-ts/cursor-loader-cobol/node';
5
+
6
+ const cursor = readCobolFile({
7
+ copybook: 'EMPREC01.cpy',
8
+ filename: 'TEST.EMP.RECORD.FILE.dat',
9
+ projection: employeeProjection,
10
+ bufferSize: 64 * 1024 // optional; default is 64 KiB
11
+ });
12
+
13
+ for await (const row of cursor) {
14
+ try { console.log(row.result.salary()); }
15
+ finally { row.close(); }
16
+ }
17
+ ```
18
+
19
+ This convenience API uses the existing `createThrowingFileCursor` and original
20
+ byte-backed projections. It compiles the copybook, geometry and requested scalar
21
+ decoders once per opened source. It deliberately does not materialise rows or
22
+ create per-field joined byte arrays. The Node file handle closes on EOF, error
23
+ or iteration cancellation; yielded `FileCursorResult` lifetimes are still
24
+ owned by the caller and require `close()`.
25
+
26
+ The standard COBOL registry can also be used directly through
27
+ `createCobolParserRegistry(details)` for other physical byte sources or
28
+ alternative cursor error policies.
29
+
30
+ # `@cobol-ts/cursor-loader-cobol`
31
+
32
+ Byte-backed COBOL projections over compiled copybook storage geometry. The original record buffers remain authoritative: the adapter selects physical byte ranges and borrowed, application-facing views rather than decoding an entire COBOL record into an object graph. `REDEFINES` alternatives are distinct views of the same storage; choosing their business meaning is the caller's responsibility.
33
+
34
+ ## Support matrix (23 October 2026)
35
+
36
+ | Capability | Current status |
37
+ | --- | --- |
38
+ | Fixed-length/fixed-blocked record **framing** | Implemented with `createCobolFixedDetails()` and known `recordLengthBytes` |
39
+ | Fixed and nested `OCCURS`, independent sibling arrays | Implemented; constant-stride arithmetic |
40
+ | `REDEFINES`, including unequal alternatives inside nested arrays | Implemented and byte-coordinate tested |
41
+ | `OCCURS DEPENDING ON` (ODO), including two sibling inner arrays | Implemented for supported fixed-location controllers |
42
+ | Three levels of nested ODO projected arrays | Implemented and tested end to end |
43
+ | Variable-body occurrence start positions | Lazy, record-owned cached boundary prefixes |
44
+ | ODO controllers at variable physical positions / one count **per outer occurrence** | **Not supported** by the current controller locator |
45
+ | Variable-length physical **record framing** (VB/RDW or other conventions) | Not implemented; `parse()` requires opened-source `recordLengthBytes` |
46
+ | Production primitive decoding for projected scalar members | Implemented for the subset documented in `README.decoder.md`; diagnostic projection details remain available for layout tests |
47
+
48
+ **Do not confuse storage layout with record framing.** `compileCobolLayout()` and `createCobolProjectionDetails()` accept symbolic ODO layouts; the `cobolParser.parse()` implementation still requires `details.recordLengthBytes`. For an ODO layout, the caller must arrange a valid framed record length before calling this parser; **the current `parse()` method accepts one `details.recordLengthBytes` for the opened source, not a varying length supplied for each record**. The end-to-end nested geometry tests construct completed `ProjectionPhysicalRecord` fixtures and bind projections directly, rather than testing an automatic ODO record-framing algorithm. `createCobolFixedDetails()` intentionally fails when the record length is not statically known.
49
+
50
+ The layout compiler applies an IBM Enterprise COBOL–oriented subset, not all possible dialect conventions. In particular, its current ODO controller validation requires suitable fixed-location controllers outside repeated occurrences. The symbolic expression algebra and jagged boundary cache are more general than this presently accepted subset.
51
+
52
+ ## Pipeline: compile once, select lazily
53
+
54
+ ```text
55
+ COBOL copybook
56
+ -> parseCopybook() AST
57
+ -> compileCobolLayout() immutable symbolic layout in bits
58
+ -> createCobolFixedDetails(layout) static frame when available
59
+ or createCobolProjectionDetails(layout) symbolic ODO geometry
60
+ -> defineProjection<T>() application definition
61
+ -> createProjection(cobolParser, details, context, definition)
62
+ compiled paths + reusable views
63
+ -> cobolParser.parse(record, details) borrow framed record bytes
64
+ -> projection getter / array index select only requested occurrences
65
+ -> scalar accessor locate original byte range
66
+ ```
67
+
68
+ The `CobolProjectionPath` discriminated union has a numeric fixed path (`offsetBits`, `sizeBits`, static `runtimeDimensions`) and a symbolic path referencing compiled entries and their left/right offsets. All physical geometry, including ODO cache contents, is in **bits**. StringPath compilation happens once per source/projection; no field-name search is needed on ordinary scalar access.
69
+
70
+ ### Fixed OCCURS example
71
+
72
+ ```cobol
73
+ 01 CUSTOMER.
74
+ 05 CUSTOMER-ID PIC 9(4).
75
+ 05 TELEPHONES OCCURS 2 TIMES.
76
+ 10 PHONE-RAW PIC X(6).
77
+ 10 PHONE-PARTS REDEFINES PHONE-RAW.
78
+ 15 PHONE-KIND PIC X.
79
+ 15 PHONE-NUMBER PIC X(5).
80
+ 05 STATUS PIC X.
81
+ ```
82
+
83
+ This is 17 bytes: `4 + 2 * 6 + 1`. Selecting `telephones[1].raw()` reads bytes `[10,16)` and `telephones[1].parts.number()` reads `[11,16)`. The second telephone is reached by a numeric six-byte stride, without a boundary cache or a duplicated decoded telephone object.
84
+
85
+ ```ts
86
+ import type {ProjectedArray} from '@cobol-ts/arrays';
87
+ import {defineProjection} from '@cobol-ts/cursor-projection';
88
+
89
+ type Phone = {raw(): string; readonly parts: {number(): string}};
90
+ type Customer = {readonly telephones: ProjectedArray<Phone>};
91
+
92
+ const definition = defineProjection<Customer>({
93
+ telephones: {type:'array', path:['CUSTOMER','TELEPHONES'], element:{
94
+ raw: {type:'string',path:['PHONE-RAW']},
95
+ parts: {type:'object',path:['PHONE-PARTS'],fields:{
96
+ number: {type:'string',path:['PHONE-NUMBER']}
97
+ }}
98
+ }}
99
+ });
100
+ ```
101
+
102
+ Nested child paths are relative to their selected parent. Fixed arrays use numeric stride multiplication, including repeated groups containing `REDEFINES` whose extent is the maximum of overlay alternatives.
103
+
104
+ ## Nested ODO example: the actual supported path
105
+
106
+ ```cobol
107
+ 01 ROW.
108
+ 05 O-COUNT PIC 9.
109
+ 05 M-COUNT PIC 9.
110
+ 05 I-COUNT PIC 9.
111
+ 05 OUTERS OCCURS 0 TO 3 TIMES DEPENDING ON O-COUNT.
112
+ 10 O-HEAD PIC X.
113
+ 10 MIDDLES OCCURS 0 TO 3 TIMES DEPENDING ON M-COUNT.
114
+ 15 M-HEAD PIC X.
115
+ 15 INNERS OCCURS 0 TO 3 TIMES DEPENDING ON I-COUNT.
116
+ 20 CODE PIC X(2).
117
+ 15 M-TAIL PIC X.
118
+ 10 O-TAIL PIC X.
119
+ 05 FINAL PIC X.
120
+ ```
121
+
122
+ With all three counts equal to 2, the directly bound completed-record fixture has 32 active bytes. The tested call:
123
+
124
+ ```ts
125
+ row.outers[1].middles[1].inners[1].code();
126
+ ```
127
+
128
+ selects record-relative bytes `[27,29)` (`db dc` in the diagnostic test). Outer occurrences are `[3,17)` and `[17,31)`; middle occurrences within outer 1 are `[18,24)` and `[24,30)`; the final byte is `[31,32)`. The test asserts these **interior coordinates**, not only total record length. A second test reaches the field across two physical buffers.
129
+
130
+ `O-COUNT`, `M-COUNT` and `I-COUNT` are at **fixed positions** at the start of the record. Thus the counts are shared among all corresponding enclosing occurrences within that record. This is a meaningful limitation: a controller located separately inside each `OUTERS` occurrence, producing different inner counts per outer instance, is not currently supported. `resolveCobolCount()` explicitly rejects variably located controller fields.
131
+
132
+ ### Lazy position caching
133
+
134
+ A variable-size OCCURS body needs positions of the preceding occurrences. The record-state cache retains only the contiguous prefix needed to locate the requested index:
135
+
136
+ ```text
137
+ OUTERS / [] starts = [3,17,31] (bytes shown for clarity)
138
+ MIDDLES / [outer=1] starts = [18,24,30]
139
+ INNERS / [outer=1,middle=1] constant two-byte stride: no starts array
140
+ ```
141
+
142
+ The real cache stores **bit boundaries** in `ArrayWithSize<number>`. Each ODO declaration is keyed by the original compiled node; branches form a lazily populated jagged hierarchy indexed by enclosing occurrence indices. To locate occurrence `i`, the cache extends its boundaries from the last known index through `i+1`, summing body extents using `evaluateStorageSize()`; subsequent lookups reuse the prefix. Calculating physical boundaries **does not** create application-facing projected children for all preceding occurrences. Fixed-width bodies use direct multiplication, not prefix caching.
143
+
144
+ Two sibling inner ODO declarations receive separate caches even when nested under the same outer occurrence. A right-anchored trailing field can be located from a trusted active record end without traversing preceding ODOs, as demonstrated by the `FINAL` fixture. Fixed-capacity trailing storage requires separate framing/anchor validation.
145
+
146
+ ## Pooling, cleanup and allocations
147
+
148
+ The physical record owns a `CobolRecordState`:
149
+
150
+ ```ts
151
+ // In the parser registry for the opened file:
152
+ cobol: {
153
+ parser: cobolParser,
154
+ parserConfig: () => preparedDetails,
155
+ createRecordState: createCobolRecordState,
156
+ cleanRecordState: cleanCobolRecordState
157
+ }
158
+ ```
159
+
160
+ **Register `cleanRecordState` for pooled COBOL sources.** On final release, the pool calls this hook after the application result has cleared its borrowed projections. It resets active ODO boundary prefixes, unbinds the count resolver and retains array capacity, jagged branches, projection slots and scratch objects. There is no generation counter.
161
+
162
+ The generic projection framework retains root array runtimes in `recordState.projectionViews` and nested array runtimes on their owning child views. Previously visited COBOL array providers (`CobolArraySelection`) and selected occurrence objects are **rebound in place**: provider methods are prototype functions, and enclosing-index arrays are updated rather than recreated for the same retained slots. Repeated getters during a record lease reuse bound selections. Different simultaneously live physical-record holders have independent state; caller references to projected objects become invalid when their owning `FileCursorResult` closes.
163
+
164
+ Two different sizes must not be confused: `ProjectedArray.length` is the current record's logical count; `ArrayWithSize.size` is the number of valid cached prefix entries. Sparse high-water element slots are retained, with an additional dense active-prefix list used to clear only children bound during the current lease. Nested ODO cache branches use the same active-prefix approach. Cleanup work is proportional to active referenced branches/children rather than a scan of historical sparse capacity; the bookkeeping trade-off has correctness tests, **not** a measured throughput benchmark.
165
+
166
+ **Allocation status.** Previously visited provider/child slots are reused across leases. First-ever visits still allocate retained capacity; extending an ODO boundary cache can allocate evaluator working state and an extent callback. The current debug scalar strings allocate intentionally. Do not describe this adapter as allocation-free without heap profiling. In particular, the size-expression evaluator and the enclosing-index binding on a cache miss remain optimisation candidates, not functional blockers.
167
+
168
+ ## Scalar values and error provenance
169
+
170
+ The scalar projection functions currently return **debug locations, not decoded COBOL business values**:
171
+
172
+ - `string` and `character`: `from/to/hex`, with zero-based record-relative bytes and exclusive end;
173
+ - `integer` and `float`: numeric encoding of the debug byte range, **not** an integer or floating-point value read from the COBOL field.
174
+
175
+ The separate `@cobol-ts/cobolcodec` package contains production-oriented codec implementations, but these are **not integrated** into the current COBOL projection scalar path.
176
+
177
+ Projection failures report source filename, record number, offending COBOL field or controller and physical bytes. The generic projection framework builds a full indexed application access path **on error**, e.g. `outers[1].middles[1].inners[1].code`. The path can only include the indices known when the failure occurs; setup failures have no runtime occurrence path.
178
+
179
+ ## Relevant tests and next steps
180
+
181
+ - `cobol.odo.projection.spec.ts`: single-level ODO selection.
182
+ - `cobol.multiple.nested.odo.spec.ts`: two sibling nested ODO arrays, zero counts and independence.
183
+ - `cobol.odo.three.level.spec.ts`: three-level projection, literal coordinates, pooled reuse and split buffers.
184
+ - `cobol.odo.positions.spec.ts`: boundary prefixes, nested branches and reuse/cleanup.
185
+ - `cobol.symbolic.allocation.spec.ts`: retained sources, selections and occurrence-index arrays.
186
+ - `cobol.occurrence.context.spec.ts`: enclosing indices and error provenance.
187
+ - `cobol.fixed.array.projection.spec.ts`, `cobol.multiple.nested.arrays.spec.ts`, `cobol.nested.redefines.projection.spec.ts`: fixed arrays, nested arrays and overlays.
188
+ - `customer.fixtures.spec.ts`, `customer.projections.spec.ts`, `cobol.layout.index.spec.ts`, `cobol.debug.range.spec.ts`: fixtures, compiled name index and range helpers.
189
+
190
+ Run the package's Jest suite and TypeScript checks in the real workspace; focused lightweight harness checks are not a substitute for the full suite. Remaining work includes occurrence-local ODO controllers, external variable-record framing, integrating scalar codecs, validation with real client files and heap/throughput benchmarks.
191
+
192
+ Companion walkthrough: *Byte-Backed COBOL Projections — Nested ODOs, Lazy Positions and Reusable Views* (Google Docs).
193
+
194
+
195
+ ## COBOL framing: FB, reserved-capacity ODO, and RDW
196
+
197
+ The Node entry point `@cobol-ts/cursor-loader-cobol/node` exposes
198
+ `readCobolFile({copybook, filename, projection, framing?})`. The same generic
199
+ byte-backed cursor, layout compiler, lazy projection and pooled record holder
200
+ are used for every framing mode:
201
+
202
+ * Omit `framing` for ordinary fixed-block data with a constant compiled copybook
203
+ extent (backward-compatible default).
204
+ * `{kind: 'fixed', recordLength: 8}` supplies a physical record size, e.g. for
205
+ FB records where space is reserved for the **maximum** ODO table capacity.
206
+ The ODO controller still controls the number of *visible* projected entries;
207
+ it does **not** change the physical eight-byte frame.
208
+ * `{kind: 'rdw'}` reads a four-byte unblocked RDW before each COBOL payload.
209
+ Its first two bytes are an unsigned big-endian length **including** the RDW;
210
+ bytes two and three must be zero. The RDW is outside the copybook's logical
211
+ data origin. The current reader does not implement VB block descriptors,
212
+ spanned VBS data, or nonzero RDW control-byte conventions.
213
+
214
+ RDW parsing obtains the header via the existing `readMore()` mechanism even
215
+ when its four bytes span four distinct physical buffers; it establishes the
216
+ physical `endByte` independently of the ODO controller. Copybook offsets and
217
+ ODO count locations begin at the COBOL payload origin, not at the RDW.
218
+ Scalar decoding continues to operate directly on fragmented borrowed buffers.
219
+ No intermediate record or field buffer is constructed.
220
+
221
+ Tests in `cursor-loader-test` cover RDW records with different active ODO
222
+ lengths; explicit FB reserved maximum capacity; corrupt/truncated headers;
223
+ 1-, 2-, 3-, 4-, 7-, and 4096-byte buffers; and an RDW-wrapped copy of the
224
+ externally specified AWS Employee binary data to verify ordinary constant
225
+ scalar offsets. The RDW fixture is **test-authored**, not an original IBM
226
+ variable-record file.
227
+
228
+ ## Optional COBOL diagnostics
229
+
230
+ `scanCobolFile` and `readCobolFile` accept `metrics?: IPutMetrics`. The same instance is passed from the top-level file options into COBOL source details, the per-record ODO cache, physical-record pooling and reusable projections. Compiled-field decoder creation and invocation, scalar field-range resolution, fixed-field fast-path dispatch and generic fixed-path resolution, fixed occurrence visits, symbolic steps, ODO controller reads, cached versus extended boundaries, and ODO cleanup visits are counted separately. Actual visited items in prefix-cache and projection cleanup loops are counted to make possible non-linear work visible. With metrics disabled, no metric names are constructed and no metrics are logged. See `@cobol-ts/metrics` and `cursor-loader-benchmark/README.metrics.md`.
231
+
232
+ ## Selecting a fixed-array representation
233
+
234
+ The compiled COBOL provider may identify an array as eligible for the shared-binding native-array path: fixed positioning, no symbolic length dependency, scalar-only child projections and no more than eight elements. That selection is automatic in the current implementation. The resulting array contains projection **views**, never decoded records. All its children resolve the active borrowed record through one shared binding, with immutable occurrence offsets. Closing the owning lease invalidates their reads without visiting and rebinding every child.
235
+
236
+ The generic lazy Proxy path is still required for larger arrays, ODO-controlled counts and more complex structures. A fixed OCCURS *count* is not proof that a field's physical position is fixed: layout compilation determines eligibility. This distinction also matters when nested fixed arrays occur under symbolic prefixes. Continue using the support matrix and framing sections above as the source of COBOL syntax and file-format coverage.
237
+
238
+ ### Opt-in small-ODO shared bindings
239
+
240
+ `scanCobolFile` and `readCobolFile` accept `experimentalSharedOdoArrays: true`. For a root-level ODO group with fixed-position table origin, fixed-width scalar elements and no more than eight declared occurrences, the provider resolves the controller **once per binding**. It exposes immutable occurrence displacements through retained child views sharing the borrowed record and active count. The public projected array uses native indexing, but decoded values still come directly from the original byte buffers on access.
241
+
242
+ This option does **not** apply to nested OCCURS/ODO tables, ODOs preceded by symbolic-position declarations, non-scalar child projections, or tables above the current eight-element threshold. Those use the lazy Proxy/position machinery unchanged. Changing a bound ODO count by reusing a pooled record requires closing the old lease before rebinding; retained children whose indexes are no longer active reject access rather than exposing stale data. The flag is an experiment and is disabled by default.
package/node.d.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './dist/node';
package/node.js ADDED
@@ -0,0 +1,2 @@
1
+ // Node.js package subpath; the implementation is compiled into dist/node.js.
2
+ module.exports = require('./dist/node.js');
package/package.json CHANGED
@@ -1,6 +1,75 @@
1
1
  {
2
2
  "name": "@cobol-ts/cursor-loader-cobol",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "description": "Fixed-length COBOL byte-backed parser with compiled occurrence paths and debug projections",
4
+ "version": "0.0.2",
5
+ "main": "dist/index",
6
+ "types": "dist/index",
7
+ "browserslist": {
8
+ "development": [
9
+ "last 1 chrome version",
10
+ "last 1 firefox version",
11
+ "last 1 safari version"
12
+ ],
13
+ "production": [
14
+ ">0.2%",
15
+ "not dead",
16
+ "not op_mini all"
17
+ ]
18
+ },
19
+ "dependencies": {
20
+ "@cobol-ts/cursor-loader-types": "0.0.2",
21
+ "@cobol-ts/layout": "0.0.2",
22
+ "@cobol-ts/errors": "0.0.2",
23
+ "@cobol-ts/copybook": "0.0.2",
24
+ "@cobol-ts/size": "0.0.2",
25
+ "@cobol-ts/cursor-projection": "0.0.2",
26
+ "@cobol-ts/cursor-file": "0.0.2",
27
+ "@cobol-ts/arrays": "0.0.2",
28
+ "@cobol-ts/codec": "0.0.2",
29
+ "@cobol-ts/metrics": "0.0.2"
30
+ },
31
+ "devDependencies": {
32
+ "typescript": "^5.2.2",
33
+ "@testing-library/jest-dom": "^6.1.4",
34
+ "@types/jest": "^29.0.0",
35
+ "@types/node": "^14.0.0",
36
+ "jest": "^29.0.0",
37
+ "ts-jest": "^29.0.0"
38
+ },
39
+ "eslintConfig": {
40
+ "extends": [
41
+ "react-app",
42
+ "react-app/jest"
43
+ ],
44
+ "overrides": [
45
+ {
46
+ "files": [
47
+ "**/*.stories.*"
48
+ ],
49
+ "rules": {
50
+ "import/no-anonymous-default-export": "off"
51
+ }
52
+ }
53
+ ]
54
+ },
55
+ "files": [
56
+ "dist/index.js",
57
+ "dist/index.d.ts",
58
+ "dist/src/",
59
+ "build/",
60
+ "dist/node.js",
61
+ "dist/node.d.ts",
62
+ "node.js",
63
+ "node.d.ts"
64
+ ],
65
+ "keywords": [
66
+ "indexing"
67
+ ],
68
+ "license": "MIT",
69
+ "repository": "git@github.com:intellimaintain/intellimaintain.git",
70
+ "scripts": {
71
+ "test": "jest --config jest.config.json --env node",
72
+ "test:watch": "npm run test -- --watch",
73
+ "start": "react-scripts start"
74
+ }
6
75
  }