@terrazzo/cli 0.2.0 → 0.2.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.
@@ -1,4 +1,4 @@
1
1
 
2
- > @terrazzo/cli@0.2.0 build /home/runner/work/terrazzo/terrazzo/packages/cli
2
+ > @terrazzo/cli@0.2.2 build /home/runner/work/terrazzo/terrazzo/packages/cli
3
3
  > tsc -p tsconfig.build.json
4
4
 
package/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # @terrazzo/cli
2
2
 
3
+ ## 0.2.2
4
+
5
+ ### Patch Changes
6
+
7
+ - [#364](https://github.com/terrazzoapp/terrazzo/pull/364) [`27cc92e`](https://github.com/terrazzoapp/terrazzo/commit/27cc92ef5e9e187b5ec7a8abe3f23bc51f59fc9c) Thanks [@drwpow](https://github.com/drwpow)! - Add init CLI options
8
+
9
+ - Updated dependencies [[`27cc92e`](https://github.com/terrazzoapp/terrazzo/commit/27cc92ef5e9e187b5ec7a8abe3f23bc51f59fc9c)]:
10
+ - @terrazzo/parser@0.2.2
11
+ - @terrazzo/token-tools@0.2.2
12
+
13
+ ## 0.2.1
14
+
15
+ ### Patch Changes
16
+
17
+ - [#358](https://github.com/terrazzoapp/terrazzo/pull/358) [`6b3c543`](https://github.com/terrazzoapp/terrazzo/commit/6b3c543a3356c582522f6e2d9b2948a0634a66df) Thanks [@christoph-fricke](https://github.com/christoph-fricke)! - Fix npm error when invoking the Terrazzo CLI through npm
18
+
3
19
  ## 0.2.0
4
20
 
5
21
  ### Minor Changes
package/bin/cli.js CHANGED
@@ -1,3 +1,5 @@
1
+ #!/usr/bin/env node
2
+
1
3
  /**
2
4
  * @module @terrazzo/cli
3
5
  * @license MIT License
@@ -23,210 +25,90 @@
23
25
  * SOFTWARE.
24
26
  */
25
27
 
26
- import fs from 'node:fs';
27
- import path from 'node:path';
28
- import { fileURLToPath } from 'node:url';
29
28
  import { parseArgs } from 'node:util';
30
- import { Logger, build, defineConfig, parse } from '@terrazzo/parser';
31
- import chokidar from 'chokidar';
29
+ import { Logger } from '@terrazzo/parser';
32
30
  import dotenv from 'dotenv';
33
- import pc from 'picocolors';
34
- import yamlToMomoa from 'yaml-to-momoa';
35
-
31
+ import { buildCmd } from '../dist/build.js';
32
+ import { checkCmd } from '../dist/check.js';
33
+ import { helpCmd } from '../dist/help.js';
34
+ import { initCmd } from '../dist/init.js';
35
+ import { loadConfig } from '../dist/shared.js';
36
+ import { versionCmd } from '../dist/version.js';
37
+
38
+ // Load env vars before anything else
39
+ // (a user may not use these at all, but in the offchance they do)
36
40
  dotenv.config();
37
41
 
38
42
  const [, , ...argsRaw] = process.argv;
39
- const cwd = new URL(`file://${process.cwd()}/`);
40
- const PKG_ROOT = new URL('../', import.meta.url);
41
- const logger = new Logger(
42
- // TODO: listen for env vars for debugging, log level, etc
43
- );
44
-
45
- const GREEN_CHECK = pc.green('✔');
46
43
 
47
44
  const { values: flags, positionals } = parseArgs({
48
45
  args: argsRaw,
49
46
  allowPositionals: true,
50
47
  options: {
51
- config: {
52
- type: 'string',
53
- short: 'c',
54
- },
55
- out: {
56
- type: 'string',
57
- short: 'o',
58
- },
59
- help: {
60
- type: 'boolean',
61
- },
62
- watch: {
63
- type: 'boolean',
64
- short: 'w',
65
- },
66
- version: {
67
- type: 'boolean',
68
- },
48
+ config: { type: 'string', short: 'c' },
49
+ out: { type: 'string', short: 'o' },
50
+ help: { type: 'boolean' },
51
+ silent: { type: 'boolean' },
52
+ quiet: { type: 'boolean' }, // secret alias for --silent because I can’t remember it
53
+ watch: { type: 'boolean', short: 'w' },
54
+ version: { type: 'boolean' },
69
55
  },
70
56
  });
71
57
 
58
+ // Note: there are 2 types of logging in the CLI. The logger passed to the
59
+ // parser will provide shared configuration for all methods, but it will throw
60
+ // Errors because it’s expected to run in a generic JS context (process.exit
61
+ // won’t always be available).
62
+ //
63
+ // However, in a CLI, errors are more numerous and expected, and users are
64
+ // likely to see multiple at once. We want to remove stacktraces just for the
65
+ // CLI context. So we wrap this logger with our own formatter that simply prints
66
+ // the raw message.
67
+ const logger = new Logger({
68
+ // set correct level of debugging
69
+ level: flags.silent || flags.quiet ? 'error' : undefined,
70
+ // add debug messages, if requested
71
+ debugScope: process.env.DEBUG,
72
+ });
73
+
72
74
  export default async function main() {
73
- const start = performance.now();
74
75
  const cmd = positionals[0];
75
76
 
76
77
  // ---
77
- // half-run commands: --help, --version, init
78
+ // Half-run commands: --help, --version, init
78
79
 
79
80
  // --version
80
81
  if (flags.version) {
81
- const { version } = JSON.parse(fs.readFileSync(new URL('./package.json', PKG_ROOT), 'utf8'));
82
- console.log(version);
82
+ versionCmd();
83
83
  process.exit(0);
84
84
  }
85
85
 
86
86
  // --help
87
87
  if (flags.help || !cmd) {
88
- showHelp();
88
+ helpCmd();
89
89
  process.exit(0);
90
90
  }
91
91
 
92
- // ---
93
- // full-run commands: build, check
94
-
95
- // setup: load terrazzo.config.js and terrazzo.config.json
96
- let configPath;
97
- if (typeof flags.config === 'string') {
98
- if (flags.config === '') {
99
- printErrors('Missing path after --config flag');
100
- process.exit(1);
101
- }
102
- configPath = resolveConfig(flags.config);
103
- }
104
- let config = {
105
- tokens: [new URL('./tokens.json', cwd)],
106
- outDir: new URL('./tokens/', cwd),
107
- plugins: [],
108
- ignore: { tokens: [], deprecated: false },
109
- };
110
- const resolvedConfigPath = resolveConfig(configPath);
111
- if (resolvedConfigPath) {
112
- try {
113
- const mod = await import(resolvedConfigPath);
114
- if (!mod.default) {
115
- printErrors(
116
- `No default export found in ${path.relative(cwd.href, resolvedConfigPath)}. See https://terrazzo.dev/docs/cli for instructions.`,
117
- );
118
- process.exit(1);
119
- }
120
- config = defineConfig(mod.default, { cwd, logger });
121
- } catch (err) {
122
- printErrors(err.message || err);
123
- process.exit(1);
124
- }
125
- } else if (cmd !== 'init' && cmd !== 'check') {
126
- printErrors('No config file found. Create one with `npx terrazzo init`.');
127
- process.exit(1);
128
- }
92
+ const { config, configPath } = await loadConfig({ cmd, flags, logger });
129
93
 
94
+ // ---
95
+ // Full-run commands: build, check, lint
130
96
  switch (cmd) {
131
97
  case 'build': {
132
- if (!Array.isArray(config.plugins) || !config.plugins.length) {
133
- printErrors(`No plugins defined! Add some in ${configPath || 'terrazzo.config.js'}`);
134
- process.exit(1);
135
- }
136
-
137
- let rawSchemas = await loadTokens(config.tokens);
138
-
139
- const watch = flags.watch;
140
-
141
- let { tokens, ast } = await parse(rawSchemas, { config, logger, yamlToMomoa });
142
- let result = await build(tokens, { ast, config, logger });
143
- writeFiles(result, config);
144
-
145
- printErrors(result.errors);
146
- printWarnings(result.warnings);
147
-
148
- if (watch) {
149
- const dt = new Intl.DateTimeFormat('en-us', {
150
- hour: '2-digit',
151
- minute: '2-digit',
152
- });
153
- const tokenWatcher = chokidar.watch(config.tokens.map((filename) => fileURLToPath(filename)));
154
- tokenWatcher.on('change', async (filename) => {
155
- try {
156
- rawSchemas = await loadTokens(config.tokens);
157
- const parseResult = await parse(rawSchemas, { config, logger, yamlToMomoa });
158
- tokens = parseResult.tokens;
159
- ast = parseResult.ast;
160
- result = await build(tokens, { ast, config, logger });
161
- console.log(
162
- `${pc.dim(dt.format(new Date()))} ${pc.green('Tz')}} ${pc.yellow(filename)} updated ${GREEN_CHECK}`,
163
- );
164
- } catch (err) {
165
- printErrors([err.message || err]);
166
- }
167
- });
168
- const configWatcher = chokidar.watch(resolveConfig(configPath));
169
- configWatcher.on('change', async (filename) => {
170
- try {
171
- console.log(
172
- `${pc.dim(dt.format(new Date()))} ${pc.green('Tz')} ${pc.yellow('Config updated. Reloading…')}`,
173
- );
174
- config = (await import(filename)).default;
175
- rawSchema = await loadTokens(config.tokens);
176
- const parseResult = await parse(tokens, { config, logger, yamlToMomoa });
177
- tokens = parseResult.tokens;
178
- ast = parseResult.ast;
179
- result = await build(tokens, { ast, config, logger });
180
- writeFiles(result, config);
181
- } catch (err) {
182
- printErrors([err.message || err]);
183
- }
184
- });
185
-
186
- // keep process occupied
187
- await new Promise(() => {});
188
- } else {
189
- printSuccess(
190
- `${Object.keys(tokens).length} token${Object.keys(tokens).length !== 1 ? 's' : ''} built ${time(start)}`,
191
- );
192
- }
193
- break;
194
- }
195
- case 'check': {
196
- const rawSchemas = await loadTokens(positionals[1] ? [resolveTokenPath(positionals[1])] : config.tokens);
197
- const filename = positionals[1] || config.tokens[0];
198
- console.log(pc.underline(filename.protocol === 'file:' ? filename.href : filename));
199
- await parse(rawSchemas, { config, continueOnError: true, logger, yamlToMomoa }); // will throw if errors
200
- printSuccess(`No errors ${time(start)}`);
98
+ await buildCmd({ config, configPath, flags, logger });
201
99
  break;
202
100
  }
101
+ case 'check':
203
102
  case 'lint': {
204
- if (!Array.isArray(config.plugins) || !config.plugins.length) {
205
- printErrors(`No plugins defined! Add some in ${configPath || 'terrazzo.config.js'}`);
206
- }
207
-
208
- const rawSchema = await loadTokens(positionals[1] ? [resolveTokenPath(positionals[1])] : config.tokens);
209
- await parse(rawSchema, { config, continueOnError: true, logger, yamlToMomoa }); // will throw if errors
210
-
103
+ await checkCmd({ config, logger, positionals });
211
104
  break;
212
105
  }
213
106
  case 'init': {
214
- if (
215
- !fs.existsSync(new URL('./terrazzo.config.js', cwd)) &&
216
- !fs.existsSync(new URL('./terrazzo.config.mjs', cwd)) &&
217
- !fs.existsSync(new URL('./terrazzo.config.cjs', cwd))
218
- ) {
219
- fs.cpSync(new URL('./terrazzo.config.mjs', PKG_ROOT), new URL('./terrazzo.config.mjs', cwd));
220
- printSuccess('terrazzo.config.mjs created');
221
- }
222
- if (!fs.existsSync(config.tokens[0])) {
223
- fs.cpSync(new URL('./tokens-example.json', PKG_ROOT), new URL(config?.tokens, cwd));
224
- printSuccess(`${config.tokens} created ${time(start)}`);
225
- }
107
+ await initCmd({ config, flags, logger });
226
108
  break;
227
109
  }
228
110
  default: {
229
- showHelp();
111
+ helpCmd();
230
112
  break;
231
113
  }
232
114
  }
@@ -236,192 +118,3 @@ export default async function main() {
236
118
  }
237
119
 
238
120
  main();
239
-
240
- /** Show help */
241
- function showHelp() {
242
- console.log(`tz
243
- [commands]
244
- build Build token artifacts from tokens.json
245
- --watch, -w Watch tokens.json for changes and recompile
246
- --no-lint Disable linters running on build
247
- check [path] Check tokens.json for syntax errors
248
- lint [path] Run linters
249
- init Create a starter tokens.json file
250
- bundle Combine multiple tokens schemas into one
251
- --out [path] Specify bundled tokens.json output
252
- convert [file] Convert Style Dictionary format to DTCG
253
- --out [path] Specify converted tokens.json output
254
-
255
- [options]
256
- --help Show this message
257
- --config, -c Path to config (default: ./terrazzo.config.js)
258
- `);
259
- }
260
-
261
- /** load tokens */
262
- async function loadTokens(tokenPaths) {
263
- const allTokens = [];
264
-
265
- if (!Array.isArray(tokenPaths)) {
266
- printErrors(`loadTokens: Expected array, received ${typeof tokenPaths}`);
267
- process.exit(1);
268
- }
269
-
270
- // if this is the default value, also check for tokens.yaml
271
- if (tokenPaths.length === 1 && tokenPaths[0].href === new URL('./tokens.json', cwd).href) {
272
- if (!fs.existsSync(tokenPaths[0])) {
273
- const yamlPath = new URL('./tokens.yaml', cwd);
274
- if (fs.existsSync(yamlPath)) {
275
- tokenPaths[0] = yamlPath;
276
- } else {
277
- printErrors(
278
- `Could not locate ${path.relative(cwd.href, tokenPaths[0].href)}. To create one, run \`npx tz init\`.`,
279
- );
280
- process.exit(1);
281
- }
282
- }
283
- }
284
-
285
- // download/read
286
- for (let i = 0; i < tokenPaths.length; i++) {
287
- const filename = tokenPaths[i];
288
-
289
- if (!(filename instanceof URL)) {
290
- printErrors(`loadTokens[${i}]: Expected URL, received ${filename}`);
291
- process.exit(1);
292
- }
293
-
294
- if (filename.protocol === 'http:' || filename.protocol === 'https:') {
295
- try {
296
- // if Figma URL
297
- if (filename.host === 'figma.com' || filename.host === 'www.figma.com') {
298
- const [_, fileKeyword, fileKey] = filename.pathname.split('/');
299
- if (fileKeyword !== 'file' || !fileKey) {
300
- printErrors(
301
- `Unexpected Figma URL. Expected "https://www.figma.com/file/:file_key/:file_name?…", received "${filename.href}"`,
302
- );
303
- process.exit(1);
304
- }
305
- const headers = new Headers({
306
- Accept: '*/*',
307
- 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:123.0) Gecko/20100101 Firefox/123.0',
308
- });
309
- if (process.env.FIGMA_ACCESS_TOKEN) {
310
- headers.set('X-FIGMA-TOKEN', process.env.FIGMA_ACCESS_TOKEN);
311
- } else {
312
- printWarnings('FIGMA_ACCESS_TOKEN not set');
313
- }
314
- const res = await fetch(`https://api.figma.com/v1/files/${fileKey}/variables/local`, {
315
- method: 'GET',
316
- headers,
317
- });
318
- if (res.ok) {
319
- allTokens.push({ filename, src: await res.text() });
320
- }
321
- const message = res.status !== 404 ? JSON.stringify(await res.json(), undefined, 2) : '';
322
- printErrors(`Figma responded with ${res.status}${message ? `:\n${message}` : ''}`);
323
- process.exit(1);
324
- break;
325
- }
326
-
327
- // otherwise, expect YAML/JSON
328
- const res = await fetch(filename, {
329
- method: 'GET',
330
- headers: { Accept: '*/*', 'User-Agent': 'Mozilla/5.0 Gecko/20100101 Firefox/123.0' },
331
- });
332
- allTokens.push({ filename, src: await res.text() });
333
- } catch (err) {
334
- printErrors(`${filename.href}: ${err}`);
335
- }
336
- } else {
337
- if (fs.existsSync(filename)) {
338
- allTokens.push({ filename, src: fs.readFileSync(filename, 'utf8') });
339
- } else {
340
- printErrors(`Could not locate ${path.relative(cwd.href, filename.href)}. To create one, run \`npx tz init\`.`);
341
- process.exit(1);
342
- }
343
- }
344
- }
345
-
346
- return allTokens;
347
- }
348
-
349
- /**
350
- * resolve config
351
- * @return {string | undefined} resolvedPath
352
- */
353
- function resolveConfig(filename) {
354
- // --config [configpath]
355
- if (filename) {
356
- const configPath = new URL(filename, cwd);
357
- if (fs.existsSync(configPath)) {
358
- return configPath.href; // ⚠️ ESM wants "file://..." URLs on Windows & Unix.
359
- }
360
- return undefined;
361
- }
362
-
363
- // default: terrazzo.config.js
364
- for (const defaultFilename of [
365
- './terrazzo.config.mjs', // .mjs takes precedence (it suggestes .js is CJS)
366
- './terrazzo.config.js',
367
- ]) {
368
- const configPath = new URL(defaultFilename, cwd);
369
- if (fs.existsSync(configPath)) {
370
- return configPath.href; // ⚠️ ESM wants "file://..." URLs on Windows & Unix.
371
- }
372
- }
373
- }
374
-
375
- /** Resolve tokens.json path (for lint command) */
376
- function resolveTokenPath(filename) {
377
- const tokensPath = new URL(filename, cwd);
378
- if (!fs.existsSync(tokensPath)) {
379
- printErrors(`Could not locate ${filename}. Does the file exist?`);
380
- process.exit(1);
381
- }
382
- if (!fs.statSync(tokensPath).isFile()) {
383
- printErrors(`Expected JSON or YAML file, received ${filename}.`);
384
- process.exit(1);
385
- }
386
- return tokensPath;
387
- }
388
-
389
- /** Print time elapsed */
390
- function time(start) {
391
- const diff = performance.now() - start;
392
- return pc.dim(diff < 750 ? `${Math.round(diff)}ms` : `${(diff / 1000).toFixed(1)}s`);
393
- }
394
-
395
- /** Print success */
396
- export function printSuccess(message) {
397
- console.log(` ${GREEN_CHECK} ${message}`);
398
- }
399
-
400
- /** Print errors */
401
- export function printErrors(errors) {
402
- if (!errors || (typeof errors !== 'string' && !Array.isArray(errors))) {
403
- return;
404
- }
405
- for (const err of Array.isArray(errors) ? errors : [errors]) {
406
- console.error(` ${pc.red(`✘ ${err}`)}`);
407
- }
408
- }
409
-
410
- /** Print warnings */
411
- export function printWarnings(warnings) {
412
- if (!warnings || (typeof warnings !== 'string' && !Array.isArray(warnings))) {
413
- return;
414
- }
415
- for (const warn of Array.isArray(warnings) ? warnings : [warnings]) {
416
- console.warn(` ${pc.yellow(`! ${warn}`)}`);
417
- }
418
- }
419
-
420
- /** Write files */
421
- export function writeFiles(result, config) {
422
- for (const { filename, contents } of result.outputFiles) {
423
- const output = new URL(filename, config.outDir);
424
- fs.mkdirSync(new URL('.', output), { recursive: true });
425
- fs.writeFileSync(output, contents);
426
- }
427
- }
@@ -0,0 +1,12 @@
1
+ import { type BuildRunnerResult, type ConfigInit, type Logger } from '@terrazzo/parser';
2
+ import { type Flags } from './shared.js';
3
+ export interface BuildOptions {
4
+ flags: Flags;
5
+ config: ConfigInit;
6
+ configPath: string;
7
+ logger: Logger;
8
+ }
9
+ /** tz build */
10
+ export declare function buildCmd({ config, configPath, flags, logger }: BuildOptions): Promise<void>;
11
+ /** Write files */
12
+ export declare function writeFiles(result: BuildRunnerResult, config: ConfigInit): void;
package/dist/build.js ADDED
@@ -0,0 +1,88 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { build, parse } from '@terrazzo/parser';
5
+ import chokidar from 'chokidar';
6
+ import pc from 'picocolors';
7
+ import yamlToMomoa from 'yaml-to-momoa';
8
+ import { DEFAULT_TOKENS_PATH, GREEN_CHECK, cwd, loadTokens, printError, printSuccess, resolveConfig, } from './shared.js';
9
+ /** tz build */
10
+ export async function buildCmd({ config, configPath, flags, logger }) {
11
+ try {
12
+ const startTime = performance.now();
13
+ if (!Array.isArray(config.plugins) || !config.plugins.length) {
14
+ logger.error({ message: `No plugins defined! Add some in ${configPath || 'terrazzo.config.js'}` });
15
+ }
16
+ // first build
17
+ let rawSchemas = await loadTokens(config.tokens, { logger });
18
+ if (!rawSchemas) {
19
+ logger.error({
20
+ message: `Error loading ${path.relative(fileURLToPath(cwd), fileURLToPath(config.tokens[0] || DEFAULT_TOKENS_PATH))}`,
21
+ });
22
+ return;
23
+ }
24
+ let { tokens, sources } = await parse(rawSchemas, { config, logger, yamlToMomoa });
25
+ let result = await build(tokens, { sources, config, logger });
26
+ writeFiles(result, config);
27
+ // --watch (handle rebuild)
28
+ if (flags.watch) {
29
+ const dt = new Intl.DateTimeFormat('en-us', {
30
+ hour: '2-digit',
31
+ minute: '2-digit',
32
+ });
33
+ async function rebuild({ messageBefore, messageAfter } = {}) {
34
+ try {
35
+ if (messageBefore) {
36
+ logger.info({ message: messageBefore });
37
+ }
38
+ rawSchemas = await loadTokens(config.tokens, { logger });
39
+ if (!rawSchemas) {
40
+ throw new Error(`Error loading ${path.relative(fileURLToPath(cwd), fileURLToPath(config.tokens[0] || DEFAULT_TOKENS_PATH))}`);
41
+ }
42
+ const parseResult = await parse(rawSchemas, { config, logger, yamlToMomoa });
43
+ tokens = parseResult.tokens;
44
+ sources = parseResult.sources;
45
+ result = await build(tokens, { sources, config, logger });
46
+ if (messageAfter) {
47
+ logger.info({ message: messageAfter });
48
+ }
49
+ writeFiles(result, config);
50
+ }
51
+ catch (err) {
52
+ console.error(pc.red(`✗ ${err.message || err}`));
53
+ // don’t exit! we’re watching, so continue as long as possible
54
+ }
55
+ }
56
+ const tokenWatcher = chokidar.watch(config.tokens.map((filename) => fileURLToPath(filename)));
57
+ tokenWatcher.on('change', async (filename) => {
58
+ await rebuild({
59
+ messageBefore: `${pc.dim(dt.format(new Date()))} ${pc.green('tz')}} ${pc.yellow(filename)} updated ${GREEN_CHECK}`,
60
+ });
61
+ });
62
+ const configWatcher = chokidar.watch(resolveConfig(configPath));
63
+ configWatcher.on('change', async () => {
64
+ await rebuild({
65
+ messageBefore: `${pc.dim(dt.format(new Date()))} ${pc.green('tz')} ${pc.yellow('Config updated. Reloading…')}`,
66
+ });
67
+ });
68
+ // keep process occupied
69
+ await new Promise(() => { });
70
+ }
71
+ else {
72
+ printSuccess(`${Object.keys(tokens).length} token${Object.keys(tokens).length !== 1 ? 's' : ''} built`, startTime);
73
+ }
74
+ }
75
+ catch (err) {
76
+ printError(err.message);
77
+ process.exit(1);
78
+ }
79
+ }
80
+ /** Write files */
81
+ export function writeFiles(result, config) {
82
+ for (const { filename, contents } of result.outputFiles) {
83
+ const output = new URL(filename, config.outDir);
84
+ fs.mkdirSync(new URL('.', output), { recursive: true });
85
+ fs.writeFileSync(output, contents);
86
+ }
87
+ }
88
+ //# sourceMappingURL=build.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"build.js","sourceRoot":"","sources":["../src/build.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,SAAS,CAAC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C,MAAM,CAAC,4BAA4B,CAAC,EAAE;iBAC/G,CAAC,CAAC;YACL,CAAC,CAAC,CAAC;YAEH,wBAAwB;YACxB,MAAM,IAAI,OAAO,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;QAC9B,CAAC;aAAM,CAAC;YACN,YAAY,CACV,GAAG,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM,SAAS,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,QAAQ,EACzF,SAAS,CACV,CAAC;QACJ,CAAC;IACH,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,UAAU,CAAE,GAAa,CAAC,OAAO,CAAC,CAAC;QACnC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;AACH,CAAC;AAED,kBAAkB;AAClB,MAAM,UAAU,UAAU,CAAC,MAAyB,EAAE,MAAkB;IACtE,KAAK,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,MAAM,CAAC,WAAW,EAAE,CAAC;QACxD,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,QAAQ,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;QAChD,EAAE,CAAC,SAAS,CAAC,IAAI,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QACxD,EAAE,CAAC,aAAa,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;IACrC,CAAC;AACH,CAAC"}
@@ -0,0 +1,9 @@
1
+ import { type ConfigInit, type Logger } from '@terrazzo/parser';
2
+ export interface CheckOptions {
3
+ /** positional CLI args */
4
+ positionals: string[];
5
+ config: ConfigInit;
6
+ logger: Logger;
7
+ }
8
+ /** tz check */
9
+ export declare function checkCmd({ config, logger, positionals }: CheckOptions): Promise<void>;
package/dist/check.js ADDED
@@ -0,0 +1,24 @@
1
+ import { parse } from '@terrazzo/parser';
2
+ import yamlToMomoa from 'yaml-to-momoa';
3
+ import { loadTokens, printError, printSuccess, resolveTokenPath } from './shared.js';
4
+ /** tz check */
5
+ export async function checkCmd({ config, logger, positionals }) {
6
+ try {
7
+ const startTime = performance.now();
8
+ const tokenPaths = positionals.slice(1).length
9
+ ? positionals.slice(1).map((tokenPath) => resolveTokenPath(tokenPath, { logger }))
10
+ : config.tokens;
11
+ const sources = await loadTokens(tokenPaths, { logger });
12
+ if (!sources?.length) {
13
+ logger.error({ message: 'Couldn’t find any tokens. Run `npx tz init` to create some.' });
14
+ return;
15
+ }
16
+ await parse(sources, { config, continueOnError: true, logger, yamlToMomoa }); // will throw if errors
17
+ printSuccess('No errors', startTime);
18
+ }
19
+ catch (err) {
20
+ printError(err.message);
21
+ process.exit(1);
22
+ }
23
+ }
24
+ //# sourceMappingURL=check.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"check.js","sourceRoot":"","sources":["../src/check.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgC,KAAK,EAAE,MAAM,kBAAkB,CAAC;AACvE,OAAO,WAAW,MAAM,eAAe,CAAC;AACxC,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AASrF,eAAe;AACf,MAAM,CAAC,KAAK,UAAU,QAAQ,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,EAAgB;IAC1E,IAAI,CAAC;QACH,MAAM,SAAS,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC;QACpC,MAAM,UAAU,GAAG,WAAW,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM;YAC5C,CAAC,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,gBAAgB,CAAC,SAAS,EAAE,EAAE,MAAM,EAAE,CAAC,CAAC;YAClF,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC;QAClB,MAAM,OAAO,GAAG,MAAM,UAAU,CAAC,UAAU,EAAE,EAAE,MAAM,EAAE,CAAC,CAAC;QACzD,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,CAAC;YACrB,MAAM,CAAC,KAAK,CAAC,EAAE,OAAO,EAAE,6DAA6D,EAAE,CAAC,CAAC;YACzF,OAAO;QACT,CAAC;QACD,MAAM,KAAK,CAAC,OAAO,EAAE,EAAE,MAAM,EAAE,eAAe,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,CAAC,CAAC,CAAC,uBAAuB;QACrG,YAAY,CAAC,WAAW,EAAE,SAAS,CAAC,CAAC;IACvC,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,UAAU,CAAE,GAAa,CAAC,OAAO,CAAC,CAAC;QACnC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;AACH,CAAC"}
package/dist/help.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ /** Show help */
2
+ export declare function helpCmd(): void;
package/dist/help.js ADDED
@@ -0,0 +1,18 @@
1
+ /** Show help */
2
+ export function helpCmd() {
3
+ console.log(`tz
4
+ [commands]
5
+ build Build token artifacts from tokens.json
6
+ --watch, -w Watch tokens.json for changes and recompile
7
+ --no-lint Disable linters running on build
8
+ check [path] Check tokens.json for errors and run linters
9
+ lint [path] (alias of check)
10
+ init Create a starter tokens.json file
11
+
12
+ [options]
13
+ --help Show this message
14
+ --config, -c Path to config (default: ./terrazzo.config.js)
15
+ --quiet Suppress warnings
16
+ `);
17
+ }
18
+ //# sourceMappingURL=help.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"help.js","sourceRoot":"","sources":["../src/help.ts"],"names":[],"mappings":"AAAA,gBAAgB;AAChB,MAAM,UAAU,OAAO;IACrB,OAAO,CAAC,GAAG,CAAC;;;;;;;;;;;;;CAab,CAAC,CAAC;AACH,CAAC"}
package/dist/index.d.ts CHANGED
@@ -1,2 +1,3 @@
1
1
  import { type Config, type ConfigInit } from '@terrazzo/parser';
2
+ export type { Command, Flags } from './shared.js';
2
3
  export declare function defineConfig(config: Config): ConfigInit;
package/dist/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { defineConfig as defineConfigCore } from '@terrazzo/parser';
2
+ import { cwd } from './shared.js';
2
3
  export function defineConfig(config) {
3
- return defineConfigCore(config, { cwd: new URL(`file://${process.cwd()}/`) });
4
+ return defineConfigCore(config, { cwd });
4
5
  }
5
6
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgC,YAAY,IAAI,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAElG,MAAM,UAAU,YAAY,CAAC,MAAc;IACzC,OAAO,gBAAgB,CAAC,MAAM,EAAE,EAAE,GAAG,EAAE,IAAI,GAAG,CAAC,UAAU,OAAO,CAAC,GAAG,EAAE,GAAG,CAAC,EAAE,CAAC,CAAC;AAChF,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgC,YAAY,IAAI,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAClG,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAIlC,MAAM,UAAU,YAAY,CAAC,MAAc;IACzC,OAAO,gBAAgB,CAAC,MAAM,EAAE,EAAE,GAAG,EAAE,CAAC,CAAC;AAC3C,CAAC"}
package/dist/init.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ import type { Logger } from '@terrazzo/parser';
2
+ export interface InitOptions {
3
+ logger: Logger;
4
+ }
5
+ export declare function initCmd({ logger }: InitOptions): Promise<void>;
package/dist/init.js ADDED
@@ -0,0 +1,212 @@
1
+ import { execSync } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { confirm, intro, multiselect, outro, select, spinner } from '@clack/prompts';
6
+ import { pluralize } from '@terrazzo/token-tools';
7
+ import { detect } from 'detect-package-manager';
8
+ import { generate } from 'escodegen';
9
+ import { parseModule } from 'meriyah';
10
+ import { DEFAULT_CONFIG_PATH, DEFAULT_TOKENS_PATH, cwd, loadConfig, printError } from './shared.js';
11
+ const INSTALL_COMMAND = {
12
+ npm: 'install -D --silent',
13
+ yarn: 'add -D --silent',
14
+ pnpm: 'add -D --silent',
15
+ bun: 'install -D --silent',
16
+ };
17
+ const DTCG_ROOT_URL = 'https://raw.githubusercontent.com/terrazzoapp/dtcg-examples/refs/heads/main/';
18
+ const DESIGN_SYSTEMS = {
19
+ 'adobe-spectrum': {
20
+ name: 'Spectrum',
21
+ author: 'Adobe',
22
+ tokens: ['adobe-spectrum.json'],
23
+ },
24
+ 'apple-hig': {
25
+ name: 'Human Interface Guidelines',
26
+ author: 'Apple',
27
+ tokens: ['apple-hig.json'],
28
+ },
29
+ 'figma-sds': {
30
+ name: 'Simple Design System',
31
+ author: 'Figma',
32
+ tokens: ['figma-sds.json'],
33
+ },
34
+ 'github-primer': {
35
+ name: 'Primer',
36
+ author: 'GitHub',
37
+ tokens: ['github-primer.json'],
38
+ },
39
+ 'ibm-carbon': {
40
+ name: 'Carbon',
41
+ author: 'IBM',
42
+ tokens: ['ibm-carbon.json'],
43
+ },
44
+ radix: {
45
+ name: 'Radix',
46
+ author: 'Radix',
47
+ tokens: ['radix.json'],
48
+ },
49
+ 'salesforce-lightning': {
50
+ name: 'Lightning',
51
+ author: 'Salesforce',
52
+ tokens: ['salesforce-lightning.json'],
53
+ },
54
+ 'shopify-polaris': {
55
+ name: 'Polaris',
56
+ author: 'Shopify',
57
+ tokens: ['shopify-polaris.json'],
58
+ },
59
+ };
60
+ export async function initCmd({ logger }) {
61
+ try {
62
+ intro('⛋ Welcome to Terrazzo');
63
+ const packageManager = await detect({ cwd: fileURLToPath(cwd) });
64
+ // TODO: pass in CLI flags?
65
+ const { config, configPath } = await loadConfig({ cmd: 'init', flags: {}, logger });
66
+ const relConfigPath = configPath
67
+ ? path.relative(fileURLToPath(cwd), fileURLToPath(new URL(configPath)))
68
+ : undefined;
69
+ let tokensPath = config.tokens[0];
70
+ let startFromDS = !(tokensPath && fs.existsSync(tokensPath));
71
+ // 1. tokens
72
+ if (tokensPath && fs.existsSync(tokensPath)) {
73
+ if (await confirm({
74
+ message: `Found tokens at ${path.relative(fileURLToPath(cwd), fileURLToPath(tokensPath))}. Overwrite with a new design system?`,
75
+ })) {
76
+ startFromDS = true;
77
+ }
78
+ }
79
+ else {
80
+ tokensPath = DEFAULT_TOKENS_PATH;
81
+ }
82
+ if (startFromDS) {
83
+ const ds = DESIGN_SYSTEMS[(await select({
84
+ message: 'Start from existing design system?',
85
+ options: [
86
+ ...Object.entries(DESIGN_SYSTEMS).map(([id, { author, name }]) => ({
87
+ value: id,
88
+ label: `${author} ${name}`,
89
+ })),
90
+ { value: 'none', label: 'None' },
91
+ ],
92
+ }))];
93
+ if (ds) {
94
+ // TODO: support multiple tokens files?
95
+ const s = spinner();
96
+ s.start('Downloading…');
97
+ const tokenSource = await fetch(new URL(ds.tokens[0], DTCG_ROOT_URL)).then((res) => res.text());
98
+ fs.writeFileSync(tokensPath, tokenSource);
99
+ s.stop('Download complete');
100
+ }
101
+ }
102
+ // 2. plugins
103
+ const existingPlugins = config.plugins.map((p) => p.name);
104
+ const pluginSelection = await multiselect({
105
+ message: 'Install plugins?',
106
+ options: [
107
+ { value: '@terrazzo/plugin-css', label: 'CSS' },
108
+ { value: '@terrazzo/plugin-js', label: 'JS + TS' },
109
+ { value: '@terrazzo/plugin-sass', label: 'Sass' },
110
+ { value: '@terrazzo/plugin-tailwind', label: 'Tailwind' },
111
+ ],
112
+ required: false,
113
+ });
114
+ const newPlugins = Array.isArray(pluginSelection)
115
+ ? pluginSelection.filter((p) => !existingPlugins.includes(p))
116
+ : [];
117
+ if (newPlugins?.length) {
118
+ const plugins = newPlugins.map((p) => ({ specifier: p.replace('@terrazzo/plugin-', ''), package: p }));
119
+ const pluginCount = `${newPlugins.length} ${pluralize(newPlugins.length, 'plugin', 'plugins')}`;
120
+ const s = spinner();
121
+ s.start(`Installing ${pluginCount}…`);
122
+ execSync([packageManager, INSTALL_COMMAND[packageManager], newPlugins.join(' ')].join(' '), {
123
+ cwd,
124
+ stdio: 'inherit',
125
+ });
126
+ s.message('Updating config');
127
+ if (configPath) {
128
+ const ast = parseModule(fs.readFileSync(configPath, 'utf8'));
129
+ const astExport = ast.body.find((node) => node.type === 'ExportDefaultDeclaration');
130
+ // 2a. add plugin imports
131
+ // note: this has the potential to duplicate plugins, but we tried our
132
+ // best to filter already, and this may be the user’s fault if they
133
+ // selected to install a plugin already installed. But also, this is
134
+ // easily-fixable, so let’s not waste too much time here (and possibly
135
+ // introduce bugs).
136
+ ast.body.push(...plugins.map((p) => ({
137
+ type: 'ImportDeclaration',
138
+ source: { type: 'Literal', value: p.package },
139
+ specifiers: [{ type: 'ImportDefaultSpecifier', local: { type: 'Identifier', name: p.specifier } }],
140
+ attributes: [],
141
+ })));
142
+ // 2b. add plugins to config.plugins
143
+ if (!astExport) {
144
+ logger.error({ message: `SyntaxError: ${relConfigPath} does not have default export.` });
145
+ return;
146
+ }
147
+ const astConfig = (astExport.declaration.type === 'CallExpression'
148
+ ? // export default defineConfig({ ... })
149
+ astExport.declaration.arguments[0]
150
+ : // export default { ... }
151
+ astExport.declaration);
152
+ if (astConfig.type !== 'ObjectExpression') {
153
+ logger.error({ message: `Config: expected object default export, received ${astConfig.type}` });
154
+ return;
155
+ }
156
+ const pluginsArray = astConfig.properties.find((property) => property.type === 'Property' && property.key.type === 'Identifier' && property.key.name === 'plugins')?.value;
157
+ const pluginsAst = plugins.map((p) => ({
158
+ type: 'CallExpression',
159
+ callee: {
160
+ type: 'Identifier',
161
+ name: p.specifier,
162
+ },
163
+ arguments: [],
164
+ }));
165
+ if (pluginsArray) {
166
+ pluginsArray.elements.push(...pluginsAst);
167
+ }
168
+ else {
169
+ astConfig.properties.push({
170
+ type: 'Property',
171
+ key: { type: 'Identifier', name: 'plugins' },
172
+ value: { type: 'ArrayExpression', elements: pluginsAst },
173
+ kind: 'init',
174
+ computed: false,
175
+ method: false,
176
+ shorthand: false,
177
+ });
178
+ }
179
+ // 2c. update new file (and we’ll probably format it wrong but hey)
180
+ fs.writeFileSync(configPath, generate(ast, {
181
+ format: {
182
+ indent: { style: ' ' },
183
+ quotes: 'single',
184
+ semicolons: true,
185
+ },
186
+ }));
187
+ }
188
+ else {
189
+ // 2a. write new config file (easy)
190
+ fs.writeFileSync(DEFAULT_CONFIG_PATH, `import { defineConfig } from '@terrazzo/cli';
191
+ ${plugins.map((p) => `import ${p.specifier} from '${p.package}';`).join('\n')}
192
+ export default defineConfig({
193
+ tokens: ['./tokens.json'],
194
+ plugins: [
195
+ ${plugins.map((p) => `${p.specifier}(),`).join('\n ')}
196
+ ],
197
+ outdir: './dist/',
198
+ lint: {
199
+ /** @see https://terrazzo.app/docs/cli/lint */
200
+ },
201
+ });`);
202
+ }
203
+ s.stop(`Installed ${pluginCount}`);
204
+ }
205
+ outro('⛋ Done! 🎉');
206
+ }
207
+ catch (err) {
208
+ printError(err.message);
209
+ process.exit(1);
210
+ }
211
+ }
212
+ //# sourceMappingURL=init.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"init.js","sourceRoot":"","sources":["../src/init.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAC9C,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,WAAW,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAErF,OAAO,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;wBACvB,MAAM,EAAE,QAAQ;wBAChB,UAAU,EAAE,IAAI;qBACjB;iBACF,CAAC,CACH,CAAC;YACJ,CAAC;iBAAM,CAAC;gBACN,mCAAmC;gBACnC,EAAE,CAAC,aAAa,CACd,mBAAmB,EACnB;EACR,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,UAAU,CAAC,CAAC,SAAS,UAAU,CAAC,CAAC,OAAO,IAAI,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC;;;;MAIvE,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,SAAS,KAAK,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC;;;;;;IAMxD,CACK,CAAC;YACJ,CAAC;YACD,CAAC,CAAC,IAAI,CAAC,aAAa,WAAW,EAAE,CAAC,CAAC;QACrC,CAAC;QAED,KAAK,CAAC,YAAY,CAAC,CAAC;IACtB,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,UAAU,CAAE,GAAa,CAAC,OAAO,CAAC,CAAC;QACnC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;AACH,CAAC"}
@@ -0,0 +1,47 @@
1
+ import { type ConfigInit, type Logger } from '@terrazzo/parser';
2
+ export declare const cwd: URL;
3
+ export declare const DEFAULT_CONFIG_PATH: URL;
4
+ export declare const DEFAULT_TOKENS_PATH: URL;
5
+ export type Command = 'build' | 'check' | 'help' | 'init' | 'version';
6
+ export declare const GREEN_CHECK: string;
7
+ export interface Flags {
8
+ /** --config, -c */
9
+ config?: string;
10
+ /** --out, -o */
11
+ out?: string;
12
+ /** --help */
13
+ help?: boolean;
14
+ /** --watch, -w */
15
+ watch?: boolean;
16
+ /** --version */
17
+ version?: boolean;
18
+ }
19
+ export interface LoadConfigOptions {
20
+ cmd: Command;
21
+ flags: Flags;
22
+ logger: Logger;
23
+ }
24
+ /** Load config */
25
+ export declare function loadConfig({ cmd, flags, logger }: LoadConfigOptions): Promise<{
26
+ config: ConfigInit;
27
+ configPath: string;
28
+ }>;
29
+ /** load tokens */
30
+ export declare function loadTokens(tokenPaths: URL[], { logger }: {
31
+ logger: Logger;
32
+ }): Promise<{
33
+ filename: URL;
34
+ src: string;
35
+ }[] | undefined>;
36
+ /** Print error */
37
+ export declare function printError(message: string): void;
38
+ /** Print success */
39
+ export declare function printSuccess(message: string, startTime?: number): void;
40
+ /** Resolve config */
41
+ export declare function resolveConfig(filename?: string): string | undefined;
42
+ /** Resolve tokens.json path (for lint command) */
43
+ export declare function resolveTokenPath(filename: string, { logger }: {
44
+ logger: Logger;
45
+ }): URL;
46
+ /** Print time elapsed */
47
+ export declare function time(start: number): string;
package/dist/shared.js ADDED
@@ -0,0 +1,184 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { defineConfig } from '@terrazzo/parser';
4
+ import pc from 'picocolors';
5
+ export const cwd = new URL(`file://${process.cwd()}/`);
6
+ export const DEFAULT_CONFIG_PATH = new URL('./terrazzo.config.mjs', cwd);
7
+ export const DEFAULT_TOKENS_PATH = new URL('./tokens.json', cwd);
8
+ export const GREEN_CHECK = pc.green('✔');
9
+ /** Load config */
10
+ export async function loadConfig({ cmd, flags, logger }) {
11
+ try {
12
+ let config = {
13
+ tokens: [DEFAULT_TOKENS_PATH],
14
+ outDir: new URL('./tokens/', cwd),
15
+ plugins: [],
16
+ lint: { build: { enabled: true }, rules: {} },
17
+ ignore: { tokens: [], deprecated: false },
18
+ };
19
+ let configPath;
20
+ if (typeof flags.config === 'string') {
21
+ if (flags.config === '') {
22
+ logger.error({ message: 'Missing path after --config flag' });
23
+ process.exit(1);
24
+ }
25
+ configPath = resolveConfig(flags.config);
26
+ }
27
+ const resolvedConfigPath = resolveConfig(configPath);
28
+ if (resolvedConfigPath) {
29
+ try {
30
+ const mod = await import(resolvedConfigPath);
31
+ if (!mod.default) {
32
+ logger.error({
33
+ message: `No default export found in ${path.relative(cwd.href, resolvedConfigPath)}. See https://terrazzo.dev/docs/cli for instructions.`,
34
+ });
35
+ }
36
+ config = defineConfig(mod.default, { cwd, logger });
37
+ }
38
+ catch (err) {
39
+ logger.error({ message: err.message || err });
40
+ }
41
+ }
42
+ else if (cmd !== 'init' && cmd !== 'check') {
43
+ logger.error({ message: 'No config file found. Create one with `npx terrazzo init`.' });
44
+ }
45
+ return { config, configPath: resolvedConfigPath };
46
+ }
47
+ catch (err) {
48
+ printError(err.message);
49
+ process.exit(1);
50
+ }
51
+ }
52
+ /** load tokens */
53
+ export async function loadTokens(tokenPaths, { logger }) {
54
+ try {
55
+ const allTokens = [];
56
+ if (!Array.isArray(tokenPaths)) {
57
+ logger.error({ message: `loadTokens: Expected array, received ${typeof tokenPaths}` });
58
+ }
59
+ // if this is the default value, also check for tokens.yaml
60
+ if (tokenPaths.length === 1 && tokenPaths[0].href === DEFAULT_TOKENS_PATH.href) {
61
+ if (!fs.existsSync(tokenPaths[0])) {
62
+ const yamlPath = new URL('./tokens.yaml', cwd);
63
+ if (fs.existsSync(yamlPath)) {
64
+ tokenPaths[0] = yamlPath;
65
+ }
66
+ else {
67
+ logger.error({
68
+ message: `Could not locate ${path.relative(cwd.href, tokenPaths[0].href)}. To create one, run \`npx tz init\`.`,
69
+ });
70
+ return;
71
+ }
72
+ }
73
+ }
74
+ // download/read
75
+ for (let i = 0; i < tokenPaths.length; i++) {
76
+ const filename = tokenPaths[i];
77
+ if (!(filename instanceof URL)) {
78
+ logger.error({ message: `Expected URL, received ${filename}`, label: `loadTokens[${i}]` });
79
+ return;
80
+ }
81
+ else if (filename.protocol === 'http:' || filename.protocol === 'https:') {
82
+ try {
83
+ // if Figma URL
84
+ if (filename.host === 'figma.com' || filename.host === 'www.figma.com') {
85
+ const [_, fileKeyword, fileKey] = filename.pathname.split('/');
86
+ if (fileKeyword !== 'file' || !fileKey) {
87
+ logger.error({
88
+ message: `Unexpected Figma URL. Expected "https://www.figma.com/file/:file_key/:file_name?…", received "${filename.href}"`,
89
+ });
90
+ }
91
+ const headers = new Headers({
92
+ Accept: '*/*',
93
+ 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:123.0) Gecko/20100101 Firefox/123.0',
94
+ });
95
+ if (process.env.FIGMA_ACCESS_TOKEN) {
96
+ headers.set('X-FIGMA-TOKEN', process.env.FIGMA_ACCESS_TOKEN);
97
+ }
98
+ else {
99
+ logger.warn({ message: 'FIGMA_ACCESS_TOKEN not set' });
100
+ }
101
+ const res = await fetch(`https://api.figma.com/v1/files/${fileKey}/variables/local`, {
102
+ method: 'GET',
103
+ headers,
104
+ });
105
+ if (res.ok) {
106
+ allTokens.push({ filename, src: await res.text() });
107
+ }
108
+ const message = res.status !== 404 ? JSON.stringify(await res.json(), undefined, 2) : '';
109
+ logger.error({ message: `Figma responded with ${res.status}${message ? `:\n${message}` : ''}` });
110
+ break;
111
+ }
112
+ // otherwise, expect YAML/JSON
113
+ const res = await fetch(filename, {
114
+ method: 'GET',
115
+ headers: { Accept: '*/*', 'User-Agent': 'Mozilla/5.0 Gecko/20100101 Firefox/123.0' },
116
+ });
117
+ allTokens.push({ filename, src: await res.text() });
118
+ }
119
+ catch (err) {
120
+ logger.error({ message: `${filename.href}: ${err}` });
121
+ return;
122
+ }
123
+ }
124
+ else {
125
+ if (fs.existsSync(filename)) {
126
+ allTokens.push({ filename, src: fs.readFileSync(filename, 'utf8') });
127
+ }
128
+ else {
129
+ logger.error({
130
+ message: `Could not locate ${path.relative(cwd.href, filename.href)}. To create one, run \`npx tz init\`.`,
131
+ });
132
+ return;
133
+ }
134
+ }
135
+ }
136
+ return allTokens;
137
+ }
138
+ catch (err) {
139
+ printError(err.message);
140
+ process.exit(1);
141
+ }
142
+ }
143
+ /** Print error */
144
+ export function printError(message) {
145
+ console.error(pc.red(`✗ ${message}`));
146
+ }
147
+ /** Print success */
148
+ export function printSuccess(message, startTime) {
149
+ console.log(`${GREEN_CHECK} ${message}${startTime ? ` ${time(startTime)}` : ''}`);
150
+ }
151
+ /** Resolve config */
152
+ export function resolveConfig(filename) {
153
+ // --config [configpath]
154
+ if (filename) {
155
+ const configPath = new URL(filename, cwd);
156
+ if (fs.existsSync(configPath)) {
157
+ return configPath.href; // ⚠️ ESM wants "file://..." URLs on Windows & Unix.
158
+ }
159
+ return undefined;
160
+ }
161
+ // note: the order isn’t significant; just try for most-common first.
162
+ // if a user has multiple files differing only by file extension, behavior is
163
+ // unpredictable and that’s on them.
164
+ return ['.js', '.mjs', '.cjs']
165
+ .map((ext) => new URL(`./terrazzo.config${ext}`, cwd))
166
+ .find((configPath) => fs.existsSync(configPath))?.href; // ⚠️ ESM wants "file://..." URLs on Windows & Unix.;
167
+ }
168
+ /** Resolve tokens.json path (for lint command) */
169
+ export function resolveTokenPath(filename, { logger }) {
170
+ const tokensPath = new URL(filename, cwd);
171
+ if (!fs.existsSync(tokensPath)) {
172
+ logger.error({ message: `Could not locate ${filename}. Does the file exist?` });
173
+ }
174
+ else if (!fs.statSync(tokensPath).isFile()) {
175
+ logger.error({ message: `Expected JSON or YAML file, received ${filename}.` });
176
+ }
177
+ return tokensPath;
178
+ }
179
+ /** Print time elapsed */
180
+ export function time(start) {
181
+ const diff = performance.now() - start;
182
+ return pc.dim(diff < 750 ? `${Math.round(diff)}ms` : `${(diff / 1000).toFixed(1)}s`);
183
+ }
184
+ //# sourceMappingURL=shared.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shared.js","sourceRoot":"","sources":["../src/shared.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAgC,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAC9E,OAAO,EAAE,MAAM,YAAY,CAAC;AAE5B,MAAM,CAAC,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,UAAU,OAAO,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;AACvD,MAAM,CAAC,MAAM,m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K,CAAC,EAAE,OAAO,EAAE,oBAAoB,QAAQ,wBAAwB,EAAE,CAAC,CAAC;IAClF,CAAC;SAAM,IAAI,CAAC,EAAE,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC;QAC7C,MAAM,CAAC,KAAK,CAAC,EAAE,OAAO,EAAE,wCAAwC,QAAQ,GAAG,EAAE,CAAC,CAAC;IACjF,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC;AAED,yBAAyB;AACzB,MAAM,UAAU,IAAI,CAAC,KAAa;IAChC,MAAM,IAAI,GAAG,WAAW,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC;IACvC,OAAO,EAAE,CAAC,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,GAAG,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;AACvF,CAAC"}
@@ -0,0 +1 @@
1
+ export declare function versionCmd(): void;
@@ -0,0 +1,6 @@
1
+ import fs from 'node:fs';
2
+ export function versionCmd() {
3
+ const { version } = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
4
+ console.log(version);
5
+ }
6
+ //# sourceMappingURL=version.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"version.js","sourceRoot":"","sources":["../src/version.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,SAAS,CAAC;AAEzB,MAAM,UAAU,UAAU;IACxB,MAAM,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,YAAY,CAAC,IAAI,GAAG,CAAC,iBAAiB,EAAE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACrG,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;AACvB,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@terrazzo/cli",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "CLI for managing design tokens using the Design Tokens Community Group (DTCG) standard and generating code for any platform via plugins.",
5
5
  "type": "module",
6
6
  "author": {
@@ -40,16 +40,18 @@
40
40
  "terrazzo": "bin/cli.js"
41
41
  },
42
42
  "dependencies": {
43
+ "@clack/prompts": "^0.8.2",
44
+ "@types/escodegen": "^0.0.10",
43
45
  "chokidar": "^3.6.0",
46
+ "detect-package-manager": "^3.0.2",
44
47
  "dotenv": "^16.4.5",
48
+ "escodegen": "^2.1.0",
45
49
  "merge-anything": "^5.1.7",
50
+ "meriyah": "^6.0.3",
46
51
  "picocolors": "^1.1.1",
47
52
  "yaml-to-momoa": "^0.0.3",
48
- "@terrazzo/parser": "^0.2.0",
49
- "@terrazzo/token-tools": "^0.2.0"
50
- },
51
- "devDependencies": {
52
- "typescript": "^5.7.2"
53
+ "@terrazzo/parser": "^0.2.2",
54
+ "@terrazzo/token-tools": "^0.2.2"
53
55
  },
54
56
  "scripts": {
55
57
  "build": "tsc -p tsconfig.build.json",