@localness/contract 0.4.3 → 0.5.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
@@ -10,6 +10,18 @@ const meta: DeliveryMeta = deliveryMetaSchema.parse(await res.json())
10
10
 
11
11
  `zod` ^4 is a peer dependency.
12
12
 
13
+ ## Rules
14
+
15
+ `@localness/contract/rules` holds the pure rules a client must apply the way the server does: `fpTranslation` (the text fingerprint behind unnamed keys), `checkI18nKey` (why a key name breaks the project's key convention, with `KEY_VIOLATION_TEXT`) and `namespaceOf` (which declared namespace a key belongs to: names are relative to the project's key prefix). The convention and the namespace names come from `GET /api/v1/meta` (`keyConvention`, `namespaces`). It does not need `zod`.
16
+
17
+ ```ts
18
+ import { checkI18nKey, namespaceOf } from '@localness/contract/rules'
19
+
20
+ const { keyConvention, namespaces } = meta
21
+ checkI18nKey('shop_login_title', keyConvention) // []
22
+ namespaceOf('shop_login_title', namespaces.map((ns) => ns.name), keyConvention.prefix) // 'login'
23
+ ```
24
+
13
25
  ## Locale files
14
26
 
15
27
  `@localness/contract/locale-file` reads and writes one-JSON-per-locale files exactly as Localness git-sync does: flat or nested keys, edits in place (key order, indentation, comments and line endings are kept), new keys appended. The `localness` CLI uses it, so a file written by either one is identical. It does not need `zod`.
package/dist/index.d.mts CHANGED
@@ -21,9 +21,10 @@ export declare const releaseMembershipResultSchema: z.ZodObject<{
21
21
  }, z.core.$strip>;
22
22
  export type ReleaseMembershipResult = z.infer<typeof releaseMembershipResultSchema>;
23
23
  /**
24
- * A declared key namespace. Keys are grouped by name — a key belongs to the
25
- * namespace it starts with, followed by a separator — so this carries no list
26
- * of keys and never renames one.
24
+ * A declared key namespace. Keys are grouped by name — after the project's key
25
+ * prefix, a key belongs to the namespace it starts with, followed by a boundary
26
+ * (`namespaceOf` in `/rules`) — so this carries no list of keys and never
27
+ * renames one.
27
28
  */
28
29
  export declare const keyNamespaceSchema: z.ZodObject<{
29
30
  id: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
@@ -59,6 +60,22 @@ export declare const deliveryOutdatedSchema: z.ZodObject<{
59
60
  outdated: z.ZodRecord<z.ZodString, z.ZodArray<z.ZodString>>;
60
61
  }, z.core.$strip>;
61
62
  export type DeliveryOutdated = z.infer<typeof deliveryOutdatedSchema>;
63
+ /**
64
+ * The project's key naming rules, for clients that name keys themselves and
65
+ * group them by namespace (`checkI18nKey` and `namespaceOf` in `/rules`).
66
+ * `prefix` is without its trailing separator; `''` means no prefix.
67
+ */
68
+ export declare const deliveryKeyConventionSchema: z.ZodObject<{
69
+ prefix: z.ZodString;
70
+ separator: z.ZodString;
71
+ style: z.ZodEnum<{
72
+ snake_case: "snake_case";
73
+ camelCase: "camelCase";
74
+ }>;
75
+ maxDepth: z.ZodNumber;
76
+ guidance: z.ZodNullable<z.ZodString>;
77
+ }, z.core.$strip>;
78
+ export type DeliveryKeyConvention = z.infer<typeof deliveryKeyConventionSchema>;
62
79
  /** `GET /api/v1/meta` — what a caller holding only a token learns first. */
63
80
  export declare const deliveryMetaSchema: z.ZodObject<{
64
81
  project: z.ZodObject<{
@@ -82,6 +99,16 @@ export declare const deliveryMetaSchema: z.ZodObject<{
82
99
  name: z.ZodString;
83
100
  sort: z.ZodNumber;
84
101
  }, z.core.$strip>>>;
102
+ keyConvention: z.ZodOptional<z.ZodObject<{
103
+ prefix: z.ZodString;
104
+ separator: z.ZodString;
105
+ style: z.ZodEnum<{
106
+ snake_case: "snake_case";
107
+ camelCase: "camelCase";
108
+ }>;
109
+ maxDepth: z.ZodNumber;
110
+ guidance: z.ZodNullable<z.ZodString>;
111
+ }, z.core.$strip>>;
85
112
  coverage: z.ZodObject<{
86
113
  keys: z.ZodNumber;
87
114
  projectKeys: z.ZodNumber;
package/dist/index.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import { t as KEY_STYLE_VALUES } from "./key-convention-C4ZHbNKy.mjs";
1
2
  import { z } from "zod/v4";
2
3
  // ../../shared/contract/release.ts
3
4
  /** A row id, which the API sends as a number but the UI also carries as text. */
@@ -22,9 +23,10 @@ const releaseMembershipResultSchema = z.object({
22
23
  });
23
24
  // ../../shared/contract/namespace.ts
24
25
  /**
25
- * A declared key namespace. Keys are grouped by name — a key belongs to the
26
- * namespace it starts with, followed by a separator — so this carries no list
27
- * of keys and never renames one.
26
+ * A declared key namespace. Keys are grouped by name — after the project's key
27
+ * prefix, a key belongs to the namespace it starts with, followed by a boundary
28
+ * (`namespaceOf` in `/rules`) — so this carries no list of keys and never
29
+ * renames one.
28
30
  */
29
31
  const keyNamespaceSchema = z.object({
30
32
  id: idSchema,
@@ -58,6 +60,19 @@ const deliveryLocaleSchema = z.record(z.string(), z.string());
58
60
  const deliveryOutdatedSchema = z.object({
59
61
  /** locale → keys */
60
62
  outdated: z.record(z.string(), z.array(z.string())) });
63
+ /**
64
+ * The project's key naming rules, for clients that name keys themselves and
65
+ * group them by namespace (`checkI18nKey` and `namespaceOf` in `/rules`).
66
+ * `prefix` is without its trailing separator; `''` means no prefix.
67
+ */
68
+ const deliveryKeyConventionSchema = z.object({
69
+ prefix: z.string(),
70
+ separator: z.string(),
71
+ style: z.enum(KEY_STYLE_VALUES),
72
+ maxDepth: z.number(),
73
+ /** The project's naming guidance, or null when unset. */
74
+ guidance: z.string().nullable()
75
+ });
61
76
  /** `GET /api/v1/meta` — what a caller holding only a token learns first. */
62
77
  const deliveryMetaSchema = z.object({
63
78
  project: z.object({
@@ -79,6 +94,8 @@ const deliveryMetaSchema = z.object({
79
94
  namespace: z.string().nullable().optional(),
80
95
  /** The names `?namespace=` accepts, in display order. */
81
96
  namespaces: z.array(keyNamespaceSchema).optional(),
97
+ /** Optional: servers before it omit it. */
98
+ keyConvention: deliveryKeyConventionSchema.optional(),
82
99
  coverage: z.object({
83
100
  keys: z.number(),
84
101
  projectKeys: z.number(),
@@ -314,4 +331,4 @@ const keyNameSuggestionSchema = z.object({
314
331
  sameSourceText: z.boolean()
315
332
  }))
316
333
  });
317
- export { captureKeyHitSchema, captureKeySearchSchema, captureMatchSchema, capturePageSchema, captureTagSchema, createPageResultSchema, deleteTagsResultSchema, deliveryBundleSchema, deliveryKeyStateSchema, deliveryKeyStatesSchema, deliveryKeysSchema, deliveryLocaleSchema, deliveryLocaleStateNameSchema, deliveryMetaSchema, deliveryOutdatedSchema, deliveryProjectRefSchema, deliveryProjectsSchema, i18nKeyNamespaceCountsSchema, idSchema, importPageResultSchema, importPageTagsSchema, importedTagSchema, keyDraftConflictSchema, keyNameSuggestionSchema, keyNamespaceSchema, keyViolationSchema, keyWriteResultSchema, projectReleaseSchema, releaseMembershipResultSchema, uploadResultSchema };
334
+ export { captureKeyHitSchema, captureKeySearchSchema, captureMatchSchema, capturePageSchema, captureTagSchema, createPageResultSchema, deleteTagsResultSchema, deliveryBundleSchema, deliveryKeyConventionSchema, deliveryKeyStateSchema, deliveryKeyStatesSchema, deliveryKeysSchema, deliveryLocaleSchema, deliveryLocaleStateNameSchema, deliveryMetaSchema, deliveryOutdatedSchema, deliveryProjectRefSchema, deliveryProjectsSchema, i18nKeyNamespaceCountsSchema, idSchema, importPageResultSchema, importPageTagsSchema, importedTagSchema, keyDraftConflictSchema, keyNameSuggestionSchema, keyNamespaceSchema, keyViolationSchema, keyWriteResultSchema, projectReleaseSchema, releaseMembershipResultSchema, uploadResultSchema };
@@ -0,0 +1,49 @@
1
+ // ../../shared/contract/key-convention.ts
2
+ /**
3
+ * The per-project rules an i18n key has to follow. Pure, so a client that
4
+ * names keys itself checks them exactly the way the server does.
5
+ */
6
+ const KEY_STYLE_VALUES = ["snake_case", "camelCase"];
7
+ const KEY_VIOLATION_TEXT = {
8
+ prefix: "Missing the project key prefix",
9
+ charset: "Uses characters the key convention does not allow",
10
+ segment: "Has an empty segment",
11
+ case: "Does not match the configured casing",
12
+ depth: "Has more segments than the convention allows"
13
+ };
14
+ const SEGMENT_PATTERN = {
15
+ snake_case: /^[a-z0-9]+$/,
16
+ camelCase: /^[a-z][A-Za-z0-9]*$/
17
+ };
18
+ /** The key an empty prefix produces nothing in front of. */
19
+ function requiredStart(convention) {
20
+ return convention.prefix ? convention.prefix + convention.separator : "";
21
+ }
22
+ /**
23
+ * Pure: every way `key` breaks the convention, in the order worth fixing.
24
+ *
25
+ * An empty key is **legal** (a symbol-only source text has no name), so it is
26
+ * not a violation here — callers treat it as "cannot name", not as an error.
27
+ *
28
+ * The prefix itself is exempt: it is copied verbatim from the project settings,
29
+ * so the configured rules govern the path that follows it.
30
+ */
31
+ function checkI18nKey(key, convention) {
32
+ if (!key) return [];
33
+ const { separator, style, maxDepth } = convention;
34
+ if (!separator) return [];
35
+ const violations = [];
36
+ const start = requiredStart(convention);
37
+ const prefixed = Boolean(start) && key.startsWith(start);
38
+ if (start && !prefixed) violations.push("prefix");
39
+ const path = prefixed ? key.slice(start.length) : key;
40
+ const separatorChars = new Set(separator.split(""));
41
+ const allowed = (char) => /[0-9a-zA-Z]/.test(char) || separatorChars.has(char);
42
+ if ([...path].some((char) => !allowed(char))) violations.push("charset");
43
+ const segments = path.split(separator);
44
+ if (segments.some((segment) => segment === "")) violations.push("segment");
45
+ if (segments.length > maxDepth) violations.push("depth");
46
+ if (segments.some((one) => one && !SEGMENT_PATTERN[style].test(one))) violations.push("case");
47
+ return violations;
48
+ }
49
+ export { KEY_VIOLATION_TEXT as n, checkI18nKey as r, KEY_STYLE_VALUES as t };
package/dist/rules.d.mts CHANGED
@@ -1,3 +1,52 @@
1
+ /**
2
+ * The per-project rules an i18n key has to follow. Pure, so a client that
3
+ * names keys itself checks them exactly the way the server does.
4
+ */
5
+ export declare const KEY_STYLE_VALUES: readonly ["snake_case", "camelCase"];
6
+ export type KeyStyle = (typeof KEY_STYLE_VALUES)[number];
7
+ export type KeyConvention = {
8
+ /** Without the trailing separator; `''` means no prefix. */
9
+ prefix: string;
10
+ /** Joins the segments. Must be non-empty — the settings schema enforces it. */
11
+ separator: string;
12
+ style: KeyStyle;
13
+ /** How many segments may follow the prefix. */
14
+ maxDepth: number;
15
+ };
16
+ /** Why a key does not follow the convention. Sent to the client as a code. */
17
+ export type KeyViolation = 'prefix' | 'charset' | 'segment' | 'case' | 'depth';
18
+ export declare const KEY_VIOLATION_TEXT: Record<KeyViolation, string>;
19
+ /**
20
+ * Pure: every way `key` breaks the convention, in the order worth fixing.
21
+ *
22
+ * An empty key is **legal** (a symbol-only source text has no name), so it is
23
+ * not a violation here — callers treat it as "cannot name", not as an error.
24
+ *
25
+ * The prefix itself is exempt: it is copied verbatim from the project settings,
26
+ * so the configured rules govern the path that follows it.
27
+ */
28
+ export declare function checkI18nKey(key: string, convention: KeyConvention): KeyViolation[];
29
+ /**
30
+ * Which declared namespace a key belongs to. Names are relative to the
31
+ * project's key prefix: a key belongs to the namespace that what follows its
32
+ * prefix starts with, followed by a boundary character. Pure, so a client
33
+ * groups keys exactly the way the server does.
34
+ *
35
+ * Any boundary counts, not just the project's `keySeparator`: imports flatten
36
+ * nested JSON with `.`, so one project routinely holds both `s2w_a` and `s2w.a`.
37
+ */
38
+ export declare const NAMESPACE_BOUNDARY: readonly ["_", ".", "-", ":", "/"];
39
+ /**
40
+ * The key without the project's prefix and the boundary after it. A key that
41
+ * does not carry the prefix comes back whole, so imported or legacy keys still
42
+ * group by the same relative names.
43
+ */
44
+ export declare function stripProjectPrefix(key: string, projectPrefix: string): string;
45
+ /**
46
+ * Names are relative to the project prefix. Case-sensitive, like keys. The
47
+ * longest name wins should two ever both match.
48
+ */
49
+ export declare function namespaceOf(key: string, names: readonly string[], projectPrefix: string): string | null;
1
50
  /**
2
51
  * Rules a client must apply the same way the server does. A draft key is named
3
52
  * after the text it was created from, so a plugin and the server that disagree
package/dist/rules.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import { n as KEY_VIOLATION_TEXT, r as checkI18nKey, t as KEY_STYLE_VALUES } from "./key-convention-C4ZHbNKy.mjs";
1
2
  // \0rolldown/runtime.js
2
3
  var __create = Object.create;
3
4
  var __defProp = Object.defineProperty;
@@ -20,7 +21,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
20
21
  value: mod,
21
22
  enumerable: true
22
23
  }) : target, mod));
23
- // ../../shared/contract/rules.ts
24
+ // ../../shared/contract/key-namespace.ts
24
25
  var import_spark_md5 = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
25
26
  (function(factory) {
26
27
  if (typeof exports === "object") module.exports = factory();
@@ -620,6 +621,48 @@ var import_spark_md5 = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((
620
621
  return SparkMD5;
621
622
  });
622
623
  })))(), 1);
624
+ /**
625
+ * Which declared namespace a key belongs to. Names are relative to the
626
+ * project's key prefix: a key belongs to the namespace that what follows its
627
+ * prefix starts with, followed by a boundary character. Pure, so a client
628
+ * groups keys exactly the way the server does.
629
+ *
630
+ * Any boundary counts, not just the project's `keySeparator`: imports flatten
631
+ * nested JSON with `.`, so one project routinely holds both `s2w_a` and `s2w.a`.
632
+ */
633
+ const NAMESPACE_BOUNDARY = [
634
+ "_",
635
+ ".",
636
+ "-",
637
+ ":",
638
+ "/"
639
+ ];
640
+ const BOUNDARY = new Set(NAMESPACE_BOUNDARY);
641
+ function startsWithBoundary(text, head) {
642
+ return Boolean(head) && text.startsWith(head) && BOUNDARY.has(text.charAt(head.length));
643
+ }
644
+ /**
645
+ * The key without the project's prefix and the boundary after it. A key that
646
+ * does not carry the prefix comes back whole, so imported or legacy keys still
647
+ * group by the same relative names.
648
+ */
649
+ function stripProjectPrefix(key, projectPrefix) {
650
+ return startsWithBoundary(key, projectPrefix) ? key.slice(projectPrefix.length + 1) : key;
651
+ }
652
+ /**
653
+ * Names are relative to the project prefix. Case-sensitive, like keys. The
654
+ * longest name wins should two ever both match.
655
+ */
656
+ function namespaceOf(key, names, projectPrefix) {
657
+ const path = stripProjectPrefix(key, projectPrefix);
658
+ let best = null;
659
+ for (const name of names) {
660
+ if (!startsWithBoundary(path, name)) continue;
661
+ if (!best || name.length > best.length) best = name;
662
+ }
663
+ return best;
664
+ }
665
+ // ../../shared/contract/rules.ts
623
666
  /** Whitespace is not part of the sentence: `'Save\n As'` and `'SaveAs'` collide on purpose. */
624
667
  const fpTranslation = (text) => {
625
668
  const normalized = text.replace(/\s+/g, "").trim();
@@ -652,4 +695,4 @@ function entryMatchesReleaseFilter(releaseIds, filter) {
652
695
  if (filter === "unassigned") return ids.length === 0;
653
696
  return ids.some((releaseId) => String(releaseId) === String(filter));
654
697
  }
655
- export { LEGACY_DRAFT_KEY_PREFIX, UNNAMED_KEY_PREFIX, entryMatchesReleaseFilter, formatI18nKeyDisplay, fpTranslation, isUnnamedKey };
698
+ export { KEY_STYLE_VALUES, KEY_VIOLATION_TEXT, LEGACY_DRAFT_KEY_PREFIX, NAMESPACE_BOUNDARY, UNNAMED_KEY_PREFIX, checkI18nKey, entryMatchesReleaseFilter, formatI18nKeyDisplay, fpTranslation, isUnnamedKey, namespaceOf, stripProjectPrefix };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@localness/contract",
3
- "version": "0.4.3",
3
+ "version": "0.5.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",