yggdryl 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
package/README.md CHANGED
@@ -1,30 +1,267 @@
1
- # yggdryl (Node.js)
1
+ # Yggdryl for JavaScript
2
2
 
3
- Node.js bindings for [**yggdryl**](https://github.com/Platob/yggdryl), backed by
4
- the Rust `yggdryl` core crate (via [napi-rs](https://napi.rs)).
3
+ ```javascript
4
+ const { json, toml, yaml } = require('yggdryl')
5
+
6
+ const bytes = json.dumps({ symbol: 'AAPL', price: 224.62 })
7
+ const trade = json.loads(bytes)
8
+ const config = toml.loads('symbol = "AAPL"\nprice = 224.62\n')
9
+ const documents = yaml.loadsAll(Buffer.from('---\nsymbol: AAPL\n---\nsymbol: MSFT\n'))
10
+
11
+ console.assert(Buffer.isBuffer(bytes))
12
+ console.assert(trade.symbol === 'AAPL')
13
+ console.assert(config.symbol === 'AAPL')
14
+ console.assert(documents[1].symbol === 'MSFT')
15
+ ```
16
+
17
+ JSON, YAML, and TOML APIs are byte-first and preserve binary
18
+ values, large integers, dates, maps, sets, and typed arrays. `load` and `dump`
19
+ also accept paths, descriptors, file URLs, and Node or WHATWG streams. Primitive
20
+ strings are content unless they name an existing regular file; `loads` always
21
+ treats them as content. Real paths redirect to Rust reader/writer methods
22
+ without a whole-file JavaScript buffer. Stream overloads are asynchronous and
23
+ apply writable backpressure without closing caller-owned I/O.
24
+
25
+ ```javascript
26
+ const { Readable, Writable } = require('node:stream')
27
+ const { json } = require('yggdryl')
28
+
29
+ async function main() {
30
+ const value = await json.load(Readable.from(['{"id":', '42}']))
31
+ await json.dump(value, new Writable({
32
+ write(chunk, _encoding, done) {
33
+ process.stdout.write(chunk, done)
34
+ },
35
+ }))
36
+ }
37
+
38
+ main()
39
+ ```
40
+
41
+ `loadAll` redirects an async byte source to the lazy `loadAllStream` iterator;
42
+ `dumpAll` redirects a writable destination to `dumpAllStream`. Single-document
43
+ stream reads use one bounded buffer because Node's async reader cannot be
44
+ passed to synchronous Rust `Read`; multi-document reads and writes stay
45
+ incremental. Buffer, ArrayBuffer, SharedArrayBuffer, DataView, and typed-array
46
+ offsets are all preserved exactly.
47
+
48
+ TOML is deliberately single-document and exposes only `loads`, `load`,
49
+ `dumps`, `dump`, `loadStream`, and `dumpStream`. Generic `codec` operations
50
+ infer `.toml` paths in Rust or accept explicit `format: 'toml'` for content.
51
+
52
+ ```javascript
53
+ const { DataType, Field, MediaType, MimeType, Uri } = require('yggdryl')
54
+
55
+ const type = DataType.fromString('struct<symbol:string,price:decimal(18,4)>')
56
+ const coarseClock = DataType.time('milliseconds')
57
+ const preciseClock = DataType.time('nanoseconds')
58
+ const field = new Field('trade', type, false, { source: 'book' })
59
+ field.setTableName('trades')
60
+ field.setParquetFieldId(17)
61
+ field.setLocation('s3://warehouse/trades/data.arrow')
62
+ field.setProperty('postgres', 'type', 'jsonb')
63
+ const file = Uri.fromPath('C:\\data\\trades.arrow')
64
+ const encoded = Uri.fromString('https://example.test/trades.csv.gz')
65
+
66
+ console.assert(Field.fromString(field.toString()).equals(field))
67
+ console.assert(coarseClock.kind === 'time32')
68
+ console.assert(preciseClock.kind === 'time64')
69
+ console.assert(field.parquetFieldId === 17)
70
+ console.assert(field.get('PARQUET:field_id') === '17')
71
+ console.assert(field.location.scheme === 's3')
72
+ console.assert(field.getProperty('postgres', 'type') === 'jsonb')
73
+ console.assert(file.toString() === 'file:///C:/data/trades.arrow')
74
+ console.assert(file.toPath() === 'C:/data/trades.arrow')
75
+ console.assert(encoded.mediaType.base.equals(MimeType.fromString('text/csv')))
76
+ encoded.setMediaType(MediaType.fromParts('application/json', ['application/gzip']))
77
+ console.assert(encoded.fileName === 'trades.json.gz')
78
+ ```
79
+
80
+ The Node-API package exposes native `DataType`, `Field`, `IOBase`, `MimeType`,
81
+ `MediaType`, `Timezone`, `Uri`, `Url`, `Urn`, and `Value` values, the record pair
82
+ `BatchReader` and `RecordOptions`, and the `iceberg` namespace over all of them.
83
+ Recursive parsing, validation, Arrow casting, record scalar conversion, codec
84
+ conversion, ordering, stable hashing, metadata, and path normalization stay in
85
+ Rust.
86
+ `DataType.time(unit)` and `fields.time(name, unit)` require an explicit unit;
87
+ seconds/milliseconds select Time32 and microseconds/nanoseconds select Time64.
88
+ They accept the same native unit aliases as datatype parsing and reject
89
+ interval layouts.
90
+
91
+ ```javascript
92
+ const { Record, fields } = require('yggdryl')
93
+
94
+ const Trade = Record.define('Trade', [
95
+ fields.int64('id'),
96
+ fields.utf8('symbol'),
97
+ fields.decimal128('price', 18, 4),
98
+ ])
99
+ const rows = [
100
+ new Trade({ id: 1n, symbol: 'AAPL', price: 2246200n }),
101
+ new Trade({ id: 2n, symbol: 'MSFT', price: 4187900n }),
102
+ ]
103
+
104
+ const batch = Trade.intoArrowRecordBatch(rows)
105
+ const restored = [...Trade.fromArrowRecordBatch(batch)]
106
+
107
+ console.assert(restored[0].symbol === 'AAPL')
108
+ console.assert(restored[1].price === 4187900n)
109
+ ```
110
+
111
+ Each defined class owns one shared native Record schema/name index. Apache
112
+ Arrow JS conversion is an explicit copied IPC boundary: it never serializes per
113
+ property access and does not claim zero-copy C Data interoperability. Use
114
+ `intoArrowRecordBatches` for bounded output, `fromArrowRecordBatchReader` for
115
+ batch-bounded input, and `intoArrowIPC`/`fromArrowIPC` for every physical layout
116
+ representable by the core `yggdryl::arrow` IPC runtime. The Apache Arrow
117
+ dependency loads only when an Arrow adapter is used.
118
+
119
+ `DataType.castArrowArray`, `Field.castArrowArray`, `DataType.castArrowBatch`,
120
+ and `Field.castArrowBatch` route copied Apache Arrow JS holders through the one
121
+ native `yggdryl::arrow` cast engine. Exact no-op casts preserve the original
122
+ Vector or RecordBatch identity; changed outputs follow `{safe: true}` by
123
+ default and never use a JavaScript conversion table.
124
+
125
+ Tabular cursor reads validate the declared source schema before any optional
126
+ target projection. Getters use a non-consuming snapshot. Overwrite, append,
127
+ indexed set, and positional upsert compute a complete validated replacement
128
+ before invoking one private atomic overwrite-all hook. `overwriteRecords`,
129
+ `appendRecords`, and `upsertRecords` provide the matching class-bound bulk
130
+ helpers and validate their options and source-to-backend cast plan before
131
+ consuming a one-shot row iterable. Dataset iterables likewise stop at their
132
+ first incompatible batch. Numeric selectors and matching table URLs with a
133
+ `#N` fragment address a batch; the exact table URL addresses the whole resource.
134
+ Tabular and dataset schema getters retain a stable canonical Arrow JS identity
135
+ and fingerprint-repair caller mutation from native state before reuse.
136
+
137
+ Run `npm run bench:record` or `npm run bench:tabular` to measure native Record
138
+ behavior and the copied-IPC read, cast, overwrite, indexed mutation, in-memory
139
+ table, and dataset paths separately. Set `YGGDRYL_BENCH_ITERATIONS` to change the
140
+ default sample count.
141
+
142
+ ```javascript
143
+ const { Record, fields } = require('yggdryl')
5
144
 
6
- ## Build
145
+ const payload = fields.struct('payload', [
146
+ fields.int64('count'),
147
+ fields.utf8('note', { nullable: true }),
148
+ ])
149
+ const value = payload.defaultJSValue()
7
150
 
8
- ```bash
9
- npm install
10
- npm run build # napi build --platform --release
11
- npm test # node --test
151
+ console.assert(value instanceof Record)
152
+ console.assert(value.count === 0n && value.note === null)
153
+ console.assert(payload.defaultJSHint().constructor instanceof Function)
154
+ console.assert(fields.int32('id').defaultArrowScalar() === 0)
155
+ console.assert(
156
+ fields.uint8('small').toSchemeCompat('spark').dataType.kind === 'int16',
157
+ )
12
158
  ```
13
159
 
14
- ## Usage
160
+ Defaults are computed by the Rust core and projected through the same typed
161
+ path as Record values. Struct defaults remain schema-bound native Records;
162
+ runtime hints use a bounded native constructor category, are frozen and
163
+ cached, and do not materialize a default value or exact Field schema.
164
+ For a Struct Field, that metadata-free hint constructor is a logical layout
165
+ hint through the generic `Record` class, so nested metadata is not exposed by
166
+ the hint. The exact default Record still retains its complete outer Field and
167
+ uses its own generated class. Hint identity is wrapper-local, not a global
168
+ interning promise for equivalent schemas.
169
+ Arrow scalars use one copied one-row IPC projection into Apache Arrow JS, and
170
+ unsupported Arrow JS layouts fail without introducing a second scalar model.
171
+ Run `npm run bench:defaults` for JavaScript defaults, cached hints,
172
+ compatibility normalization, and Arrow-scalar IPC materialization.
15
173
 
16
174
  ```javascript
17
- const { Uri, Url } = require('yggdryl')
175
+ const { Field, MediaType, MimeType } = require('yggdryl')
18
176
 
19
- const uri = new Uri('urn:isbn:0451450523')
20
- console.log(uri.scheme) // urn
21
- console.log(uri.path) // isbn:0451450523
177
+ const media = MediaType.fromParts(
178
+ MimeType.CSV,
179
+ new Set([MimeType.GZIP, MimeType.ZSTD]),
180
+ )
181
+ const field = new Field('payload', 'binary', false, {
182
+ 'HTTPS:Content-Type': 'text/csv; charset=utf-8',
183
+ })
184
+ field.setMediaType(media)
22
185
 
23
- const url = new Url('https://user:pw@example.com:8443/api?v=1#top')
24
- console.log(url.host) // example.com
25
- console.log(url.port) // 8443
26
- console.log(url.username) // user
27
- console.log(url.toString()) // https://user:pw@example.com:8443/api?v=1#top
186
+ console.assert(field.mimeType.equals(MimeType.CSV))
187
+ console.assert(field.contentEncoding === 'gzip, zstd')
188
+ console.assert(field.get('HTTPS:CONTENT-TYPE') === 'text/csv')
28
189
  ```
29
190
 
30
- Invalid input throws.
191
+ `MimeType` exposes every native known value as a frozen class constant and
192
+ accepts custom validated MIME names. `MediaType()` defaults to octet-stream;
193
+ its iterable adapters consume once and `encodings` returns a detached Array.
194
+ HTTP and HTTPS Field input shares canonical lowercase `http:*` Arrow metadata.
195
+ Raw headers preserve parameters, while typed MIME/media, exact unsigned
196
+ content length (`bigint`), and absolute HTTP Location accessors remain native.
197
+ Media pair updates are atomic and cache-aware.
198
+
199
+ ```javascript
200
+ const { DataType, Field, fields } = require('yggdryl')
201
+
202
+ const id = fields.int32('id', { nullable: false })
203
+ const tags = fields.list('tags', fields.utf8('item'))
204
+ const row = DataType.fromFields([id, tags])
205
+
206
+ console.assert(id instanceof Field)
207
+ console.assert(tags.dataType.kind === 'list')
208
+ console.assert(row.kind === 'struct')
209
+ console.assert(id.showDiff(id) === '✓ equal')
210
+ console.assert([...id.showDiffs(fields.int64('id'))].length > 0)
211
+ ```
212
+
213
+ The `fields` namespace covers every datatype variant and returns the same
214
+ generic native `Field`; TypeScript retains the exact kind/value view. Equality
215
+ can ignore recursive metadata with `equals(other, false)`, while `showDiffs`
216
+ returns a UTF-8 iterator and `showDiff` joins its terminal-readable lines.
217
+
218
+ Finite alternatives can use `DataType.variant(fields)` or
219
+ `fields.variant(name, fields, options)`. Both assign dense Arrow Union type IDs
220
+ in declaration order and retain the ordinary `union` kind; Record values use
221
+ the explicit `{ typeId, value }` shape. Iceberg/Parquet Variant and PostgreSQL
222
+ `json/jsonb` remain explicit adapter formats, not aliases for this tagged Arrow
223
+ layout.
224
+
225
+ ```javascript
226
+ const fs = require('node:fs')
227
+ const os = require('node:os')
228
+ const path = require('node:path')
229
+ const arrow = require('apache-arrow')
230
+ const { BatchReader, Field, IOBase, fields, iceberg } = require('yggdryl')
231
+
232
+ // A location is absolute: a handle is a URL, and a relative name names no root.
233
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'yggdryl-'))
234
+
235
+ const schema = iceberg.assignFieldIds(
236
+ fields.struct('row', [Field.from('id: int64'), Field.from('venue: utf8')], {
237
+ nullable: false,
238
+ }),
239
+ )
240
+ const rows = new arrow.Table({
241
+ id: arrow.vectorFromArray([1n, 2n], new arrow.Int64()),
242
+ venue: arrow.vectorFromArray(['XNAS', 'XNYS'], new arrow.Utf8()),
243
+ })
244
+
245
+ // A handle reads and writes records through the encoding its name declares.
246
+ const file = new IOBase(path.join(root, 'trades.parquet'))
247
+ file.writeArrowBatchReader(BatchReader.from(rows))
248
+ console.assert(file.readArrowBatchReader().toTable().numRows === 2)
249
+
250
+ // An Iceberg table is a folder, and a folder is all it ever touches.
251
+ const table = iceberg.Table.create(path.join(root, 'trades'), schema, ['venue'])
252
+ table.append(rows)
253
+ console.assert(table.currentSnapshot.operation === 'append')
254
+ console.assert(table.dataFiles().length === 2)
255
+ ```
256
+
257
+ `BatchReader` is the one record shape: a read returns one, a write consumes one,
258
+ and each batch crosses as its own Apache Arrow IPC stream, because Arrow JS has
259
+ no C Data consumer. `BatchReader.from` accepts another reader, an Arrow JS
260
+ `Table` or `RecordBatch`, an array of batches, or Arrow IPC bytes. The encoding
261
+ is never an argument: `recordOptions()` derives it from the handle's media type,
262
+ covering Arrow IPC and Apache Parquet.
263
+
264
+ Use the complete [JavaScript guide](https://platob.github.io/yggdryl/extensions/javascript/)
265
+ for schema and identifier APIs, the [Record and Arrow guide](https://platob.github.io/yggdryl/extensions/javascript/records/)
266
+ for typed rows and copied IPC interoperability, and the [codec guide](https://platob.github.io/yggdryl/extensions/javascript/codecs/)
267
+ for safe class registries, generic format inference, and streaming.
@@ -0,0 +1,133 @@
1
+ 'use strict'
2
+
3
+ const fs = require('node:fs')
4
+ const os = require('node:os')
5
+ const path = require('node:path')
6
+ const { performance } = require('node:perf_hooks')
7
+ const { Readable, Writable } = require('node:stream')
8
+ const { Value, codec, json, toml, yaml } = require('yggdryl')
9
+
10
+ const value = {
11
+ trades: Array.from({ length: 1_000 }, (_, index) => ({
12
+ id: BigInt(index),
13
+ price: index / 100,
14
+ symbol: `SYM${index % 20}`,
15
+ })),
16
+ }
17
+ const exotic = {
18
+ bytes: Buffer.from([0, 1, 127, 255]),
19
+ map: new Map([[{ venue: 'XPAR' }, new Set([1n, 2n])]]),
20
+ nan: Number.NaN,
21
+ regexp: /a\/b/giu,
22
+ typed: new Uint16Array([0, 65535]),
23
+ }
24
+ // The temporal and decimal boundary is its own cost: each value crosses as
25
+ // parts rather than as one number, and a Date is rebuilt on the way back.
26
+ const temporal = {
27
+ at: Value.timestamp(1700000000000000n, 'us', 'UTC'),
28
+ date: new Date('2026-08-15T12:30:00.000Z'),
29
+ on: Value.date(19723),
30
+ price: Value.decimal(-1050n, 2),
31
+ sinceMidnight: Value.time(45296000000n, 'us'),
32
+ took: Value.duration(90n, 's'),
33
+ }
34
+ let deep = { leaf: true }
35
+ for (let depth = 0; depth < 24; depth += 1) deep = { nested: deep }
36
+
37
+ function measure(name, bytes, iterations, operation) {
38
+ for (let index = 0; index < 5; index += 1) operation()
39
+ const started = performance.now()
40
+ for (let index = 0; index < iterations; index += 1) operation()
41
+ const elapsed = performance.now() - started
42
+ const throughput = (bytes * iterations) / (elapsed / 1_000) / (1024 * 1024)
43
+ console.log(
44
+ `${name}: ${(elapsed / iterations).toFixed(3)} ms/op, ${throughput.toFixed(1)} MiB/s`,
45
+ )
46
+ }
47
+
48
+ async function measureAsync(name, bytes, iterations, operation) {
49
+ for (let index = 0; index < 2; index += 1) await operation()
50
+ const started = performance.now()
51
+ for (let index = 0; index < iterations; index += 1) await operation()
52
+ const elapsed = performance.now() - started
53
+ const throughput = (bytes * iterations) / (elapsed / 1_000) / (1024 * 1024)
54
+ console.log(
55
+ `${name}: ${(elapsed / iterations).toFixed(3)} ms/op, ${throughput.toFixed(1)} MiB/s`,
56
+ )
57
+ }
58
+
59
+ async function main() {
60
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'yggdryl-node-bench-'))
61
+ try {
62
+ for (const [name, format, extension] of [
63
+ ['json', json, 'json'],
64
+ ['toml', toml, 'toml'],
65
+ ['yaml', yaml, 'yaml'],
66
+ ]) {
67
+ const encoded = format.dumps(value)
68
+ const text = encoded.toString('utf8')
69
+ const padded = Buffer.concat([Buffer.from('xx'), encoded, Buffer.from('yy')])
70
+ const view = new DataView(
71
+ padded.buffer,
72
+ padded.byteOffset + 2,
73
+ encoded.byteLength,
74
+ )
75
+ const file = path.join(directory, `value.${extension}`)
76
+ fs.writeFileSync(file, encoded)
77
+
78
+ // Keep these group spellings stable so before/after runs remain comparable.
79
+ measure(`${name}/slice`, encoded.length, 100, () => format.loads(encoded))
80
+ measure(`${name}/string`, encoded.length, 100, () => format.loads(text))
81
+ measure(`${name}/offset_view`, encoded.length, 100, () => format.loads(view))
82
+ measure(`${name}/reader_path`, encoded.length, 100, () => format.load(file))
83
+ measure(`${name}/vector_emit`, encoded.length, 100, () => format.dumps(value))
84
+ measure(`${name}/writer_path`, encoded.length, 100, () => format.dump(value, file))
85
+ await measureAsync(`${name}/reader_stream`, encoded.length, 25, () =>
86
+ format.load(Readable.from([encoded])),
87
+ )
88
+ await measureAsync(`${name}/writer_stream`, encoded.length, 25, () =>
89
+ format.dump(
90
+ value,
91
+ new Writable({ write(_chunk, _encoding, done) { done() } }),
92
+ ),
93
+ )
94
+
95
+ const exoticEncoded = format.dumps(exotic)
96
+ measure(`${name}/exotic_values`, exoticEncoded.length, 50, () =>
97
+ format.loads(exoticEncoded),
98
+ )
99
+ const temporalEncoded = format.dumps(temporal)
100
+ measure(`${name}/temporal_values`, temporalEncoded.length, 50, () =>
101
+ format.loads(temporalEncoded),
102
+ )
103
+ const deepEncoded = format.dumps(deep)
104
+ measure(`${name}/deep_nested`, deepEncoded.length, 50, () =>
105
+ format.loads(deepEncoded),
106
+ )
107
+ }
108
+
109
+ // The pivot is the conversion every load and dump crosses, measured on its
110
+ // own against the same payload so a codec number can be read against it.
111
+ const pivotBytes = json.dumps(value).length
112
+ measure('pivot/from_js', pivotBytes, 100, () => Value.fromJs(value))
113
+ const pivot = Value.fromJs(value)
114
+ measure('pivot/as_js', pivotBytes, 100, () => pivot.asJs())
115
+
116
+ const inferred = json.dumps(value)
117
+ measure('generic/content_sniff', inferred.length, 100, () => codec.from(inferred))
118
+ measure('generic/explicit_json', inferred.length, 100, () =>
119
+ codec.from(inferred, { format: 'json' }),
120
+ )
121
+ const inferredToml = toml.dumps(value)
122
+ measure('generic/content_infer_toml', inferredToml.length, 50, () =>
123
+ codec.from(inferredToml),
124
+ )
125
+ } finally {
126
+ fs.rmSync(directory, { force: true, recursive: true })
127
+ }
128
+ }
129
+
130
+ main().catch((error) => {
131
+ console.error(error)
132
+ process.exitCode = 1
133
+ })