rida-format 2.0.0 → 3.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 3.0.2
4
+
5
+ - Aligned the version numbering for Python, Node.js, and RIDA Studio.
6
+ - Made encrypted and unencrypted datasets readable across all three editions, including existing files written with either index header layout.
7
+
8
+ ## 2.0.1 — Encrypted delivery and application examples
9
+
10
+ - Added direct encrypted CDN delivery guidance and server-only key handling.
11
+ - Added detailed product catalogue and multilingual help-centre examples.
12
+ - Clarified whole-field reads, nested values, map lookup, and multi-field requests.
13
+ - Updated documentation and package numbering; the data format is unchanged.
14
+
3
15
  ## 2.0.0 — Detailed usage guide
4
16
 
5
17
  - Expanded the Node.js README with installation, CLI and JavaScript API instructions.
package/README.md CHANGED
@@ -750,6 +750,73 @@ length, or catalog structure. An app that receives the key must protect it as
750
750
  carefully as any other secret; a key embedded in a client app can be extracted
751
751
  by someone who controls that device.
752
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.
759
+
760
+ ```text
761
+ Reader with a key → CDN byte-range request → encrypted value → local decryption
762
+ ```
763
+
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.
819
+
753
820
  ## Read a local dataset
754
821
 
755
822
  The reader finds a sibling `NameIndex.rida` automatically. For a local file it
@@ -1080,16 +1147,170 @@ it does not change the encoding of the data values.
1080
1147
 
1081
1148
  ## Format compatibility
1082
1149
 
1083
- The Node.js reader and builder handle the RIDA 0.3.3 data/index format. The
1150
+ The Node.js reader and builder use the same data and index format as Python
1151
+ and RIDA Studio 3.0.2. The reader also accepts the older Python index layout. The
1084
1152
  index stores the value codec, encryption flag, data length, SHA-256 digest, and
1085
1153
  compressed catalog. The catalog stores field names, record IDs when needed,
1086
1154
  record-to-value offsets, and the dense or sparse layout. Values are compact
1087
1155
  UTF-8 JSON, optionally raw-Deflate compressed per field, then optionally
1088
1156
  encrypted with AES-256-GCM.
1089
1157
 
1090
- Reading a dataset does not convert or rewrite it. The Node.js code can read a
1091
- compatible dataset built by the Python RIDA 0.3.3 release. Building a dataset
1092
- creates new output files from JSON; it does not edit the source JSON.
1158
+ Reading a dataset does not convert or rewrite it. Existing encrypted datasets
1159
+ still require their original key. Building a dataset creates new output files
1160
+ from JSON and leaves the source JSON intact.
1161
+
1162
+ ## Detailed application examples
1163
+
1164
+ 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.
1165
+
1166
+ ### One product. Only the description your customer needs.
1167
+
1168
+ Your product catalogue can contain thousands of records. Each product may have a price, specifications, images, stock information, and descriptions in several languages.
1169
+
1170
+ ```text
1171
+ catalogue/
1172
+ └── products/
1173
+ └── 2812.json
1174
+ ```
1175
+
1176
+ Example record:
1177
+
1178
+ ```json
1179
+ {
1180
+ "name": "Travel Backpack",
1181
+ "price": 49,
1182
+ "stock": 120,
1183
+ "specifications": {
1184
+ "capacity": "30 litres",
1185
+ "weight": "900 grams"
1186
+ },
1187
+ "english": {
1188
+ "title": "Ready for everyday travel",
1189
+ "description": "A lightweight backpack with a padded laptop compartment."
1190
+ },
1191
+ "hindi": {
1192
+ "title": "Roz ke safar ke liye",
1193
+ "description": "Halka backpack, laptop ke liye alag padded jagah ke saath.",
1194
+ "care": [
1195
+ "Haath se saaf karein",
1196
+ "Chhaon mein sukhayein"
1197
+ ]
1198
+ },
1199
+ "images": [
1200
+ "front.webp",
1201
+ "back.webp"
1202
+ ]
1203
+ }
1204
+ ```
1205
+
1206
+ Build the example:
1207
+
1208
+ ```sh
1209
+ npx rida-format build ./catalogue --output ./CatalogueData.rida --records-dir .
1210
+ ```
1211
+
1212
+ #### Your customer chooses Hindi
1213
+
1214
+ 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.
1215
+
1216
+ ```js
1217
+ import { RidaReader } from "rida-format";
1218
+
1219
+ const reader = await RidaReader.open("./CatalogueData.rida");
1220
+ try {
1221
+ const prefix = reader.resolve("products");
1222
+ if (!prefix) throw new Error("Folder not found in the map");
1223
+ const recordIds = reader.recordsUnder(prefix);
1224
+ // This exact example: 2812.json is the only record.
1225
+ const recordId = recordIds[0];
1226
+ console.log(await reader.get(recordId, "hindi"));
1227
+ console.log(await reader.getMany(recordId, ["price", "hindi"]));
1228
+ } finally {
1229
+ await reader.close();
1230
+ }
1231
+ ```
1232
+
1233
+ 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.
1234
+
1235
+
1236
+ ### A complete help page. In the selected language.
1237
+
1238
+ A help centre can organise complete multilingual instructions inside deeply nested folders. Each language can contain a heading, introduction, steps, and troubleshooting.
1239
+
1240
+ ```text
1241
+ help-centre/
1242
+ └── guides/
1243
+ └── account/
1244
+ └── recovery/
1245
+ └── pages/
1246
+ ├── 1.json
1247
+ ├── 2.json
1248
+ └── 3812.json
1249
+ ```
1250
+
1251
+ Example record:
1252
+
1253
+ ```json
1254
+ {
1255
+ "title": "Recover your account",
1256
+ "category": "Account access",
1257
+ "english": {
1258
+ "heading": "Reset your password",
1259
+ "steps": [
1260
+ "Open account recovery",
1261
+ "Enter your email",
1262
+ "Follow the reset link"
1263
+ ]
1264
+ },
1265
+ "spanish": {
1266
+ "heading": "Restablece tu contraseña",
1267
+ "introduction": "Sigue estos pasos para recuperar el acceso a tu cuenta.",
1268
+ "steps": [
1269
+ "Abre la página de recuperación",
1270
+ "Introduce tu correo electrónico",
1271
+ "Sigue el enlace para restablecer la contraseña"
1272
+ ],
1273
+ "troubleshooting": {
1274
+ "email_missing": "Revisa la carpeta de correo no deseado.",
1275
+ "link_expired": "Solicita un nuevo enlace."
1276
+ }
1277
+ }
1278
+ }
1279
+ ```
1280
+
1281
+ Build the example:
1282
+
1283
+ ```sh
1284
+ npx rida-format build ./help-centre --output ./HelpData.rida --records-dir .
1285
+ ```
1286
+
1287
+ #### Your user needs Spanish instructions
1288
+
1289
+ 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.
1290
+
1291
+ ```js
1292
+ import { RidaReader } from "rida-format";
1293
+
1294
+ const reader = await RidaReader.open("./HelpData.rida");
1295
+ try {
1296
+ const prefix = reader.resolve("guides", "account", "recovery", "pages");
1297
+ if (!prefix) throw new Error("Folder not found in the map");
1298
+ const recordIds = reader.recordsUnder(prefix);
1299
+ // This exact example: 3812.json follows 1.json and 2.json.
1300
+ const recordId = recordIds[2];
1301
+ console.log(await reader.get(recordId, "spanish"));
1302
+ console.log(await reader.getMany(recordId, ["title", "category", "spanish"]));
1303
+ } finally {
1304
+ await reader.close();
1305
+ }
1306
+ ```
1307
+
1308
+ 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.
1309
+
1310
+
1311
+ 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.
1312
+
1313
+ 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.
1093
1314
 
1094
1315
  ## Current scope and limits
1095
1316
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rida-format",
3
- "version": "2.0.0",
3
+ "version": "3.0.2",
4
4
  "description": "Node.js reader and tools for RIDA 0.3.3 datasets",
5
5
  "type": "module",
6
6
  "engines": {
package/src/cli.js CHANGED
@@ -36,7 +36,8 @@ function parseArgs(args) {
36
36
  if (FLAGS.has(arg)) options[arg] = true;
37
37
  else if (VALUE_OPTIONS.has(arg)) {
38
38
  const value = args[++i];
39
- if (!value || value.startsWith("--")) throw new Error(`Missing value after ${arg}`);
39
+ const dashPrefixedKey = arg === "--key" && /^-[A-Za-z0-9_-]{42}=?$/.test(value ?? "");
40
+ if (!value || (value.startsWith("--") && !dashPrefixedKey)) throw new Error(`Missing value after ${arg}`);
40
41
  options[arg.slice(2).replaceAll("-", "")] = value;
41
42
  } else if (arg.startsWith("--")) throw new Error(`Unknown option: ${arg}`);
42
43
  else positional.push(arg);
package/src/index.js CHANGED
@@ -7,10 +7,11 @@ import { inflateRawSync } from "node:zlib";
7
7
  const require = createRequire(import.meta.url);
8
8
  const lzma = require("lzma-native");
9
9
 
10
- export const version = "2.0.0";
10
+ export const version = "3.0.2";
11
11
  export const MERGE_GAP_LIMIT = 660;
12
12
  const INDEX_MAGIC = Buffer.from("RIDAIDX1");
13
13
  const CATALOG_MAGIC = Buffer.from("RDACAT01");
14
+ const INDEX_LENGTH_LOW_WORD = 0xFFFFFFFFn;
14
15
 
15
16
  export class RidaError extends Error {
16
17
  constructor(message, options) { super(message, options); this.name = "RidaError"; }
@@ -45,7 +46,6 @@ function parseIndex(raw) {
45
46
  const recordCount = raw.readUInt32BE(20);
46
47
  const dataLengthBig = raw.readBigUInt64BE(24);
47
48
  need(versionNo === 1, `Unsupported RIDA index version: ${versionNo}`);
48
- need(dataLengthBig <= BigInt(Number.MAX_SAFE_INTEGER), "RIDA data file is too large for this Node.js runtime");
49
49
  const codecNo = raw.readUInt32BE(32);
50
50
  need(codecNo === 1 || codecNo === 2, "RIDA index has an unknown value codec");
51
51
  const catalog = raw.subarray(72);
@@ -55,13 +55,13 @@ function parseIndex(raw) {
55
55
  version: 3,
56
56
  indexVersion: versionNo,
57
57
  recordCount,
58
- dataLength: Number(dataLengthBig),
59
58
  valueCodec: codecNo === 1 ? "deflate-per-field" : "plain",
60
59
  encrypted: Boolean(raw.readUInt32BE(36) & 1),
61
60
  digest: Buffer.from(raw.subarray(40, 72)),
62
61
  catalogLength,
63
62
  rawCatalogLength,
64
63
  },
64
+ dataLengthBig,
65
65
  catalog,
66
66
  };
67
67
  }
@@ -160,6 +160,28 @@ function locate(catalog, recordId, wantedNames) {
160
160
  return found;
161
161
  }
162
162
 
163
+ function resolveDataLength(length, catalog) {
164
+ // Older Python writers put their length in the high word. A genuine
165
+ // multiple of 4 GiB has the same encoding; the catalog gives the real end.
166
+ if (length && !(length & INDEX_LENGTH_LOW_WORD)) {
167
+ let end = 0;
168
+ if (catalog.recordCount) {
169
+ const recordId = catalog.ids.at(-1) ?? catalog.recordCount;
170
+ const rowStart = catalog.rowDataStart + catalog.rowOffsets.at(-2);
171
+ const rowEnd = catalog.rowDataStart + catalog.rowOffsets.at(-1);
172
+ [end] = readVarint(catalog.raw.subarray(rowStart, rowEnd), 0);
173
+ for (const [offset, size] of locate(catalog, recordId, catalog.fields).values()) {
174
+ end = Math.max(end, offset + size);
175
+ }
176
+ }
177
+ const catalogEnd = BigInt(end);
178
+ need(catalogEnd === length || catalogEnd === (length >> 32n), "RIDA data length does not match its catalog");
179
+ length = catalogEnd;
180
+ }
181
+ need(length <= BigInt(Number.MAX_SAFE_INTEGER), "RIDA data file is too large for this Node.js runtime");
182
+ return Number(length);
183
+ }
184
+
163
185
  function normalizeKey(key) {
164
186
  if (key == null) return null;
165
187
  if (Buffer.isBuffer(key) || key instanceof Uint8Array) {
@@ -230,8 +252,9 @@ export class RidaReader {
230
252
  else indexLocation = companionPath(String(data), "Index.rida");
231
253
  }
232
254
  const [indexBytes, mapBytes] = await Promise.all([bytesFrom(indexLocation), map ? bytesFrom(map) : (dataIsUrl ? Promise.resolve(null) : readFile(companionPath(String(data), "Map.json")).catch(() => null))]);
233
- const { info, catalog: compressed } = parseIndex(indexBytes);
255
+ const { info, dataLengthBig, catalog: compressed } = parseIndex(indexBytes);
234
256
  const catalog = await parseCatalog(compressed, info);
257
+ info.dataLength = resolveDataLength(dataLengthBig, catalog);
235
258
  const normalizedKey = normalizeKey(key);
236
259
  need(!info.encrypted || normalizedKey, "This RIDA file is encrypted; provide its private key");
237
260
  let mapping = null;
@@ -239,8 +262,13 @@ export class RidaReader {
239
262
  let handle = null;
240
263
  if (!dataIsUrl) {
241
264
  handle = await open(data instanceof URL ? data : String(data), "r");
242
- const stat = await handle.stat();
243
- need(stat.size === info.dataLength, "RIDA data file does not match its index");
265
+ try {
266
+ const stat = await handle.stat();
267
+ need(stat.size === info.dataLength, "RIDA data file does not match its index");
268
+ } catch (error) {
269
+ await handle.close();
270
+ throw error;
271
+ }
244
272
  }
245
273
  return new RidaReader(data, handle, info, catalog, mapping, normalizedKey);
246
274
  }