@cbortech/cbor 0.26.5 → 0.26.6

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.
Files changed (40) hide show
  1. package/README.ja.md +95 -34
  2. package/README.md +99 -38
  3. package/dist/ast/index.cjs +1 -1
  4. package/dist/ast/index.js +2 -2
  5. package/dist/cbor.d.ts +8 -0
  6. package/dist/cddl/ast.d.ts +196 -0
  7. package/dist/cddl/controls.d.ts +28 -0
  8. package/dist/cddl/equal.d.ts +19 -0
  9. package/dist/cddl/errors.d.ts +91 -0
  10. package/dist/cddl/index.cjs +3 -0
  11. package/dist/cddl/index.cjs.map +1 -0
  12. package/dist/cddl/index.d.ts +52 -0
  13. package/dist/cddl/index.js +67 -0
  14. package/dist/cddl/index.js.map +1 -0
  15. package/dist/cddl/parser.d.ts +13 -0
  16. package/dist/cddl/position.d.ts +13 -0
  17. package/dist/cddl/prelude.d.ts +5 -0
  18. package/dist/cddl/schema.d.ts +90 -0
  19. package/dist/cddl/tokenizer.d.ts +138 -0
  20. package/dist/cddl/validator.d.ts +30 -0
  21. package/dist/cddl/writer.d.ts +23 -0
  22. package/dist/index.cjs +7 -7
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.d.ts +2 -0
  25. package/dist/index.js +104 -77
  26. package/dist/index.js.map +1 -1
  27. package/dist/mapEntries-BhMlCwYo.cjs +15 -0
  28. package/dist/mapEntries-BhMlCwYo.cjs.map +1 -0
  29. package/dist/{mapEntries-Clr-oNtQ.js → mapEntries-Czxt-cmd.js} +427 -422
  30. package/dist/mapEntries-Czxt-cmd.js.map +1 -0
  31. package/dist/schema-BmGsaEaW.cjs +63 -0
  32. package/dist/schema-BmGsaEaW.cjs.map +1 -0
  33. package/dist/schema-BxkgvUY6.js +1977 -0
  34. package/dist/schema-BxkgvUY6.js.map +1 -0
  35. package/dist/types.d.ts +89 -0
  36. package/dist/utils/base64.d.ts +12 -0
  37. package/package.json +23 -6
  38. package/dist/mapEntries-6hy7UgeN.cjs +0 -15
  39. package/dist/mapEntries-6hy7UgeN.cjs.map +0 -1
  40. package/dist/mapEntries-Clr-oNtQ.js.map +0 -1
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Structured errors thrown by the CDDL tokenizer, parser, and compiler.
3
+ *
4
+ * Both carry source positions so tooling (editors, linters, playgrounds) can
5
+ * point at the offending range without parsing the message.
6
+ */
7
+ /** A semantic problem found while compiling a syntactically valid CDDL file. */
8
+ export interface CddlWarning {
9
+ /** Stable machine-readable identifier, e.g. 'undefined-name'. */
10
+ code: 'no-rules' | 'duplicate-rule' | 'undefined-name' | 'generic-arity' | 'invalid-major' | 'invalid-root';
11
+ message: string;
12
+ /** Character offset of the start of the offending range in the source input. */
13
+ start?: number;
14
+ /** Character offset just past the end of the offending range. */
15
+ end?: number;
16
+ }
17
+ /**
18
+ * A single validation failure. When a data item does not match the schema,
19
+ * the reported error is the one recorded at the deepest point the matcher
20
+ * reached (failures discarded by backtracking are noise and are not kept).
21
+ */
22
+ export interface CddlValidationError {
23
+ message: string;
24
+ /** Location inside the instance, e.g. '/claims/2/name' ('' = root). */
25
+ path: string;
26
+ /** Instance-side source offsets (byte offsets for CBOR input, character
27
+ * offsets for CDN input), when the input carried them. */
28
+ start?: number;
29
+ end?: number;
30
+ /** The CDDL rule being matched when the failure was recorded. */
31
+ ruleName?: string;
32
+ /** Schema-side source offsets of the CDDL construct that failed to match. */
33
+ schemaStart?: number;
34
+ schemaEnd?: number;
35
+ }
36
+ /** A non-fatal observation made while validating (e.g. unsupported control
37
+ * operators, whose targets are then matched without the constraint). */
38
+ export interface CddlValidationWarning {
39
+ message: string;
40
+ schemaStart?: number;
41
+ schemaEnd?: number;
42
+ }
43
+ /** Result of {@link CddlSchema.validate}. */
44
+ export interface ValidationResult {
45
+ valid: boolean;
46
+ /** Empty when valid; otherwise the deepest-reach failure(s). */
47
+ errors: CddlValidationError[];
48
+ /** Present when the validator had to approximate or skip constraints. */
49
+ warnings?: CddlValidationWarning[];
50
+ }
51
+ /** Syntax error thrown by the CDDL tokenizer and parser. */
52
+ export declare class CddlSyntaxError extends SyntaxError {
53
+ /** Character offset of the start of the offending range in the source input. */
54
+ readonly offset?: number;
55
+ /** 1-based line number of the offending range. */
56
+ readonly line?: number;
57
+ /** 1-based column number of the offending range. */
58
+ readonly column?: number;
59
+ /** Character offset just past the end of the offending range. */
60
+ readonly endOffset?: number;
61
+ constructor(message: string, position?: {
62
+ offset?: number;
63
+ line?: number;
64
+ column?: number;
65
+ endOffset?: number;
66
+ });
67
+ }
68
+ /**
69
+ * Error thrown when a data item does not match a CDDL schema supplied via
70
+ * the `cddl` option of a throwing entry point (`CBOR.parse`, `CBOR.decode`,
71
+ * `CBOR.fromCDN`, `CBOR.encode`, …). Non-throwing checks (`CBOR.validate`,
72
+ * `CddlSchema.validate`) report the same failures in their result instead.
73
+ */
74
+ export declare class CddlMismatchError extends Error {
75
+ /** The deepest-reach validation failure(s). */
76
+ readonly errors: CddlValidationError[];
77
+ /** Non-fatal validator observations (approximated/skipped constraints). */
78
+ readonly warnings: CddlValidationWarning[];
79
+ constructor(errors: CddlValidationError[], warnings?: CddlValidationWarning[]);
80
+ }
81
+ /**
82
+ * Semantic error thrown by `CDDL.compile` in strict mode (the default) when
83
+ * a syntactically valid file has semantic problems: undefined names,
84
+ * duplicate rule definitions, generic arity mismatches, and the like.
85
+ * With `strict: false` the same problems are collected into
86
+ * `CddlSchema.warnings` instead.
87
+ */
88
+ export declare class CddlSemanticError extends Error {
89
+ readonly warnings: CddlWarning[];
90
+ constructor(warnings: CddlWarning[]);
91
+ }
@@ -0,0 +1,3 @@
1
+ Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:`Module`}});const e=require("../schema-BmGsaEaW.cjs");function t(e,t){let n=Math.max(0,Math.min(t,e.length)),r=1,i=0;for(let t=0;t<n;t++)e.charCodeAt(t)===10&&(r++,i=t+1);return{line:r,column:n-i+1}}var n=class{static compile(t,n){return e.n(t,n)}};function r(t){let n=new e.o(t),r=[];for(;;){let e=n.consume();if(e.type===`EOF`)break;r.push(e)}return{tokens:r,comments:n.comments}}function i(t){let n=new e.o(t),r=[];try{for(;;){let e=n.consume();if(e.type===`EOF`)break;r.push(e)}return{tokens:r,comments:n.comments}}catch(i){let a=i instanceof e.l?i:new e.l(i instanceof Error?i.message:String(i)),o=n.lastEndOffset;if(o<t.length){let e=1,n=1;for(let r=0;r<o;r++)t[r]===`
2
+ `?(e++,n=1):n++;r.push({type:`ERROR`,value:t.slice(o),raw:t.slice(o),line:e,col:n,offset:o,endOffset:t.length})}return{tokens:r,comments:n.comments,error:a}}}exports.CDDL=n,exports.default=n,exports.CddlMismatchError=e.s,exports.CddlSchema=e.t,exports.CddlSemanticError=e.c,exports.CddlSyntaxError=e.l,exports.PRELUDE_CDDL=e.r,exports.getPreludeRules=e.i,exports.parseCDDL=e.a,exports.positionAt=t,exports.tokenize=r,exports.tokenizeLenient=i;
3
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","names":[],"sources":["../../src/cddl/position.ts","../../src/cddl/index.ts"],"sourcesContent":["/**\n * Convert a character offset (as carried by CDDL AST nodes, CddlWarning,\n * and CddlValidationError.schemaStart/schemaEnd or start/end for CDN input)\n * into a 1-based line/column position, for CLI-style `file:line:col`\n * reporting.\n *\n * Offsets are JS string indices (UTF-16 code units), matching everything\n * else in this library. Offsets past the end of the text clamp to its end.\n */\nexport function positionAt(\n text: string,\n offset: number\n): { line: number; column: number } {\n const end = Math.max(0, Math.min(offset, text.length));\n let line = 1;\n let lineStart = 0;\n for (let i = 0; i < end; i++) {\n if (text.charCodeAt(i) === 0x0a) {\n line++;\n lineStart = i + 1;\n }\n }\n return { line, column: end - lineStart + 1 };\n}\n","/**\n * Public CDDL API (`@cbortech/cbor/cddl`).\n *\n * Phase 1 covers the grammar layer of RFC 8610 + RFC 9682: compiling CDDL\n * text into a checked rule table (`CDDL.compile`), re-serializing it\n * (`schema.format()`), and the lower-level tokenization API used by tooling\n * such as syntax highlighters. Validating CBOR/CDN data against a schema is\n * a later phase.\n */\n\nimport { CddlTokenizer, type CddlComment, type CddlToken } from './tokenizer';\nimport { CddlSyntaxError } from './errors';\nimport { compile, CddlSchema, type CompileOptions } from './schema';\n\nexport type { CddlToken, CddlTokenType, CddlComment } from './tokenizer';\nexport {\n CddlSyntaxError,\n CddlSemanticError,\n CddlMismatchError,\n} from './errors';\nexport type {\n CddlWarning,\n CddlValidationError,\n CddlValidationWarning,\n ValidationResult,\n} from './errors';\nexport type { ValidateOptions } from './validator';\nexport { CddlSchema } from './schema';\nexport type { CompileOptions } from './schema';\nexport { parseCDDL } from './parser';\nexport type { ParseCddlResult } from './parser';\nexport { PRELUDE_CDDL, getPreludeRules } from './prelude';\nexport { positionAt } from './position';\nexport type { CddlFormatOptions } from './writer';\nexport type {\n CddlRule,\n CddlType,\n CddlType1,\n CddlType2,\n CddlValue,\n CddlRef,\n CddlParenType,\n CddlMapType,\n CddlArrayType,\n CddlUnwrap,\n CddlEnum,\n CddlTagged,\n CddlMajor,\n CddlAny,\n CddlGroup,\n CddlGroupEntry,\n CddlEntryValue,\n CddlEntryGroup,\n CddlOccur,\n CddlMemberKey,\n CddlNodeBase,\n} from './ast';\n\n/** Main CDDL facade — mirrors the shape of the `CBOR` facade. */\nexport class CDDL {\n /**\n * Parse and compile a CDDL data model.\n *\n * @example\n * const schema = CDDL.compile(`person = { name: tstr, ? age: uint }`);\n * schema.root.name; // 'person'\n */\n static compile(text: string, options?: CompileOptions): CddlSchema {\n return compile(text, options);\n }\n}\n\nexport default CDDL;\n\nexport interface TokenizeResult {\n /** Scanned tokens in source order, excluding the final EOF token. */\n tokens: CddlToken[];\n /** Comments encountered while scanning, in source order. */\n comments: CddlComment[];\n}\n\nexport interface TokenizeLenientResult extends TokenizeResult {\n /**\n * The scan failure, if any. When set, `tokens` ends with a synthetic\n * `ERROR` token covering the source from the last clean token to the end\n * of the input.\n */\n error?: CddlSyntaxError;\n}\n\n/**\n * Tokenize CDDL text. Throws {@link CddlSyntaxError} on invalid input.\n */\nexport function tokenize(text: string): TokenizeResult {\n const tokenizer = new CddlTokenizer(text);\n const tokens: CddlToken[] = [];\n for (;;) {\n const tok = tokenizer.consume();\n if (tok.type === 'EOF') break;\n tokens.push(tok);\n }\n return { tokens, comments: tokenizer.comments };\n}\n\n/**\n * Error-tolerant tokenization for editors and highlighters: never throws on\n * invalid input. Tokens before the failure are returned as scanned; the\n * remainder of the input is covered by a single synthetic `ERROR` token and\n * the failure is reported in `error`.\n */\nexport function tokenizeLenient(text: string): TokenizeLenientResult {\n const tokenizer = new CddlTokenizer(text);\n const tokens: CddlToken[] = [];\n try {\n for (;;) {\n const tok = tokenizer.consume();\n if (tok.type === 'EOF') break;\n tokens.push(tok);\n }\n return { tokens, comments: tokenizer.comments };\n } catch (e) {\n const error =\n e instanceof CddlSyntaxError\n ? e\n : new CddlSyntaxError(e instanceof Error ? e.message : String(e));\n const start = tokenizer.lastEndOffset;\n if (start < text.length) {\n let line = 1;\n let col = 1;\n for (let i = 0; i < start; i++) {\n if (text[i] === '\\n') {\n line++;\n col = 1;\n } else {\n col++;\n }\n }\n tokens.push({\n type: 'ERROR',\n value: text.slice(start),\n raw: text.slice(start),\n line,\n col,\n offset: start,\n endOffset: text.length,\n });\n }\n return { tokens, comments: tokenizer.comments, error };\n }\n}\n"],"mappings":"yIASA,SAAgB,EACd,EACA,EACkC,CAClC,IAAM,EAAM,KAAK,IAAI,EAAG,KAAK,IAAI,EAAQ,EAAK,MAAM,CAAC,EACjD,EAAO,EACP,EAAY,EAChB,IAAK,IAAI,EAAI,EAAG,EAAI,EAAK,IACnB,EAAK,WAAW,CAAC,IAAM,KACzB,IACA,EAAY,EAAI,GAGpB,MAAO,CAAE,OAAM,OAAQ,EAAM,EAAY,CAAE,CAC7C,CCoCA,IAAa,EAAb,KAAkB,CAQhB,OAAO,QAAQ,EAAc,EAAsC,CACjE,OAAO,EAAA,EAAQ,EAAM,CAAO,CAC9B,CACF,EAuBA,SAAgB,EAAS,EAA8B,CACrD,IAAM,EAAY,IAAI,EAAA,EAAc,CAAI,EAClC,EAAsB,CAAC,EAC7B,OAAS,CACP,IAAM,EAAM,EAAU,QAAQ,EAC9B,GAAI,EAAI,OAAS,MAAO,MACxB,EAAO,KAAK,CAAG,CACjB,CACA,MAAO,CAAE,SAAQ,SAAU,EAAU,QAAS,CAChD,CAQA,SAAgB,EAAgB,EAAqC,CACnE,IAAM,EAAY,IAAI,EAAA,EAAc,CAAI,EAClC,EAAsB,CAAC,EAC7B,GAAI,CACF,OAAS,CACP,IAAM,EAAM,EAAU,QAAQ,EAC9B,GAAI,EAAI,OAAS,MAAO,MACxB,EAAO,KAAK,CAAG,CACjB,CACA,MAAO,CAAE,SAAQ,SAAU,EAAU,QAAS,CAChD,OAAS,EAAG,CACV,IAAM,EACJ,aAAa,EAAA,EACT,EACA,IAAI,EAAA,EAAgB,aAAa,MAAQ,EAAE,QAAU,OAAO,CAAC,CAAC,EAC9D,EAAQ,EAAU,cACxB,GAAI,EAAQ,EAAK,OAAQ,CACvB,IAAI,EAAO,EACP,EAAM,EACV,IAAK,IAAI,EAAI,EAAG,EAAI,EAAO,IACrB,EAAK,KAAO;GACd,IACA,EAAM,GAEN,IAGJ,EAAO,KAAK,CACV,KAAM,QACN,MAAO,EAAK,MAAM,CAAK,EACvB,IAAK,EAAK,MAAM,CAAK,EACrB,OACA,MACA,OAAQ,EACR,UAAW,EAAK,MAClB,CAAC,CACH,CACA,MAAO,CAAE,SAAQ,SAAU,EAAU,SAAU,OAAM,CACvD,CACF"}
@@ -0,0 +1,52 @@
1
+ import { CddlComment, CddlToken } from './tokenizer';
2
+ import { CddlSyntaxError } from './errors';
3
+ import { CddlSchema, CompileOptions } from './schema';
4
+ export type { CddlToken, CddlTokenType, CddlComment } from './tokenizer';
5
+ export { CddlSyntaxError, CddlSemanticError, CddlMismatchError, } from './errors';
6
+ export type { CddlWarning, CddlValidationError, CddlValidationWarning, ValidationResult, } from './errors';
7
+ export type { ValidateOptions } from './validator';
8
+ export { CddlSchema } from './schema';
9
+ export type { CompileOptions } from './schema';
10
+ export { parseCDDL } from './parser';
11
+ export type { ParseCddlResult } from './parser';
12
+ export { PRELUDE_CDDL, getPreludeRules } from './prelude';
13
+ export { positionAt } from './position';
14
+ export type { CddlFormatOptions } from './writer';
15
+ export type { CddlRule, CddlType, CddlType1, CddlType2, CddlValue, CddlRef, CddlParenType, CddlMapType, CddlArrayType, CddlUnwrap, CddlEnum, CddlTagged, CddlMajor, CddlAny, CddlGroup, CddlGroupEntry, CddlEntryValue, CddlEntryGroup, CddlOccur, CddlMemberKey, CddlNodeBase, } from './ast';
16
+ /** Main CDDL facade — mirrors the shape of the `CBOR` facade. */
17
+ export declare class CDDL {
18
+ /**
19
+ * Parse and compile a CDDL data model.
20
+ *
21
+ * @example
22
+ * const schema = CDDL.compile(`person = { name: tstr, ? age: uint }`);
23
+ * schema.root.name; // 'person'
24
+ */
25
+ static compile(text: string, options?: CompileOptions): CddlSchema;
26
+ }
27
+ export default CDDL;
28
+ export interface TokenizeResult {
29
+ /** Scanned tokens in source order, excluding the final EOF token. */
30
+ tokens: CddlToken[];
31
+ /** Comments encountered while scanning, in source order. */
32
+ comments: CddlComment[];
33
+ }
34
+ export interface TokenizeLenientResult extends TokenizeResult {
35
+ /**
36
+ * The scan failure, if any. When set, `tokens` ends with a synthetic
37
+ * `ERROR` token covering the source from the last clean token to the end
38
+ * of the input.
39
+ */
40
+ error?: CddlSyntaxError;
41
+ }
42
+ /**
43
+ * Tokenize CDDL text. Throws {@link CddlSyntaxError} on invalid input.
44
+ */
45
+ export declare function tokenize(text: string): TokenizeResult;
46
+ /**
47
+ * Error-tolerant tokenization for editors and highlighters: never throws on
48
+ * invalid input. Tokens before the failure are returned as scanned; the
49
+ * remainder of the input is covered by a single synthetic `ERROR` token and
50
+ * the failure is reported in `error`.
51
+ */
52
+ export declare function tokenizeLenient(text: string): TokenizeLenientResult;
@@ -0,0 +1,67 @@
1
+ import { a as e, c as t, i as n, l as r, n as i, o as a, r as o, s, t as c } from "../schema-BxkgvUY6.js";
2
+ //#region src/cddl/position.ts
3
+ function l(e, t) {
4
+ let n = Math.max(0, Math.min(t, e.length)), r = 1, i = 0;
5
+ for (let t = 0; t < n; t++) e.charCodeAt(t) === 10 && (r++, i = t + 1);
6
+ return {
7
+ line: r,
8
+ column: n - i + 1
9
+ };
10
+ }
11
+ //#endregion
12
+ //#region src/cddl/index.ts
13
+ var u = class {
14
+ static compile(e, t) {
15
+ return i(e, t);
16
+ }
17
+ };
18
+ function d(e) {
19
+ let t = new a(e), n = [];
20
+ for (;;) {
21
+ let e = t.consume();
22
+ if (e.type === "EOF") break;
23
+ n.push(e);
24
+ }
25
+ return {
26
+ tokens: n,
27
+ comments: t.comments
28
+ };
29
+ }
30
+ function f(e) {
31
+ let t = new a(e), n = [];
32
+ try {
33
+ for (;;) {
34
+ let e = t.consume();
35
+ if (e.type === "EOF") break;
36
+ n.push(e);
37
+ }
38
+ return {
39
+ tokens: n,
40
+ comments: t.comments
41
+ };
42
+ } catch (i) {
43
+ let a = i instanceof r ? i : new r(i instanceof Error ? i.message : String(i)), o = t.lastEndOffset;
44
+ if (o < e.length) {
45
+ let t = 1, r = 1;
46
+ for (let n = 0; n < o; n++) e[n] === "\n" ? (t++, r = 1) : r++;
47
+ n.push({
48
+ type: "ERROR",
49
+ value: e.slice(o),
50
+ raw: e.slice(o),
51
+ line: t,
52
+ col: r,
53
+ offset: o,
54
+ endOffset: e.length
55
+ });
56
+ }
57
+ return {
58
+ tokens: n,
59
+ comments: t.comments,
60
+ error: a
61
+ };
62
+ }
63
+ }
64
+ //#endregion
65
+ export { u as CDDL, u as default, s as CddlMismatchError, c as CddlSchema, t as CddlSemanticError, r as CddlSyntaxError, o as PRELUDE_CDDL, n as getPreludeRules, e as parseCDDL, l as positionAt, d as tokenize, f as tokenizeLenient };
66
+
67
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/cddl/position.ts","../../src/cddl/index.ts"],"sourcesContent":["/**\n * Convert a character offset (as carried by CDDL AST nodes, CddlWarning,\n * and CddlValidationError.schemaStart/schemaEnd or start/end for CDN input)\n * into a 1-based line/column position, for CLI-style `file:line:col`\n * reporting.\n *\n * Offsets are JS string indices (UTF-16 code units), matching everything\n * else in this library. Offsets past the end of the text clamp to its end.\n */\nexport function positionAt(\n text: string,\n offset: number\n): { line: number; column: number } {\n const end = Math.max(0, Math.min(offset, text.length));\n let line = 1;\n let lineStart = 0;\n for (let i = 0; i < end; i++) {\n if (text.charCodeAt(i) === 0x0a) {\n line++;\n lineStart = i + 1;\n }\n }\n return { line, column: end - lineStart + 1 };\n}\n","/**\n * Public CDDL API (`@cbortech/cbor/cddl`).\n *\n * Phase 1 covers the grammar layer of RFC 8610 + RFC 9682: compiling CDDL\n * text into a checked rule table (`CDDL.compile`), re-serializing it\n * (`schema.format()`), and the lower-level tokenization API used by tooling\n * such as syntax highlighters. Validating CBOR/CDN data against a schema is\n * a later phase.\n */\n\nimport { CddlTokenizer, type CddlComment, type CddlToken } from './tokenizer';\nimport { CddlSyntaxError } from './errors';\nimport { compile, CddlSchema, type CompileOptions } from './schema';\n\nexport type { CddlToken, CddlTokenType, CddlComment } from './tokenizer';\nexport {\n CddlSyntaxError,\n CddlSemanticError,\n CddlMismatchError,\n} from './errors';\nexport type {\n CddlWarning,\n CddlValidationError,\n CddlValidationWarning,\n ValidationResult,\n} from './errors';\nexport type { ValidateOptions } from './validator';\nexport { CddlSchema } from './schema';\nexport type { CompileOptions } from './schema';\nexport { parseCDDL } from './parser';\nexport type { ParseCddlResult } from './parser';\nexport { PRELUDE_CDDL, getPreludeRules } from './prelude';\nexport { positionAt } from './position';\nexport type { CddlFormatOptions } from './writer';\nexport type {\n CddlRule,\n CddlType,\n CddlType1,\n CddlType2,\n CddlValue,\n CddlRef,\n CddlParenType,\n CddlMapType,\n CddlArrayType,\n CddlUnwrap,\n CddlEnum,\n CddlTagged,\n CddlMajor,\n CddlAny,\n CddlGroup,\n CddlGroupEntry,\n CddlEntryValue,\n CddlEntryGroup,\n CddlOccur,\n CddlMemberKey,\n CddlNodeBase,\n} from './ast';\n\n/** Main CDDL facade — mirrors the shape of the `CBOR` facade. */\nexport class CDDL {\n /**\n * Parse and compile a CDDL data model.\n *\n * @example\n * const schema = CDDL.compile(`person = { name: tstr, ? age: uint }`);\n * schema.root.name; // 'person'\n */\n static compile(text: string, options?: CompileOptions): CddlSchema {\n return compile(text, options);\n }\n}\n\nexport default CDDL;\n\nexport interface TokenizeResult {\n /** Scanned tokens in source order, excluding the final EOF token. */\n tokens: CddlToken[];\n /** Comments encountered while scanning, in source order. */\n comments: CddlComment[];\n}\n\nexport interface TokenizeLenientResult extends TokenizeResult {\n /**\n * The scan failure, if any. When set, `tokens` ends with a synthetic\n * `ERROR` token covering the source from the last clean token to the end\n * of the input.\n */\n error?: CddlSyntaxError;\n}\n\n/**\n * Tokenize CDDL text. Throws {@link CddlSyntaxError} on invalid input.\n */\nexport function tokenize(text: string): TokenizeResult {\n const tokenizer = new CddlTokenizer(text);\n const tokens: CddlToken[] = [];\n for (;;) {\n const tok = tokenizer.consume();\n if (tok.type === 'EOF') break;\n tokens.push(tok);\n }\n return { tokens, comments: tokenizer.comments };\n}\n\n/**\n * Error-tolerant tokenization for editors and highlighters: never throws on\n * invalid input. Tokens before the failure are returned as scanned; the\n * remainder of the input is covered by a single synthetic `ERROR` token and\n * the failure is reported in `error`.\n */\nexport function tokenizeLenient(text: string): TokenizeLenientResult {\n const tokenizer = new CddlTokenizer(text);\n const tokens: CddlToken[] = [];\n try {\n for (;;) {\n const tok = tokenizer.consume();\n if (tok.type === 'EOF') break;\n tokens.push(tok);\n }\n return { tokens, comments: tokenizer.comments };\n } catch (e) {\n const error =\n e instanceof CddlSyntaxError\n ? e\n : new CddlSyntaxError(e instanceof Error ? e.message : String(e));\n const start = tokenizer.lastEndOffset;\n if (start < text.length) {\n let line = 1;\n let col = 1;\n for (let i = 0; i < start; i++) {\n if (text[i] === '\\n') {\n line++;\n col = 1;\n } else {\n col++;\n }\n }\n tokens.push({\n type: 'ERROR',\n value: text.slice(start),\n raw: text.slice(start),\n line,\n col,\n offset: start,\n endOffset: text.length,\n });\n }\n return { tokens, comments: tokenizer.comments, error };\n }\n}\n"],"mappings":";;AASA,SAAgB,EACd,GACA,GACkC;CAClC,IAAM,IAAM,KAAK,IAAI,GAAG,KAAK,IAAI,GAAQ,EAAK,MAAM,CAAC,GACjD,IAAO,GACP,IAAY;CAChB,KAAK,IAAI,IAAI,GAAG,IAAI,GAAK,KACvB,AAAI,EAAK,WAAW,CAAC,MAAM,OACzB,KACA,IAAY,IAAI;CAGpB,OAAO;EAAE;EAAM,QAAQ,IAAM,IAAY;CAAE;AAC7C;;;ACoCA,IAAa,IAAb,MAAkB;CAQhB,OAAO,QAAQ,GAAc,GAAsC;EACjE,OAAO,EAAQ,GAAM,CAAO;CAC9B;AACF;AAuBA,SAAgB,EAAS,GAA8B;CACrD,IAAM,IAAY,IAAI,EAAc,CAAI,GAClC,IAAsB,CAAC;CAC7B,SAAS;EACP,IAAM,IAAM,EAAU,QAAQ;EAC9B,IAAI,EAAI,SAAS,OAAO;EACxB,EAAO,KAAK,CAAG;CACjB;CACA,OAAO;EAAE;EAAQ,UAAU,EAAU;CAAS;AAChD;AAQA,SAAgB,EAAgB,GAAqC;CACnE,IAAM,IAAY,IAAI,EAAc,CAAI,GAClC,IAAsB,CAAC;CAC7B,IAAI;EACF,SAAS;GACP,IAAM,IAAM,EAAU,QAAQ;GAC9B,IAAI,EAAI,SAAS,OAAO;GACxB,EAAO,KAAK,CAAG;EACjB;EACA,OAAO;GAAE;GAAQ,UAAU,EAAU;EAAS;CAChD,SAAS,GAAG;EACV,IAAM,IACJ,aAAa,IACT,IACA,IAAI,EAAgB,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC,CAAC,GAC9D,IAAQ,EAAU;EACxB,IAAI,IAAQ,EAAK,QAAQ;GACvB,IAAI,IAAO,GACP,IAAM;GACV,KAAK,IAAI,IAAI,GAAG,IAAI,GAAO,KACzB,AAAI,EAAK,OAAO,QACd,KACA,IAAM,KAEN;GAGJ,EAAO,KAAK;IACV,MAAM;IACN,OAAO,EAAK,MAAM,CAAK;IACvB,KAAK,EAAK,MAAM,CAAK;IACrB;IACA;IACA,QAAQ;IACR,WAAW,EAAK;GAClB,CAAC;EACH;EACA,OAAO;GAAE;GAAQ,UAAU,EAAU;GAAU;EAAM;CACvD;AACF"}
@@ -0,0 +1,13 @@
1
+ import { CddlComment } from './tokenizer';
2
+ import { CddlRule } from './ast';
3
+ export interface ParseCddlResult {
4
+ /** Rules in source order (unmerged; `/=` and `//=` appear as-is). */
5
+ rules: CddlRule[];
6
+ /** `;` comments encountered while scanning, in source order. */
7
+ comments: CddlComment[];
8
+ }
9
+ /**
10
+ * Parse CDDL text into rule ASTs.
11
+ * Throws {@link CddlSyntaxError} on invalid input.
12
+ */
13
+ export declare function parseCDDL(text: string): ParseCddlResult;
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Convert a character offset (as carried by CDDL AST nodes, CddlWarning,
3
+ * and CddlValidationError.schemaStart/schemaEnd or start/end for CDN input)
4
+ * into a 1-based line/column position, for CLI-style `file:line:col`
5
+ * reporting.
6
+ *
7
+ * Offsets are JS string indices (UTF-16 code units), matching everything
8
+ * else in this library. Offsets past the end of the text clamp to its end.
9
+ */
10
+ export declare function positionAt(text: string, offset: number): {
11
+ line: number;
12
+ column: number;
13
+ };
@@ -0,0 +1,5 @@
1
+ import { CddlRule } from './ast';
2
+ /** Verbatim text of the RFC 8610 Appendix D standard prelude. */
3
+ export declare const PRELUDE_CDDL = "any = #\n\nuint = #0\nnint = #1\nint = uint / nint\n\nbstr = #2\nbytes = bstr\ntstr = #3\ntext = tstr\n\ntdate = #6.0(tstr)\ntime = #6.1(number)\nnumber = int / float\nbiguint = #6.2(bstr)\nbignint = #6.3(bstr)\nbigint = biguint / bignint\ninteger = int / bigint\nunsigned = uint / biguint\ndecfrac = #6.4([e10: int, m: integer])\nbigfloat = #6.5([e2: int, m: integer])\neb64url = #6.21(any)\neb64legacy = #6.22(any)\neb16 = #6.23(any)\nencoded-cbor = #6.24(bstr)\nuri = #6.32(tstr)\nb64url = #6.33(tstr)\nb64legacy = #6.34(tstr)\nregexp = #6.35(tstr)\nmime-message = #6.36(tstr)\ncbor-any = #6.55799(any)\n\nfloat16 = #7.25\nfloat32 = #7.26\nfloat64 = #7.27\nfloat16-32 = float16 / float32\nfloat32-64 = float32 / float64\nfloat = float16-32 / float64\n\nfalse = #7.20\ntrue = #7.21\nbool = false / true\nnil = #7.22\nnull = nil\nundefined = #7.23\n";
4
+ /** The parsed prelude rules by name, parsed once and cached. */
5
+ export declare function getPreludeRules(): Map<string, CddlRule>;
@@ -0,0 +1,90 @@
1
+ import { CddlFormatOptions } from './writer';
2
+ import { CddlComment } from './tokenizer';
3
+ import { ValidateOptions } from './validator';
4
+ import { CborItem } from '../ast/CborItem';
5
+ import { CddlWarning, ValidationResult } from './errors';
6
+ import { CddlRule } from './ast';
7
+ export interface CompileOptions {
8
+ /**
9
+ * When true (the default), semantic problems (undefined names, duplicate
10
+ * rules, generic arity mismatches) throw a {@link CddlSemanticError}.
11
+ * When false, they are collected into {@link CddlSchema.warnings}.
12
+ */
13
+ strict?: boolean;
14
+ }
15
+ /**
16
+ * A compiled CDDL data model.
17
+ *
18
+ * `rules` maps each rule name to its definitions in source order: the base
19
+ * definition plus any `/=` / `//=` choice extensions. User rules shadow
20
+ * prelude names; the prelude itself is available via `getPreludeRules()`.
21
+ */
22
+ export declare class CddlSchema {
23
+ /**
24
+ * The CDDL source text this schema was compiled from. AST node offsets
25
+ * (and validation errors' `schemaStart`/`schemaEnd`) index into it, so
26
+ * tooling can render positions without carrying the text separately.
27
+ */
28
+ readonly source: string;
29
+ /** `;` comments collected while parsing, in source order. */
30
+ readonly comments: readonly CddlComment[];
31
+ /** All rules in source order, as parsed (extensions unmerged). */
32
+ readonly ast: readonly CddlRule[];
33
+ /** Rule definitions by name (base definition first, then extensions). */
34
+ readonly rules: ReadonlyMap<string, readonly CddlRule[]>;
35
+ /**
36
+ * The root of the data model: the first rule in the source (RFC 8610 §3.1).
37
+ * Unset only for an empty model compiled with `strict: false`.
38
+ */
39
+ readonly root?: CddlRule;
40
+ /** Semantic problems collected with `strict: false`; unset when clean. */
41
+ readonly warnings?: CddlWarning[];
42
+ /** @internal — use `CDDL.compile()`. */
43
+ constructor(source: string, comments: readonly CddlComment[], ast: CddlRule[], rules: Map<string, CddlRule[]>, root: CddlRule | undefined, warnings: CddlWarning[]);
44
+ /**
45
+ * Serialize the data model back to CDDL text.
46
+ *
47
+ * Compact one-rule-per-line output by default; pass `indent` for a
48
+ * pretty layout (one group entry per line) and `preserveComments` to
49
+ * re-emit `;` comments.
50
+ *
51
+ * @example
52
+ * CDDL.compile(text).format({ indent: 2, preserveComments: true });
53
+ */
54
+ format(options?: CddlFormatOptions): string;
55
+ /**
56
+ * Validate a data item against this schema's root rule — the first rule
57
+ * in source order (RFC 8610 §3.1). Pass `{ rule: 'otherName' }` to
58
+ * validate against a different rule instead: any non-generic rule usable
59
+ * as a type, defined in the schema or its prelude (e.g. `'uint'`).
60
+ * Generic rules (`g<T> = ...`) and group-only rules are reported as
61
+ * validation failures, as is an unknown name (see
62
+ * {@link ValidateOptions.rule}).
63
+ *
64
+ * Accepts a CborItem, CBOR bytes (decoded with `decodeCBOR`), or CDN text
65
+ * (parsed with `parseCDN`). Validation failures are reported in the
66
+ * result, not thrown; decode/parse failures of the input throw as usual.
67
+ *
68
+ * @example
69
+ * const schema = CDDL.compile('person = { name: tstr, ? age: uint }');
70
+ * const result = schema.validate('{"name": "kudo", "age": 42}');
71
+ * result.valid; // true
72
+ *
73
+ * @example
74
+ * // Validate against a rule other than the root.
75
+ * const schema = CDDL.compile(`
76
+ * p1 = { name: tstr, ? addr: tstr }
77
+ * p2 = { name: tstr, ? age: uint }
78
+ * `);
79
+ * schema.validate('{"name": "kudo", "age": 42}', { rule: 'p2' }).valid; // true
80
+ */
81
+ validate(input: CborItem | Uint8Array | string, options?: ValidateOptions): ValidationResult;
82
+ }
83
+ /**
84
+ * Parse and compile CDDL text.
85
+ *
86
+ * Throws `CddlSyntaxError` on grammar errors. Semantic problems throw a
87
+ * {@link CddlSemanticError} by default; pass `strict: false` to collect them
88
+ * into `schema.warnings` instead.
89
+ */
90
+ export declare function compile(text: string, options?: CompileOptions): CddlSchema;
@@ -0,0 +1,138 @@
1
+ /**
2
+ * CDDL lexer (internal).
3
+ *
4
+ * Implements the token-level grammar of RFC 8610 as updated by RFC 9682
5
+ * (Appendix A collected ABNF). Used by parser.ts and exposed through the
6
+ * `tokenize()` / `tokenizeLenient()` helpers in index.ts so tooling such as
7
+ * syntax highlighters stays in exact agreement with parsing behavior.
8
+ */
9
+ export type CddlTokenType = 'ID' | 'INT' | 'FLOAT' | 'TSTR' | 'BYTES' | 'HASH' | 'ASSIGN' | 'SLASH_EQ' | 'DSLASH_EQ' | 'SLASH' | 'DSLASH' | 'COMMA' | 'LPAREN' | 'RPAREN' | 'LBRACE' | 'RBRACE' | 'LBRACKET' | 'RBRACKET' | 'LT' | 'GT' | 'TILDE' | 'AMP' | 'RANGE_INCL' | 'RANGE_EXCL' | 'CTLOP' | 'STAR' | 'PLUS' | 'QUEST' | 'ARROW' | 'COLON' | 'CARET' | 'EOF'
10
+ /** Synthetic token emitted by tokenizeLenient() for the unscannable tail. */
11
+ | 'ERROR';
12
+ export interface CddlToken {
13
+ type: CddlTokenType;
14
+ /** Processed value: decoded string content, raw numeric text, id text, etc. */
15
+ value: string;
16
+ /** Original source text for this token. */
17
+ raw: string;
18
+ line: number;
19
+ col: number;
20
+ /** Character offset of the first character of this token in the source input. */
21
+ offset: number;
22
+ /** Character offset just past the last character of this token in the source input. */
23
+ endOffset: number;
24
+ /** Only set when type === 'BYTES': the qualifier ('' | 'h' | 'b64'). */
25
+ qualifier?: '' | 'h' | 'b64';
26
+ /** Only set when type === 'BYTES': the decoded byte content. */
27
+ bytes?: Uint8Array;
28
+ /** Only set when type === 'HASH': the major digit (0–9), absent for bare '#'. */
29
+ hashMajor?: number;
30
+ /** Only set when type === 'HASH': the literal head-number after the dot. */
31
+ hashAI?: bigint;
32
+ /**
33
+ * Only set when type === 'HASH': the head-number is a `<type>` expression
34
+ * (RFC 9682 §3.2); the tokens for `<` type `>` follow this token.
35
+ */
36
+ hashAIExpr?: boolean;
37
+ }
38
+ /** A `;` line comment collected while scanning. */
39
+ export interface CddlComment {
40
+ /** Comment text after the ';' marker, without the trailing newline. */
41
+ text: string;
42
+ start: number;
43
+ end: number;
44
+ line: number;
45
+ col: number;
46
+ }
47
+ export declare class CddlTokenizer {
48
+ private readonly input;
49
+ private pos;
50
+ private line;
51
+ private col;
52
+ /** Comments encountered while scanning, in source order. */
53
+ readonly comments: CddlComment[];
54
+ /** Character offset just past the last successfully scanned token. */
55
+ lastEndOffset: number;
56
+ constructor(input: string);
57
+ private _eof;
58
+ private _ch;
59
+ private _advance;
60
+ private _fail;
61
+ /**
62
+ * Skip S = *(SP / NL) where NL = COMMENT / CRLF.
63
+ *
64
+ * Per the ABNF only SP (0x20), LF, and CRLF are whitespace; horizontal tab
65
+ * is not valid CDDL whitespace and is rejected with a targeted message.
66
+ * Deliberate leniency: a bare CR (not part of CRLF) is also accepted as
67
+ * whitespace, as source-level line-ending normalization.
68
+ */
69
+ private _skipWs;
70
+ /**
71
+ * COMMENT = ";" *PCHAR CRLF — collected into `this.comments`.
72
+ *
73
+ * Deliberate leniency: content characters are not PCHAR-validated, and a
74
+ * comment terminated by end-of-input (no trailing newline) is accepted.
75
+ */
76
+ private _scanComment;
77
+ private _make;
78
+ /** Scan and return the next token (skipping whitespace and comments). */
79
+ consume(): CddlToken;
80
+ /**
81
+ * id = EALPHA *(*("-" / ".") (EALPHA / DIGIT))
82
+ *
83
+ * Interior '-' and '.' runs are allowed when followed by an EALPHA/DIGIT,
84
+ * so `a.b`, `a-b`, and even `tstr.size` are single ids (the ABNF note
85
+ * "space may be needed before the operator if type2 ends in a name" exists
86
+ * for exactly this reason). This includes `..`: RFC 8610 §2.2.2.1 says
87
+ * `min..max` "is not a range expression but a single name" — a range with
88
+ * a name on the left-hand side must be written `min .. max`.
89
+ */
90
+ private _scanIdText;
91
+ /**
92
+ * number = hexfloat / (int ["." fraction] ["e" exponent])
93
+ * hexfloat = ["-"] "0x" 1*HEXDIG ["." 1*HEXDIG] "p" exponent
94
+ * uint = DIGIT1 *DIGIT / "0x" 1*HEXDIG / "0b" 1*BINDIG / "0"
95
+ *
96
+ * The token `value` is the raw numeric text; the parser converts it.
97
+ * A '.' followed by another '.' is never consumed (range operator).
98
+ */
99
+ private _scanNumber;
100
+ /** Scan a uint (decimal / 0x / 0b) for a '#' head-number; returns raw text. */
101
+ private _scanUintRaw;
102
+ /**
103
+ * "#" — any
104
+ * "#" DIGIT ["." head-number] — major type (and tag/simple shorthands)
105
+ * head-number = uint / "<" type ">" (RFC 9682 §3.2)
106
+ *
107
+ * The '#', major digit, and a literal head-number are fused into a single
108
+ * HASH token (they must be adjacent in the source; `# 6` is a bare '#'
109
+ * followed by the value 6). For the `<type>` form, hashAIExpr is set and
110
+ * the `<` type `>` tokens follow.
111
+ */
112
+ private _scanHash;
113
+ /** text = %x22 *SCHAR %x22 — single-line, strict SCHAR/SESC per RFC 9682. */
114
+ private _scanText;
115
+ /**
116
+ * bytes = [bsqual] %x27 *BCHAR %x27
117
+ *
118
+ * Unqualified: content is UTF-8-encoded like a text string ('\'' must be
119
+ * escaped). Qualified h''/b64'': whitespace and ';' line comments inside
120
+ * the literal are ignored, then the rest is hex / base64 decoded
121
+ * (RFC 8610 §3.1).
122
+ */
123
+ private _scanBytes;
124
+ /**
125
+ * Read the body of a '"' text string or "'" byte string, decoding escapes.
126
+ *
127
+ * SCHAR = %x20-21 / %x23-5B / %x5D-7E / NONASCII / SESC
128
+ * BCHAR = %x20-26 / %x28-5B / %x5D-7E / NONASCII / SESC / "\'" / CRLF
129
+ * SESC = "\" ( %x22 / "/" / "\" / b / f / n / r / t / (%x75 hexchar) )
130
+ */
131
+ private _readStringBody;
132
+ /**
133
+ * hexchar (RFC 9682): after `\u`, either `{...}` with a scalar value
134
+ * (leading zeros allowed, surrogates rejected) or 4 hex digits, where a
135
+ * high surrogate must be immediately followed by `\uXXXX` low surrogate.
136
+ */
137
+ private _readUnicodeEscape;
138
+ }
@@ -0,0 +1,30 @@
1
+ import { CddlSchema } from './schema';
2
+ import { CborItem } from '../ast/CborItem';
3
+ import { ValidationResult } from './errors';
4
+ import { CddlValue } from './ast';
5
+ export interface ValidateOptions {
6
+ /** Recursion guard for rule references and nested groups (default 256). */
7
+ maxDepth?: number;
8
+ /** Total backtracking step budget (default 1e6). */
9
+ maxSteps?: number;
10
+ /** Feature names accepted by the `.feature` control operator. */
11
+ features?: string[];
12
+ /**
13
+ * Name of the rule to validate against, in place of the schema's root
14
+ * (the first rule in source order — RFC 8610 §3.1 defines only one root
15
+ * per model). Any non-generic rule usable as a type can be selected,
16
+ * defined in the schema or its prelude — e.g. a variant used only as a
17
+ * component elsewhere.
18
+ *
19
+ * An unknown name fails validation (`errors[0].message` is `'<name>' is
20
+ * not defined`) rather than throwing, matching how an unresolved `$ref`
21
+ * inside the schema is reported. A generic rule (`g<T> = ...`) also fails
22
+ * validation rather than throwing: there is no `genericArgs` site to bind
23
+ * its parameters from here, so it cannot be selected directly. Likewise a
24
+ * group-only rule fails with `group rule '<name>' cannot be used as a
25
+ * type`, exactly as when such a rule is referenced in type position.
26
+ */
27
+ rule?: string;
28
+ }
29
+ export declare function validateItem(schema: CddlSchema, item: CborItem, options?: ValidateOptions): ValidationResult;
30
+ export declare function matchesLiteral(item: CborItem, v: CddlValue): boolean;
@@ -0,0 +1,23 @@
1
+ import { CddlComment } from './tokenizer';
2
+ import { CddlRule } from './ast';
3
+ export interface CddlFormatOptions {
4
+ /**
5
+ * Pretty-print groups with one entry per line, indented by this many
6
+ * spaces (or by the given string). Omit for compact single-line rules.
7
+ */
8
+ indent?: number | string;
9
+ /**
10
+ * Re-emit `;` comments. Rule-level comments are kept in both layouts;
11
+ * comments attached to group entries require `indent` (the pretty
12
+ * layout). Only effective when the formatter has the comment stream and
13
+ * source text — i.e. when called through `CddlSchema.format()`.
14
+ */
15
+ preserveComments?: boolean;
16
+ }
17
+ /** @internal Extras supplied by CddlSchema.format(). */
18
+ export interface CddlFormatContext {
19
+ source?: string;
20
+ comments?: readonly CddlComment[];
21
+ }
22
+ /** Format rules (in the given order) as CDDL text with a trailing newline. */
23
+ export declare function formatCddl(rules: readonly CddlRule[], options?: CddlFormatOptions & CddlFormatContext): string;