rida-format 0.3.3 → 2.0.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/README.md CHANGED
@@ -1,84 +1,1341 @@
1
- # RIDA Node.js tools — 0.3.3
1
+ # RIDA for Node.js
2
2
 
3
- This folder contains a Node.js command-line reader and builder for RIDA 0.3.3 files. It reads the same data and index format as the Python release. It does not convert or rewrite an existing dataset when reading it.
3
+ RIDA means **Range Indexed Data Access**. `rida-format` is the Node.js reader,
4
+ builder, and command-line tool for RIDA datasets. It turns JSON records into a
5
+ small set of files: one data file holds the values, and an index tells a reader
6
+ where each value lives. A reader can then ask an HTTP server or CDN for only the
7
+ bytes needed for a lookup.
4
8
 
5
- ## Install for local use
9
+ The npm package name is **`rida-format`**. The package version is shown in
10
+ `package.json` and with the command's `--version` option.
6
11
 
7
- From this folder:
12
+ ## What RIDA does
13
+
14
+ A normal JSON download usually transfers a whole document or record even when
15
+ an app needs one field. RIDA separates the values from their addresses. The
16
+ reader uses a local index to find a value's byte range, then reads that range
17
+ from the data file.
18
+
19
+ For a local dataset, the reader opens the data and index files on disk. For a
20
+ remote dataset, the data URL must point to a server or CDN that supports HTTP
21
+ byte-range requests and returns `206 Partial Content`. RIDA does not upload
22
+ files or provide hosting; you choose where the data file is stored and served.
23
+
24
+ RIDA is useful when an app often needs one or a few fields from a large,
25
+ mostly-static collection. The amount saved depends on the size of the requested
26
+ values, the number of fields requested, and the host's request and transfer
27
+ pricing. A range read still has HTTP request and response headers.
28
+
29
+ ## The dataset files
30
+
31
+ A build may create up to four files. The data, index, and map are not all sent
32
+ to the CDN:
33
+
34
+ | File | What it contains | Where it is normally kept |
35
+ | --- | --- | --- |
36
+ | `Name.rida` | Stored record-field values | Server, object storage, or CDN |
37
+ | `NameIndex.rida` | Catalog that maps record IDs and field names to byte ranges, plus format metadata and a SHA-256 digest | With the reader; for a remote URL, it can be fetched from the matching URL or supplied separately |
38
+ | `NameMap.json` | Human-readable folder names for numbered IDs and a field-name map, when a folder build needs one | With the reader |
39
+ | `NameKey.rida` | A generated 256-bit key, only when encryption is enabled | Private; never publish it beside a public data file |
40
+
41
+ The exact output names follow the chosen data filename. For example, an
42
+ encrypted build of the nested multilingual pages shown below produces:
43
+
44
+ ```text
45
+ WebsiteData.rida the stored page values
46
+ WebsiteIndex.rida the catalogue used to locate those values
47
+ WebsiteMap.json the folder names behind numbered record IDs
48
+ WebsiteKey.rida the key used to decrypt the values
49
+ ```
50
+
51
+ The key file is created only when the builder generates a new encryption key.
52
+ If you supply an existing key, keep that key separately. A map is created when
53
+ a numbered folder build has folder names to preserve; datasets with named IDs
54
+ or no nested folder paths may not need one.
55
+
56
+ ### What each file does during a lookup
57
+
58
+ **Data:** `WebsiteData.rida` holds the actual values: the English, Hindi, Urdu,
59
+ and Spanish page content, for example. Put this file on your server or CDN.
60
+ It can be large because the reader requests only the ranges it needs.
61
+
62
+ **Catalogue:** `WebsiteIndex.rida` is the index file containing the catalogue.
63
+ Given a record ID and a field name, it tells the reader the starting byte and
64
+ stored length of that value in the data file. It also identifies the codec and
65
+ encryption settings. The catalogue is what makes a direct range lookup possible;
66
+ the app does not scan the data file to find a page or language.
67
+
68
+ **Map:** `WebsiteMap.json` associates numbered folder prefixes with readable
69
+ names and lists the field-name mapping. For example, it connects the prefix
70
+ `1/1/1/1` with `guides/getting-started/installation/pages`. You can use the map
71
+ to resolve that folder path and list its record IDs instead of guessing how
72
+ many `1/` components to write. The catalogue supplies the actual record IDs;
73
+ the map gives their folder prefixes human-readable names. It does not store
74
+ page content or byte locations, and it does not preserve original JSON
75
+ filenames as a separate filename list.
76
+
77
+ **Key:** `WebsiteKey.rida` lets the reader decrypt encrypted field values.
78
+ It is not needed for an unencrypted dataset and is not a storage-provider API
79
+ key. Keep it private and provide it to an authorised reader. The key does not
80
+ choose a record or calculate its byte range; the map and catalogue handle
81
+ those jobs.
82
+
83
+ ### Find a record without guessing its numeric path
84
+
85
+ For the nested pages example, keep the matching map and index beside the local
86
+ data file. The reader discovers those companions automatically:
87
+
88
+ ```js
89
+ import { RidaReader } from "rida-format";
90
+
91
+ const reader = await RidaReader.open("./WebsiteData.rida");
92
+ try {
93
+ const prefix = reader.resolve("guides", "getting-started", "installation", "pages");
94
+ if (!prefix) throw new Error("The requested folder is not in this map");
95
+
96
+ console.log(prefix); // "1/1/1/1" for this example
97
+ console.log(reader.recordsUnder(prefix)); // the four page record IDs
98
+ console.log(reader.fields); // english, hindi, urdu, spanish
99
+
100
+ const spanish = await reader.get(
101
+ "guides/getting-started/installation/pages/2",
102
+ "spanish",
103
+ );
104
+ console.log(spanish);
105
+ } finally {
106
+ await reader.close();
107
+ }
108
+ ```
109
+
110
+ This example opens an unencrypted dataset. For an encrypted build, also supply
111
+ its key using the `key` option, as shown in [Encryption and keys](#encryption-and-keys).
112
+ For a remote data URL, supply the map explicitly; it is not discovered from
113
+ the remote URL automatically. Keep the data, catalogue, and map from the same
114
+ build together, because rebuilding a changed folder tree can change the IDs
115
+ and byte addresses.
116
+
117
+ The index contains a 72-byte header followed by a compressed catalog. The
118
+ header has no text label or descriptive header block; it contains fixed binary
119
+ fields used by the reader. The data file contains encoded values, not a copy of
120
+ the input JSON document. The map contains folder and field labels; it is not
121
+ needed to look up a record by its numeric ID.
122
+
123
+ ## Requirements
124
+
125
+ - Node.js **20 or newer**.
126
+ - npm, which is included with the standard Node.js installers.
127
+ - The package dependency `lzma-native`, used to read and write the XZ/LZMA
128
+ compressed catalog. It includes native code. Installation uses a compatible
129
+ prebuilt binary when available; some systems may need native build tools.
130
+ - No database, cloud SDK, account, or server process is required by the
131
+ library. Remote reads use Node.js `fetch` and ordinary HTTP requests.
132
+
133
+ ## Install from npm
134
+
135
+ Install the package in the Node.js project that will use RIDA:
136
+
137
+ ```sh
138
+ npm install rida-format
139
+ ```
140
+
141
+ To see the command-line help after installation:
142
+
143
+ ```sh
144
+ npx rida-format --help
145
+ ```
146
+
147
+ To check the installed package version:
148
+
149
+ ```sh
150
+ npx rida-format --version
151
+ ```
152
+
153
+ The examples below use `npx rida-format`. If you install the package globally,
154
+ you can run the command directly as `rida-format --help`.
155
+
156
+ ```sh
157
+ npm install -g rida-format
158
+ rida-format --help
159
+ ```
160
+
161
+ If you are working inside a downloaded copy of the package source instead of
162
+ installing it as a dependency, install its dependencies and run its CLI file:
8
163
 
9
164
  ```sh
10
165
  npm install
11
- node ./src/cli.js --help
166
+ npm run start -- --help
12
167
  ```
13
168
 
14
- Node.js 20 or newer is required. `lzma-native` reads and writes the XZ catalog. It includes native code; installation uses a prebuilt binary when available and may need a compiler on other systems.
169
+ ## Input JSON
170
+
171
+ The builder accepts either a folder of record files or one large JSON file.
172
+
173
+ ### Folder of JSON records
174
+
175
+ Use a folder when each record is already saved as its own JSON file. This works
176
+ for many kinds of mostly-static JSON data: product catalogues, help articles,
177
+ public directories, app configuration snapshots, or archived sensor readings.
178
+ The records do not have to describe the same subject as long as your app has a
179
+ reason to publish and read them as one dataset.
180
+
181
+ RIDA reads each visible `.json` file as one record; the filename is not treated
182
+ as the record's JSON content. Nested folders are searched too. File extensions
183
+ are case-insensitive, and files or folders whose names start with `.` are
184
+ skipped.
185
+
186
+ For example, this folder contains three records:
187
+
188
+ ```text
189
+ records/
190
+ └── catalogue-export/
191
+ ├── accessories/
192
+ │ ├── SKU-1001.json
193
+ │ └── SKU-1002.json
194
+ └── furniture/
195
+ └── SKU-1001.json
196
+ ```
197
+
198
+ Every file must have a JSON object at its top level. The object is one record;
199
+ its keys are field names and its values are the field contents. For example,
200
+ `records/catalogue-export/accessories/SKU-1001.json` can contain:
201
+
202
+ ```json
203
+ {
204
+ "sku": "SKU-1001",
205
+ "name": "Desk lamp",
206
+ "price": 1299,
207
+ "available": true,
208
+ "details": { "colour": "black", "warranty_months": 12 }
209
+ }
210
+ ```
211
+
212
+ Strings, numbers, booleans, `null`, arrays, and nested objects are all valid
213
+ field values. The whole file must be valid JSON: comments, trailing commas,
214
+ `NaN`, and `Infinity` are not accepted. An empty file, a top-level array, or a
215
+ top-level string is not a record file; use the single-file array format below
216
+ if your source is an array of records.
217
+
218
+ Build the folder like this:
219
+
220
+ ```sh
221
+ npx rida-format scan ./records
222
+ npx rida-format build ./records --output ./CatalogueData.rida
223
+ ```
224
+
225
+ `scan` reports how many records and fields it found and which field names are
226
+ available. It only reads the input and does not create output files. `build`
227
+ then reads the records and creates the data file, matching index, and map when
228
+ the folder names need one. It does not modify the source JSON files, and it
229
+ will stop rather than overwrite an output file that already exists.
230
+
231
+ ### Folder names and record IDs
232
+
233
+ By default, folder records receive numeric IDs derived from their folder path
234
+ and their position among files in that folder. For example, records inside
235
+ `accessories/` and `furniture/` get distinct IDs even when both contain a file
236
+ named `SKU-1001.json`. The map file connects generated folder prefixes back to
237
+ their original names and also keeps the field-name mapping. Keep
238
+ `CatalogueMap.json` with the app when you want to resolve names; it is not
239
+ required for a lookup that already has the numeric record ID.
240
+
241
+ Treat numbered IDs as positions in the input tree. If you add, remove, rename,
242
+ or reorder folders or files, rebuild and distribute the matching index and map
243
+ with the data file; old IDs may point to different records. Keep the input tree
244
+ unchanged when you need IDs to remain consistent across builds.
245
+
246
+ If the JSON filenames are already meaningful IDs, use `--named-ids` to use
247
+ each filename without its `.json` extension. A product export might look like
248
+ this:
249
+
250
+ ```text
251
+ named-records/
252
+ ├── SKU-1001.json
253
+ └── SKU-1002.json
254
+ ```
255
+
256
+ ```sh
257
+ npx rida-format build ./named-records --named-ids --output ./CatalogueData.rida
258
+ npx rida-format get ./CatalogueData.rida SKU-1001 price
259
+ ```
260
+
261
+ If two files have the same basename, RIDA makes the IDs unique by adding a
262
+ suffix, such as `1` and `1-2`. Named IDs do not preserve folder names as
263
+ lookupable prefixes; choose numbered IDs when the app should navigate by the
264
+ folder hierarchy.
265
+
266
+ ### Deeply nested folders: a five-part record ID
267
+
268
+ Folders can have several levels. A device-data export, for example, might
269
+ organise records by region, city, device, and date:
270
+
271
+ ```text
272
+ sensor-export/
273
+ └── europe/
274
+ └── berlin/
275
+ └── device-001/
276
+ └── 2026-10-01/
277
+ └── 1.json
278
+ ```
279
+
280
+ Select the source folder itself with `--records-dir .` to retain this entire
281
+ hierarchy beneath that root:
282
+
283
+ ```sh
284
+ npx rida-format scan ./sensor-export --records-dir .
285
+ npx rida-format build ./sensor-export --records-dir . --output ./SensorsData.rida
286
+ ```
287
+
288
+ For this tree, with one child at each level and one record file, the record ID
289
+ is `1/1/1/1/1`. The first four numbers identify folders; the last identifies
290
+ the record inside the final folder. The source root `sensor-export/` is not
291
+ another ID component. Use the ID without a leading slash.
292
+
293
+ The generated `SensorsMap.json` records the folder names:
294
+
295
+ ```json
296
+ {
297
+ "version": 1,
298
+ "records": 1,
299
+ "paths": {
300
+ "1": "europe",
301
+ "1/1": "berlin",
302
+ "1/1/1": "device-001",
303
+ "1/1/1/1": "2026-10-01"
304
+ },
305
+ "fields": {
306
+ "1": "temperature",
307
+ "2": "diagnostics",
308
+ "3": "history"
309
+ }
310
+ }
311
+ ```
312
+
313
+ Those example field entries correspond to the record shown below. Real IDs
314
+ and map entries depend on the folders and files in your actual input. More
315
+ folder levels produce longer IDs; five components are an example, not a format
316
+ limit. Folder depth does not make a lookup download the surrounding folders
317
+ or records: the index still identifies the requested field's range directly.
318
+ Normal filesystem path limits and available memory still apply.
319
+
320
+ The same structure can organise other datasets:
321
+
322
+ | Use case | Example record path beneath the source root | Field an app might request |
323
+ | --- | --- | --- |
324
+ | Product catalogue | `region/category/brand/model/1.json` | `price`, `availability`, or `specifications` |
325
+ | Help centre | `language/product/version/topic/1.json` | `answer` or `steps` |
326
+ | Public directory | `country/state/city/category/1.json` | `address` or `opening_hours` |
327
+ | Configuration snapshots | `environment/service/version/region/1.json` | `settings` |
328
+ | Archived device readings | `region/city/device/date/1.json` | `temperature` or `diagnostics` |
329
+
330
+ The subject does not change the lookup: the app supplies a record ID and a
331
+ field name. Folder names provide organisation, and the map preserves that
332
+ organisation for the reader.
333
+
334
+ ### A field can contain a complete object or array
335
+
336
+ Deep folders and nested JSON are separate things. Folders determine record
337
+ IDs. Within each record, RIDA stores every **top-level field value** as a
338
+ separate value, including any nested objects or arrays inside it. For example,
339
+ the sensor record above can contain:
340
+
341
+ ```json
342
+ {
343
+ "temperature": 24.6,
344
+ "diagnostics": {
345
+ "battery_percent": 82,
346
+ "firmware": "2.4.1",
347
+ "status": "healthy",
348
+ "network": { "signal_dbm": -61, "connected": true }
349
+ },
350
+ "history": [
351
+ { "time": "10:00", "temperature": 24.1 },
352
+ { "time": "10:05", "temperature": 24.6 }
353
+ ]
354
+ }
355
+ ```
356
+
357
+ Read just the temperature:
358
+
359
+ ```sh
360
+ npx rida-format get ./SensorsData.rida 1/1/1/1/1 temperature
361
+ ```
362
+
363
+ Read the complete diagnostics object, including its nested `network` object:
364
+
365
+ ```sh
366
+ npx rida-format get ./SensorsData.rida 1/1/1/1/1 diagnostics
367
+ ```
368
+
369
+ The result contains all the diagnostics shown above. RIDA reads the stored
370
+ range for `diagnostics`, decompresses it if needed, decrypts it when a key is
371
+ required, and returns the complete JSON value. It does not need to fetch
372
+ `temperature` or `history` for that call. The same lookup works against a CDN:
373
+
374
+ ```sh
375
+ npx rida-format get https://cdn.example.com/SensorsData.rida 1/1/1/1/1 diagnostics \
376
+ --index ./SensorsIndex.rida
377
+ ```
378
+
379
+ A range does not have a fixed tiny size. It contains however many stored bytes
380
+ that field needs. A long article, detailed specifications object, or large
381
+ history array is returned in full when you ask for that field. Compression may
382
+ make its transferred bytes smaller than its decoded JSON; encryption adds
383
+ nonce and authentication bytes. A large field still requires a correspondingly
384
+ large read, and the current builder must be able to fit one record in memory.
385
+
386
+ RIDA does not automatically turn nested keys into independent fields. In the
387
+ example, `diagnostics.network.signal_dbm` is inside `diagnostics`; it is not a
388
+ separately indexed field. If your app often needs only that one value, give it
389
+ its own top-level key before building, for example:
390
+
391
+ ```json
392
+ {
393
+ "temperature": 24.6,
394
+ "battery_percent": 82,
395
+ "signal_dbm": -61,
396
+ "connected": true
397
+ }
398
+ ```
399
+
400
+ Now a `get` for `signal_dbm` reads only that field's stored value. A dotted
401
+ top-level key such as `"network.signal_dbm"` is also allowed, but it is a literal
402
+ field name, not an instruction to traverse a nested object. Choose field
403
+ boundaries around what your screens actually need: one whole object when the
404
+ screen needs all its details, separate fields when screens need small pieces.
405
+
406
+ To read several fields or the entire record, use:
407
+
408
+ ```sh
409
+ npx rida-format get-many ./SensorsData.rida 1/1/1/1/1 temperature diagnostics
410
+ npx rida-format record ./SensorsData.rida 1/1/1/1/1
411
+ ```
412
+
413
+ Multi-field reads may merge nearby ranges. A whole-record read returns all
414
+ present fields, so its transfer is larger than reading one small field.
415
+
416
+ ### Complete multilingual pages inside nested folders
417
+
418
+ A documentation site or mobile app can keep each page as one record, with
419
+ separate language fields inside that record. For example:
420
+
421
+ ```text
422
+ site-content/
423
+ └── guides/
424
+ └── getting-started/
425
+ └── installation/
426
+ └── pages/
427
+ ├── 1.json
428
+ ├── 2.json
429
+ ├── 3.json
430
+ └── 4.json
431
+ ```
432
+
433
+ Here there are four page records, not sixteen language records. Each file can
434
+ contain `english`, `hindi`, `urdu`, and `spanish`. Each language can hold a
435
+ complete page object with a title, paragraphs, steps, and other JSON content.
436
+ For example, `pages/2.json` could contain:
437
+
438
+ ```json
439
+ {
440
+ "english": {
441
+ "title": "Install the application",
442
+ "paragraphs": [
443
+ "Download the installer for your operating system.",
444
+ "Open the installer and follow the instructions."
445
+ ],
446
+ "steps": ["Choose a folder", "Finish installation", "Open the application"]
447
+ },
448
+ "hindi": {
449
+ "title": "ऐप्लिकेशन इंस्टॉल करें",
450
+ "paragraphs": [
451
+ "अपने ऑपरेटिंग सिस्टम के लिए इंस्टॉलर डाउनलोड करें।",
452
+ "इंस्टॉलर खोलें और निर्देशों का पालन करें।"
453
+ ],
454
+ "steps": ["फ़ोल्डर चुनें", "इंस्टॉलेशन पूरा करें", "ऐप्लिकेशन खोलें"]
455
+ },
456
+ "urdu": {
457
+ "title": "ایپلیکیشن انسٹال کریں",
458
+ "paragraphs": [
459
+ "اپنے آپریٹنگ سسٹم کے لیے انسٹالر ڈاؤن لوڈ کریں۔",
460
+ "انسٹالر کھولیں اور ہدایات پر عمل کریں۔"
461
+ ],
462
+ "steps": ["فولڈر منتخب کریں", "انسٹالیشن مکمل کریں", "ایپلیکیشن کھولیں"]
463
+ },
464
+ "spanish": {
465
+ "title": "Instalar la aplicación",
466
+ "paragraphs": [
467
+ "Descarga el instalador para tu sistema operativo.",
468
+ "Abre el instalador y sigue las instrucciones."
469
+ ],
470
+ "steps": ["Elige una carpeta", "Completa la instalación", "Abre la aplicación"]
471
+ }
472
+ }
473
+ ```
474
+
475
+ The other files use the same language fields for their own page content. Build
476
+ all four pages while retaining the folder hierarchy:
477
+
478
+ ```sh
479
+ npx rida-format build ./site-content --records-dir . --output ./WebsiteData.rida
480
+ ```
481
+
482
+ For this exact tree, the four folder components form the prefix `1/1/1/1`, and
483
+ the last component selects a page:
484
+
485
+ | Source file | Record ID |
486
+ | --- | --- |
487
+ | `guides/getting-started/installation/pages/1.json` | `1/1/1/1/1` |
488
+ | `guides/getting-started/installation/pages/2.json` | `1/1/1/1/2` |
489
+ | `guides/getting-started/installation/pages/3.json` | `1/1/1/1/3` |
490
+ | `guides/getting-started/installation/pages/4.json` | `1/1/1/1/4` |
491
+
492
+ Fetch page 2 in Spanish:
493
+
494
+ ```sh
495
+ npx rida-format get ./WebsiteData.rida 1/1/1/1/2 spanish
496
+ ```
497
+
498
+ This returns the complete Spanish value: its title, both paragraphs, and all
499
+ three steps. It reads the stored range for `spanish` from page 2. It does not
500
+ need the English, Hindi, or Urdu values, or pages 1, 3, and 4. With the matching
501
+ map loaded, a readable folder path also works:
502
+
503
+ ```sh
504
+ npx rida-format get ./WebsiteData.rida guides/getting-started/installation/pages/2 spanish
505
+ ```
506
+
507
+ Upload `WebsiteData.rida` to your CDN and keep the index with the reader. The
508
+ same Spanish lookup then uses the remote data URL:
509
+
510
+ ```sh
511
+ npx rida-format get https://cdn.example.com/WebsiteData.rida 1/1/1/1/2 spanish \
512
+ --index ./WebsiteIndex.rida
513
+ ```
514
+
515
+ The language field can contain a much longer page than this example. All of
516
+ its content will be returned, including nested objects and arrays. The range
517
+ size follows the stored Spanish value's size; a long page is not guaranteed
518
+ to fit into a few hundred bytes. Folder nesting does not add other pages to
519
+ that range.
520
+
521
+ If a screen needs two languages, request both. If it needs all languages for
522
+ the page, read the complete record:
523
+
524
+ ```sh
525
+ npx rida-format get-many ./WebsiteData.rida 1/1/1/1/2 english spanish
526
+ npx rida-format record ./WebsiteData.rida 1/1/1/1/2
527
+ ```
528
+
529
+ The complete-record call returns English, Hindi, Urdu, and Spanish for page 2.
530
+ It does not return every page in the `pages` folder. For a screen that needs
531
+ only a translated title, give each title its own top-level field, such as
532
+ `spanish_title`; otherwise requesting `spanish` also transfers its paragraphs
533
+ and steps.
534
+
535
+ ### More than one group in the input folder
536
+
537
+ When the source folder has JSON files directly inside it and also has
538
+ immediate subfolders with JSON records, or when it has multiple immediate
539
+ subfolders containing records, RIDA sees separate groups. The Node.js CLI
540
+ reports an error and tells you how to select a group or combine groups; it
541
+ does not choose for you or silently mix unrelated files.
542
+
543
+ To build just one group, point `--records-dir` at that folder inside the source:
544
+
545
+ ```text
546
+ source/
547
+ ├── config.json
548
+ ├── customers/
549
+ │ └── C-1001.json
550
+ ├── orders/
551
+ │ └── O-5001.json
552
+ └── products/
553
+ └── SKU-1001.json
554
+ ```
555
+
556
+ ```sh
557
+ npx rida-format build ./source --records-dir products \
558
+ --output ./ProductsData.rida
559
+ ```
560
+
561
+ `--records-dir` searches the selected folder and all of its nested folders.
562
+ It excludes files outside that folder. You can build `customers`, `orders`,
563
+ and `products` as separate datasets, or intentionally combine groups using
564
+ `--combine-groups`. Combining groups with different fields uses the union of
565
+ their fields by default; see [Folder groups](#folder-groups) for how to choose
566
+ between union and common fields.
567
+
568
+ ### One JSON object mapping IDs to records
569
+
570
+ The top-level object can map record IDs to record objects. The IDs must be
571
+ strings:
572
+
573
+ ```json
574
+ {
575
+ "product-1001": { "name": "Desk lamp", "price": 1299 },
576
+ "product-1002": { "name": "Office chair", "price": 7499 }
577
+ }
578
+ ```
579
+
580
+ ### One JSON array of records
581
+
582
+ An array needs `--id-key` so the builder knows which field supplies each
583
+ record's ID:
584
+
585
+ ```json
586
+ [
587
+ { "id": "event-1001", "type": "signup", "source": "web" },
588
+ { "id": "event-1002", "type": "purchase", "source": "mobile" }
589
+ ]
590
+ ```
591
+
592
+ The value of the selected ID field is converted to text. The ID field remains a
593
+ regular field in the record too.
594
+
595
+ The single-file reader processes records one at a time instead of parsing the
596
+ entire JSON document into memory at once. The current record and catalog
597
+ metadata still need memory, so an individual record must fit in memory.
598
+
599
+ ## Scan before building
600
+
601
+ `scan` counts records and lists the fields it finds. It is useful for checking
602
+ the input and spotting the field names an app can request:
603
+
604
+ ```sh
605
+ npx rida-format scan ./records
606
+ npx rida-format scan ./records.json
607
+ npx rida-format scan ./records-array.json --id-key id
608
+ ```
609
+
610
+ For a folder, the command reports the number of records, field names, and the
611
+ number of mapped folders. Scanning does not create a RIDA dataset.
15
612
 
16
613
  ## Build a dataset
17
614
 
18
- A folder can contain one JSON object per `.json` file. Nested folders are included. By default RIDA gives each folder and record a numbered ID and writes a `Map.json` when those IDs need folder names.
615
+ Build from a folder:
616
+
617
+ ```sh
618
+ npx rida-format build ./records --output ./BooksData.rida
619
+ ```
620
+
621
+ Build from an object mapping IDs to records:
622
+
623
+ ```sh
624
+ npx rida-format build ./records.json --output ./BooksData.rida
625
+ ```
626
+
627
+ Build from an array using its `id` field:
628
+
629
+ ```sh
630
+ npx rida-format build ./records-array.json --id-key id --output ./BooksData.rida
631
+ ```
632
+
633
+ If `--output` is omitted, the output name is based on the source file or folder.
634
+ The builder also creates the matching index and any required map or key files.
635
+ It refuses to overwrite an output file that already exists; choose a new output
636
+ name or move the old files first.
637
+
638
+ ### Folder groups
639
+
640
+ If the input folder contains JSON files directly and also has immediate
641
+ subfolders containing JSON records, the builder treats those as separate
642
+ groups. It stops and asks you to choose one of two approaches:
643
+
644
+ 1. Select one group with `--records-dir`.
645
+ 2. Include the groups together with `--combine-groups`.
646
+
647
+ For example, to use only the `items` subfolder:
19
648
 
20
649
  ```sh
21
- node ./src/cli.js scan ./records
22
- node ./src/cli.js build ./records --output ./books.rida
650
+ npx rida-format build ./source --records-dir items --output ./ItemsData.rida
23
651
  ```
24
652
 
25
- The build creates `books.rida` and `booksIndex.rida`. It also creates `booksMap.json` when folder IDs need a map. Existing data or index files are not overwritten.
653
+ `--records-dir` is a folder path inside the source folder. Its JSON files and
654
+ subfolders are included.
26
655
 
27
- The tool also accepts one large JSON file whose top-level object maps IDs to record objects. A top-level JSON array needs `--id-key`. It reads one record at a time, rather than loading the whole JSON file:
656
+ To combine groups into one dataset:
28
657
 
29
658
  ```sh
30
- node ./src/cli.js build ./records.json --id-key id --output ./records.rida
659
+ npx rida-format build ./source --combine-groups --output ./AllData.rida
31
660
  ```
32
661
 
33
- Useful build options:
662
+ By default, a combined dataset uses the **union** of fields: every field found
663
+ in any group is kept. A record that does not have one of those fields simply
664
+ has no value stored for it. To keep only fields present in every group, use the
665
+ common schema:
666
+
667
+ ```sh
668
+ npx rida-format build ./source --combine-groups --combined-schema common \
669
+ --output ./SharedFieldsData.rida
670
+ ```
671
+
672
+ The common schema drops fields that are not shared by all groups. Choose it
673
+ only if those fields are not needed. `--combined-schema` accepts `common` or
674
+ `union` and applies to combined builds.
675
+
676
+ ## Record IDs and the map
677
+
678
+ Folder builds use numbered IDs by default. Files in a flat folder receive
679
+ sequential IDs such as `1`, `2`, and `3`. Nested folders add a numbered level,
680
+ such as `1/1`, `1/2`, or `2/1`. The ordering is deterministic: folders and
681
+ filenames are sorted, with numeric filenames ordered numerically.
682
+
683
+ When nested folders need human-readable names, the build writes `NameMap.json`.
684
+ It contains the folder paths and the field names associated with their numeric
685
+ IDs. Keep that map with the reader if your application needs those labels.
686
+
687
+ `--named-ids` uses each file's basename as its record ID instead of numbered
688
+ folder paths. If names collide, the builder adds suffixes such as `-2` and
689
+ `-3`. This mode does not create the numbered folder map.
690
+
691
+ For a single JSON object or array, the record IDs come from the object's keys
692
+ or `--id-key`; the builder keeps those IDs instead of deriving them from folder
693
+ positions.
694
+
695
+ ## Build options
696
+
697
+ | Option | Meaning | Default |
698
+ | --- | --- | --- |
699
+ | `--output FILE` | Data file path to create | Name based on the input |
700
+ | `--mode auto\|dense\|sparse` | Choose how record-to-field locations are stored in the catalog | `auto` |
701
+ | `--codec deflate-per-field\|plain` | Compress each stored value separately, or store its JSON bytes without compression | `deflate-per-field` |
702
+ | `--compression 0-9` | XZ compression level for the catalog; this does not set the value codec | `9` |
703
+ | `--encrypt` | Generate a new key and encrypt every stored value | Off |
704
+ | `--key KEY_OR_FILE` | Encrypt with an existing 32-byte key supplied as text or a file | None |
705
+ | `--records-dir FOLDER` | Select a folder inside the input folder | None |
706
+ | `--combine-groups` | Combine multiple input groups into one dataset | Off |
707
+ | `--combined-schema common\|union` | Keep fields shared by all groups, or all fields found across them | `union` |
708
+ | `--id-key FIELD` | ID field for a top-level JSON array | None |
709
+ | `--named-ids` | Use JSON file basenames rather than numbered folder IDs | Off |
710
+
711
+ `auto` selects a catalog layout by comparing the dense and sparse row sizes.
712
+ Choose `dense` or `sparse` to force a layout. This setting affects the catalog,
713
+ not the field values in the data file.
714
+
715
+ `deflate-per-field` writes one raw Deflate stream per value. `plain` writes the
716
+ compact UTF-8 JSON representation of each value without value compression.
717
+ `--compression` controls compression of the catalog stored in the index; it is
718
+ separate from the per-value codec.
719
+
720
+ The command prints progress while scanning records and writing values. It does
721
+ not provide a byte-accurate percentage for every internal step.
722
+
723
+ ## Encryption and keys
724
+
725
+ Use `--encrypt` to create a new random 256-bit AES key and encrypt every value:
726
+
727
+ ```sh
728
+ npx rida-format build ./records --output ./PrivateData.rida --encrypt
729
+ ```
730
+
731
+ This creates `PrivateDataKey.rida`. The key file contains base64url text. Keep
732
+ it private and back it up securely; if it is lost, encrypted values cannot be
733
+ read. Do not upload the key with the public data file.
734
+
735
+ You can also pass an existing 32-byte key as a file or as base64/base64url or
736
+ hex text:
737
+
738
+ ```sh
739
+ npx rida-format build ./records --output ./PrivateData.rida --key ./my-key.txt
740
+ ```
741
+
742
+ Use either `--encrypt` or `--key`, not both. Encryption is applied after the
743
+ chosen value codec, so the order is JSON encoding, optional Deflate compression,
744
+ then AES-256-GCM encryption. Each encrypted value has a 12-byte nonce and a
745
+ 16-byte authentication tag in addition to its encoded contents.
746
+
747
+ Encryption protects values from people who can download the data file but do
748
+ not have the key. It does not hide the index's record count, field names, data
749
+ length, or catalog structure. An app that receives the key must protect it as
750
+ carefully as any other secret; a key embedded in a client app can be extracted
751
+ by someone who controls that device.
752
+
753
+ ### Encrypted data directly from your CDN
754
+
755
+ You can host an encrypted RIDA data file at a public CDN URL while keeping its
756
+ contents unreadable without the decryption key. The reader uses its index to
757
+ find the requested value, downloads that encrypted byte range, and decrypts it
758
+ where the reader runs. You do not need to download the whole dataset first.
34
759
 
35
760
  ```text
36
- --mode auto|dense|sparse Choose the catalog layout (default: auto)
37
- --codec deflate-per-field|plain Compress each value, or store raw JSON
38
- --compression 0-9 Set XZ catalog compression (default: 9)
39
- --encrypt Create a fresh AES-256-GCM key
40
- --key FILE_OR_TEXT Reuse a 32-byte key in base64url or hex form
41
- --records-dir FOLDER Build from a selected folder inside the source
42
- --combine-groups Combine immediate JSON groups into one dataset
43
- --combined-schema common|union Keep only shared fields, or every field (default)
44
- --named-ids Use JSON file names for record IDs
761
+ Reader with a key → CDN byte-range request → encrypted value → local decryption
45
762
  ```
46
763
 
47
- Keep the generated `Key.rida` private. Without it encrypted values cannot be read. The key is separate from the data, index, and map files.
764
+ For example, a page record can contain separate `english`, `hindi`, `urdu`, and
765
+ `spanish` fields. Requesting page 2's `spanish` field downloads the stored bytes
766
+ for that field, including encryption overhead. If Spanish contains a complete
767
+ object with a title, paragraphs, and steps, you receive that complete object.
768
+ A larger value needs a larger range: RIDA does not make every response a fixed
769
+ number of bytes. HTTP headers and network overhead are additional to the value.
770
+
771
+ #### Option 1: give the authorized reader the key
772
+
773
+ Your application can authorize a user and provide the key to a compatible
774
+ reader. Subsequent reads can go directly to the CDN, with decryption on the
775
+ user's device. Keep the index and map with the reader so it can find the correct
776
+ record and field without guessing paths.
777
+
778
+ If your Worker or backend would otherwise exist only to validate a token on
779
+ **every data request**, this arrangement can avoid that proxy's execution and
780
+ extra network hop for those reads. RIDA itself adds no encryption subscription
781
+ fee. Storage, CDN delivery, your authorization service, and other hosting
782
+ services can still have charges; this is not a promise that every CDN security
783
+ feature or paid plan becomes unnecessary.
784
+
785
+ The trade-off is that a user who holds the key can copy it and read the values
786
+ encrypted with it. A public URL lets anyone download ciphertext; encryption
787
+ protects the contents, not access to that URL. The index and map can also reveal
788
+ record names, field names, and dataset structure.
789
+
790
+ Expiring a session or token does **not** revoke a copied key. To exclude that
791
+ key from future data, use a new key and newly encrypted data. Previously
792
+ downloaded data remains readable with its original key. Choose this approach
793
+ when your application accepts these limits.
794
+
795
+ #### Option 2: keep the key on your Next.js server
796
+
797
+ Store the key in a server-only environment variable such as `RIDA_KEY`. Never
798
+ use a `NEXT_PUBLIC_` variable for it, import it into client code, or return the
799
+ key in an API response. Keep the key file out of public assets as well.
800
+
801
+ ```text
802
+ User → your server checks access → CDN encrypted range
803
+ → server decrypts → permitted content returned to the user
804
+ ```
805
+
806
+ Your server checks the user's permission, fetches the requested encrypted range,
807
+ decrypts it, and returns the permitted content. The key stays on the server,
808
+ but reads now pass through your backend and its running costs remain. Keeping a
809
+ key in an environment variable does not by itself give a browser direct reads:
810
+ the browser needs the key to decrypt locally, or the server must decrypt for it.
811
+
812
+ Use this option when each read needs an account permission check. Encryption
813
+ and per-request authorization solve different problems; choose where decryption
814
+ happens according to the access rules your application needs.
815
+
816
+ The npm package runs in Node.js, including a Next.js server. Direct decryption
817
+ in a browser or mobile app requires a compatible reader for that platform;
818
+ installing this Node.js package does not itself supply a browser reader.
48
819
 
49
- ## Read a dataset
820
+ ## Read a local dataset
821
+
822
+ The reader finds a sibling `NameIndex.rida` automatically. For a local file it
823
+ also loads a sibling `NameMap.json` if one exists. Read one value:
824
+
825
+ ```sh
826
+ npx rida-format get ./BooksData.rida 1/1 translation.urdu
827
+ ```
828
+
829
+ Read several fields from one record:
830
+
831
+ ```sh
832
+ npx rida-format get-many ./BooksData.rida 1/1 title translation.urdu
833
+ ```
834
+
835
+ Read all fields present in a record:
836
+
837
+ ```sh
838
+ npx rida-format record ./BooksData.rida 1/1
839
+ ```
840
+
841
+ Show dataset information and field names:
842
+
843
+ ```sh
844
+ npx rida-format info ./BooksData.rida
845
+ ```
846
+
847
+ If the files have different names or locations, pass the index and map paths
848
+ explicitly:
849
+
850
+ ```sh
851
+ npx rida-format get ./BooksData.rida 1/1 translation.urdu \
852
+ --index ./Catalog.rida --map ./Names.json
853
+ ```
854
+
855
+ For encrypted values, supply the key file:
856
+
857
+ ```sh
858
+ npx rida-format get ./PrivateData.rida 1/1 title --key ./PrivateDataKey.rida
859
+ npx rida-format get-many ./PrivateData.rida 1/1 title body --key ./PrivateDataKey.rida
860
+ npx rida-format record ./PrivateData.rida 1/1 --key ./PrivateDataKey.rida
861
+ ```
862
+
863
+ The CLI prints each result as JSON. A missing record, field, index, or required
864
+ key produces an error and a non-zero command exit status.
865
+
866
+ ## Read from an HTTP URL or CDN
867
+
868
+ Give the reader a direct URL to the data file:
869
+
870
+ ```sh
871
+ npx rida-format get https://cdn.example.com/BooksData.rida 1/1 translation.urdu
872
+ ```
873
+
874
+ When `--index` is omitted, the reader derives an adjacent index URL by replacing
875
+ `Data` in the data filename with `Index`. For example, a data URL ending in
876
+ `BooksData.rida` uses `BooksIndex.rida`. If your index is stored elsewhere,
877
+ provide it explicitly:
878
+
879
+ ```sh
880
+ npx rida-format get https://cdn.example.com/BooksData.rida 1/1 title \
881
+ --index https://app.example.com/catalog/BooksIndex.rida
882
+ ```
883
+
884
+ For a remote read, the index is fetched when the reader opens. The map is not
885
+ automatically discovered from a remote URL. Provide it with `--map` if the
886
+ lookup needs folder names; otherwise use the numbered record ID:
50
887
 
51
888
  ```sh
52
- node ./src/cli.js info ./books.rida
53
- node ./src/cli.js get ./books.rida 1/1/1/1 translation.urdu --key ./booksKey.rida
54
- node ./src/cli.js get-many ./books.rida 1/1/1/1 title translation.urdu --key ./booksKey.rida
55
- node ./src/cli.js record ./books.rida 1/1/1/1 --key ./booksKey.rida
56
- node ./src/cli.js verify ./books.rida --key ./booksKey.rida
889
+ npx rida-format get https://cdn.example.com/BooksData.rida 1/1/1/5 title \
890
+ --map https://app.example.com/catalog/BooksMap.json
57
891
  ```
58
892
 
59
- The JavaScript API is also available from `src/index.js`:
893
+ The HTTP host must honor the `Range` request and return status `206` with
894
+ exactly the requested number of bytes. If the host returns the whole file
895
+ instead, the reader stops with an error rather than accepting that response.
896
+ RIDA does not add cloud-provider authentication headers; use a publicly
897
+ readable URL or a signed URL that allows the request.
898
+
899
+ One `get` requests one value range. `get-many` and `record` can merge nearby
900
+ values into fewer ranges. A whole-record read may transfer gaps between nearby
901
+ values as well as the requested values. Every HTTP request also has headers, so
902
+ the bytes shown by a CDN may be greater than the requested file-range bytes.
903
+
904
+ ### Put the data file on a CDN
905
+
906
+ RIDA creates the files; it does not upload or host them. A typical setup is:
907
+
908
+ 1. Build the dataset on your computer.
909
+ 2. Keep `NameIndex.rida` and, when present, `NameMap.json` with the app or
910
+ reader, or host the index where the reader can fetch it.
911
+ 3. Upload `NameData.rida` to object storage or a CDN origin. If the reader is
912
+ expected to derive the index URL automatically, upload the matching index
913
+ beside it too.
914
+ 4. Make the data object readable through a direct HTTPS URL.
915
+ 5. Open that URL with `RidaReader` or pass it to a CLI read command.
916
+
917
+ For example, if `BooksData.rida` is at
918
+ `https://data.example.com/BooksData.rida`, the reader derives the sibling
919
+ `BooksIndex.rida` URL unless `index` is supplied explicitly. Keep the index
920
+ available at that derived URL, or pass the actual index URL. A remote map is
921
+ not discovered automatically; pass its URL only when the app needs names from
922
+ numbered folder IDs.
923
+
924
+ Before relying on a storage/CDN setup, check that a request with a `Range`
925
+ header receives `206 Partial Content`, a matching `Content-Range`, and only the
926
+ requested bytes. A host that returns `200 OK` with the entire object cannot be
927
+ used for a RIDA range read. Also check that the URL is public or signed for the
928
+ app's requests, that cross-origin browser requests allow the needed headers,
929
+ and that the CDN cache key and cache rules preserve the requested byte range.
930
+ RIDA does not configure any of these provider settings for you.
931
+
932
+ Any object store or CDN can work if its public file URL supports the required
933
+ HTTP range behavior. This can include services such as Bunny, Cloudflare R2,
934
+ Amazon S3, Google Cloud Storage, Azure Blob Storage, or Backblaze B2, but the
935
+ exact URL, permissions, and CDN configuration matter. This is compatibility
936
+ through ordinary HTTP; the package does not include provider-specific upload
937
+ or account-management integrations.
938
+
939
+ The first remote open loads the index; each lookup then requests data ranges.
940
+ You can pass an index file bundled with the app, or let the reader fetch the
941
+ index from its URL. Keep the encryption key private. A
942
+ browser or mobile app that contains the key cannot keep it secret from a device
943
+ owner; encryption is useful when the application has a safe way to deliver and
944
+ protect that key.
945
+
946
+ ### What a lookup transfers
947
+
948
+ A single-field lookup requests the byte range for that stored value. It does
949
+ not download the whole RIDA data file and does not hash the whole file. A
950
+ `get-many` call may combine nearby fields into one range; `getRecord` reads all
951
+ fields. When fields are far apart, the reader can make more than one range
952
+ request rather than transferring a large unused gap.
953
+
954
+ The payload size and the CDN's logged or billed byte count can differ. HTTP
955
+ headers, TLS and protocol overhead, provider accounting units, and range/cache
956
+ handling can add to what the application asks for. In one Bunny test, a 256-byte
957
+ range was recorded in the dashboard as about 1.02 kB. Treat the range length as
958
+ the requested file payload, not as a promise that every provider will bill
959
+ exactly that many bytes.
960
+
961
+ ### Example delivery-cost comparison
962
+
963
+ For a reference workload of 27,647 records and 34 fields, an average complete
964
+ JSON record is about 7.69 KB; an average stored RIDA field value with per-field
965
+ Deflate is about 143 bytes. If an application usually asks for one field, this
966
+ model estimates roughly 98% fewer data bytes than transferring the whole JSON
967
+ record.
968
+
969
+ The table shows an illustrative one-billion-lookups-per-month estimate. It
970
+ compares delivery charges for that workload, not a quote for your account and
971
+ not a measured result from every provider. The RIDA estimate assumes one
972
+ requested field per lookup and the measured average field size.
973
+
974
+ | Provider and region | Billing basis in the estimate | Whole JSON | RIDA field read |
975
+ | --- | --- | ---: | ---: |
976
+ | Bunny CDN Standard, Asia | Per GB delivered | $230.79/mo | $4.29/mo |
977
+ | Bunny CDN Volume, first tier | Per GB delivered | $38.46/mo | $0.71/mo |
978
+ | AWS CloudFront, US / Europe | Per GB delivered | $653.90/mo | $12.15/mo |
979
+ | AWS CloudFront, India | Per GB delivered | $1,307.80/mo | $24.31/mo |
980
+ | Google Cloud CDN, US / Europe | Per GB delivered | $615.44/mo | $11.44/mo |
981
+ | Google Cloud CDN, Asia | Per GB delivered | $923.16/mo | $17.16/mo |
982
+ | Azure CDN, Zone 1 | Per GB delivered | $623.13/mo | $11.58/mo |
983
+ | Azure CDN, Zone 2 | Per GB delivered | $1,038.55/mo | $19.30/mo |
984
+ | Backblaze B2 + Bunny CDN | Per GB delivered | $76.93/mo | $1.43/mo |
985
+ | Cloudflare R2 Class B reads | Per read in this estimate | $356.40/mo | $356.40/mo |
986
+
987
+ RIDA's smaller response can reduce transfer charges on providers that bill for
988
+ GB delivered. It does not automatically reduce a per-request charge: the R2
989
+ example stays the same because both cases use one read per lookup in this
990
+ model. `get-many` can reduce request count when an app needs several nearby
991
+ fields, but it may transfer bytes between those fields too.
992
+
993
+ These figures cover the modeled delivery workload only. Actual charges depend
994
+ on current provider rates, user locations, cache-hit behavior, request count,
995
+ minimum charges, taxes, storage size, and how many fields the app asks for.
996
+ Storage is an additional line item; in the compared setups, 5 GB was estimated
997
+ at roughly $0.02–$0.37 per month and 50 GB at $0.20–$3.70. Any storage
998
+ allowance is account-wide and depends on the provider's current plan. Check the
999
+ provider's current price and account terms before using these numbers for a
1000
+ budget. SQL databases also have compute, storage, and query charges that this
1001
+ delivery table does not compare; compare both systems with the same workload
1002
+ and service requirements.
1003
+
1004
+ ### When RIDA can replace repeated database reads
1005
+
1006
+ RIDA is designed for data that is built ahead of time and then read many times:
1007
+ for example, a public reference collection, a catalogue, or records that
1008
+ change only when the publisher creates a new dataset. The app uses the index
1009
+ to locate a field and fetches its bytes from the data file.
1010
+
1011
+ RIDA is not a general database. It does not provide live writes, transactions,
1012
+ SQL queries, user-specific filtering, or server-side joins. If an application
1013
+ needs those features, a database remains necessary. A system can also use both:
1014
+ keep changing/private application data in a database and serve a large static
1015
+ read-only collection through RIDA. Whether that costs less depends on the real
1016
+ read pattern, response sizes, hosting and database plans, and operational needs;
1017
+ the delivery table above is not a SQL price comparison.
1018
+
1019
+ ## Inspect and verify
1020
+
1021
+ `info` opens the index and prints the record count, field names, codec, catalog
1022
+ layout, encryption flag, and data length:
1023
+
1024
+ ```sh
1025
+ npx rida-format info ./BooksData.rida
1026
+ ```
1027
+
1028
+ `verify` reads the entire data file in chunks and checks its SHA-256 digest
1029
+ against the digest in the index:
1030
+
1031
+ ```sh
1032
+ npx rida-format verify ./BooksData.rida
1033
+ npx rida-format verify https://cdn.example.com/BooksData.rida
1034
+ ```
1035
+
1036
+ For a remote URL, verification transfers the complete data file. It is not a
1037
+ small lookup and can use significant bandwidth and time. A normal `get` reads
1038
+ only its requested range and does not hash the entire data file.
1039
+
1040
+ ## Use the JavaScript API
1041
+
1042
+ Import the reader from the installed package:
1043
+
1044
+ ```js
1045
+ import { RidaReader } from "rida-format";
1046
+
1047
+ const reader = await RidaReader.open("./BooksData.rida");
1048
+ try {
1049
+ const value = await reader.get("1/1", "translation.urdu");
1050
+ console.log(value);
1051
+ } finally {
1052
+ await reader.close();
1053
+ }
1054
+ ```
1055
+
1056
+ Read a URL in the same way:
1057
+
1058
+ ```js
1059
+ import { RidaReader } from "rida-format";
1060
+
1061
+ const reader = await RidaReader.open("https://cdn.example.com/BooksData.rida", {
1062
+ index: "https://app.example.com/catalog/BooksIndex.rida",
1063
+ });
1064
+ try {
1065
+ console.log(await reader.get("1/1/1/5", "title"));
1066
+ } finally {
1067
+ await reader.close();
1068
+ }
1069
+ ```
1070
+
1071
+ For an encrypted dataset, pass the key as a string, `Buffer`, or `Uint8Array`:
60
1072
 
61
1073
  ```js
62
- import { RidaReader } from "./src/index.js";
1074
+ import { readFile } from "node:fs/promises";
1075
+ import { RidaReader } from "rida-format";
63
1076
 
64
- const reader = await RidaReader.open("./books.rida", { key: "base64url-key-text" });
65
- const value = await reader.get("1/1/1/1", "translation.urdu");
66
- await reader.close();
1077
+ const key = (await readFile("./BooksKey.rida", "utf8")).trim();
1078
+ const reader = await RidaReader.open("./BooksData.rida", { key });
1079
+ try {
1080
+ console.log(await reader.get("1/1", "title"));
1081
+ console.log(await reader.getMany("1/1", ["title", "translation.urdu"]));
1082
+ console.log(await reader.getRecord("1/1"));
1083
+ } finally {
1084
+ await reader.close();
1085
+ }
67
1086
  ```
68
1087
 
69
- It supports local data files and HTTP servers/CDNs that honor byte-range requests. `getMany()` can combine nearby value ranges into fewer requests. The index and optional map stay with the reader; the CDN serves the data file.
1088
+ Reader methods and properties:
1089
+
1090
+ | API | Purpose |
1091
+ | --- | --- |
1092
+ | `RidaReader.open(data, options)` | Open a local data path or HTTP/HTTPS data URL. Options: `index`, `map`, `key`. |
1093
+ | `reader.get(recordId, field)` | Read and decode one field value. |
1094
+ | `reader.getMany(recordId, fields)` | Read several named fields; nearby ranges may be combined. Returns an object keyed by field name. |
1095
+ | `reader.getRecord(recordId)` | Read every field in the record. |
1096
+ | `reader.info` | Index metadata, including encryption and digest information. |
1097
+ | `reader.fields` | List of field names from the catalog. |
1098
+ | `reader.recordCount` | Number of records in the dataset. |
1099
+ | `reader.valueCodec` | `deflate-per-field` or `plain`. |
1100
+ | `reader.mode` | `dense` or `sparse` catalog layout. |
1101
+ | `reader.verifyData()` | Read all data bytes and compare the SHA-256 digest. |
1102
+ | `reader.resolve(...folderNames)` | Resolve folder names through a loaded map. |
1103
+ | `reader.recordsUnder(prefix)` | List record IDs beneath a numbered prefix. |
1104
+ | `reader.close()` | Close the local file handle. Call it when finished. |
70
1105
 
71
- ## Current boundaries
1106
+ The builder functions are exported from the package's `./builder` subpath:
72
1107
 
73
- - Folder builds handle one JSON object per record file. The selected folder is scanned to discover fields, then read again to write values. Large datasets do not need all value contents held in memory at once; record IDs and catalog row metadata are kept in memory.
74
- - Both folder input and a single large JSON file are read record by record. The IDs and catalog row information stay in memory; the full set of JSON values does not.
75
- - Multiple JSON groups require `--records-dir` to select one, or `--combine-groups`. Combined builds support both common and union schemas.
76
- - The CLI provides `scan`, `build`, `info`, `get`, `get-many`, `record`, and `verify`. Python's inspection helpers and automatic remote index-cache installer are not ported yet.
1108
+ ```js
1109
+ import { build, scan } from "rida-format/builder";
1110
+
1111
+ const report = await scan("./records");
1112
+ console.log(report.recordCount, report.fields);
77
1113
 
78
- ## License and publishing
1114
+ const result = await build("./records", "./BooksData.rida", {
1115
+ mode: "auto",
1116
+ codec: "deflate-per-field",
1117
+ compression: 9,
1118
+ });
1119
+ console.log(result);
1120
+ ```
79
1121
 
80
- The included license specifically permits publishing this Node.js edition as the standalone npm package `rida-format`. It does not grant permission to publish other RIDA editions as standalone packages. Keep the included `LICENSE` file with the package.
1122
+ `scan(source, options)` returns the source path, record count, field names, and
1123
+ folder mapping information. `build(source, output, options)` returns the output
1124
+ paths, record and field counts, selected layout and codec, encryption status,
1125
+ and data/catalog byte counts. Builder option names use JavaScript camel case:
1126
+ `idKey`, `recordsDir`, `combineGroups`, `combinedSchema`, `numbered`, `mode`,
1127
+ `codec`, `compression`, `encrypt`, and `key`.
1128
+
1129
+ ## Value codec and catalog compression
1130
+
1131
+ The **value codec** controls how each field value is stored:
1132
+
1133
+ | Codec | What is stored | Use |
1134
+ | --- | --- | --- |
1135
+ | `deflate-per-field` | Each value is compact JSON encoded as UTF-8 and compressed in its own raw Deflate stream | Default; often reduces transfer for text and structured values |
1136
+ | `plain` | Each value is compact JSON encoded as UTF-8 without value compression | Useful when values are tiny or already compressed |
1137
+
1138
+ Choose the codec while building:
1139
+
1140
+ ```sh
1141
+ npx rida-format build ./records --output ./BooksData.rida --codec plain
1142
+ ```
1143
+
1144
+ The **catalog compression** option (`--compression 0` through `--compression
1145
+ 9`) is separate. It controls how the index catalog is compressed with XZ/LZMA;
1146
+ it does not change the encoding of the data values.
81
1147
 
82
1148
  ## Format compatibility
83
1149
 
84
- RIDA 0.3.3 stores only value bytes in the data file. The index has a 72-byte header followed by an XZ/LZMA catalog. Catalog rows point to values encoded as compact UTF-8 JSON, either plain or raw Deflate per field. Encryption wraps each encoded value as a 12-byte nonce, AES-256-GCM ciphertext, and 16-byte authentication tag. The map contains numbered folder names and field labels; the key is separate and private.
1150
+ The Node.js reader and builder handle the RIDA 0.3.3 data/index format. The
1151
+ index stores the value codec, encryption flag, data length, SHA-256 digest, and
1152
+ compressed catalog. The catalog stores field names, record IDs when needed,
1153
+ record-to-value offsets, and the dense or sparse layout. Values are compact
1154
+ UTF-8 JSON, optionally raw-Deflate compressed per field, then optionally
1155
+ encrypted with AES-256-GCM.
1156
+
1157
+ Reading a dataset does not convert or rewrite it. The Node.js code can read a
1158
+ compatible dataset built by the Python RIDA 0.3.3 release. Building a dataset
1159
+ creates new output files from JSON; it does not edit the source JSON.
1160
+
1161
+ ## Detailed application examples
1162
+
1163
+ These examples use numbered record IDs and the generated map. Build each example folder as its own dataset. The IDs shown apply only to these exact folder trees; adding or rearranging records can change numbered positions.
1164
+
1165
+ ### One product. Only the description your customer needs.
1166
+
1167
+ Your product catalogue can contain thousands of records. Each product may have a price, specifications, images, stock information, and descriptions in several languages.
1168
+
1169
+ ```text
1170
+ catalogue/
1171
+ └── products/
1172
+ └── 2812.json
1173
+ ```
1174
+
1175
+ Example record:
1176
+
1177
+ ```json
1178
+ {
1179
+ "name": "Travel Backpack",
1180
+ "price": 49,
1181
+ "stock": 120,
1182
+ "specifications": {
1183
+ "capacity": "30 litres",
1184
+ "weight": "900 grams"
1185
+ },
1186
+ "english": {
1187
+ "title": "Ready for everyday travel",
1188
+ "description": "A lightweight backpack with a padded laptop compartment."
1189
+ },
1190
+ "hindi": {
1191
+ "title": "Roz ke safar ke liye",
1192
+ "description": "Halka backpack, laptop ke liye alag padded jagah ke saath.",
1193
+ "care": [
1194
+ "Haath se saaf karein",
1195
+ "Chhaon mein sukhayein"
1196
+ ]
1197
+ },
1198
+ "images": [
1199
+ "front.webp",
1200
+ "back.webp"
1201
+ ]
1202
+ }
1203
+ ```
1204
+
1205
+ Build the example:
1206
+
1207
+ ```sh
1208
+ npx rida-format build ./catalogue --output ./CatalogueData.rida --records-dir .
1209
+ ```
1210
+
1211
+ #### Your customer chooses Hindi
1212
+
1213
+ Request the hindi field. The reader uses the map to resolve the record and the index to find its byte range. The response contains the complete Hindi value: its title, description, and care instructions. Price, stock, specifications, English content, and image URLs are not selected.
1214
+
1215
+ ```js
1216
+ import { RidaReader } from "rida-format";
1217
+
1218
+ const reader = await RidaReader.open("./CatalogueData.rida");
1219
+ try {
1220
+ const prefix = reader.resolve("products");
1221
+ if (!prefix) throw new Error("Folder not found in the map");
1222
+ const recordIds = reader.recordsUnder(prefix);
1223
+ // This exact example: 2812.json is the only record.
1224
+ const recordId = recordIds[0];
1225
+ console.log(await reader.get(recordId, "hindi"));
1226
+ console.log(await reader.getMany(recordId, ["price", "hindi"]));
1227
+ } finally {
1228
+ await reader.close();
1229
+ }
1230
+ ```
1231
+
1232
+ Need the price too? Request price and hindi together with a multi-field read. Nearby ranges can be combined; the number of HTTP requests depends on their positions in the data file.
1233
+
1234
+
1235
+ ### A complete help page. In the selected language.
1236
+
1237
+ A help centre can organise complete multilingual instructions inside deeply nested folders. Each language can contain a heading, introduction, steps, and troubleshooting.
1238
+
1239
+ ```text
1240
+ help-centre/
1241
+ └── guides/
1242
+ └── account/
1243
+ └── recovery/
1244
+ └── pages/
1245
+ ├── 1.json
1246
+ ├── 2.json
1247
+ └── 3812.json
1248
+ ```
1249
+
1250
+ Example record:
1251
+
1252
+ ```json
1253
+ {
1254
+ "title": "Recover your account",
1255
+ "category": "Account access",
1256
+ "english": {
1257
+ "heading": "Reset your password",
1258
+ "steps": [
1259
+ "Open account recovery",
1260
+ "Enter your email",
1261
+ "Follow the reset link"
1262
+ ]
1263
+ },
1264
+ "spanish": {
1265
+ "heading": "Restablece tu contraseña",
1266
+ "introduction": "Sigue estos pasos para recuperar el acceso a tu cuenta.",
1267
+ "steps": [
1268
+ "Abre la página de recuperación",
1269
+ "Introduce tu correo electrónico",
1270
+ "Sigue el enlace para restablecer la contraseña"
1271
+ ],
1272
+ "troubleshooting": {
1273
+ "email_missing": "Revisa la carpeta de correo no deseado.",
1274
+ "link_expired": "Solicita un nuevo enlace."
1275
+ }
1276
+ }
1277
+ }
1278
+ ```
1279
+
1280
+ Build the example:
1281
+
1282
+ ```sh
1283
+ npx rida-format build ./help-centre --output ./HelpData.rida --records-dir .
1284
+ ```
1285
+
1286
+ #### Your user needs Spanish instructions
1287
+
1288
+ Request the spanish field to receive the complete Spanish object, including its nested troubleshooting content. English instructions are not selected. Use the generated map to find the folder prefix rather than guessing a numbered path.
1289
+
1290
+ ```js
1291
+ import { RidaReader } from "rida-format";
1292
+
1293
+ const reader = await RidaReader.open("./HelpData.rida");
1294
+ try {
1295
+ const prefix = reader.resolve("guides", "account", "recovery", "pages");
1296
+ if (!prefix) throw new Error("Folder not found in the map");
1297
+ const recordIds = reader.recordsUnder(prefix);
1298
+ // This exact example: 3812.json follows 1.json and 2.json.
1299
+ const recordId = recordIds[2];
1300
+ console.log(await reader.get(recordId, "spanish"));
1301
+ console.log(await reader.getMany(recordId, ["title", "category", "spanish"]));
1302
+ } finally {
1303
+ await reader.close();
1304
+ }
1305
+ ```
1306
+
1307
+ Need page metadata too? Request title, category, and spanish together. RIDA selects stored fields, not individual properties inside them. If troubleshooting needs independent reads, store it in a separate top-level field.
1308
+
1309
+
1310
+ A field can contain a complete object or array, not just a short sentence. A long value needs a larger byte range. An encrypted build returns the same selected values after decryption with the key. Encryption and HTTP headers add overhead; responses are not a fixed few bytes. Merged ranges can also include small gaps between selected values.
1311
+
1312
+ The filenames are source names, not guaranteed numbered record IDs. The map describes folder prefixes; records_under / recordsUnder lists their record IDs. Keep the chosen ID in your application when selecting a record. For a large catalogue, use your own product identifier field or mapping to associate business IDs with numbered record IDs.
1313
+
1314
+ ## Current scope and limits
1315
+
1316
+ - The CLI commands are `scan`, `build`, `info`, `get`, `get-many`, `record`,
1317
+ and `verify`.
1318
+ - The reader supports local data files and HTTP/HTTPS data URLs with byte-range
1319
+ support.
1320
+ - Opening a remote reader fetches its index; the index is not fetched using a
1321
+ byte range. Keep it small enough for the client to load, or pass a suitable
1322
+ index explicitly.
1323
+ - A local map file is discovered beside a local data file. A remote map must be
1324
+ passed explicitly with `--map` or the API's `map` option.
1325
+ - The Node.js reader does not currently provide Python's automatic remote
1326
+ index-cache installer, provider-specific upload tools, exact-match search
1327
+ indexes, numeric-range search indexes, or full-text search indexes.
1328
+ - RIDA does not upload, host, cache, or manage billing for your data. Those are
1329
+ handled by your storage provider, CDN, and application.
1330
+ - A single record must fit in memory while it is parsed. The builder does not
1331
+ keep the full collection of JSON values in memory, but it keeps record IDs
1332
+ and catalog metadata for the build.
1333
+ - `verify` reads the full data region. Use it when you want a complete file
1334
+ integrity check, not for each user lookup.
1335
+
1336
+ ## License
1337
+
1338
+ The included `LICENSE` file governs use of this package. It includes specific
1339
+ permission for publishing this Node.js edition as the standalone npm package
1340
+ `rida-format`. Read the complete license before redistributing or embedding the
1341
+ package in another product.