Skip to content
cliff-formatPublic

About

CLIFF for JavaScript: a browser-first TypeScript implementation of CLIFF 1.0/1.1 (Contextual Localization Integrated File Format) with strict and tolerant parsers, serializer, validator, and JSON converters for browser and Node.js.

Topics

Resources

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

CLIFF for JavaScript

CLIFF — the Contextual Localization Integrated File Format

CI CLIFF 1.0 | 1.1 Node.js 22+ License Version 0.2.0


CLIFF keeps translation context — namespace, clan, group path, entry ID, type, emotion, width — next to every string, in a line-oriented format that stays cheap for translators and LLMs alike. cliff-js is the JavaScript and TypeScript implementation of that format: a typed data model, a strict parser, a tolerant parser, a canonical serializer, a validator, JSON converters, a CLIFF-native web runtime, a DeepSeek translation client and a Vite plugin.

Parse Strict mode rejects exactly what the grammar rejects; tolerant mode applies the seven documented repairs of Appendix C and reports each one.
Serialize Canonical output that round-trips, preserving the specification version the document declared.
Validate Required fields, closed vocabularies, status rules, duplicate IDs, ICU brace balance, layout, display width, and style.
Convert Lossless CLIFF-shaped JSON, plus flat and nested JSON for runtime resources.
Typed and browser-first ESM, CommonJS and .d.ts from one source; no runtime dependencies and no Node built-ins in the browser entry points.

The implementation targets CLIFF 1.1 and is checked against the normative examples of both 1.0 and 1.1, plus the cliff-test conformance fixtures.

Packages

Package Purpose
@cliff-format/core Data model, strict and tolerant parser, canonical serializer, validator
@cliff-format/json CLIFF-shaped, flat and nested JSON conversion
@cliff-format/i18n CLIFF-native runtime, t() builder, ICU and React adapter
@cliff-format/translate DeepSeek translation with CLIFF input and output
@cliff-format/vite .cliff imports, virtual:cliff and typed entry IDs

The core package contains no Node built-ins and no runtime dependencies. @cliff-format/json declares @cliff-format/core as a peer dependency.

Installation

pnpm add @cliff-format/core

Add the JSON package when converting to or from JSON resources:

pnpm add @cliff-format/core @cliff-format/json

Node.js 22 or newer is required for the build and test tooling. The published packages run in modern browsers.

Quick start

import { parse, serialize, validate } from "@cliff-format/core";

const text = [
  "CLIFF 1.1",
  "namespace: demo",
  "clan: settings",
  "source-language: en-US",
  "target-language: zh-CN",
  "",
  "[Video]",
  "type: label",
  "",
  "<Resolution>",
  'source: "Resolution"',
  'target: "分辨率"',
  "status: final",
  "",
].join("\n");

const document = parse(text);
console.log(document.specVersion);               // "1.1"
console.log(document.header.namespace);          // "demo"
console.log(document.groups[0]?.path);           // "Video"
console.log(document.groups[0]?.entries[0]?.id); // "Resolution"

console.log(serialize(document));                 // canonical CLIFF

for (const issue of validate(text)) {
  console.log(issue.line, issue.category, issue.message);
}

parse is the strict syntax and structure parser. It does not enforce required fields, vocabularies, ICU balance, duplicate IDs, layout or width. validate is the full semantic gate and returns diagnostics instead of throwing for invalid CLIFF content.

Strict and tolerant parsing

CLIFF 1.1 defines two readings of the same syntax, and @cliff-format/core exposes both. Strict is the default; the mode is never chosen for you.

Strict (parse) rejects everything the grammar rejects:

  • identifiers may use A-Z a-z 0-9 _ -, never ., are case-sensitive, and are never rewritten;
  • tags (type, emotion, status, variant) stay in their closed vocabularies;
  • one optional trailing , or ; per line is accepted and is never re-emitted;
  • a file-layout mismatch is a warning, because layout is a recommendation;
  • resource limits are enforced.

Tolerant (parseTolerant) adds the seven relaxations of Appendix C and reports every repair:

Relaxation Input Result
C.2.1 bare scalar in a list-typed field emotion: objective ["objective"]
C.2.2 repeated field in one scope two target: lines concatenated / appended in order
C.2.3 quoted tag status: "final" final
C.2.4 quoted entry ID <"resolution"> resolution
C.2.5 identifier with a reserved character <Save & Load> Save-Load (+ collision handling)
C.2.6 version-line spelling cliff 1.1.0 CLIFF 1.1
C.2.7 quoted key "context": "…" context: "…"

Every repair is recorded, so nothing is fixed silently:

import { parseTolerant } from "@cliff-format/core";

const { document, corrections } = parseTolerant(modelOutput);
for (const correction of corrections) {
  console.log(correction.line, correction.category, correction.message, correction.before, "->", correction.after);
}

Categories: list-shape, field-repeat, tag-quote, name-quote, name-normalized, id-collision, version.

The mode never guesses. Appendix C.5 lists what a tolerant parser must refuse — a missing required field, a word outside a closed vocabulary, an unbalanced ICU brace, a malformed line, an unsupported version — and those raise CliffParseError or CliffValidationError with a line number and a category.

parseTolerant enforces the C.6 output guarantee: the repaired document validates under the strict rules, and canonical output is a fixed point.

The JavaScript implementation follows Appendix C and does not add the extra cliff-python leniencies for a missing version line, tag case folding or nested list flattening. See docs/conformance.md for the complete difference list.

JSON conversion

@cliff-format/json provides three shapes:

  • CLIFF-shaped JSON — the lossless form. It preserves the header, group metadata, every entry field, extensions and the declared specification version.
  • Flat JSON — dotted keys mapped to strings.
  • Nested JSON — nested objects suitable for simple i18next resources.
import { parse } from "@cliff-format/core";
import {
  fromCliJson,
  fromFlatJson,
  toCliJson,
  toFlatJson,
  toNestedJson,
} from "@cliff-format/json";

const document = parse(text);

const lossless = toCliJson(document);
const restored = fromCliJson(lossless);

const { document: imported, warnings } = fromFlatJson(
  { "video.resolution": "分辨率" },
  {
    namespace: "demo",
    clan: "settings",
    sourceLanguage: "en-US",
    targetLanguage: "zh-CN",
  },
);

const flat = toFlatJson(imported, { keyStyle: "canonical" });
const nested = toNestedJson(imported);

Flat and nested JSON are lossy runtime-resource views. They do not carry header prose, context, types, emotion, status, width, reviewer, references or extensions. Use CLIFF-shaped JSON when those matter.

Format Fidelity
CLIFF-shaped JSON Lossless
Flat JSON key/value only
Nested JSON key/value only

Import options include valueRole, entryType, entryStatus and keySeparator. See the JSON package README for the complete option list.

Web localization

@cliff-format/i18n reads and writes CLIFF directly. A scope is mandatory because CLIFF requires namespace and clan:

import { createI18n, TYPE, EMOTION } from "@cliff-format/i18n";

const i18n = createI18n({
  locale: "zh-CN",
  fallbackLocale: "en-US",
  resources: [cliffText],
});

const { t } = i18n.scope({ namespace: "demo", clan: "settings", group: "video" });

const label = t("resolution").render();
const authored = t("contrast")
  .source("Contrast")
  .type(TYPE.noun)
  .emotion(EMOTION.objective)
  .render();

Calling .source() enters authoring mode; render() and commit() are compile-time unavailable until .type() or .typeFromGroup() supplies the required CLIFF type. Lookup mode reads the metadata from CLIFF. A draft is a real status: initial entry exported by toCliff().

The main entry uses messageformat for MF2 and @messageformat/icu-messageformat-1 for MF1. Use @cliff-format/i18n/lite to omit the ICU runtime, and @cliff-format/i18n/react for useTranslation().

DeepSeek translation exchanges CLIFF only:

import { createDeepSeekTranslator } from "@cliff-format/translate";

const translator = createDeepSeekTranslator({
  apiKey: process.env.DEEPSEEK_API_KEY,
  model: "deepseek-flash",
  temperature: 1.3,
  thinking: "off",
});

const result = await translator.translate(cliffText, { targetLanguage: "zh-CN" });

See docs/web-localization.md for the entry ID grammar, builder states and runtime design.

API

Function Description
parse(input, options?) Strict syntax and structure parser. Throws CliffParseError.
parseTolerant(input, options?) Appendix C repairs plus full validation. Returns { document, corrections }.
validate(input, options?) Full semantic validation. Returns ValidationIssue[].
validateDocument(document, options?) Validate a hand-built or imported document.
serialize(document, options?) Canonical CLIFF output.
displayWidth(text) Rendered display width under UAX #11, with grapheme clustering.
effectiveContext / effectiveType / effectiveEmotion / effectiveMaxWidth Resolve a group-inherited value for one entry.
canonicalId / isName / isTag / normalizeIdentifier Identifier rules and canonical IDs.
toCliJson / fromCliJson / toJsonString / fromJsonString Lossless CLIFF-shaped JSON.
fromFlatJson / toFlatJson / fromNestedJson / toNestedJson Runtime-resource JSON views.

Diagnostics

Category Meaning
syntax, semantic, vocabulary, icu, id Errors: the file does not conform.
warning A recommendation (layout mismatch, glossary shape, width overflow).
extension An x- field was ignored, as the specification requires.
correction A tolerant parse repaired something; reports before → after.
style A deviation from the style guide; never an error.

Resource limits

parse, parseTolerant and validate accept configurable limits:

Limit Default
maxBytes 16 MiB
maxLines 1,000,000
maxLineLength 1,048,576 UTF-16 code units
maxStringLength 1,048,576 UTF-16 code units
maxGroupSegments 64
maxListItems 10,000
maxEntries 1,000,000

Exceeding a limit raises a located CliffLimitError instead of exhausting memory. Limits apply in strict and tolerant mode alike.

Browser usage

The browser entry points use only standard JavaScript, TextEncoder/TextDecoder, fetch and Intl APIs. They do not import Node built-ins; the Vite plugin is Node-only.

const bytes = new Uint8Array(await file.arrayBuffer());
const document = parse(bytes);
const issues = validate(bytes);

Both string and Uint8Array input are accepted; byte input is decoded as strict UTF-8. The packages can run in a module worker. See docs/browser.md.

Repository layout

cliff-js/
├── packages/
│   ├── core/          # @cliff-format/core
│   ├── json/          # @cliff-format/json
│   ├── i18n/          # @cliff-format/i18n
│   ├── translate/     # @cliff-format/translate
│   └── vite/          # @cliff-format/vite
├── fixtures/upstream/ # specification examples and conformance fixtures
├── docs/              # architecture, API, conformance, security, VCS policy
├── browser/           # Playwright browser smoke test
├── scripts/           # checks, fixture sync, package smoke test
└── .github/workflows/ # CI, VCS and release workflows

The core package has no runtime dependencies. i18n, translation and build-plugin packages live beside it and depend on the core public API.

Development

pnpm install
pnpm verify

pnpm verify runs lint, type checking, tests, builds, package metadata checks, version checks, boundary checks, the browser bundle check and the fixture provenance check. The Playwright suite runs in CI with pnpm test:browser.

The repository follows the English-only version control policy. Development integrates on dev; main is release-only. Feature and fix pull requests target dev, while release merges target main. Documentation-only changes skip the heavy CI workflow; the lightweight VCS workflow still checks the commit message. A full run can be started manually from the Actions tab.

Links

License

MIT — see LICENSE. The CLIFF wordmark under docs/assets/ comes from the CLIFF project and is licensed under the MIT License as well.

About

CLIFF for JavaScript: a browser-first TypeScript implementation of CLIFF 1.0/1.1 (Contextual Localization Integrated File Format) with strict and tolerant parsers, serializer, validator, and JSON converters for browser and Node.js.

Topics

Resources

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Contributors

Languages