@terrazzo/plugin-js 2.1.0 → 2.2.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 +8 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -2
- package/dist/index.js.map +1 -1
- package/package.json +5 -5
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
# @terrazzo/plugin-js
|
|
2
2
|
|
|
3
|
+
## 2.2.0
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#705](https://github.com/terrazzoapp/terrazzo/pull/705) [`8979deb`](https://github.com/terrazzoapp/terrazzo/commit/8979deb7eba13db9999a9d30fa04fc55f3c12fe1) Thanks [@suikkee](https://github.com/suikkee)! - Fixed an issue where TokenNormalizedSet was missing from the generated type imports.
|
|
8
|
+
|
|
9
|
+
Previously, the build logic only included individual token types in the .d.ts imports. This change ensures that TokenNormalizedSet, a structural type required for permutations, is always included in the generated imports.
|
|
10
|
+
|
|
3
11
|
## 2.1.0
|
|
4
12
|
|
|
5
13
|
### Patch Changes
|
package/dist/index.d.ts
CHANGED
|
@@ -15,6 +15,8 @@ interface JSPluginOptions<T extends Record<string, string> = Record<string, stri
|
|
|
15
15
|
}
|
|
16
16
|
type Resolver<T extends Record<string, string>> = (input: T) => TokenNormalizedSet;
|
|
17
17
|
declare const FILE_HEADER = "/** ------------------------------------------\n * Autogenerated by \u26CB Terrazzo. DO NOT EDIT!\n * ------------------------------------------- */";
|
|
18
|
+
/** Types that are always imported in generated .d.ts files, regardless of which token types are used. */
|
|
19
|
+
declare const BASE_IMPORT_TYPES: string[];
|
|
18
20
|
declare const TYPE_MAP: Record<Token['$type'], string>;
|
|
19
21
|
//#endregion
|
|
20
22
|
//#region src/build.d.ts
|
|
@@ -51,5 +53,5 @@ declare function pluginJS({
|
|
|
51
53
|
contexts
|
|
52
54
|
}?: JSPluginOptions): Plugin;
|
|
53
55
|
//#endregion
|
|
54
|
-
export { DEFAULT_PROPERTIES, FILE_HEADER, JSPluginOptions, Resolver, TYPE_MAP, buildDTS, buildJS, pluginJS as default };
|
|
56
|
+
export { BASE_IMPORT_TYPES, DEFAULT_PROPERTIES, FILE_HEADER, JSPluginOptions, Resolver, TYPE_MAP, buildDTS, buildJS, pluginJS as default };
|
|
55
57
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/lib.ts","../src/build.ts","../src/index.ts"],"mappings":";;;cAEa,kBAAA,EAAoB,
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/lib.ts","../src/build.ts","../src/index.ts"],"mappings":";;;cAEa,kBAAA,EAAoB,GAAG,OAAO,eAAA;AAAA,UAe1B,eAAA,WAA0B,MAAA,mBAAyB,MAAA;EAfvD;;;;EAoBX,QAAA;EALe;EAOf,QAAA,mBAA2B,CAAA,GAAI,CAAA,OAAQ,CAAA;EAP2B;EASlE,UAAA,UAAoB,eAAA;AAAA;AAAA,KAGV,QAAA,WAAmB,MAAA,qBAA2B,KAAA,EAAO,CAAA,KAAM,kBAAA;AAAA,cAE1D,WAAA;;cAKA,iBAAA;AAAA,cAEA,QAAA,EAAU,MAAM,CAAC,KAAA;;;iBCzBd,OAAA,CAAA;EACd,QAAA;EACA,UAAA;EACA,MAAA;EACA;AAAA;EAEA,QAAA,EAAU,UAAA;EACV,UAAA,EAAY,GAAA,OAAU,eAAA;EACtB,QAAA,GAAW,MAAA;EACX,MAAA,EAAQ,MAAA;AAAA;EACJ,IAAA;EAAc,OAAA,EAAS,MAAA,SAAe,KAAA;AAAA;AAAA,iBA0E5B,QAAA,CAAA;EACd,QAAA;EACA,QAAA;EACA,UAAA;EACA;AAAA;EAEA,QAAA,EAAU,UAAA;EACV,QAAA,GAAW,MAAA;EACX,UAAA,EAAY,GAAA,OAAU,eAAA;EACtB,OAAA,EAAS,MAAA,SAAe,KAAA;AAAA;;;iBCnGF,QAAA,CAAA;EACtB,QAAA;EACA,UAAA,EAAY,cAAA;EACZ;AAAA,IACC,eAAA,GAAuB,MAAA"}
|
package/dist/index.js
CHANGED
|
@@ -11,6 +11,8 @@ const DEFAULT_PROPERTIES = new Set([
|
|
|
11
11
|
const FILE_HEADER = `/** ------------------------------------------
|
|
12
12
|
* Autogenerated by ⛋ Terrazzo. DO NOT EDIT!
|
|
13
13
|
* ------------------------------------------- */`;
|
|
14
|
+
/** Types that are always imported in generated .d.ts files, regardless of which token types are used. */
|
|
15
|
+
const BASE_IMPORT_TYPES = ["TokenNormalizedSet"];
|
|
14
16
|
const TYPE_MAP = {
|
|
15
17
|
boolean: "BooleanTokenNormalized",
|
|
16
18
|
border: "BorderTokenNormalized",
|
|
@@ -40,7 +42,7 @@ function buildJS({ resolver, properties, logger, contexts }) {
|
|
|
40
42
|
const typeMap = {};
|
|
41
43
|
let output = FILE_HEADER;
|
|
42
44
|
output += "\n";
|
|
43
|
-
const permutations = (contexts ? calculatePermutations(Object.entries(contexts)) : resolver.listPermutations()).map((value) => ({
|
|
45
|
+
const permutations = (contexts ? calculatePermutations(Object.entries(contexts)) : resolver.listPermutations?.() ?? []).map((value) => ({
|
|
44
46
|
value,
|
|
45
47
|
id: JSON.stringify(Object.fromEntries(Object.entries(value).sort((a, b) => a[0].localeCompare(b[0], "en-us", { numeric: true }))))
|
|
46
48
|
}));
|
|
@@ -98,6 +100,7 @@ function buildDTS({ resolver, contexts, properties, typeMap }) {
|
|
|
98
100
|
let output = FILE_HEADER;
|
|
99
101
|
output += "\n";
|
|
100
102
|
output += "import type {\n";
|
|
103
|
+
for (const $baseType of BASE_IMPORT_TYPES) output += ` ${$baseType},\n`;
|
|
101
104
|
for (const $type of unique$type) if ($type in TYPE_MAP) output += ` ${TYPE_MAP[$type]},\n`;
|
|
102
105
|
output += "} from \"@terrazzo/parser\";";
|
|
103
106
|
output += "\n\n";
|
|
@@ -177,6 +180,6 @@ function pluginJS({ filename = "index.js", properties: userProperties, contexts
|
|
|
177
180
|
};
|
|
178
181
|
}
|
|
179
182
|
//#endregion
|
|
180
|
-
export { DEFAULT_PROPERTIES, FILE_HEADER, TYPE_MAP, buildDTS, buildJS, pluginJS as default };
|
|
183
|
+
export { BASE_IMPORT_TYPES, DEFAULT_PROPERTIES, FILE_HEADER, TYPE_MAP, buildDTS, buildJS, pluginJS as default };
|
|
181
184
|
|
|
182
185
|
//# 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.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;G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/B,MAAM,QAAQ;EAAE,OAAO;EAAmB,OAAO;EAAuB;AAExE,QAAO;EACL,MAAM;EACN,OAAO,GAAG,SAAS;AACjB,OAAI,MAAM,QAAQ,eAAe,IAAI,CAAC,eAAe,OACnD,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"}
|
|
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\n/** Types that are always imported in generated .d.ts files, regardless of which token types are used. */\nexport const BASE_IMPORT_TYPES: string[] = ['TokenNormalizedSet'];\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 { BASE_IMPORT_TYPES, 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 // todo: replace internal usage of listPermutations\n const permutations = (\n contexts ? calculatePermutations(Object.entries(contexts)) : (resolver.listPermutations?.() ?? [])\n ).map((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 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 $baseType of BASE_IMPORT_TYPES) {\n output += ` ${$baseType},\\n`;\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;AAQF,CAAC;AAgBD,MAAa,cAAc;;;;AAK3B,MAAa,oBAA8B,CAAC,oBAAoB;AAEhE,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;AACd;;;AC5CA,MAAM,yBAAyB;AAE/B,SAAgB,QAAQ,EACtB,UACA,YACA,QACA,YAM4D;CAC5D,MAAM,QAAQ;EAAE,OAAO;EAAmB,OAAO;CAAsB;CACvE,MAAM,UAA0C,CAAC;CAGjD,IAAI,SAAS;CACb,UA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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.
|
|
32
|
-
"@terrazzo/parser": "^2.
|
|
31
|
+
"@terrazzo/cli": "^2.2.0",
|
|
32
|
+
"@terrazzo/parser": "^2.2.0"
|
|
33
33
|
},
|
|
34
34
|
"dependencies": {
|
|
35
35
|
"scule": "^1.3.0",
|
|
36
|
-
"@terrazzo/parser": "^2.
|
|
36
|
+
"@terrazzo/parser": "^2.2.0"
|
|
37
37
|
},
|
|
38
38
|
"devDependencies": {
|
|
39
39
|
"dtcg-examples": "^1.0.3",
|
|
40
|
-
"@terrazzo/cli": "^2.
|
|
40
|
+
"@terrazzo/cli": "^2.2.0"
|
|
41
41
|
},
|
|
42
42
|
"scripts": {
|
|
43
43
|
"build": "rolldown -c && attw --profile esm-only --pack .",
|