@terrazzo/plugin-js 2.0.3 → 2.1.0

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 CHANGED
@@ -1,5 +1,12 @@
1
1
  # @terrazzo/plugin-js
2
2
 
3
+ ## 2.1.0
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [[`2845b02`](https://github.com/terrazzoapp/terrazzo/commit/2845b02718db1ddbf5e17efdc53ff16109b63d28), [`de25711`](https://github.com/terrazzoapp/terrazzo/commit/de25711f65c10c58776f7b71c5621f6228387f79), [`6261145`](https://github.com/terrazzoapp/terrazzo/commit/62611450071c4c1e09a1ffd78998cbfdc36605ba)]:
8
+ - @terrazzo/cli@2.1.0
9
+
3
10
  ## 2.0.3
4
11
 
5
12
  ### Patch Changes
package/dist/index.js CHANGED
@@ -1,6 +1,5 @@
1
1
  import { calculatePermutations } from "@terrazzo/parser";
2
2
  import { pascalCase } from "scule";
3
-
4
3
  //#region src/lib.ts
5
4
  const DEFAULT_PROPERTIES = new Set([
6
5
  "$type",
@@ -30,7 +29,6 @@ const TYPE_MAP = {
30
29
  typography: "TypographyTokenNormalized",
31
30
  transition: "TransitionTokenNormalized"
32
31
  };
33
-
34
32
  //#endregion
35
33
  //#region src/build.ts
36
34
  const RESOLVER_JSDOC_COMMENT = "/** Produce a token set from a given input. */";
@@ -144,7 +142,6 @@ function localTypeName($type) {
144
142
  function serializeToken(token, includeProperties) {
145
143
  return `${JSON.stringify(token.id)}:${JSON.stringify(Object.fromEntries(Object.entries(token).filter(([k]) => includeProperties.has(k))))}`;
146
144
  }
147
-
148
145
  //#endregion
149
146
  //#region src/index.ts
150
147
  function pluginJS({ filename = "index.js", properties: userProperties, contexts } = {}) {
@@ -179,7 +176,7 @@ function pluginJS({ filename = "index.js", properties: userProperties, contexts
179
176
  }
180
177
  };
181
178
  }
182
-
183
179
  //#endregion
184
180
  export { DEFAULT_PROPERTIES, FILE_HEADER, TYPE_MAP, buildDTS, buildJS, pluginJS as default };
181
+
185
182
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/lib.ts","../src/build.ts","../src/index.ts"],"sourcesContent":["import type { Token, TokenNormalized, TokenNormalizedSet } from '@terrazzo/parser';\n\nexport const DEFAULT_PROPERTIES: Set<keyof TokenNormalized> = new Set([\n '$type',\n '$value',\n '$description',\n '$extensions',\n '$deprecated',\n // 'id',\n // 'jsonID',\n // 'aliasOf',\n // 'aliasChain',\n // 'aliasedBy',\n // 'dependencies',\n // 'group',\n]);\n\nexport interface JSPluginOptions<T extends Record<string, string> = Record<string, string>> {\n /**\n * Change the output filename\n * @default \"index.js\"\n */\n filename?: string;\n /** Only generate permutations for the specified modifiers (by default, generate all permutations) */\n contexts?: { [key in keyof T]: T[keyof T][] };\n /** Only include specified properties as part of token output. */\n properties?: (keyof TokenNormalized)[];\n}\n\nexport type Resolver<T extends Record<string, string>> = (input: T) => TokenNormalizedSet;\n\nexport const FILE_HEADER = `/** ------------------------------------------\n * Autogenerated by ⛋ Terrazzo. DO NOT EDIT!\n * ------------------------------------------- */`;\n\nexport const TYPE_MAP: Record<Token['$type'], string> = {\n boolean: 'BooleanTokenNormalized',\n border: 'BorderTokenNormalized',\n color: 'ColorTokenNormalized',\n cubicBezier: 'CubicBezierTokenNormalized',\n dimension: 'DimensionTokenNormalized',\n duration: 'DurationTokenNormalized',\n fontFamily: 'FontFamilyTokenNormalized',\n fontWeight: 'FontWeightTokenNormalized',\n gradient: 'GradientTokenNormalized',\n link: 'LinkTokenNormalized',\n number: 'NumberTokenNormalized',\n shadow: 'ShadowTokenNormalized',\n string: 'StringTokenNormalized',\n strokeStyle: 'StrokeStyleTokenNormalized',\n typography: 'TypographyTokenNormalized',\n transition: 'TransitionTokenNormalized',\n};\n","import {\n calculatePermutations,\n type Logger,\n type Resolver,\n type ResolverModifierNormalized,\n type Token,\n type TokenNormalized,\n} from '@terrazzo/parser';\nimport { pascalCase } from 'scule';\nimport { FILE_HEADER, TYPE_MAP } from './lib.js';\n\nconst RESOLVER_JSDOC_COMMENT = '/** Produce a token set from a given input. */';\n\nexport function buildJS({\n resolver,\n properties,\n logger,\n contexts,\n}: {\n resolver: Resolver;\n properties: Set<keyof TokenNormalized>;\n contexts?: Record<string, string[]>;\n logger: Logger;\n}): { code: string; typeMap: Record<string, Token['$type']> } {\n const entry = { group: 'plugin' as const, label: '@terrazzo/plugin-js' };\n const typeMap: Record<string, Token['$type']> = {};\n\n // here, output not being an array drastically reduces memory usage for large token sets\n let output = FILE_HEADER;\n output += '\\n';\n\n // 1. Permutations\n const permutations = (contexts ? calculatePermutations(Object.entries(contexts)) : resolver.listPermutations()).map(\n (value) => ({\n value,\n // Note: id MUST have modifiers sorted alphabetically, so we can index them shallowly\n id: JSON.stringify(\n Object.fromEntries(Object.entries(value).sort((a, b) => a[0].localeCompare(b[0], 'en-us', { numeric: true }))),\n ),\n }),\n );\n output += 'export const PERMUTATIONS = {\\n';\n let permutationI = 1;\n for (const { value, id } of permutations) {\n const start = performance.now();\n try {\n const tokens = resolver.apply(value);\n output += ` ${JSON.stringify(id)}: {\\n`;\n for (const id of Object.keys(tokens)) {\n output += ` ${serializeToken(tokens[id]!, properties)},\\n`;\n if (!(id in typeMap)) {\n typeMap[id] = tokens[id]!.$type;\n }\n }\n output += ' },\\n';\n } catch (err) {\n logger.error({ ...entry, message: (err as Error).message });\n }\n const timing = performance.now() - start;\n logger.info({\n ...entry,\n message: `Permutation ${permutationI}/${permutations.length} done (${id})`,\n timing,\n });\n permutationI++;\n }\n output += '};\\n';\n\n // 2. Input defaults\n const inputDefaults = Object.fromEntries(\n resolver.source.resolutionOrder\n .filter((i) => i.type === 'modifier' && 'default' in i)\n .map((m) => [m.name, (m as ResolverModifierNormalized).default!]),\n );\n output += `const INPUT_DEFAULTS = ${JSON.stringify(inputDefaults)};\\n`;\n\n // 3. Resolver\n output += RESOLVER_JSDOC_COMMENT;\n output += '\\n';\n output += `export const resolver = {\n apply(userInput) {\n if (!userInput || typeof userInput !== \"object\") {\n throw new Error(\\`invalid input: \\${userInput}\\`);\n }\n const input = { ...INPUT_DEFAULTS, ...userInput };\n const inputKey = JSON.stringify(Object.fromEntries(Object.entries(input).sort((a, b) => a[0].localeCompare(b[0], \"en-us\", { numeric: true }))));\n return PERMUTATIONS[inputKey];\n },\n listPermutations() {\n return [${permutations.map((p) => p.id).join(', ')}];\n },\n};\\n`;\n\n return { code: output, typeMap };\n}\n\nexport function buildDTS({\n resolver,\n contexts,\n properties,\n typeMap,\n}: {\n resolver: Resolver;\n contexts?: Record<string, string[]>;\n properties: Set<keyof TokenNormalized>;\n typeMap: Record<string, Token['$type']>;\n}): string {\n const unique$type = new Set(Object.values(typeMap));\n\n let output = FILE_HEADER;\n output += '\\n';\n output += 'import type {\\n';\n for (const $type of unique$type) {\n if ($type in TYPE_MAP) {\n output += ` ${TYPE_MAP[$type]},\\n`;\n }\n }\n output += '} from \"@terrazzo/parser\";';\n output += '\\n\\n';\n output += 'export const PERMUTATIONS: Record<string, TokenNormalizedSet>;\\n\\n';\n output += `type InputType = ${buildInputType(resolver, contexts)}\\n\\n`;\n for (const $type of unique$type) {\n if (!($type in TYPE_MAP)) {\n continue;\n }\n output += `export type ${localTypeName($type)} = Pick<${TYPE_MAP[$type]}, ${[...properties].map((p) => JSON.stringify(p)).join(' | ')}>;\\n`;\n }\n output += '\\nexport interface Tokens {\\n';\n for (const [id, $type] of Object.entries(typeMap)) {\n output += ` ${JSON.stringify(id)}: ${$type in TYPE_MAP ? localTypeName($type) : 'any'};\\n`;\n }\n output += '}\\n';\n output += '\\n';\n output += RESOLVER_JSDOC_COMMENT;\n output += '\\n';\n output += `export const resolver: {\n apply(input: InputType): Tokens;\n listPermutations(): InputType[];\n};\n`;\n return output;\n}\n\n/** Generate TypeScript definition of valid inputs given a resolver */\nfunction buildInputType(resolver: Resolver, contexts?: Record<string, string[]>): string {\n const validContexts: Record<string, string[]> = contexts ?? {};\n if (!Object.keys(validContexts).length) {\n for (const [name, m] of Object.entries(resolver.source.modifiers ?? {})) {\n validContexts[name] = Object.keys(m.contexts);\n }\n for (const m of resolver.source.resolutionOrder) {\n if (m?.type !== 'modifier') {\n continue;\n }\n validContexts[m.name] = Object.keys(m.contexts);\n }\n }\n\n let output = '{';\n for (const [name, values] of Object.entries(validContexts)) {\n output += `\\n ${JSON.stringify(name)}: ${values.length ? values.map((v) => JSON.stringify(v)).join(' | ') : 'never'};`;\n }\n output += '\\n};';\n return output;\n}\n\nfunction localTypeName($type: Token['$type']): string {\n return pascalCase($type);\n}\n\n/** Serialize normalized Tokens set into a string */\nfunction serializeToken(token: TokenNormalized, includeProperties: Set<keyof TokenNormalized>): string {\n return `${JSON.stringify(token.id)}:${JSON.stringify(Object.fromEntries(Object.entries(token).filter(([k]) => includeProperties.has(k as keyof TokenNormalized))))}`;\n}\n","import type { Plugin } from '@terrazzo/parser';\nimport { buildDTS, buildJS } from './build.js';\nimport { DEFAULT_PROPERTIES, type JSPluginOptions } from './lib.js';\n\nexport * from './build.js';\nexport * from './lib.js';\n\nexport default function pluginJS({\n filename = 'index.js',\n properties: userProperties,\n contexts,\n}: JSPluginOptions = {}): Plugin {\n const entry = { group: 'plugin' as const, label: '@terrazzo/plugin-js' };\n\n return {\n name: '@terrazzo/plugin-js',\n config(_, context) {\n if (Array.isArray(userProperties) && !userProperties.length) {\n context.logger.error({ ...entry, message: 'properties option can’t be empty' });\n }\n },\n\n // As of 2.0, this plugin no longer pre-transforms values, because every instance\n // generates a unique output.\n async build({ resolver, outputFile, context }) {\n const properties = userProperties ? new Set(userProperties) : DEFAULT_PROPERTIES;\n const { code: js, typeMap } = buildJS({\n resolver,\n contexts,\n properties,\n logger: context.logger,\n });\n outputFile(filename, js);\n\n const dts = buildDTS({ resolver, contexts, properties, typeMap });\n const dtsFilename = typeof filename === 'string' ? filename.replace(/\\.(c|m)?js$/, '.d.$1ts') : 'index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C9D,MAAM,EAAE,MAAM,IAAI,YAAY,QAAQ;IACpC;IACA;IACA;IACA,QAAQ,QAAQ;IACjB,CAAC;AACF,cAAW,UAAU,GAAG;GAExB,MAAM,MAAM,SAAS;IAAE;IAAU;IAAU;IAAY;IAAS,CAAC;AAEjE,cADoB,OAAO,aAAa,WAAW,SAAS,QAAQ,eAAe,UAAU,GAAG,cACxE,IAAI;;EAE/B"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/lib.ts","../src/build.ts","../src/index.ts"],"sourcesContent":["import type { Token, TokenNormalized, TokenNormalizedSet } from '@terrazzo/parser';\n\nexport const DEFAULT_PROPERTIES: Set<keyof TokenNormalized> = new Set([\n '$type',\n '$value',\n '$description',\n '$extensions',\n '$deprecated',\n // 'id',\n // 'jsonID',\n // 'aliasOf',\n // 'aliasChain',\n // 'aliasedBy',\n // 'dependencies',\n // 'group',\n]);\n\nexport interface JSPluginOptions<T extends Record<string, string> = Record<string, string>> {\n /**\n * Change the output filename\n * @default \"index.js\"\n */\n filename?: string;\n /** Only generate permutations for the specified modifiers (by default, generate all permutations) */\n contexts?: { [key in keyof T]: T[keyof T][] };\n /** Only include specified properties as part of token output. */\n properties?: (keyof TokenNormalized)[];\n}\n\nexport type Resolver<T extends Record<string, string>> = (input: T) => TokenNormalizedSet;\n\nexport const FILE_HEADER = `/** ------------------------------------------\n * Autogenerated by ⛋ Terrazzo. DO NOT EDIT!\n * ------------------------------------------- */`;\n\nexport const TYPE_MAP: Record<Token['$type'], string> = {\n boolean: 'BooleanTokenNormalized',\n border: 'BorderTokenNormalized',\n color: 'ColorTokenNormalized',\n cubicBezier: 'CubicBezierTokenNormalized',\n dimension: 'DimensionTokenNormalized',\n duration: 'DurationTokenNormalized',\n fontFamily: 'FontFamilyTokenNormalized',\n fontWeight: 'FontWeightTokenNormalized',\n gradient: 'GradientTokenNormalized',\n link: 'LinkTokenNormalized',\n number: 'NumberTokenNormalized',\n shadow: 'ShadowTokenNormalized',\n string: 'StringTokenNormalized',\n strokeStyle: 'StrokeStyleTokenNormalized',\n typography: 'TypographyTokenNormalized',\n transition: 'TransitionTokenNormalized',\n};\n","import {\n calculatePermutations,\n type Logger,\n type Resolver,\n type ResolverModifierNormalized,\n type Token,\n type TokenNormalized,\n} from '@terrazzo/parser';\nimport { pascalCase } from 'scule';\nimport { FILE_HEADER, TYPE_MAP } from './lib.js';\n\nconst RESOLVER_JSDOC_COMMENT = '/** Produce a token set from a given input. */';\n\nexport function buildJS({\n resolver,\n properties,\n logger,\n contexts,\n}: {\n resolver: Resolver;\n properties: Set<keyof TokenNormalized>;\n contexts?: Record<string, string[]>;\n logger: Logger;\n}): { code: string; typeMap: Record<string, Token['$type']> } {\n const entry = { group: 'plugin' as const, label: '@terrazzo/plugin-js' };\n const typeMap: Record<string, Token['$type']> = {};\n\n // here, output not being an array drastically reduces memory usage for large token sets\n let output = FILE_HEADER;\n output += '\\n';\n\n // 1. Permutations\n const permutations = (contexts ? calculatePermutations(Object.entries(contexts)) : resolver.listPermutations()).map(\n (value) => ({\n value,\n // Note: id MUST have modifiers sorted alphabetically, so we can index them shallowly\n id: JSON.stringify(\n Object.fromEntries(Object.entries(value).sort((a, b) => a[0].localeCompare(b[0], 'en-us', { numeric: true }))),\n ),\n }),\n );\n output += 'export const PERMUTATIONS = {\\n';\n let permutationI = 1;\n for (const { value, id } of permutations) {\n const start = performance.now();\n try {\n const tokens = resolver.apply(value);\n output += ` ${JSON.stringify(id)}: {\\n`;\n for (const id of Object.keys(tokens)) {\n output += ` ${serializeToken(tokens[id]!, properties)},\\n`;\n if (!(id in typeMap)) {\n typeMap[id] = tokens[id]!.$type;\n }\n }\n output += ' },\\n';\n } catch (err) {\n logger.error({ ...entry, message: (err as Error).message });\n }\n const timing = performance.now() - start;\n logger.info({\n ...entry,\n message: `Permutation ${permutationI}/${permutations.length} done (${id})`,\n timing,\n });\n permutationI++;\n }\n output += '};\\n';\n\n // 2. Input defaults\n const inputDefaults = Object.fromEntries(\n resolver.source.resolutionOrder\n .filter((i) => i.type === 'modifier' && 'default' in i)\n .map((m) => [m.name, (m as ResolverModifierNormalized).default!]),\n );\n output += `const INPUT_DEFAULTS = ${JSON.stringify(inputDefaults)};\\n`;\n\n // 3. Resolver\n output += RESOLVER_JSDOC_COMMENT;\n output += '\\n';\n output += `export const resolver = {\n apply(userInput) {\n if (!userInput || typeof userInput !== \"object\") {\n throw new Error(\\`invalid input: \\${userInput}\\`);\n }\n const input = { ...INPUT_DEFAULTS, ...userInput };\n const inputKey = JSON.stringify(Object.fromEntries(Object.entries(input).sort((a, b) => a[0].localeCompare(b[0], \"en-us\", { numeric: true }))));\n return PERMUTATIONS[inputKey];\n },\n listPermutations() {\n return [${permutations.map((p) => p.id).join(', ')}];\n },\n};\\n`;\n\n return { code: output, typeMap };\n}\n\nexport function buildDTS({\n resolver,\n contexts,\n properties,\n typeMap,\n}: {\n resolver: Resolver;\n contexts?: Record<string, string[]>;\n properties: Set<keyof TokenNormalized>;\n typeMap: Record<string, Token['$type']>;\n}): string {\n const unique$type = new Set(Object.values(typeMap));\n\n let output = FILE_HEADER;\n output += '\\n';\n output += 'import type {\\n';\n for (const $type of unique$type) {\n if ($type in TYPE_MAP) {\n output += ` ${TYPE_MAP[$type]},\\n`;\n }\n }\n output += '} from \"@terrazzo/parser\";';\n output += '\\n\\n';\n output += 'export const PERMUTATIONS: Record<string, TokenNormalizedSet>;\\n\\n';\n output += `type InputType = ${buildInputType(resolver, contexts)}\\n\\n`;\n for (const $type of unique$type) {\n if (!($type in TYPE_MAP)) {\n continue;\n }\n output += `export type ${localTypeName($type)} = Pick<${TYPE_MAP[$type]}, ${[...properties].map((p) => JSON.stringify(p)).join(' | ')}>;\\n`;\n }\n output += '\\nexport interface Tokens {\\n';\n for (const [id, $type] of Object.entries(typeMap)) {\n output += ` ${JSON.stringify(id)}: ${$type in TYPE_MAP ? localTypeName($type) : 'any'};\\n`;\n }\n output += '}\\n';\n output += '\\n';\n output += RESOLVER_JSDOC_COMMENT;\n output += '\\n';\n output += `export const resolver: {\n apply(input: InputType): Tokens;\n listPermutations(): InputType[];\n};\n`;\n return output;\n}\n\n/** Generate TypeScript definition of valid inputs given a resolver */\nfunction buildInputType(resolver: Resolver, contexts?: Record<string, string[]>): string {\n const validContexts: Record<string, string[]> = contexts ?? {};\n if (!Object.keys(validContexts).length) {\n for (const [name, m] of Object.entries(resolver.source.modifiers ?? {})) {\n validContexts[name] = Object.keys(m.contexts);\n }\n for (const m of resolver.source.resolutionOrder) {\n if (m?.type !== 'modifier') {\n continue;\n }\n validContexts[m.name] = Object.keys(m.contexts);\n }\n }\n\n let output = '{';\n for (const [name, values] of Object.entries(validContexts)) {\n output += `\\n ${JSON.stringify(name)}: ${values.length ? values.map((v) => JSON.stringify(v)).join(' | ') : 'never'};`;\n }\n output += '\\n};';\n return output;\n}\n\nfunction localTypeName($type: Token['$type']): string {\n return pascalCase($type);\n}\n\n/** Serialize normalized Tokens set into a string */\nfunction serializeToken(token: TokenNormalized, includeProperties: Set<keyof TokenNormalized>): string {\n return `${JSON.stringify(token.id)}:${JSON.stringify(Object.fromEntries(Object.entries(token).filter(([k]) => includeProperties.has(k as keyof TokenNormalized))))}`;\n}\n","import type { Plugin } from '@terrazzo/parser';\nimport { buildDTS, buildJS } from './build.js';\nimport { DEFAULT_PROPERTIES, type JSPluginOptions } from './lib.js';\n\nexport * from './build.js';\nexport * from './lib.js';\n\nexport default function pluginJS({\n filename = 'index.js',\n properties: userProperties,\n contexts,\n}: JSPluginOptions = {}): Plugin {\n const entry = { group: 'plugin' as const, label: '@terrazzo/plugin-js' };\n\n return {\n name: '@terrazzo/plugin-js',\n config(_, context) {\n if (Array.isArray(userProperties) && !userProperties.length) {\n context.logger.error({ ...entry, message: 'properties option can’t be empty' });\n }\n },\n\n // As of 2.0, this plugin no longer pre-transforms values, because every instance\n // generates a unique output.\n async build({ resolver, outputFile, context }) {\n const properties = userProperties ? new Set(userProperties) : DEFAULT_PROPERTIES;\n const { code: js, typeMap } = buildJS({\n resolver,\n contexts,\n properties,\n logger: context.logger,\n });\n outputFile(filename, js);\n\n const dts = buildDTS({ resolver, contexts, properties, typeMap });\n const dtsFilename = typeof filename === 'string' ? filename.replace(/\\.(c|m)?js$/, '.d.$1ts') : 'index.d.ts';\n outputFile(dtsFilename, dts);\n },\n };\n}\n"],"mappings":";;;AAEA,MAAa,qBAAiD,IAAI,IAAI;CACpE;CACA;CACA;CACA;CACA;CAQD,CAAC;AAgBF,MAAa,cAAc;;;AAI3B,MAAa,WAA2C;CACtD,SAAS;CACT,QAAQ;CACR,OAAO;CACP,aAAa;CACb,WAAW;CACX,UAAU;CACV,YAAY;CACZ,YAAY;CACZ,UAAU;CACV,MAAM;CACN,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,aAAa;CACb,YAAY;CACZ,YAAY;CACb;;;ACzCD,MAAM,yBAAyB;AAE/B,SAAgB,QAAQ,EACtB,UACA,YACA,QACA,YAM4D;CAC5D,MAAM,QAAQ;EAAE,OAAO;EAAmB,OAAO;EAAuB;CACxE,MAAM,UAA0C,EAAE;CAGlD,IAAI,SAAS;AACb,WAAU;CAGV,MAAM,gBAAgB,WAAW,sBAAsB,OAAO,QAAQ,SAAS,CAAC,GAAG,SAAS,kBAAkB,EAAE,KAC7G,WAAW;EACV;EAEA,IAAI,KAAK,UACP,OAAO,YAAY,OAAO,QAAQ,MAAM,CAAC,MAAM,GAAG,MAAM,EAAE,GAAG,cAAc,EAAE,IAAI,SAAS,EAAE,SAAS,MAAM,CAAC,CAAC,CAAC,CAC/G;EACF,EACF;AACD,WAAU;CACV,IAAI,eAAe;AACnB,MAAK,MAAM,EAAE,OAAO,QAAQ,cAAc;EACxC,MAAM,QAAQ,YAAY,KAAK;AAC/B,MAAI;GACF,MAAM,SAAS,SAAS,MAAM,MAAM;AACpC,aAAU,KAAK,KAAK,UAAU,GAAG,CAAC;AAClC,QAAK,MAAM,MAAM,OAAO,KAAK,OAAO,EAAE;AACpC,cAAU,OAAO,eAAe,O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,SAAQ,OAAO,MAAM;IAAE,GAAG;IAAO,SAAS;IAAoC,CAAC;;EAMnF,MAAM,MAAM,EAAE,UAAU,YAAY,WAAW;GAC7C,MAAM,aAAa,iBAAiB,IAAI,IAAI,eAAe,GAAG;GAC9D,MAAM,EAAE,MAAM,IAAI,YAAY,QAAQ;IACpC;IACA;IACA;IACA,QAAQ,QAAQ;IACjB,CAAC;AACF,cAAW,UAAU,GAAG;GAExB,MAAM,MAAM,SAAS;IAAE;IAAU;IAAU;IAAY;IAAS,CAAC;AAEjE,cADoB,OAAO,aAAa,WAAW,SAAS,QAAQ,eAAe,UAAU,GAAG,cACxE,IAAI;;EAE/B"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@terrazzo/plugin-js",
3
- "version": "2.0.3",
3
+ "version": "2.1.0",
4
4
  "description": "Use DTCG tokens in Node.js for server-rendered applications.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -28,16 +28,16 @@
28
28
  "directory": "./packages/plugin-js/"
29
29
  },
30
30
  "peerDependencies": {
31
- "@terrazzo/cli": "^2.0.3",
32
- "@terrazzo/parser": "^2.0.3"
31
+ "@terrazzo/cli": "^2.1.0",
32
+ "@terrazzo/parser": "^2.1.0"
33
33
  },
34
34
  "dependencies": {
35
35
  "scule": "^1.3.0",
36
- "@terrazzo/parser": "^2.0.3"
36
+ "@terrazzo/parser": "^2.1.0"
37
37
  },
38
38
  "devDependencies": {
39
39
  "dtcg-examples": "^1.0.3",
40
- "@terrazzo/cli": "^2.0.3"
40
+ "@terrazzo/cli": "^2.1.0"
41
41
  },
42
42
  "scripts": {
43
43
  "build": "rolldown -c && attw --profile esm-only --pack .",