@localness/contract 0.5.1 → 0.6.0

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
@@ -33,6 +33,10 @@ const { entries } = readLocaleFile(source)
33
33
  const next = writeLocaleFile(source, { 'home.title': 'Welcome', 'old.key': null }, 'nested-json')
34
34
  ```
35
35
 
36
+ Arrays are read by index: `{"steps":[{"title":"A"}],"tips":["x"]}` gives the keys `steps.0.title` and `tips.0`. Such a key can only be updated in place. `unwritableKeys` refuses a new key under an array (`steps.1.title` while `steps` has one element, `tips.x`), and a `null` for a key inside an array is ignored, so no write ever adds or removes an element and shifts the keys after it. `inArray(path)` tells such a key apart: `inArray(readLocaleFile(source).paths.get(key)!)`.
37
+
38
+ `paths` and `blocked` hold `LocaleKeyPath` (`(string | number)[]`, a number per array index), and `arrays` lists the path of every array. Before 0.6.0 they were `string[]` and arrays were only `blocked`.
39
+
36
40
  ## Versioning
37
41
 
38
42
  Independent of the Localness server version.
@@ -31,31 +31,45 @@ export declare function localeFilesScopeError(dir: string, pattern: string): str
31
31
  export declare function localeFileName(locale: string, localeMap: Record<string, string> | null): string;
32
32
  /** `/`-separated path of a locale's file. `dir` must pass `localeFilesScopeError`. */
33
33
  export declare function localeFilePath(dir: string, pattern: string, locale: string, localeMap: Record<string, string> | null): string;
34
+ /** JSON path of a value: property names, and a number for each array index. */
35
+ export type LocaleKeyPath = (string | number)[];
34
36
  /**
35
37
  * Keys are read the same way Translations import reads them — nested objects
36
38
  * joined with `.` — and every key remembers the property path it came from, so
37
39
  * a write lands on that exact property even in a file that mixes flat and
38
40
  * nested keys.
41
+ *
42
+ * Arrays are read by index: `{"list":[{"title":"A"}]}` is the key
43
+ * `list.0.title`. A key inside an array (see `inArray`) can only be updated:
44
+ * no write adds or removes an array element, since that would shift the keys
45
+ * of the elements after it.
39
46
  */
40
47
  export type LocaleFileContent = {
41
48
  entries: Record<string, string>;
42
- paths: Map<string, string[]>;
43
- /** Paths holding something other than an object or text (arrays, null). */
44
- blocked: string[][];
49
+ paths: Map<string, LocaleKeyPath>;
50
+ /** Paths holding something other than an object, array or text (null). */
51
+ blocked: LocaleKeyPath[];
52
+ /** Path of every array, empty ones included. */
53
+ arrays: LocaleKeyPath[];
45
54
  };
55
+ /** True when the path runs through an array, so its key may be updated but never added or removed. */
56
+ export declare function inArray(path: readonly (string | number)[]): boolean;
46
57
  export declare function readLocaleFile(source: string): LocaleFileContent;
47
58
  /**
48
59
  * Keys a write cannot place. A key already in the file is always writable, in
49
60
  * place. A new nested key is not when its path runs into an existing value
50
61
  * (`a` is text, so `a.b` has nowhere to go), would replace an object, has an
51
62
  * empty segment, or collides that way with another new key — then neither of
52
- * the two is written, since there is no right one to pick.
63
+ * the two is written, since there is no right one to pick. In either format a
64
+ * new key under an array (`list.4` when `list` has four elements, `list.x`) is
65
+ * not writable: arrays only take updates to the elements they already have.
53
66
  */
54
67
  export declare function unwritableKeys(file: LocaleFileContent, keys: string[], format: LocaleFileFormat): Set<string>;
55
68
  /**
56
69
  * Sets each entry in place and leaves everything else byte-for-byte: key
57
70
  * order, indentation, comments and line endings. A new key goes to the end of
58
- * its parent object. A `null` value removes the key. `source` null creates the
59
- * file. Callers must drop `unwritableKeys` first.
71
+ * its parent object. A `null` value removes the key, except a key inside an
72
+ * array, which is left as it is. `source` null creates the file. Callers must
73
+ * drop `unwritableKeys` first.
60
74
  */
61
75
  export declare function writeLocaleFile(source: string | null, entries: Record<string, string | null>, format: LocaleFileFormat): string;
@@ -1256,6 +1256,10 @@ function localeFileName(locale, localeMap) {
1256
1256
  function localeFilePath(dir, pattern, locale, localeMap) {
1257
1257
  return `${dir}/${pattern.replace(LOCALE_PLACEHOLDER, localeFileName(locale, localeMap))}`;
1258
1258
  }
1259
+ /** True when the path runs through an array, so its key may be updated but never added or removed. */
1260
+ function inArray(path) {
1261
+ return path.some((segment) => typeof segment === "number");
1262
+ }
1259
1263
  function readLocaleFile(source) {
1260
1264
  const errors = [];
1261
1265
  const root = parseTree(source, errors, { allowTrailingComma: true });
@@ -1265,45 +1269,48 @@ function readLocaleFile(source) {
1265
1269
  const entries = emptyEntries();
1266
1270
  const paths = /* @__PURE__ */ new Map();
1267
1271
  const blocked = [];
1268
- const walk = (node, path) => {
1269
- for (const property of node.children ?? []) {
1270
- const [nameNode, valueNode] = property.children ?? [];
1271
- if (!nameNode || !valueNode) continue;
1272
- const segments = [...path, String(nameNode.value)];
1273
- switch (valueNode.type) {
1274
- case "object":
1275
- walk(valueNode, segments);
1276
- break;
1277
- case "string":
1278
- case "number":
1279
- case "boolean": {
1280
- const key = segments.join(".");
1281
- paths.set(key, segments);
1282
- const text = normalizeLocaleText(valueNode.value);
1283
- if (text !== null) entries[key] = text;
1284
- break;
1285
- }
1286
- case "array":
1287
- case "null":
1288
- case "property":
1289
- blocked.push(segments);
1290
- break;
1291
- default: {
1292
- const unreachable = valueNode.type;
1293
- throw new Error(`Unknown JSON node type: ${unreachable}`);
1272
+ const arrays = [];
1273
+ const visit = (node, segments) => {
1274
+ switch (node.type) {
1275
+ case "object":
1276
+ for (const property of node.children ?? []) {
1277
+ const [nameNode, valueNode] = property.children ?? [];
1278
+ if (nameNode && valueNode) visit(valueNode, [...segments, String(nameNode.value)]);
1294
1279
  }
1280
+ break;
1281
+ case "array":
1282
+ arrays.push(segments);
1283
+ node.children?.forEach((element, index) => visit(element, [...segments, index]));
1284
+ break;
1285
+ case "string":
1286
+ case "number":
1287
+ case "boolean": {
1288
+ const key = segments.join(".");
1289
+ paths.set(key, segments);
1290
+ const text = normalizeLocaleText(node.value);
1291
+ if (text !== null) entries[key] = text;
1292
+ break;
1293
+ }
1294
+ case "null":
1295
+ case "property":
1296
+ blocked.push(segments);
1297
+ break;
1298
+ default: {
1299
+ const unreachable = node.type;
1300
+ throw new Error(`Unknown JSON node type: ${unreachable}`);
1295
1301
  }
1296
1302
  }
1297
1303
  };
1298
- walk(root, []);
1304
+ visit(root, []);
1299
1305
  return {
1300
1306
  entries,
1301
1307
  paths,
1302
- blocked
1308
+ blocked,
1309
+ arrays
1303
1310
  };
1304
1311
  }
1305
1312
  function isPrefix(a, b) {
1306
- return a.length <= b.length && a.every((segment, i) => segment === b[i]);
1313
+ return a.length <= b.length && a.every((segment, i) => String(segment) === String(b[i]));
1307
1314
  }
1308
1315
  function newKeyPath(key, format) {
1309
1316
  switch (format) {
@@ -1317,11 +1324,18 @@ function newKeyPath(key, format) {
1317
1324
  * place. A new nested key is not when its path runs into an existing value
1318
1325
  * (`a` is text, so `a.b` has nowhere to go), would replace an object, has an
1319
1326
  * empty segment, or collides that way with another new key — then neither of
1320
- * the two is written, since there is no right one to pick.
1327
+ * the two is written, since there is no right one to pick. In either format a
1328
+ * new key under an array (`list.4` when `list` has four elements, `list.x`) is
1329
+ * not writable: arrays only take updates to the elements they already have.
1321
1330
  */
1322
1331
  function unwritableKeys(file, keys, format) {
1323
1332
  const out = /* @__PURE__ */ new Set();
1324
- const occupied = [...file.paths.values(), ...file.blocked];
1333
+ const occupied = [
1334
+ ...file.paths.values(),
1335
+ ...file.blocked,
1336
+ ...file.arrays
1337
+ ];
1338
+ const arrayKeys = file.arrays.map((path) => path.join("."));
1325
1339
  const fresh = keys.filter((key) => !file.paths.has(key)).map((key) => ({
1326
1340
  key,
1327
1341
  path: newKeyPath(key, format)
@@ -1331,7 +1345,7 @@ function unwritableKeys(file, keys, format) {
1331
1345
  out.add(item.key);
1332
1346
  continue;
1333
1347
  }
1334
- const hitsFile = occupied.some((path) => isPrefix(path, item.path) || isPrefix(item.path, path));
1348
+ const hitsFile = arrayKeys.some((prefix) => item.key === prefix || item.key.startsWith(`${prefix}.`)) || occupied.some((path) => isPrefix(path, item.path) || isPrefix(item.path, path));
1335
1349
  const hitsFresh = fresh.some((other) => other.key !== item.key && (isPrefix(other.path, item.path) || isPrefix(item.path, other.path)));
1336
1350
  if (hitsFile || hitsFresh) out.add(item.key);
1337
1351
  }
@@ -1355,8 +1369,9 @@ function detectIndent(source) {
1355
1369
  /**
1356
1370
  * Sets each entry in place and leaves everything else byte-for-byte: key
1357
1371
  * order, indentation, comments and line endings. A new key goes to the end of
1358
- * its parent object. A `null` value removes the key. `source` null creates the
1359
- * file. Callers must drop `unwritableKeys` first.
1372
+ * its parent object. A `null` value removes the key, except a key inside an
1373
+ * array, which is left as it is. `source` null creates the file. Callers must
1374
+ * drop `unwritableKeys` first.
1360
1375
  */
1361
1376
  function writeLocaleFile(source, entries, format) {
1362
1377
  let text = source ?? "{}\n";
@@ -1375,7 +1390,7 @@ function writeLocaleFile(source, entries, format) {
1375
1390
  set(known ?? newKeyPath(key, format), value);
1376
1391
  continue;
1377
1392
  }
1378
- if (!known) continue;
1393
+ if (!known || inArray(known)) continue;
1379
1394
  set(known, void 0);
1380
1395
  for (let depth = known.length - 1; depth > 0; depth--) {
1381
1396
  const parent = known.slice(0, depth);
@@ -1386,4 +1401,4 @@ function writeLocaleFile(source, entries, format) {
1386
1401
  }
1387
1402
  return text.endsWith("\n") ? text : `${text}${eol}`;
1388
1403
  }
1389
- export { DEFAULT_LOCALE_FILE_PATTERN, LOCALE_KEY_SEPARATOR, LOCALE_PLACEHOLDER, LocaleFileFormat, emptyEntries, localeFileName, localeFilePath, localeFilesScopeError, normalizeLocaleText, readLocaleFile, unwritableKeys, writeLocaleFile };
1404
+ export { DEFAULT_LOCALE_FILE_PATTERN, LOCALE_KEY_SEPARATOR, LOCALE_PLACEHOLDER, LocaleFileFormat, emptyEntries, inArray, localeFileName, localeFilePath, localeFilesScopeError, normalizeLocaleText, readLocaleFile, unwritableKeys, writeLocaleFile };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@localness/contract",
3
- "version": "0.5.1",
3
+ "version": "0.6.0",
4
4
  "description": "Response contracts of the Localness public /api/v1: zod schemas and the types inferred from them.",
5
5
  "license": "Elastic-2.0",
6
6
  "type": "module",