@terrazzo/parser 0.0.11 → 0.0.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,18 @@
1
+ # @terrazzo/parser
2
+
3
+ ## 0.0.13
4
+
5
+ ### Patch Changes
6
+
7
+ - [#289](https://github.com/terrazzoapp/terrazzo/pull/289) [`0fc9738`](https://github.com/terrazzoapp/terrazzo/commit/0fc9738bb3dfecb680d225e4bd3970f21cfe8079) Thanks [@drwpow](https://github.com/drwpow)! - Add YAML support
8
+
9
+ - [#291](https://github.com/terrazzoapp/terrazzo/pull/291) [`6a875b1`](https://github.com/terrazzoapp/terrazzo/commit/6a875b163539dba8111911851a7819732056b3aa) Thanks [@drwpow](https://github.com/drwpow)! - Allow negative dimension values
10
+
11
+ ## 0.0.12
12
+
13
+ ### Patch Changes
14
+
15
+ - [#285](https://github.com/terrazzoapp/terrazzo/pull/285) [`e8a0df1`](https://github.com/terrazzoapp/terrazzo/commit/e8a0df1f3b50cf7cb292bcc475aae271feae4569) Thanks [@drwpow](https://github.com/drwpow)! - Add support for multiple token files
16
+
17
+ - Updated dependencies [[`e8a0df1`](https://github.com/terrazzoapp/terrazzo/commit/e8a0df1f3b50cf7cb292bcc475aae271feae4569)]:
18
+ - @terrazzo/token-tools@0.0.6
package/build/index.d.ts CHANGED
@@ -4,7 +4,7 @@ import type { ConfigInit } from '../config.js';
4
4
  import type Logger from '../logger.js';
5
5
 
6
6
  export interface BuildRunnerOptions {
7
- ast: DocumentNode;
7
+ sources: { filename?: URL; src: string; document: DocumentNode }[];
8
8
  config: ConfigInit;
9
9
  logger?: Logger;
10
10
  }
@@ -73,8 +73,8 @@ export interface TransformHookOptions {
73
73
  mode?: string;
74
74
  },
75
75
  ): void;
76
- /** Momoa document */
77
- ast: DocumentNode;
76
+ /** Momoa documents */
77
+ sources: { filename?: URL; src: string; document: DocumentNode }[];
78
78
  }
79
79
 
80
80
  export interface BuildHookOptions {
@@ -82,8 +82,8 @@ export interface BuildHookOptions {
82
82
  tokens: Record<string, TokenNormalized>;
83
83
  /** Query transformed values */
84
84
  getTransforms(params: TransformParams): TokenTransformed[];
85
- /** Momoa document */
86
- ast: DocumentNode;
85
+ /** Momoa documents */
86
+ sources: { filename?: URL; src: string; document: DocumentNode }[];
87
87
  outputFile: (
88
88
  /** Filename to output (relative to outDir) */
89
89
  filename: string,
@@ -101,8 +101,8 @@ export interface BuildEndHookOptions {
101
101
  tokens: Record<string, TokenNormalized>;
102
102
  /** Query transformed values */
103
103
  getTransforms(params: TransformParams): TokenTransformed[];
104
- /** Momoa document */
105
- ast: DocumentNode;
104
+ /** Momoa documents */
105
+ sources: { filename?: URL; src: string; document: DocumentNode }[];
106
106
  /** Final files to be written */
107
107
  outputFiles: OutputFileExpanded[];
108
108
  }
package/build/index.js CHANGED
@@ -5,7 +5,7 @@ import Logger from '../logger.js';
5
5
  /**
6
6
  * @typedef {object} BuildRunnerOptions
7
7
  * @typedef {Record<string, TokenNormalized>} BuildRunnerOptions.tokens
8
- * @typedef {DocumentNode} BuildRunnerOptions.ast
8
+ * @typedef {Array} BuildRunnerOptions.sources
9
9
  * @typedef {ConfigInit} BuildRunnerOptions.config
10
10
  * @typedef {Logger} BuildRunnerOptions.logger
11
11
  * @typedef {import("@humanwhocodes/momoa").DocumentNode} DocumentNode
@@ -60,7 +60,7 @@ function validateTransformParams({ params, token, logger, pluginName }) {
60
60
  * @param {BuildOptions} options
61
61
  * @return {Promise<BuildResult>}
62
62
  */
63
- export default async function build(tokens, { ast, logger = new Logger(), config }) {
63
+ export default async function build(tokens, { sources, logger = new Logger(), config }) {
64
64
  const formats = {};
65
65
  const result = { outputFiles: [] };
66
66
 
@@ -95,7 +95,7 @@ export default async function build(tokens, { ast, logger = new Logger(), config
95
95
  if (typeof plugin.transform === 'function') {
96
96
  await plugin.transform({
97
97
  tokens,
98
- ast,
98
+ sources,
99
99
  getTransforms,
100
100
  setTransform(id, params) {
101
101
  if (transformsLocked) {
@@ -165,7 +165,7 @@ export default async function build(tokens, { ast, logger = new Logger(), config
165
165
  const pluginBuildStart = performance.now();
166
166
  await plugin.build({
167
167
  tokens,
168
- ast,
168
+ sources,
169
169
  getTransforms,
170
170
  outputFile(filename, contents) {
171
171
  const resolved = new URL(filename, config.outDir);
@@ -196,7 +196,7 @@ export default async function build(tokens, { ast, logger = new Logger(), config
196
196
  if (typeof plugin.buildEnd === 'function') {
197
197
  await plugin.buildEnd({
198
198
  tokens,
199
- ast,
199
+ sources,
200
200
  getTransforms,
201
201
  format: (formatID) => createFormatter(formatID),
202
202
  outputFiles: structruedClone(result.outputFiles),
@@ -0,0 +1,56 @@
1
+ // MIT License
2
+ //
3
+ // Copyright (c) 2014-present Sebastian McKenzie and other contributors
4
+ //
5
+ // Permission is hereby granted, free of charge, to any person obtaining
6
+ // a copy of this software and associated documentation files (the
7
+ // "Software"), to deal in the Software without restriction, including
8
+ // without limitation the rights to use, copy, modify, merge, publish,
9
+ // distribute, sublicense, and/or sell copies of the Software, and to
10
+ // permit persons to whom the Software is furnished to do so, subject to
11
+ // the following conditions:
12
+ //
13
+ // The above copyright notice and this permission notice shall be
14
+ // included in all copies or substantial portions of the Software.
15
+ //
16
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
+ // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
+ // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
+ // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
+ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23
+
24
+ export interface Location {
25
+ line: number;
26
+ column: number;
27
+ }
28
+
29
+ export interface NodeLocation {
30
+ end?: Location;
31
+ start: Location;
32
+ }
33
+
34
+ export interface Options {
35
+ /** Syntax highlight the code as JavaScript for terminals. default: false */
36
+ highlightCode?: boolean;
37
+ /** The number of lines to show above the error. default: 2 */
38
+ linesAbove?: number;
39
+ /** The number of lines to show below the error. default: 3 */
40
+ linesBelow?: number;
41
+ /**
42
+ * Forcibly syntax highlight the code as JavaScript (for non-terminals);
43
+ * overrides highlightCode.
44
+ * default: false
45
+ */
46
+ forceColor?: boolean;
47
+ /**
48
+ * Pass in a string to be displayed inline (if possible) next to the
49
+ * highlighted location in the code. If it can't be positioned inline,
50
+ * it will be placed above the code frame.
51
+ * default: nothing
52
+ */
53
+ message?: string;
54
+ }
55
+
56
+ export function codeFrameColumns(input: string, location: NodeLocation, options?: Options): string;
@@ -0,0 +1,141 @@
1
+ // This is copied from @babel/code-frame package but without the heavyweight color highlighting
2
+ // (note: Babel loads both chalk AND picocolors, and doesn’t treeshake well)
3
+ // Babel is MIT-licensed and unaffiliated with this project.
4
+
5
+ // MIT License
6
+ //
7
+ // Copyright (c) 2014-present Sebastian McKenzie and other contributors
8
+ //
9
+ // Permission is hereby granted, free of charge, to any person obtaining
10
+ // a copy of this software and associated documentation files (the
11
+ // "Software"), to deal in the Software without restriction, including
12
+ // without limitation the rights to use, copy, modify, merge, publish,
13
+ // distribute, sublicense, and/or sell copies of the Software, and to
14
+ // permit persons to whom the Software is furnished to do so, subject to
15
+ // the following conditions:
16
+ //
17
+ // The above copyright notice and this permission notice shall be
18
+ // included in all copies or substantial portions of the Software.
19
+ //
20
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21
+ // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22
+ // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23
+ // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24
+ // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25
+ // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26
+ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27
+
28
+ /**
29
+ * Extract what lines should be marked and highlighted.
30
+ */
31
+
32
+ function getMarkerLines(loc, source, opts = {}) {
33
+ const startLoc = {
34
+ column: 0,
35
+ line: -1,
36
+ ...loc.start,
37
+ };
38
+ const endLoc = {
39
+ ...startLoc,
40
+ ...loc.end,
41
+ };
42
+ const { linesAbove = 2, linesBelow = 3 } = opts || {};
43
+ const startLine = startLoc.line;
44
+ const startColumn = startLoc.column;
45
+ const endLine = endLoc.line;
46
+ const endColumn = endLoc.column;
47
+
48
+ let start = Math.max(startLine - (linesAbove + 1), 0);
49
+ let end = Math.min(source.length, endLine + linesBelow);
50
+
51
+ if (startLine === -1) {
52
+ start = 0;
53
+ }
54
+
55
+ if (endLine === -1) {
56
+ end = source.length;
57
+ }
58
+
59
+ const lineDiff = endLine - startLine;
60
+ const markerLines = {};
61
+
62
+ if (lineDiff) {
63
+ for (let i = 0; i <= lineDiff; i++) {
64
+ const lineNumber = i + startLine;
65
+
66
+ if (!startColumn) {
67
+ markerLines[lineNumber] = true;
68
+ } else if (i === 0) {
69
+ const sourceLength = source[lineNumber - 1].length;
70
+
71
+ markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1];
72
+ } else if (i === lineDiff) {
73
+ markerLines[lineNumber] = [0, endColumn];
74
+ } else {
75
+ const sourceLength = source[lineNumber - i].length;
76
+
77
+ markerLines[lineNumber] = [0, sourceLength];
78
+ }
79
+ }
80
+ } else {
81
+ if (startColumn === endColumn) {
82
+ if (startColumn) {
83
+ markerLines[startLine] = [startColumn, 0];
84
+ } else {
85
+ markerLines[startLine] = true;
86
+ }
87
+ } else {
88
+ markerLines[startLine] = [startColumn, endColumn - startColumn];
89
+ }
90
+ }
91
+
92
+ return { start, end, markerLines };
93
+ }
94
+
95
+ /**
96
+ * RegExp to test for newlines in terminal.
97
+ */
98
+
99
+ const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
100
+
101
+ export function codeFrameColumns(rawLines, loc, opts = {}) {
102
+ const lines = rawLines.split(NEWLINE);
103
+ const { start, end, markerLines } = getMarkerLines(loc, lines, opts);
104
+ const hasColumns = loc.start && typeof loc.start.column === 'number';
105
+
106
+ const numberMaxWidth = String(end).length;
107
+
108
+ let frame = rawLines
109
+ .split(NEWLINE, end)
110
+ .slice(start, end)
111
+ .map((line, index) => {
112
+ const number = start + 1 + index;
113
+ const paddedNumber = ` ${number}`.slice(-numberMaxWidth);
114
+ const gutter = ` ${paddedNumber} |`;
115
+ const hasMarker = markerLines[number];
116
+ const lastMarkerLine = !markerLines[number + 1];
117
+ if (hasMarker) {
118
+ let markerLine = '';
119
+ if (Array.isArray(hasMarker)) {
120
+ const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, ' ');
121
+ const numberOfMarkers = hasMarker[1] || 1;
122
+
123
+ markerLine = ['\n ', gutter.replace(/\d/g, ' '), ' ', markerSpacing, '^'.repeat(numberOfMarkers)].join('');
124
+
125
+ if (lastMarkerLine && opts.message) {
126
+ markerLine += ` ${opts.message}`;
127
+ }
128
+ }
129
+ return ['>', gutter, line.length > 0 ? ` ${line}` : '', markerLine].join('');
130
+ } else {
131
+ return ` ${gutter}${line.length > 0 ? ` ${line}` : ''}`;
132
+ }
133
+ })
134
+ .join('\n');
135
+
136
+ if (opts.message && !hasColumns) {
137
+ frame = `${' '.repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`;
138
+ }
139
+
140
+ return frame;
141
+ }
package/lint/index.d.ts CHANGED
@@ -26,7 +26,8 @@ export interface LinterOptions<O = any> {
26
26
  id: string;
27
27
  severity: LintRuleSeverity;
28
28
  };
29
- ast: DocumentNode;
29
+ document: DocumentNode;
30
+ filename?: URL;
30
31
  source?: string;
31
32
  /** Any options the user has declared for this plugin */
32
33
  options?: O;
@@ -34,7 +35,8 @@ export interface LinterOptions<O = any> {
34
35
  export type Linter = (options: LinterOptions) => Promise<LintNotice[] | undefined>;
35
36
 
36
37
  export interface LintRunnerOptions {
37
- ast: DocumentNode;
38
+ document: DocumentNode;
39
+ filename?: URL;
38
40
  config: ConfigInit;
39
41
  logger: Logger;
40
42
  }
@@ -1,5 +1,4 @@
1
1
  import { isAlias, isTokenMatch } from '@terrazzo/token-tools';
2
- import deepEqual from 'deep-equal';
3
2
 
4
3
  export default function ruleDuplicateValues({ tokens, rule: { severity }, options }) {
5
4
  if (severity === 'off') {
@@ -51,7 +50,7 @@ export default function ruleDuplicateValues({ tokens, rule: { severity }, option
51
50
  // everything else: use deepEqual
52
51
  let isDuplicate = false;
53
52
  for (const v of values[t.$type]?.values() ?? []) {
54
- if (deepEqual(t.$value, v)) {
53
+ if (JSON.stringify(t.$value) === JSON.stringify(v)) {
55
54
  notices.push({ message: `Duplicated value (${t.id})`, node: t.sourceNode });
56
55
  isDuplicate = true;
57
56
  break;
package/logger.d.ts CHANGED
@@ -13,12 +13,14 @@ export interface LogEntry {
13
13
  message: string;
14
14
  /** (optional) Prefix message with label */
15
15
  label?: string;
16
+ /** (optional) File in disk */
17
+ filename?: URL;
16
18
  /** Continue on error? (default: false) */
17
19
  continueOnError?: boolean;
18
20
  /** (optional) Show a code frame for the erring node */
19
21
  node?: AnyNode;
20
22
  /** (optional) To show a code frame, provide the original source code */
21
- source?: string;
23
+ src?: string;
22
24
  }
23
25
 
24
26
  export interface DebugEntry {
@@ -29,7 +31,7 @@ export interface DebugEntry {
29
31
  /** Error message to be logged */
30
32
  message: string;
31
33
  /** (optional) Show code below message */
32
- codeFrame?: { source: string; line: number; column: number };
34
+ codeFrame?: { src: string; line: number; column: number };
33
35
  /** (optional) Display performance timing */
34
36
  timing?: number;
35
37
  }
package/logger.js CHANGED
@@ -1,6 +1,6 @@
1
- import { codeFrameColumns } from '@babel/code-frame';
2
1
  import color from 'picocolors';
3
2
  import wcmatch from 'wildcard-match';
3
+ import { codeFrameColumns } from './lib/code-frame.js';
4
4
 
5
5
  export const LOG_ORDER = ['error', 'warn', 'info', 'debug'];
6
6
 
@@ -23,8 +23,10 @@ export function formatMessage(entry, severity) {
23
23
  if (severity in MESSAGE_COLOR) {
24
24
  message = MESSAGE_COLOR[severity](message);
25
25
  }
26
- if (entry.source) {
27
- message = `${message}\n\n${codeFrameColumns(entry.source, { start: entry.node?.loc?.start })}`;
26
+ if (entry.src) {
27
+ const start = entry.node?.loc?.start;
28
+ // note: strip "file://" protocol, but not href
29
+ message = `${message}\n\n${entry.filename ? `${entry.filename.href.replace(/^file:\/\//, '')}:${start?.line ?? 0}:${start?.column ?? 0}\n\n` : ''}${codeFrameColumns(entry.src, { start }, { highlightCode: false })}`;
28
30
  }
29
31
  return message;
30
32
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@terrazzo/parser",
3
- "version": "0.0.11",
3
+ "version": "0.0.13",
4
4
  "description": "Parser/validator for the Design Tokens Community Group (DTCG) standard.",
5
5
  "type": "module",
6
6
  "author": {
@@ -30,19 +30,20 @@
30
30
  },
31
31
  "license": "MIT",
32
32
  "dependencies": {
33
- "@babel/code-frame": "^7.24.7",
34
- "@humanwhocodes/momoa": "^3.1.1",
33
+ "@humanwhocodes/momoa": "^3.2.0",
35
34
  "@types/babel__code-frame": "^7.0.6",
36
35
  "@types/culori": "^2.1.1",
37
- "@types/deep-equal": "^1.0.4",
38
36
  "culori": "^4.0.1",
39
- "deep-equal": "^2.2.3",
40
37
  "is-what": "^4.1.16",
41
38
  "merge-anything": "^5.1.7",
42
39
  "picocolors": "^1.0.1",
43
40
  "wildcard-match": "^5.1.3",
44
- "yaml": "^2.4.5",
45
- "@terrazzo/token-tools": "^0.0.4"
41
+ "yaml": "^2.5.0",
42
+ "@terrazzo/token-tools": "^0.0.6"
43
+ },
44
+ "devDependencies": {
45
+ "esbuild": "^0.23.0",
46
+ "yaml-to-momoa": "^0.0.1"
46
47
  },
47
48
  "scripts": {
48
49
  "lint": "biome check .",
package/parse/index.d.ts CHANGED
@@ -1,28 +1,39 @@
1
1
  import type { DocumentNode } from '@humanwhocodes/momoa';
2
2
  import type { TokenNormalized } from '@terrazzo/token-tools';
3
+ import type yamlToMomoa from 'yaml-to-momoa';
3
4
  import type { ConfigInit } from '../config.js';
4
5
  import type Logger from '../logger.js';
5
6
 
6
7
  export * from './validate.js';
7
8
 
9
+ export interface ParseInput {
10
+ /** Source filename (if read from disk) */
11
+ filename?: URL;
12
+ /** JSON/YAML string, or JSON-serializable object (if already in memory) */
13
+ src: string | object;
14
+ }
15
+
8
16
  export interface ParseOptions {
9
17
  logger?: Logger;
18
+ config: ConfigInit;
10
19
  /** Skip lint step (default: false) */
11
20
  skipLint?: boolean;
12
- config: ConfigInit;
13
21
  /** Continue on error? (Useful for `tz check`) (default: false) */
14
22
  continueOnError?: boolean;
23
+ /** Provide yamlToMomoa module to parse YAML (by default, this isn’t shipped to cut down on package weight) */
24
+ yamlToMomoa?: typeof yamlToMomoa;
15
25
  }
16
26
 
17
27
  export interface ParseResult {
18
28
  tokens: Record<string, TokenNormalized>;
19
- ast: DocumentNode;
29
+ /** ASTs are returned in order of input array */
30
+ sources: { filename?: URL; src: string; document: DocumentNode }[];
20
31
  }
21
32
 
22
33
  /**
23
34
  * Parse and validate Tokens JSON, and lint it
24
35
  */
25
- export default function parse(input: string | object, options?: ParseOptions): Promise<ParseResult>;
36
+ export default function parse(input: ParseInput[], options?: ParseOptions): Promise<ParseResult>;
26
37
 
27
38
  /** Determine if an input is likely a JSON string */
28
39
  export function maybeJSONString(input: unknown): boolean;