@cbortech/cbor 0.27.1 → 0.27.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.
Files changed (51) hide show
  1. package/README.ja.md +27 -0
  2. package/README.md +28 -0
  3. package/dist/ast/CborItem.d.ts +17 -2
  4. package/dist/ast/CborTag.d.ts +22 -0
  5. package/dist/ast/CborUnresolvedAppExt.d.ts +9 -0
  6. package/dist/ast/index.cjs +1 -1
  7. package/dist/ast/index.js +2 -2
  8. package/dist/cbor/tagLabels.d.ts +26 -0
  9. package/dist/cddl/eRefScope.d.ts +241 -0
  10. package/dist/cddl/eref.d.ts +64 -0
  11. package/dist/cddl/implicitTags.d.ts +28 -0
  12. package/dist/cddl/index.cjs +2 -2
  13. package/dist/cddl/index.cjs.map +1 -1
  14. package/dist/cddl/index.d.ts +2 -0
  15. package/dist/cddl/index.js +26 -25
  16. package/dist/cddl/index.js.map +1 -1
  17. package/dist/cddl/validator.d.ts +98 -2
  18. package/dist/cdn/index.cjs +1 -1
  19. package/dist/cdn/index.js +1 -1
  20. package/dist/cdn/serialize-utils.d.ts +20 -13
  21. package/dist/extensions/eref.d.ts +135 -0
  22. package/dist/index.cjs +7 -7
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.d.ts +1 -0
  25. package/dist/index.js +190 -81
  26. package/dist/index.js.map +1 -1
  27. package/dist/js/fromJS.d.ts +23 -1
  28. package/dist/mapEntries-8zshEr-t.js +7085 -0
  29. package/dist/mapEntries-8zshEr-t.js.map +1 -0
  30. package/dist/mapEntries-DwHPAzCN.cjs +68 -0
  31. package/dist/mapEntries-DwHPAzCN.cjs.map +1 -0
  32. package/dist/schema-7r2xjpMK.js +345 -0
  33. package/dist/schema-7r2xjpMK.js.map +1 -0
  34. package/dist/schema-YiigSWjR.cjs +8 -0
  35. package/dist/schema-YiigSWjR.cjs.map +1 -0
  36. package/dist/{serialize-utils-h-CVB9rg.js → serialize-utils-BQtutOo6.js} +14 -6
  37. package/dist/serialize-utils-BQtutOo6.js.map +1 -0
  38. package/dist/{serialize-utils-DhlW61ZX.cjs → serialize-utils-DQ8T3Mzw.cjs} +5 -5
  39. package/dist/serialize-utils-DQ8T3Mzw.cjs.map +1 -0
  40. package/dist/types.d.ts +153 -4
  41. package/package.json +8 -8
  42. package/dist/mapEntries-CCLaJSaJ.js +0 -4127
  43. package/dist/mapEntries-CCLaJSaJ.js.map +0 -1
  44. package/dist/mapEntries-CZZJScaj.cjs +0 -13
  45. package/dist/mapEntries-CZZJScaj.cjs.map +0 -1
  46. package/dist/schema-DN9inJny.js +0 -1977
  47. package/dist/schema-DN9inJny.js.map +0 -1
  48. package/dist/schema-zsg5yCPK.cjs +0 -63
  49. package/dist/schema-zsg5yCPK.cjs.map +0 -1
  50. package/dist/serialize-utils-DhlW61ZX.cjs.map +0 -1
  51. package/dist/serialize-utils-h-CVB9rg.js.map +0 -1
package/README.ja.md CHANGED
@@ -1211,6 +1211,29 @@ const value = CBOR.parse('{"x": 12, "y": -3}', {
1211
1211
  検証オプションは `cddlValidationOptions` で渡せます。`cddl` は
1212
1212
  `new CBOR({ cddl: … })` のようにインスタンスのデフォルトにもできます。
1213
1213
 
1214
+ スキーマを指定すると、スキーマ自体が要求するタグは JavaScript 側で省略
1215
+ できます。`toJS()` は、prelude の `time = #6.1(number)` のような `#6.N(…)`
1216
+ 型に一致したタグを外し、`fromJS()` はタグのない値にそれを補います。
1217
+
1218
+ ```ts
1219
+ import { CBOR } from '@cbortech/cbor';
1220
+
1221
+ const cddl = 'event = { t: time }';
1222
+
1223
+ CBOR.parse(`{"t": DT'1969-07-21T02:56:16Z'}`, { cddl });
1224
+ // { t: -14159024 }(Tag.symbol のない素の number)
1225
+
1226
+ CBOR.stringify({ t: -14159024 }, { cddl });
1227
+ // {"t":DT'1969-07-21T02:56:16Z'}
1228
+ ```
1229
+
1230
+ タグを外すのは `fromJS()` で復元できる場合だけです。タグなしの値もその
1231
+ 位置で妥当な場合(`time / number`)や、スキーマがタグを要求しない場合
1232
+ (`any`)はタグを残します。推論は、値がそのままではスキーマに一致しない
1233
+ ときにだけ行います。すべてのタグを明示的に保持・要求するには
1234
+ `implicitTags: false`(`ToJSOptions` と `FromJSOptions` のオプション)を
1235
+ 指定します。
1236
+
1214
1237
  `CDDL.compile()` は `CddlSyntaxError` または `CddlSemanticError` を throw
1215
1238
  します。`{ strict: false }` を指定すると、意味上の問題を
1216
1239
  `schema.warnings` に収集できます。コンパイル済みスキーマは
@@ -1251,6 +1274,7 @@ CDDL コンパイラは `@cbortech/cbor/cddl`
1251
1274
  - CDN (CBOR-EDN)
1252
1275
  - [draft-ietf-cbor-edn-literals-25](https://datatracker.ietf.org/doc/draft-ietf-cbor-edn-literals/25/)
1253
1276
  - [draft-ietf-cbor-edn-literals-27](https://datatracker.ietf.org/doc/draft-ietf-cbor-edn-literals/27/)
1277
+ - [draft-ietf-cbor-edn-e-ref-03](https://datatracker.ietf.org/doc/draft-ietf-cbor-edn-e-ref/03/)
1254
1278
  - CDDL
1255
1279
  - [RFC 8610](https://www.rfc-editor.org/rfc/rfc8610)
1256
1280
  - [RFC 9682](https://www.rfc-editor.org/rfc/rfc9682)
@@ -1267,6 +1291,9 @@ CDDL コンパイラは `@cbortech/cbor/cddl`
1267
1291
  `#6.<type>` / `#7.<type>` head number に対応しています。コメントの `PCHAR`
1268
1292
  検証、単独 CR の改行、EOF で終わるコメントは、collected ABNF よりも意図的に
1269
1293
  寛容に受理します。
1294
+ - draft-ietf-cbor-edn-e-ref の `e'...'` application extension を試験的に
1295
+ サポートしています(draft本文より狭いスコープで、整数リテラルに直接束縛された
1296
+ 名前のみ対応 — 文字列定数や、他の定数への別名参照は解決できません)。
1270
1297
 
1271
1298
  ## ライセンス
1272
1299
 
package/README.md CHANGED
@@ -1223,6 +1223,29 @@ Throwing methods such as `parse`, `decode`, and `encode` throw
1223
1223
  in `result.cddlErrors`. Pass validator options through `cddlValidationOptions`,
1224
1224
  or set `cddl` as an instance default with `new CBOR({ cddl: … })`.
1225
1225
 
1226
+ With a schema, tags the schema itself requires can be left implicit in
1227
+ JavaScript. `toJS()` drops a tag matched by a `#6.N(…)` type such as the
1228
+ prelude's `time = #6.1(number)`, and `fromJS()` adds it back to a value that
1229
+ lacks it:
1230
+
1231
+ ```ts
1232
+ import { CBOR } from '@cbortech/cbor';
1233
+
1234
+ const cddl = 'event = { t: time }';
1235
+
1236
+ CBOR.parse(`{"t": DT'1969-07-21T02:56:16Z'}`, { cddl });
1237
+ // { t: -14159024 } (a plain number, no Tag.symbol)
1238
+
1239
+ CBOR.stringify({ t: -14159024 }, { cddl });
1240
+ // {"t":DT'1969-07-21T02:56:16Z'}
1241
+ ```
1242
+
1243
+ A tag is dropped only when `fromJS()` would restore it: it is kept where the
1244
+ untagged value is also valid on its own (`time / number`) or where the schema
1245
+ doesn't require it (`any`). Inference only runs when the value doesn't
1246
+ already match the schema. Pass `implicitTags: false` (a `ToJSOptions` and
1247
+ `FromJSOptions` option) to keep or require every tag explicitly.
1248
+
1226
1249
  `CDDL.compile()` throws `CddlSyntaxError` or `CddlSemanticError`; use
1227
1250
  `{ strict: false }` to collect semantic issues in `schema.warnings` instead.
1228
1251
  Compiled schemas can be formatted with `schema.format()`. The subpath also
@@ -1263,6 +1286,7 @@ types).
1263
1286
  - CDN (CBOR-EDN)
1264
1287
  - [draft-ietf-cbor-edn-literals-25](https://datatracker.ietf.org/doc/draft-ietf-cbor-edn-literals/25/)
1265
1288
  - [draft-ietf-cbor-edn-literals-27](https://datatracker.ietf.org/doc/draft-ietf-cbor-edn-literals/27/)
1289
+ - [draft-ietf-cbor-edn-e-ref-03](https://datatracker.ietf.org/doc/draft-ietf-cbor-edn-e-ref/03/)
1266
1290
  - CDDL
1267
1291
  - [RFC 8610](https://www.rfc-editor.org/rfc/rfc8610)
1268
1292
  - [RFC 9682](https://www.rfc-editor.org/rfc/rfc9682)
@@ -1280,6 +1304,10 @@ Implementation notes:
1280
1304
  `#7.<type>` head numbers. Comment `PCHAR` validation, bare CR line endings,
1281
1305
  and comments ending at EOF are intentionally accepted more leniently than the
1282
1306
  collected ABNF.
1307
+ - Experimental support for draft-ietf-cbor-edn-e-ref's `e'...'` application
1308
+ extension, limited to names bound directly to an integer literal (the
1309
+ draft's own scope is broader) — a string constant, or an alias to another
1310
+ named constant, doesn't resolve.
1283
1311
 
1284
1312
  ## License
1285
1313
 
@@ -341,8 +341,10 @@ export declare abstract class CborItem {
341
341
  * (`h'...'`, `b64'...'`, ...) depends on the `sqstr` option.
342
342
  *
343
343
  * This method deliberately does *not* also cover the "is this (or does
344
- * it wrap) a prefixed literal" question — a prefixed literal has no word
345
- * count to check, but still disqualifies under the strict rule (and, per
344
+ * it wrap) a prefixed literal" question — a byte-string literal has no
345
+ * word count to check, and an app-string literal (`dt'...'`) is
346
+ * word-counted from its rendered content, but either disqualifies only
347
+ * under the strict rule (and, per
346
348
  * `strict`, is an ordinary leaf under the loose one). That's handled
347
349
  * generically elsewhere instead, from the *actual rendered text* rather
348
350
  * than predicted from this node's type: `isPrefixedLiteralText` for a
@@ -379,6 +381,19 @@ export declare abstract class CborItem {
379
381
  * it, the same as `strict`.
380
382
  */
381
383
  _isMultiWordText(_options: ToCDNOptions | undefined, _strict?: boolean, _path?: readonly unknown[]): boolean;
384
+ /**
385
+ * @internal
386
+ * Optional override: an alternate plain-string spelling to use as this
387
+ * node's `toJS()` object key, in place of `CborMap.toObject()`'s generic
388
+ * `toCDN()` fallback for a non-text-string key. Returns `undefined` to use
389
+ * that default. The base class implements no such override; a subclass
390
+ * that carries an alternate key spelling for a non-text key (e.g. a CDDL
391
+ * e-ref annotated integer key — see `extensions/eref.ts`) overrides this
392
+ * instead of `CborMap` special-casing that subclass directly. Takes the
393
+ * full `ToJSOptions` (unlike `_toCDN`'s options) since a key-naming choice
394
+ * like e-ref's `eRefKeys` is a `toJS()`-only concept with no CDN analogue.
395
+ */
396
+ _jsObjectKey(_options: ToJSOptions | undefined): string | undefined;
382
397
  /** Serialize this node to CBOR binary. */
383
398
  toCBOR(options?: ToCBOROptions): Uint8Array;
384
399
  /** Serialize this node to a CDN text string. */
@@ -13,6 +13,14 @@ export declare class CborTag extends CborItem {
13
13
  * (`0x3e7`, decimal, …) when `preserveNumberFormat` is set.
14
14
  */
15
15
  ednSource?: string;
16
+ /**
17
+ * Set by `cddl`-validated decoding/parsing/conversion when the schema
18
+ * itself implies this tag at its position (see `cddl/implicitTags.ts`),
19
+ * so `toJS()` can leave it off the JS value — see
20
+ * `ToJSOptions.implicitTags`.
21
+ * @internal
22
+ */
23
+ _implicit: boolean;
16
24
  constructor(tag: number | bigint, content: CborItem, options?: {
17
25
  encodingWidth?: EncodingWidth;
18
26
  ednSource?: string;
@@ -47,6 +55,20 @@ export declare class CborTag extends CborItem {
47
55
  _isMultiWordText(options: ToCDNOptions | undefined, strict?: boolean, path?: readonly unknown[]): boolean;
48
56
  _encodeTo(writer: CborWriter, options?: ToCBOROptions): void;
49
57
  _toCDN(options: ToCDNOptions | undefined, depth: number, path?: readonly unknown[]): string;
58
+ /**
59
+ * The hex-dump comment for this tag's head: `Tag N`, followed by an
60
+ * RFC 9277 label when there is one — `Tag 55799 (self-described CBOR)`,
61
+ * `Tag 1668546929 (CoAP Content-Format 112)`, `Tag 1330664270 ("OPSN")`
62
+ * for a protocol-specific tag spelling four printable ASCII characters.
63
+ */
64
+ hexDumpComment(): string;
50
65
  _toHexDump(depth: number, options?: ToCDNOptions): AnnotatedLine[];
51
66
  _toJS(options?: ToJSOptions, path?: readonly unknown[], occurrence?: Occurrence): unknown;
67
+ /**
68
+ * Attach this tag to the converted content `value` — unless `stripTags`,
69
+ * or the tag is schema-implied (`_implicit`) and `implicitTags` isn't
70
+ * `false`.
71
+ * @internal
72
+ */
73
+ _tagJS(value: unknown, options?: ToJSOptions): unknown;
52
74
  }
@@ -12,5 +12,14 @@ export declare const CPA999_TAG = 999n;
12
12
  */
13
13
  export declare class CborUnresolvedAppExt extends CborTag {
14
14
  constructor(prefix: string, items: CborItem[]);
15
+ /** App-string form (`prefix'text'`), as opposed to an app-sequence. */
16
+ private get _isAppString();
17
+ /**
18
+ * An app-string (`e'alg'`) renders as a plain literal, not the
19
+ * `[prefix, text]` array it wraps, so it's a leaf for
20
+ * `inlineLeafContainers` — word-counted like a text string instead (via
21
+ * `CborTag._isMultiWordText`'s tokenizing of the rendered output).
22
+ */
23
+ get _containsCdnContainer(): boolean;
15
24
  _toCDN(options: ToCDNOptions | undefined, depth: number): string;
16
25
  }
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../mapEntries-CZZJScaj.cjs");exports.CborArray=e.E,exports.CborBigNint=e._,exports.CborBigUint=e.v,exports.CborByteString=e.k,exports.CborEmbeddedCBOR=e.C,exports.CborFloat=e.j,exports.CborIndefiniteByteString=e.O,exports.CborIndefiniteTextString=e.D,exports.CborItem=e.F,exports.CborMap=e.T,exports.CborNint=e.N,exports.CborSimple=e.w,exports.CborTag=e.A,exports.CborTextString=e.h,exports.CborUint=e.P;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../mapEntries-DwHPAzCN.cjs");exports.CborArray=e.I,exports.CborBigNint=e.O,exports.CborBigUint=e.k,exports.CborByteString=e.z,exports.CborEmbeddedCBOR=e.N,exports.CborFloat=e.V,exports.CborIndefiniteByteString=e.R,exports.CborIndefiniteTextString=e.L,exports.CborItem=e.W,exports.CborMap=e.F,exports.CborNint=e.H,exports.CborSimple=e.P,exports.CborTag=e.B,exports.CborTextString=e.E,exports.CborUint=e.U;
package/dist/ast/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import { A as e, C as t, D as n, E as r, F as i, N as a, O as o, P as s, T as c, _ as l, h as u, j as d, k as f, v as p, w as m } from "../mapEntries-CCLaJSaJ.js";
2
- export { r as CborArray, l as CborBigNint, p as CborBigUint, f as CborByteString, t as CborEmbeddedCBOR, d as CborFloat, o as CborIndefiniteByteString, n as CborIndefiniteTextString, i as CborItem, c as CborMap, a as CborNint, m as CborSimple, e as CborTag, u as CborTextString, s as CborUint };
1
+ import { B as e, E as t, F as n, H as r, I as i, L as a, N as o, O as s, P as c, R as l, U as u, V as d, W as f, k as p, z as m } from "../mapEntries-8zshEr-t.js";
2
+ export { i as CborArray, s as CborBigNint, p as CborBigUint, m as CborByteString, o as CborEmbeddedCBOR, d as CborFloat, l as CborIndefiniteByteString, a as CborIndefiniteTextString, f as CborItem, n as CborMap, r as CborNint, c as CborSimple, e as CborTag, t as CborTextString, u as CborUint };
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Human-readable labels for tag numbers defined by RFC 9277 (On Stable
3
+ * Storage for Items in CBOR), used to annotate `Tag N` hex-dump comments.
4
+ */
5
+ /**
6
+ * Inverse of RFC 9277 Appendix B's `TN(ct) = 0x63740101 + (ct / 255) *
7
+ * 256 + ct % 255`: returns the CoAP Content-Format number `tag` stands for, or
8
+ * `undefined` when `tag` isn't in that range. The mapping never produces a
9
+ * zero byte, so a tag with a zero in either of its low two bytes isn't one.
10
+ */
11
+ export declare function coapContentFormatOfTag(tag: bigint): number | undefined;
12
+ /**
13
+ * The four ASCII characters spelled by a protocol-specific tag number
14
+ * (RFC 9277 §2.1 encourages a mnemonic of four ASCII codes, e.g.
15
+ * `1330664270` = `0x4F50534E` = `"OPSN"`), or `undefined` when `tag` is
16
+ * outside `0x01000000`..`0xFFFFFFFF` or any byte isn't printable ASCII
17
+ * (`0x20`..`0x7E`).
18
+ */
19
+ export declare function asciiMnemonicOfTag(tag: bigint): string | undefined;
20
+ /**
21
+ * RFC 9277 label for `tag`, for a hex-dump comment — `self-described CBOR`,
22
+ * `CoAP Content-Format 112`, `"OPSN"` — or `undefined` when there's none.
23
+ * The CoAP range is checked before the ASCII mnemonic: it is a specific
24
+ * allocation, and its `"ct"` prefix would otherwise read as a mnemonic.
25
+ */
26
+ export declare function rfc9277TagLabel(tag: bigint): string | undefined;
@@ -0,0 +1,241 @@
1
+ import { CddlSchema } from './schema';
2
+ import { CddlGroupEntry, CddlMemberKey, CddlType, CddlType1 } from './ast';
3
+ import { CborItem } from '../ast/CborItem';
4
+ import { ValidateOptions } from './validator';
5
+ /**
6
+ * The CDDL type governing one position in a JS value tree — opaque outside
7
+ * this module; obtain one via `resolveRootScope()`, then `resolveNestedScope()`
8
+ * for each property that itself holds a nested object.
9
+ */
10
+ export interface ERefScope {
11
+ /**
12
+ * Every distinct alternative shape this position's type could resolve
13
+ * to — one array per `/`/`//` choice alternative (including every
14
+ * `/=`/`//=` extension of the rule), each holding *that* alternative's
15
+ * own complete group entries. Kept separate, not merged into one flat
16
+ * list, so `scopeNameToValue()` can tell "this name means the same thing
17
+ * in every alternative that mentions it, and isn't plain text in any of
18
+ * them" (safe) apart from "different alternatives disagree about it"
19
+ * (unsafe) — see the module doc.
20
+ */
21
+ readonly alternatives: readonly (readonly CddlGroupEntry[])[];
22
+ }
23
+ /**
24
+ * The scope for the schema's own root rule (or `ruleName`, matching
25
+ * `ValidateOptions.rule` — `fromJS()`'s own eRefKeys resolution should
26
+ * start from the same rule the caller will actually validate against).
27
+ * `undefined` when the named rule doesn't exist, isn't a map type, or
28
+ * can't be resolved this way at all — see the module doc's Scope note.
29
+ */
30
+ export declare function resolveRootScope(schema: CddlSchema, ruleName?: string): ERefScope | undefined;
31
+ /**
32
+ * The CDDL type governing an *array* position — the counterpart of
33
+ * `ERefScope` for a value that is a `CborArray`/JS array rather than a
34
+ * map/object. One positional element-type list per array alternative this
35
+ * position's type could resolve to (kept separate, the same way
36
+ * `ERefScope.alternatives` is). Only produced for arrays whose every entry
37
+ * is exactly one element (no `?`/`*`/`+`), so element *i* of an array of
38
+ * length *n* is governed by entry *i* of every alternative of length *n* —
39
+ * no matching against the data required. An alternative of a different
40
+ * length simply can't be the one the data matched, so it's skipped
41
+ * (`resolveElementPosition()`).
42
+ */
43
+ export interface ERefArrayScope {
44
+ readonly elementTypes: readonly (readonly CddlType[])[];
45
+ }
46
+ /**
47
+ * Everything known about one position in the value tree: its scope if the
48
+ * value there is a map (`map`), and its positional element types if it's an
49
+ * array (`array`). Both may be set when the governing type is a `/` choice
50
+ * between a map and an array; the walker uses whichever matches the value
51
+ * actually found there.
52
+ */
53
+ export interface ERefPosition {
54
+ readonly map?: ERefScope;
55
+ readonly array?: ERefArrayScope;
56
+ }
57
+ /** A position nothing is known about — no names apply anywhere below it. */
58
+ export declare const NO_POSITION: ERefPosition;
59
+ /**
60
+ * `resolveRootScope()`'s own counterpart covering an array root too —
61
+ * e.g. `COSE_Sign1 = [protected: …, unprotected: header_map, …]`.
62
+ */
63
+ export declare function resolveRootPosition(schema: CddlSchema, ruleName?: string): ERefPosition;
64
+ /**
65
+ * `resolveNestedScope()`'s own counterpart covering an array value too —
66
+ * the position of `identifier`'s own value within map scope `scope`.
67
+ */
68
+ export declare function resolveNestedPosition(schema: CddlSchema, scope: ERefScope, identifier: string | bigint, respectDeclarationOrder?: boolean): ERefPosition;
69
+ /**
70
+ * The position of element `index` within an array of `length` elements
71
+ * governed by `arrayScope` — the union of entry `index`'s own type across
72
+ * every alternative of exactly that length (see `ERefArrayScope`'s own
73
+ * doc). `NO_POSITION` when no alternative has that length.
74
+ */
75
+ export declare function resolveElementPosition(schema: CddlSchema, arrayScope: ERefArrayScope, index: number, length: number): ERefPosition;
76
+ /**
77
+ * The e-ref name a member key gives the integer key `keyValue` it
78
+ * consumed — the member's own `&(name: value)` binding for that value (from
79
+ * a fully literal enum group, the only kind that pins the key down to one
80
+ * named value), or a bare reference to a constant rule with that value.
81
+ * `undefined` for any other member key (a bareword/literal key, a wildcard,
82
+ * a controlled or non-literal key), or when the reference is a generic
83
+ * parameter (`paramBound`), which names no rule at all.
84
+ */
85
+ export declare function memberKeyName(schema: CddlSchema, mk: CddlMemberKey, keyValue: bigint, paramBound: (name: string) => boolean): string | undefined;
86
+ /** A type that is just a reference to rule `name` (the validation root). */
87
+ export declare function ruleRefType(name: string): CddlType;
88
+ /**
89
+ * `type`'s own fixed-shape array alternatives (see `ERefArrayScope`), or
90
+ * `undefined` when it may be an array of some other shape.
91
+ */
92
+ export declare function arrayScopeOfType(schema: CddlSchema, type: CddlType): ERefArrayScope | undefined;
93
+ /**
94
+ * The array alternatives in `arrayScope` a decoded array's `items`
95
+ * actually satisfy — same length, and every element matching its own
96
+ * entry's type. An element whose check runs out of budget keeps its
97
+ * alternative (including an extra alternative only ever makes annotation
98
+ * more conservative, never wrong).
99
+ */
100
+ export declare function matchingArrayAlternatives(schema: CddlSchema, arrayScope: ERefArrayScope, items: readonly CborItem[], options?: ValidateOptions): ERefArrayScope;
101
+ /**
102
+ * `type`'s own `/` alternatives with parentheses and (non-generic) type-rule
103
+ * references expanded in place — including every `/=` extension of a
104
+ * referenced rule — so each result is a `type1` that is neither of those.
105
+ * A controlled alternative (`bstr .cbor T`) is kept whole, never looked
106
+ * into. `undefined` when some alternative can't be expanded this way (a
107
+ * generic reference, a rule defined nowhere, or a group rule referenced as
108
+ * a type). A reference cycle contributes no alternatives of its own.
109
+ */
110
+ export declare function typeAlternatives(schema: CddlSchema, type: CddlType, seen?: ReadonlySet<string>): CddlType1[] | undefined;
111
+ /** One `CddlType` whose alternatives are all of `types`' own, combined. */
112
+ export declare function mergeTypes(types: readonly CddlType[]): CddlType;
113
+ /**
114
+ * Name → value, from every `&(name: value)`/bare-constant-reference entry
115
+ * directly at a member-key position among `scope`'s own alternatives (not
116
+ * entries nested inside a further nested map) — the names `fromJS()` may
117
+ * convert *this* object's own direct property names against.
118
+ *
119
+ * A name is included only when it's *consistently* eRefKeys-eligible
120
+ * across every one of `scope`'s own alternatives: excluded entirely if
121
+ * *any* alternative uses it as a plain bareword/quoted-text member key
122
+ * (that alternative wants a literal text key there, and which alternative
123
+ * the JS value being converted actually corresponds to isn't known without
124
+ * validating it — something this module doesn't attempt), and excluded if
125
+ * the alternatives that *do* bind it via `&(name: value)`/a bare
126
+ * constant-rule reference disagree on the value. An alternative that
127
+ * doesn't mention the name at all is simply silent on it, not a conflict.
128
+ *
129
+ * A `&(name: value)` binding's own value is computed fresh per scope —
130
+ * unlike a bare reference to a constant rule (`? group_mode => bool`),
131
+ * whose value comes from the rule's own, genuinely schema-wide definition,
132
+ * so it's looked up via `getERefTables(schema).ruleConstantValues` — never
133
+ * plain `byName`, which also mixes in any `&(name: value)` enum *label*
134
+ * bound to `name` elsewhere in the schema (irrelevant here: a bare type
135
+ * reference names a *rule*, not "this spelling however it's used
136
+ * anywhere" — see `ruleConstantValues`'s own doc).
137
+ *
138
+ * This *value* is safe to use positionally as-is — it's exactly the
139
+ * integer this position's own schema names, independent of anything
140
+ * elsewhere in the document. Whether the resulting key should also be
141
+ * *labeled* `e'name'` is a separate question `resolvesGloballyTo()`
142
+ * answers — see its own doc for why.
143
+ *
144
+ * `respectDeclarationOrder` (default `true`) controls whether a name
145
+ * declared before a same-alternative wildcard is included per that
146
+ * relaxation — see the module doc's own note on why `fromJS()` must pass
147
+ * `false` here instead, falling back to the plain "any open entry anywhere
148
+ * in this alternative excludes every name in it" behavior.
149
+ */
150
+ export declare function scopeNameToValue(schema: CddlSchema, scope: ERefScope, respectDeclarationOrder?: boolean): ReadonlyMap<string, bigint>;
151
+ /**
152
+ * Whether `name` labeling `value` here would also resolve the *same* way
153
+ * through `parseAppString()` (`e'name'`'s own parse direction), which
154
+ * consults `getERefTables(schema).byName` — a single, genuinely
155
+ * schema-wide table, unlike `scopeNameToValue()`'s own position-scoped
156
+ * one. A name can be locally unambiguous at one member-key position (safe
157
+ * to use as *this* key's integer value — see `scopeNameToValue()`) while
158
+ * being bound to a *different* value, or ambiguously to more than one, at
159
+ * some other, unrelated member-key position elsewhere in the same schema.
160
+ * Labeling the key `e'name'` in that case would round-trip incorrectly (or
161
+ * not at all) through `fromCDN()` against the very same schema, so
162
+ * `fromJS()` only does so when this returns `true` — otherwise the key
163
+ * still gets the correct integer value, just as a plain, unlabeled
164
+ * integer (see `js/fromJS.ts`'s own use of this).
165
+ */
166
+ export declare function resolvesGloballyTo(schema: CddlSchema, name: string, value: bigint): boolean;
167
+ /**
168
+ * `scopeNameToValue()`'s own result, inverted — dropping any value bound to
169
+ * more than one *different* name at this position, since picking either
170
+ * would be an arbitrary, unjustified choice this position's own schema
171
+ * doesn't actually make (each individual name is still unambiguous on its
172
+ * own — see `scopeNameToValue()`'s own doc — this is only about two
173
+ * *different* names colliding on the same value). Used wherever a caller
174
+ * already has an integer *value* (not a name) — e.g. an already-decoded map
175
+ * key, or a `MapEntries` entry whose key is a plain number rather than a
176
+ * string — and needs to know which name, if any, unambiguously describes
177
+ * it at this position, so it can resolve a nested scope for that entry's
178
+ * own value the same way a literal string key's name would (see
179
+ * `extensions/eref.ts` and `js/fromJS.ts`'s own uses).
180
+ */
181
+ export declare function scopeValueToName(schema: CddlSchema, scope: ERefScope): ReadonlyMap<bigint, string>;
182
+ /**
183
+ * The scope for `identifier`'s own nested value — matching, across every
184
+ * one of `scope`'s own alternatives, an entry whose member key is either a
185
+ * literal bareword/quoted-text key equal to `identifier` (a `string`), the
186
+ * `&(name: value)`/bare-reference entry that names it (only when
187
+ * `identifier` is itself one of `scope`'s own `scopeNameToValue()` names),
188
+ * *or* a differently-spelled member key that resolves to that exact same
189
+ * integer value — e.g. a literal `1: …` entry in one alternative and
190
+ * `&(data: 1) => …` in another both govern the same wire position, even
191
+ * though only the second one *names* it. Passing `identifier` as a
192
+ * `bigint` instead skips name resolution entirely and matches purely by
193
+ * that integer value — for a wire key with no name of its own at all, e.g.
194
+ * a literal `1: &(AES-CCM-16-64-128: 10)` entry, whose value can still be
195
+ * resolved this way even though the key `1` itself was never eRefKeys
196
+ * -eligible (see `extensions/eref.ts`'s own use of this for exactly this
197
+ * case). Every matching entry's own value type is resolved into the
198
+ * nested scope's own alternatives (kept separate from each other the same
199
+ * way `scope`'s own were — see the module doc); `undefined` when nothing
200
+ * matches `identifier` at all, when what matches doesn't resolve to a map
201
+ * type anywhere, or when an open/wildcard member key (`firstOpenIndex()`)
202
+ * at or before the matching entry, *within that same alternative*, could
203
+ * equally claim the same wire key with a shape this resolver can't pin
204
+ * down — see `firstOpenIndex()`'s own doc for exactly when that does and
205
+ * doesn't apply. The object being converted might just as well belong to
206
+ * that open entry instead of whichever named one matched literally, so
207
+ * descending as if it definitely doesn't would risk exactly the same
208
+ * "wrong alternative" misconversion `scopeNameToValue()`'s own doc
209
+ * describes for `scope`'s own direct names.
210
+ *
211
+ * `respectDeclarationOrder` (default `true`) — see `scopeNameToValue()`'s
212
+ * own doc; `fromJS()` passes `false` when descending from a JS property
213
+ * name it hasn't (or can't) also convert to an integer key this same way,
214
+ * so the nested scope it resolves stays consistent with that decision.
215
+ */
216
+ export declare function resolveNestedScope(schema: CddlSchema, scope: ERefScope, identifier: string | bigint, respectDeclarationOrder?: boolean): ERefScope | undefined;
217
+ /**
218
+ * The name safely labeling `value` when it's the value of `identifier`'s
219
+ * own entry within `scope` — resolving that entry's own value type
220
+ * (`matchingValueType()`, the same position-aware matching
221
+ * `resolveNestedScope()` uses) via `resolveEnumNames()`. Symmetric with
222
+ * `resolveNestedScope()`, but for a value whose *type* is (or resolves to)
223
+ * a closed `&(name: value)` choice of named integer constants — e.g.
224
+ * `? &(gp_enc_alg: -4) => &(AES-CCM-16-64-128: 10, …)` — rather than a
225
+ * nested map. `identifier` may be a `bigint` to match purely by the key's
226
+ * own value when it has no name of its own at all (see
227
+ * `resolveNestedScope()`'s own doc). `undefined` when no matching entry's
228
+ * value type names `value` this way, when any matching entry's value type
229
+ * can't be confidently resolved (see `resolveEnumNames()`'s own doc), or
230
+ * when `scope` has an open/wildcard member key. Always uses the relaxed,
231
+ * declaration-order-aware matching (see `scopeNameToValue()`'s own doc) —
232
+ * every caller is on the annotation side, resolving an already-decoded
233
+ * wire value, never `fromJS()`'s own forward conversion.
234
+ */
235
+ export declare function resolveValueEnumName(schema: CddlSchema, scope: ERefScope, identifier: string | bigint, value: bigint): string | undefined;
236
+ /**
237
+ * The name `type` — a value's own type, e.g. the merged types of the members that consumed it —
238
+ * safely gives integer `value`: resolved via `resolveEnumNames()`, so any
239
+ * choice accepting the same integer under no name blocks it.
240
+ */
241
+ export declare function enumNameOfType(schema: CddlSchema, type: CddlType, value: bigint): string | undefined;
@@ -0,0 +1,64 @@
1
+ import { CddlSchema } from './schema';
2
+ import { CddlType } from './ast';
3
+ export interface ERefTables {
4
+ /** Name → value, for resolving `e'name'` while parsing CDN. */
5
+ readonly byName: ReadonlyMap<string, bigint>;
6
+ /**
7
+ * Value → name, for annotating a validated integer map key with a name —
8
+ * populated only from a binding at a genuine map-member-key position
9
+ * (a `&(name: value)` literal, or a bare reference to a constant rule
10
+ * used as the member key itself — never from either construct appearing
11
+ * anywhere else, and never from a general constant rule that isn't
12
+ * referenced at a member-key position at all) and only when neither the
13
+ * name nor the value is ambiguous (see the module doc and
14
+ * `ambiguousNames`).
15
+ */
16
+ readonly byValue: ReadonlyMap<bigint, string>;
17
+ /**
18
+ * Name → value, the exact inverse of `byValue` (safe and unambiguous by
19
+ * construction: every name appearing in `byValue` appears there with
20
+ * exactly one value, since a name bound to more than one value is already
21
+ * excluded — see `ambiguousNames`). Used for the reverse direction:
22
+ * `fromJS()`'s `eRefKeys` option converting a plain-object property name
23
+ * back to the integer key it names, symmetric with `ToJSOptions.eRefKeys`.
24
+ */
25
+ readonly nameToValue: ReadonlyMap<string, bigint>;
26
+ /**
27
+ * Names that were seen bound to more than one different value anywhere in
28
+ * the schema, and so were excluded from `byName` (and, transitively, from
29
+ * every `byValue`/`nameToValue` entry that would have named a value after
30
+ * one of them) — kept separately only to produce a clearer "ambiguous"
31
+ * error message than a plain "not defined" one would.
32
+ */
33
+ readonly ambiguousNames: ReadonlySet<string>;
34
+ /**
35
+ * Name → value, from `name = <int literal>` rule definitions **only**
36
+ * (including every `/=`/`//=` extension of the same name, when they all
37
+ * agree on a single value) — deliberately excludes a name that's *only*
38
+ * ever used as an `&(name: value)` enum label somewhere in the schema,
39
+ * even though that label also feeds `byName`/`nameToValue` (a
40
+ * general-purpose lookup that doesn't distinguish the two, correctly, for
41
+ * `e'name'`'s own CDN parse direction). A *bare* type reference at a
42
+ * member-key position (`? group_mode => bool`, or a wildcard's own key
43
+ * type, `* group_mode => …`) means "this rule's own constant value" —
44
+ * e.g. `group_mode = 3` — never "this spelling, however it's used
45
+ * anywhere in the schema"; conflating the two would let an unrelated
46
+ * `&(group_mode: 2) => …` enum label elsewhere make a wildcard whose key
47
+ * type is the *rule* `group_mode` (which might not even be an integer
48
+ * type at all) look like a closed, safe reference when it isn't — see
49
+ * `cddl/eRefScope.ts`'s own use of this.
50
+ */
51
+ readonly ruleConstantValues: ReadonlyMap<string, bigint>;
52
+ }
53
+ /**
54
+ * Extract (and cache, per schema instance) the `e'...'` name tables for a
55
+ * compiled CDDL schema.
56
+ */
57
+ export declare function getERefTables(schema: CddlSchema): ERefTables;
58
+ /**
59
+ * The literal integer value of a `type`, when it reduces to a single
60
+ * `type1` alternative with no range/control operator. `undefined` for
61
+ * anything else. Exported for `eRefScope.ts`'s own, position-aware name
62
+ * extraction, which needs the exact same check for an entry's own value.
63
+ */
64
+ export declare function literalIntOfType(type: CddlType): bigint | undefined;
@@ -0,0 +1,28 @@
1
+ import { CddlSchema } from './schema';
2
+ import { TagRecord, ValidateOptions } from './validator';
3
+ import { CborItem } from '../ast/CborItem';
4
+ /**
5
+ * `item` with every tag the schema implies — but that the item lacks —
6
+ * added via `makeTag`, when that is what makes it valid. Returns `item`
7
+ * itself (unchanged) when it already validates, or when even inference
8
+ * cannot make it valid (the caller's own validation then reports why).
9
+ * Nodes are replaced in place inside their containers; the returned root
10
+ * differs from `item` only when the root itself gets tagged.
11
+ */
12
+ export declare function inferImplicitTags(schema: CddlSchema, item: CborItem, options: ValidateOptions | undefined, makeTag: (tag: bigint, inner: CborItem) => CborItem): CborItem;
13
+ /**
14
+ * Flag (`CborTag._implicit`) every tag in `item` that the schema implies
15
+ * and that `inferImplicitTags()` would restore exactly if it were left off;
16
+ * clear the flag on every other tag. `trail` holds the records of the
17
+ * caller's own successful validation of `item` (its candidates: every tag
18
+ * matched by a literal `#6.N`).
19
+ *
20
+ * The candidate set shrinks until stripping it and inferring again yields
21
+ * back exactly that set: a tag that isn't restored (another alternative
22
+ * accepts the untagged content, the untagged tree already validates, …)
23
+ * drops out, and dropping one can change what the rest infer, hence the
24
+ * rounds. If inference would ever tag something that wasn't tagged, or
25
+ * the rounds run out, nothing is flagged — omission is an optimization,
26
+ * never worth a round trip that changes the data.
27
+ */
28
+ export declare function markImplicitTags(schema: CddlSchema, item: CborItem, options: ValidateOptions | undefined, trail: readonly TagRecord[]): void;
@@ -1,3 +1,3 @@
1
- Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:`Module`}});const e=require("../schema-zsg5yCPK.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;
1
+ Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:`Module`}});const e=require("../mapEntries-DwHPAzCN.cjs"),t=require("../schema-YiigSWjR.cjs");function n(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 r=class{static compile(e,n){return t.n(e,n)}};function i(t){let n=new e.p(t),r=[];for(;;){let e=n.consume();if(e.type===`EOF`)break;r.push(e)}return{tokens:r,comments:n.comments}}function a(t){let n=new e.p(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.$?i:new e.$(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=r,exports.default=r,exports.CddlMismatchError=e.Z,exports.CddlSchema=t.t,exports.CddlSemanticError=e.Q,exports.CddlSyntaxError=e.$,exports.PRELUDE_CDDL=e.u,exports.getERefTables=e.m,exports.getPreludeRules=e.d,exports.parseCDDL=e.f,exports.positionAt=n,exports.tokenize=i,exports.tokenizeLenient=a;
3
3
  //# sourceMappingURL=index.cjs.map
@@ -1 +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"}
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 { getERefTables } from './eref';\nexport type { ERefTables } from './eref';\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":"iLASA,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,CCsCA,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"}
@@ -10,6 +10,8 @@ export type { CompileOptions } from './schema';
10
10
  export { parseCDDL } from './parser';
11
11
  export type { ParseCddlResult } from './parser';
12
12
  export { PRELUDE_CDDL, getPreludeRules } from './prelude';
13
+ export { getERefTables } from './eref';
14
+ export type { ERefTables } from './eref';
13
15
  export { positionAt } from './position';
14
16
  export type { CddlFormatOptions } from './writer';
15
17
  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';