@kanso-labs/unplugin-style-dictionary 0.2.5 → 0.3.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/README.md +80 -24
- package/dist/cjs/_virtual/_rolldown/runtime.cjs +23 -0
- package/dist/cjs/index.cjs +268 -0
- package/dist/cjs/index.cjs.map +1 -0
- package/dist/cjs/index.d.cts +9 -0
- package/dist/cjs/rolldown.cjs +6 -0
- package/dist/cjs/rolldown.cjs.map +1 -0
- package/dist/cjs/rolldown.d.cts +5 -0
- package/dist/cjs/rollup.cjs +6 -0
- package/dist/cjs/rollup.cjs.map +1 -0
- package/dist/cjs/rollup.d.cts +5 -0
- package/dist/cjs/types.d.cts +43 -0
- package/dist/cjs/vite.cjs +6 -0
- package/dist/cjs/vite.cjs.map +1 -0
- package/dist/cjs/vite.d.cts +5 -0
- package/dist/cjs/webpack.cjs +6 -0
- package/dist/cjs/webpack.cjs.map +1 -0
- package/dist/cjs/webpack.d.cts +5 -0
- package/dist/index.d.ts +9 -7
- package/dist/index.js +202 -150
- package/dist/index.js.map +1 -1
- package/dist/rolldown.d.ts +6 -2
- package/dist/rolldown.js +3 -3
- package/dist/rolldown.js.map +1 -1
- package/dist/rollup.d.ts +6 -2
- package/dist/rollup.js +3 -3
- package/dist/rollup.js.map +1 -1
- package/dist/types.d.ts +31 -27
- package/dist/vite.d.ts +6 -2
- package/dist/vite.js +3 -3
- package/dist/vite.js.map +1 -1
- package/dist/webpack.d.ts +6 -2
- package/dist/webpack.js +3 -3
- package/dist/webpack.js.map +1 -1
- package/package.json +54 -25
- package/dist/index.cjs +0 -2
- package/dist/index.cjs.map +0 -1
- package/dist/rolldown.cjs +0 -2
- package/dist/rolldown.cjs.map +0 -1
- package/dist/rollup.cjs +0 -2
- package/dist/rollup.cjs.map +0 -1
- package/dist/vite.cjs +0 -2
- package/dist/vite.cjs.map +0 -1
- package/dist/webpack.cjs +0 -2
- package/dist/webpack.cjs.map +0 -1
package/README.md
CHANGED
|
@@ -1,18 +1,35 @@
|
|
|
1
1
|
# unplugin-style-dictionary
|
|
2
2
|
|
|
3
|
-
A lightweight, robust [unplugin](https://unplugin.unjs.io/)-based plugin to
|
|
3
|
+
A lightweight, robust [unplugin](https://unplugin.unjs.io/)-based plugin to
|
|
4
|
+
compile **Style Dictionary** design tokens ahead of your bundler, with automatic
|
|
5
|
+
watching, rebuilding, and hot reloading (HMR) under Vite's dev server.
|
|
4
6
|
|
|
5
|
-
Built on unplugin, the same core plugin targets **Vite**, **Rolldown**,
|
|
7
|
+
Built on unplugin, the same core plugin targets **Vite**, **Rolldown**,
|
|
8
|
+
**Rollup**, and **Webpack** from a single implementation — useful when a project
|
|
9
|
+
has more than one build surface (e.g. Storybook/Vitest on Vite, and a package
|
|
10
|
+
build on Rolldown/tsdown) that both need tokens compiled ahead of them.
|
|
6
11
|
|
|
7
12
|
## Features
|
|
8
13
|
|
|
9
|
-
- **Multi-bundler**: One implementation, four entry points — Vite, Rolldown,
|
|
10
|
-
|
|
11
|
-
- **
|
|
12
|
-
|
|
13
|
-
- **
|
|
14
|
-
|
|
15
|
-
-
|
|
14
|
+
- **Multi-bundler**: One implementation, four entry points — Vite, Rolldown,
|
|
15
|
+
Rollup, and Webpack.
|
|
16
|
+
- **Asynchronous builds**: Native support for Style Dictionary v4/v5 async
|
|
17
|
+
compilation API.
|
|
18
|
+
- **Automatic watching**: Reads the `source` and `include` patterns from your
|
|
19
|
+
Style Dictionary configurations and automatically watches them. Live
|
|
20
|
+
rebuild-on-change is fully supported under Vite's dev server; other targets
|
|
21
|
+
rebuild on change wherever the host bundler itself runs a persistent watch
|
|
22
|
+
mode.
|
|
23
|
+
- **Config flexibility**: Supports file paths (JSON, JS, MJS, CJS, TS),
|
|
24
|
+
configuration objects, or functions — including registering custom formats at
|
|
25
|
+
config-resolution time.
|
|
26
|
+
- **Atomic writes**: Every generated file is written to a temporary sibling and
|
|
27
|
+
renamed into place, so code importing a token file while it is being rebuilt
|
|
28
|
+
never reads a half-written file.
|
|
29
|
+
- **Multi-configuration**: Can run multiple Style Dictionary configurations in
|
|
30
|
+
parallel (useful for multi-brand or multi-theme projects).
|
|
31
|
+
- **TypeScript Support**: Fully written in TypeScript and exports complete type
|
|
32
|
+
definitions.
|
|
16
33
|
|
|
17
34
|
## Installation
|
|
18
35
|
|
|
@@ -20,7 +37,9 @@ Built on unplugin, the same core plugin targets **Vite**, **Rolldown**, **Rollup
|
|
|
20
37
|
npm install @kanso-labs/unplugin-style-dictionary style-dictionary --save-dev
|
|
21
38
|
```
|
|
22
39
|
|
|
23
|
-
|
|
40
|
+
_Note: `style-dictionary` and your bundler (`vite`, `rolldown`, `rollup`, or
|
|
41
|
+
`webpack`) are peer dependencies, so you can manage their versions
|
|
42
|
+
independently._
|
|
24
43
|
|
|
25
44
|
## Usage
|
|
26
45
|
|
|
@@ -56,7 +75,11 @@ export default {
|
|
|
56
75
|
}
|
|
57
76
|
```
|
|
58
77
|
|
|
59
|
-
Rolldown (and tools built on it, like [tsdown](https://tsdown.dev/)) is
|
|
78
|
+
Rolldown (and tools built on it, like [tsdown](https://tsdown.dev/)) is
|
|
79
|
+
typically run as a one-shot build rather than a long-lived dev server, so under
|
|
80
|
+
this target the plugin compiles tokens once in `buildStart` rather than watching
|
|
81
|
+
for changes. That's enough to guarantee generated token files exist before the
|
|
82
|
+
rest of the build consumes them.
|
|
60
83
|
|
|
61
84
|
### Rollup / Webpack
|
|
62
85
|
|
|
@@ -65,16 +88,33 @@ import StyleDictionary from '@kanso-labs/unplugin-style-dictionary/rollup'
|
|
|
65
88
|
// or: import StyleDictionary from '@kanso-labs/unplugin-style-dictionary/webpack'
|
|
66
89
|
```
|
|
67
90
|
|
|
91
|
+
A `webpack.config.js` is often CommonJS rather than ESM. Each target entry is
|
|
92
|
+
the plugin factory itself, so `require` it directly — there is no `.default` to
|
|
93
|
+
unwrap:
|
|
94
|
+
|
|
95
|
+
```javascript
|
|
96
|
+
const StyleDictionary = require('@kanso-labs/unplugin-style-dictionary/webpack')
|
|
97
|
+
|
|
98
|
+
module.exports = {
|
|
99
|
+
plugins: [StyleDictionary({ config: 'sd.config.json' })],
|
|
100
|
+
}
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
_Note: `require` of this package needs Node 20.19+ or 22.12+, because `unplugin`
|
|
104
|
+
itself is ESM-only and the CommonJS build reaches it through `require(esm)`.
|
|
105
|
+
Importing from ESM has no such floor._
|
|
106
|
+
|
|
68
107
|
### Multiple Configurations
|
|
69
108
|
|
|
70
|
-
If you have multiple themes or sub-brands, pass an array of config paths or
|
|
109
|
+
If you have multiple themes or sub-brands, pass an array of config paths or
|
|
110
|
+
objects:
|
|
71
111
|
|
|
72
112
|
```typescript
|
|
73
113
|
StyleDictionary({
|
|
74
114
|
config: [
|
|
75
115
|
'tokens/config/sd-base.config.json',
|
|
76
|
-
'tokens/config/sd-theme.config.json'
|
|
77
|
-
]
|
|
116
|
+
'tokens/config/sd-theme.config.json',
|
|
117
|
+
],
|
|
78
118
|
})
|
|
79
119
|
```
|
|
80
120
|
|
|
@@ -90,16 +130,22 @@ StyleDictionary({
|
|
|
90
130
|
css: {
|
|
91
131
|
transformGroup: 'css',
|
|
92
132
|
buildPath: 'dist/css/',
|
|
93
|
-
files: [{ destination: 'variables.css', format: 'css/variables' }]
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
}
|
|
133
|
+
files: [{ destination: 'variables.css', format: 'css/variables' }],
|
|
134
|
+
},
|
|
135
|
+
},
|
|
136
|
+
},
|
|
97
137
|
})
|
|
98
138
|
```
|
|
99
139
|
|
|
100
140
|
### Custom Formats
|
|
101
141
|
|
|
102
|
-
`config` also accepts a function, which is the pattern to use when you need to
|
|
142
|
+
`config` also accepts a function, which is the pattern to use when you need to
|
|
143
|
+
register a custom Style Dictionary format (via
|
|
144
|
+
`StyleDictionary.registerFormat()`, or any other `register*` call) before it's
|
|
145
|
+
referenced by name in the returned config. The function re-runs on every build —
|
|
146
|
+
including watch-triggered rebuilds under Vite — so the format is always
|
|
147
|
+
registered before it's needed; re-registering the same format name on every
|
|
148
|
+
rebuild is safe (Style Dictionary silently replaces the existing one).
|
|
103
149
|
|
|
104
150
|
```typescript
|
|
105
151
|
// Named `styleDictionaryPlugin` here to avoid colliding with the `StyleDictionary`
|
|
@@ -125,7 +171,9 @@ export default defineConfig({
|
|
|
125
171
|
custom: {
|
|
126
172
|
transformGroup: 'css',
|
|
127
173
|
buildPath: 'dist/',
|
|
128
|
-
files: [
|
|
174
|
+
files: [
|
|
175
|
+
{ destination: 'tokens.txt', format: 'custom/my-format' },
|
|
176
|
+
],
|
|
129
177
|
},
|
|
130
178
|
},
|
|
131
179
|
}
|
|
@@ -176,12 +224,20 @@ export interface UnpluginStyleDictionaryOptions {
|
|
|
176
224
|
|
|
177
225
|
## Migrating from `vite-plugin-style-dictionary`
|
|
178
226
|
|
|
179
|
-
This package was previously published as
|
|
227
|
+
This package was previously published as
|
|
228
|
+
`@kanso-labs/vite-plugin-style-dictionary`, implemented directly as a Vite
|
|
229
|
+
plugin. As of this unplugin-based rewrite:
|
|
180
230
|
|
|
181
231
|
- The package is renamed to `@kanso-labs/unplugin-style-dictionary`.
|
|
182
|
-
- The root import no longer resolves to a ready-to-use Vite plugin. Import the
|
|
183
|
-
-
|
|
184
|
-
-
|
|
232
|
+
- The root import no longer resolves to a ready-to-use Vite plugin. Import the
|
|
233
|
+
bundler-specific entry point instead:
|
|
234
|
+
`@kanso-labs/unplugin-style-dictionary/vite` (a drop-in replacement for the
|
|
235
|
+
old default export), `/rolldown`, `/rollup`, or `/webpack`.
|
|
236
|
+
- The exported options type is renamed from `VitePluginStyleDictionaryOptions`
|
|
237
|
+
to `UnpluginStyleDictionaryOptions`. The shape of the options (`config`,
|
|
238
|
+
`watch`, `silent`) is unchanged.
|
|
239
|
+
- Behavior under Vite is unchanged: the same `buildStart`-time compilation and
|
|
240
|
+
dev-server watch/rebuild logic as before.
|
|
185
241
|
|
|
186
242
|
## License
|
|
187
243
|
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
//#region \0rolldown/runtime.js
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __copyProps = (to, from, except, desc) => {
|
|
9
|
+
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
|
10
|
+
key = keys[i];
|
|
11
|
+
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
|
|
12
|
+
get: ((k) => from[k]).bind(null, key),
|
|
13
|
+
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
|
|
19
|
+
value: mod,
|
|
20
|
+
enumerable: true
|
|
21
|
+
}) : target, mod));
|
|
22
|
+
//#endregion
|
|
23
|
+
exports.__toESM = __toESM;
|
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
Object.defineProperties(exports, {
|
|
2
|
+
__esModule: { value: true },
|
|
3
|
+
[Symbol.toStringTag]: { value: "Module" }
|
|
4
|
+
});
|
|
5
|
+
const require_runtime = require("./_virtual/_rolldown/runtime.cjs");
|
|
6
|
+
let node_fs = require("node:fs");
|
|
7
|
+
node_fs = require_runtime.__toESM(node_fs, 1);
|
|
8
|
+
let node_path = require("node:path");
|
|
9
|
+
node_path = require_runtime.__toESM(node_path, 1);
|
|
10
|
+
let node_url = require("node:url");
|
|
11
|
+
let node_zlib = require("node:zlib");
|
|
12
|
+
node_zlib = require_runtime.__toESM(node_zlib, 1);
|
|
13
|
+
let style_dictionary = require("style-dictionary");
|
|
14
|
+
style_dictionary = require_runtime.__toESM(style_dictionary, 1);
|
|
15
|
+
let unplugin = require("unplugin");
|
|
16
|
+
//#region src/index.ts
|
|
17
|
+
function matchesWatchedFile(file, patterns) {
|
|
18
|
+
const normalizedFile = file.replace(/\\/g, "/");
|
|
19
|
+
return patterns.some((pattern) => {
|
|
20
|
+
if (pattern === normalizedFile) return true;
|
|
21
|
+
return normalizedFile.startsWith(pattern.replace(/\/\*\*/g, "")) || pattern.includes("*") && new RegExp(pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*")).test(normalizedFile);
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
function discardTemporaryFile(temporary) {
|
|
25
|
+
try {
|
|
26
|
+
node_fs.default.rmSync(temporary, { force: true });
|
|
27
|
+
} catch {}
|
|
28
|
+
}
|
|
29
|
+
function errorMessage(error) {
|
|
30
|
+
return error instanceof Error ? error.message : String(error);
|
|
31
|
+
}
|
|
32
|
+
function isConfig(value) {
|
|
33
|
+
return typeof value === "object" && value !== null;
|
|
34
|
+
}
|
|
35
|
+
function unwrapDefault(value) {
|
|
36
|
+
return typeof value === "object" && value !== null && "default" in value ? value.default ?? value : value;
|
|
37
|
+
}
|
|
38
|
+
let temporaryFileCounter = 0;
|
|
39
|
+
function temporaryPathFor(destination) {
|
|
40
|
+
const extension = node_path.default.extname(destination);
|
|
41
|
+
return node_path.default.join(node_path.default.dirname(destination), `.${node_path.default.basename(destination, extension)}.${process.pid}.${temporaryFileCounter++}.tmp`);
|
|
42
|
+
}
|
|
43
|
+
const writeFileAtomic = async (file, data, options) => {
|
|
44
|
+
if (typeof file !== "string") return node_fs.default.promises.writeFile(file, data, options);
|
|
45
|
+
const temporary = temporaryPathFor(file);
|
|
46
|
+
try {
|
|
47
|
+
await node_fs.default.promises.writeFile(temporary, data, options);
|
|
48
|
+
await node_fs.default.promises.rename(temporary, file);
|
|
49
|
+
} catch (err) {
|
|
50
|
+
discardTemporaryFile(temporary);
|
|
51
|
+
throw err;
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
const writeFileSyncAtomic = (file, data, options) => {
|
|
55
|
+
if (typeof file !== "string") {
|
|
56
|
+
node_fs.default.writeFileSync(file, data, options);
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
const temporary = temporaryPathFor(file);
|
|
60
|
+
try {
|
|
61
|
+
node_fs.default.writeFileSync(temporary, data, options);
|
|
62
|
+
node_fs.default.renameSync(temporary, file);
|
|
63
|
+
} catch (err) {
|
|
64
|
+
discardTemporaryFile(temporary);
|
|
65
|
+
throw err;
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
const atomicVolume = Object.create(node_fs.default, {
|
|
69
|
+
promises: { value: Object.create(node_fs.default.promises, { writeFile: { value: writeFileAtomic } }) },
|
|
70
|
+
writeFileSync: { value: writeFileSyncAtomic }
|
|
71
|
+
});
|
|
72
|
+
const unpluginFactory = (options = {}) => {
|
|
73
|
+
const { silent = false } = options;
|
|
74
|
+
let root = process.cwd();
|
|
75
|
+
const log = (message, type = "info") => {
|
|
76
|
+
if (silent) return;
|
|
77
|
+
const prefix = "[unplugin-style-dictionary]";
|
|
78
|
+
if (type === "error") console.error(`\x1b[31m${prefix} ${message}\x1b[0m`);
|
|
79
|
+
else if (type === "success") console.log(`\x1b[32m${prefix} ${message}\x1b[0m`);
|
|
80
|
+
else console.log(`\x1b[36m${prefix} ${message}\x1b[0m`);
|
|
81
|
+
};
|
|
82
|
+
const resolveConfigs = async () => {
|
|
83
|
+
let rawConfig = options.config;
|
|
84
|
+
if (!rawConfig) for (const file of [
|
|
85
|
+
"sd.config.json",
|
|
86
|
+
"config.json",
|
|
87
|
+
"sd.config.js",
|
|
88
|
+
"sd.config.mjs"
|
|
89
|
+
]) {
|
|
90
|
+
const fullPath = node_path.default.resolve(root, file);
|
|
91
|
+
if (node_fs.default.existsSync(fullPath)) {
|
|
92
|
+
rawConfig = file;
|
|
93
|
+
break;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
if (!rawConfig) {
|
|
97
|
+
log("No configuration specified and no default config file found. Style Dictionary will not compile.", "error");
|
|
98
|
+
return [];
|
|
99
|
+
}
|
|
100
|
+
if (typeof rawConfig === "function") rawConfig = await rawConfig();
|
|
101
|
+
return (Array.isArray(rawConfig) ? rawConfig : [rawConfig]).map((conf) => {
|
|
102
|
+
if (typeof conf === "string") {
|
|
103
|
+
const fullPath = node_path.default.resolve(root, conf);
|
|
104
|
+
return {
|
|
105
|
+
config: fullPath,
|
|
106
|
+
dir: node_path.default.dirname(fullPath),
|
|
107
|
+
file: fullPath
|
|
108
|
+
};
|
|
109
|
+
} else return {
|
|
110
|
+
config: conf,
|
|
111
|
+
dir: root
|
|
112
|
+
};
|
|
113
|
+
});
|
|
114
|
+
};
|
|
115
|
+
const getWatchFiles = async (resolvedConfigs) => {
|
|
116
|
+
const filesToWatch = /* @__PURE__ */ new Set();
|
|
117
|
+
for (const item of resolvedConfigs) {
|
|
118
|
+
if (item.file) filesToWatch.add(item.file.replace(/\\/g, "/"));
|
|
119
|
+
let configObj = null;
|
|
120
|
+
if (typeof item.config === "string") try {
|
|
121
|
+
let loaded;
|
|
122
|
+
if (item.config.endsWith(".json")) loaded = JSON.parse(node_fs.default.readFileSync(item.config, "utf-8"));
|
|
123
|
+
else {
|
|
124
|
+
const fileUrl = (0, node_url.pathToFileURL)(item.config).href;
|
|
125
|
+
loaded = unwrapDefault(await import(`${fileUrl}?t=${Date.now()}`));
|
|
126
|
+
}
|
|
127
|
+
if (isConfig(loaded)) configObj = loaded;
|
|
128
|
+
else log(`Config file did not resolve to a configuration object: ${item.config}`, "error");
|
|
129
|
+
} catch (err) {
|
|
130
|
+
log(`Failed to parse config file: ${item.config}. Error: ${errorMessage(err)}`, "error");
|
|
131
|
+
}
|
|
132
|
+
else configObj = item.config;
|
|
133
|
+
if (configObj) {
|
|
134
|
+
const addPattern = (pattern) => {
|
|
135
|
+
if (typeof pattern === "string") {
|
|
136
|
+
const normalized = (node_path.default.isAbsolute(pattern) ? pattern : node_path.default.resolve(item.dir, pattern)).replace(/\\/g, "/");
|
|
137
|
+
filesToWatch.add(normalized);
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
if (configObj.source) {
|
|
141
|
+
if (Array.isArray(configObj.source)) configObj.source.forEach(addPattern);
|
|
142
|
+
else addPattern(configObj.source);
|
|
143
|
+
}
|
|
144
|
+
if (configObj.include) {
|
|
145
|
+
if (Array.isArray(configObj.include)) configObj.include.forEach(addPattern);
|
|
146
|
+
else addPattern(configObj.include);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
if (options.watch) {
|
|
151
|
+
const extraWatches = Array.isArray(options.watch) ? options.watch : [options.watch];
|
|
152
|
+
for (const pattern of extraWatches) {
|
|
153
|
+
const absolutePattern = node_path.default.isAbsolute(pattern) ? pattern : node_path.default.resolve(root, pattern);
|
|
154
|
+
filesToWatch.add(absolutePattern.replace(/\\/g, "/"));
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
return Array.from(filesToWatch);
|
|
158
|
+
};
|
|
159
|
+
const runBuilds = async (resolvedConfigs, context) => {
|
|
160
|
+
const startTime = Date.now();
|
|
161
|
+
try {
|
|
162
|
+
if (!context) log("Compiling design tokens...", "info");
|
|
163
|
+
const generatedFiles = /* @__PURE__ */ new Set();
|
|
164
|
+
for (const item of resolvedConfigs) {
|
|
165
|
+
const sd = new style_dictionary.default(item.config);
|
|
166
|
+
await sd.hasInitialized;
|
|
167
|
+
const silentSD = await sd.extend({ log: { verbosity: "silent" } });
|
|
168
|
+
silentSD.volume = atomicVolume;
|
|
169
|
+
await silentSD.buildAllPlatforms();
|
|
170
|
+
if (!context && !silent) for (const platform of Object.values(silentSD.platforms)) {
|
|
171
|
+
const buildPath = platform.buildPath ?? "";
|
|
172
|
+
for (const file of platform.files ?? []) if (file.destination) {
|
|
173
|
+
const absoluteBuildPath = node_path.default.isAbsolute(buildPath) ? buildPath : node_path.default.resolve(root, buildPath);
|
|
174
|
+
const absoluteDestination = node_path.default.isAbsolute(file.destination) ? file.destination : node_path.default.resolve(absoluteBuildPath, file.destination);
|
|
175
|
+
generatedFiles.add(absoluteDestination);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
const duration = Date.now() - startTime;
|
|
180
|
+
if (context) log(`Rebuilt design tokens due to change in ${context} (${duration}ms)`, "success");
|
|
181
|
+
else {
|
|
182
|
+
if (!silent && generatedFiles.size > 0) {
|
|
183
|
+
const fileInfos = [];
|
|
184
|
+
for (const filePath of generatedFiles) if (node_fs.default.existsSync(filePath)) {
|
|
185
|
+
const displayPath = node_path.default.relative(root, filePath).replace(/\\/g, "/");
|
|
186
|
+
const dir = node_path.default.dirname(displayPath);
|
|
187
|
+
const base = node_path.default.basename(displayPath);
|
|
188
|
+
const coloredPath = dir === "." ? `\x1b[32m${base}\x1b[0m` : `\x1b[90m${dir}/\x1b[0m\x1b[32m${base}\x1b[0m`;
|
|
189
|
+
try {
|
|
190
|
+
const sizeStr = `${(node_fs.default.statSync(filePath).size / 1024).toFixed(2)} kB`;
|
|
191
|
+
const content = node_fs.default.readFileSync(filePath);
|
|
192
|
+
const gzipSizeStr = `${(node_zlib.default.gzipSync(content).length / 1024).toFixed(2)} kB`;
|
|
193
|
+
fileInfos.push({
|
|
194
|
+
coloredPath,
|
|
195
|
+
gzipSizeStr,
|
|
196
|
+
relativeDisplayPath: displayPath,
|
|
197
|
+
sizeStr
|
|
198
|
+
});
|
|
199
|
+
} catch {}
|
|
200
|
+
}
|
|
201
|
+
if (fileInfos.length > 0) {
|
|
202
|
+
const longestPathLength = Math.max(...fileInfos.map((f) => f.relativeDisplayPath.length), 0);
|
|
203
|
+
const longestSizeLength = Math.max(...fileInfos.map((f) => f.sizeStr.length), 0);
|
|
204
|
+
for (const info of fileInfos) {
|
|
205
|
+
const pathPadding = " ".repeat(Math.max(2, longestPathLength - info.relativeDisplayPath.length + 2));
|
|
206
|
+
const sizePadded = info.sizeStr.padStart(longestSizeLength);
|
|
207
|
+
console.log(`${info.coloredPath}${pathPadding}\x1b[90m${sizePadded} │ gzip: ${info.gzipSizeStr}\x1b[0m`);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
log(`Compiled successfully! (${duration}ms)`, "success");
|
|
212
|
+
}
|
|
213
|
+
} catch (err) {
|
|
214
|
+
const duration = Date.now() - startTime;
|
|
215
|
+
log(`Compilation failed after ${duration}ms: ${errorMessage(err)}`, "error");
|
|
216
|
+
}
|
|
217
|
+
};
|
|
218
|
+
return {
|
|
219
|
+
async buildStart() {
|
|
220
|
+
const resolved = await resolveConfigs();
|
|
221
|
+
if (resolved.length === 0) return;
|
|
222
|
+
const watchFiles = await getWatchFiles(resolved);
|
|
223
|
+
for (const file of watchFiles) this.addWatchFile(file);
|
|
224
|
+
await runBuilds(resolved);
|
|
225
|
+
},
|
|
226
|
+
name: "unplugin-style-dictionary",
|
|
227
|
+
vite: {
|
|
228
|
+
configResolved(config) {
|
|
229
|
+
root = config.root || process.cwd();
|
|
230
|
+
},
|
|
231
|
+
async configureServer(server) {
|
|
232
|
+
const resolved = await resolveConfigs();
|
|
233
|
+
if (resolved.length === 0) return;
|
|
234
|
+
const filesToWatch = await getWatchFiles(resolved);
|
|
235
|
+
server.watcher.add(filesToWatch);
|
|
236
|
+
server.watcher.on("all", (_event, file) => {
|
|
237
|
+
if (!matchesWatchedFile(file, filesToWatch)) return;
|
|
238
|
+
(async () => {
|
|
239
|
+
try {
|
|
240
|
+
const currentResolved = await resolveConfigs();
|
|
241
|
+
await runBuilds(currentResolved, node_path.default.basename(file));
|
|
242
|
+
const newWatches = await getWatchFiles(currentResolved);
|
|
243
|
+
server.watcher.add(newWatches);
|
|
244
|
+
} catch (err) {
|
|
245
|
+
log(`Rebuild failed: ${errorMessage(err)}`, "error");
|
|
246
|
+
}
|
|
247
|
+
})();
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
},
|
|
251
|
+
async watchChange(id) {
|
|
252
|
+
const resolved = await resolveConfigs();
|
|
253
|
+
if (resolved.length === 0) return;
|
|
254
|
+
const watchFiles = await getWatchFiles(resolved);
|
|
255
|
+
if (!matchesWatchedFile(id, watchFiles)) return;
|
|
256
|
+
await runBuilds(resolved, node_path.default.basename(id));
|
|
257
|
+
for (const file of watchFiles) this.addWatchFile(file);
|
|
258
|
+
}
|
|
259
|
+
};
|
|
260
|
+
};
|
|
261
|
+
const unplugin$1 = /* #__PURE__ */ (0, unplugin.createUnplugin)(unpluginFactory);
|
|
262
|
+
//#endregion
|
|
263
|
+
exports.default = unplugin$1;
|
|
264
|
+
exports.unplugin = unplugin$1;
|
|
265
|
+
exports.matchesWatchedFile = matchesWatchedFile;
|
|
266
|
+
exports.unpluginFactory = unpluginFactory;
|
|
267
|
+
|
|
268
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["path","fs","pathToFileURL","StyleDictionary","zlib","unplugin"],"sources":["../../src/index.ts"],"sourcesContent":["import type { Config } from 'style-dictionary'\nimport type { UnpluginFactory } from 'unplugin'\nimport type { ViteDevServer } from 'vite'\n\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport zlib from 'node:zlib'\nimport StyleDictionary from 'style-dictionary'\nimport { createUnplugin } from 'unplugin'\n\nimport type { UnpluginStyleDictionaryOptions } from './types.js'\n\nexport type * from './types.js'\n\n// Whether `file` matches one of the resolved config/token watch patterns.\n// Shared by the Vite-specific `configureServer` watcher and the universal\n// `watchChange` hook — both need it, and both must skip files that don't\n// match: without this filter, `watchChange` reacts to *any* changed\n// module-graph file, including this plugin's own generated output (since\n// consuming code imports it). Every regenerate is itself a \"change\", which\n// without filtering re-triggers a rebuild forever.\nexport function matchesWatchedFile(file: string, patterns: string[]): boolean {\n const normalizedFile = file.replace(/\\\\/g, '/')\n\n return patterns.some((pattern) => {\n // If the pattern is an exact file path\n if (pattern === normalizedFile) return true\n\n // If the pattern is a glob, we check if the file matches it.\n // Note: A simple string match or simple glob matcher can be used here.\n // For simplicity and correctness, since token source paths are usually globs,\n // we can match based on path directory containment or general matching.\n // Let's implement a robust matchesGlob check or check if it's one of the token files.\n // Chokidar triggers on actual files, so we want to check if the changed file matches\n // any of the config files or token files/globs.\n return (\n normalizedFile.startsWith(pattern.replace(/\\/\\*\\*/g, '')) ||\n (pattern.includes('*') &&\n new RegExp(\n pattern.replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&').replace(/\\*/g, '.*'),\n ).test(normalizedFile))\n )\n })\n}\n\n// Best-effort cleanup of a temporary file whose write or rename failed. The\n// original failure is what the caller reports, so nothing here may throw.\nfunction discardTemporaryFile(temporary: string): void {\n try {\n fs.rmSync(temporary, { force: true })\n } catch {\n // Ignore: a leftover temporary file is not worth masking the real error.\n }\n}\n\n// `catch` binds `unknown`, and a thrown non-Error — a string, a rejected\n// value out of a config module — carries no `.message`. The `as Error` casts\n// this replaces claimed otherwise and printed `undefined` for exactly those\n// cases, which is the least useful thing a failure log can say.\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\n// A config file is an untyped boundary: `JSON.parse` and a dynamic `import`\n// both hand back `any`, and an `any` assigned to `configObj` spreads through\n// every read of it downstream. These two narrow that boundary once, here.\n// They are type predicates rather than assertions on purpose — a predicate is\n// a check the compiler verifies, where a cast is only a claim.\nfunction isConfig(value: unknown): value is Config {\n return typeof value === 'object' && value !== null\n}\n\n// A config module may expose its config as a `default` export or as the\n// namespace itself. `'default' in value` is what lets the compiler reach\n// `.default` without a cast.\nfunction unwrapDefault(value: unknown): unknown {\n return typeof value === 'object' && value !== null && 'default' in value\n ? (value.default ?? value)\n : value\n}\n\n// Style Dictionary writes every generated file with a plain `writeFile` on the\n// volume it was handed, which truncates the destination and then streams the\n// new contents into it. Anything reading that file inside the window sees a\n// partial file: a consuming test run whose tokens are rebuilt mid-suite, or a\n// dev-server request landing on a rebuild, gets a truncated module and fails\n// to parse it. Writing a sibling temporary file and renaming it over the\n// destination closes the window — `rename` is atomic within a filesystem, so a\n// concurrent reader sees either the whole old file or the whole new one.\n\n// Temporary path for an atomic write of `destination`.\n//\n// It has to be a sibling of the destination, because `rename` is only atomic\n// within one filesystem and the system temp directory is often a different\n// mount. The final extension is dropped rather than kept, so the temporary\n// file cannot match a pattern written for the generated file's own extension —\n// `matchesWatchedFile` tests its globs unanchored, and a leftover\n// `vars.css.tmp` would match a `*.css` watch. The pid and counter make the\n// name unique, so two writes of the same destination — parallel platforms in\n// one build, or two builds overlapping — never share a temporary file.\nlet temporaryFileCounter = 0\n\nfunction temporaryPathFor(destination: string): string {\n const extension = path.extname(destination)\n\n return path.join(\n path.dirname(destination),\n `.${path.basename(destination, extension)}.${process.pid}.${temporaryFileCounter++}.tmp`,\n )\n}\n\nconst writeFileAtomic: typeof fs.promises.writeFile = async (\n file,\n data,\n options,\n) => {\n // A file handle or descriptor is already-open state that a rename cannot\n // stand in for, so only a path is written atomically.\n if (typeof file !== 'string') {\n return fs.promises.writeFile(file, data, options)\n }\n\n const temporary = temporaryPathFor(file)\n\n try {\n await fs.promises.writeFile(temporary, data, options)\n await fs.promises.rename(temporary, file)\n } catch (err) {\n discardTemporaryFile(temporary)\n throw err\n }\n}\n\nconst writeFileSyncAtomic: typeof fs.writeFileSync = (file, data, options) => {\n if (typeof file !== 'string') {\n fs.writeFileSync(file, data, options)\n return\n }\n\n const temporary = temporaryPathFor(file)\n\n try {\n fs.writeFileSync(temporary, data, options)\n fs.renameSync(temporary, file)\n } catch (err) {\n discardTemporaryFile(temporary)\n throw err\n }\n}\n\n// `node:fs` with both write entry points swapped for their atomic\n// equivalents, handed to Style Dictionary as the volume it builds through.\n// Everything else — reads, `mkdir`, `access`, the `promises` namespace — is\n// inherited from `node:fs` unchanged, so only the moment a file becomes\n// visible to readers changes. Custom actions receive this volume too, so\n// whatever they emit is written the same way.\n//\n// It is assigned onto the instance rather than passed as the `volume`\n// constructor option on purpose: that option marks the volume as a custom\n// filesystem shim, which switches Style Dictionary's path resolution off for\n// every read as well.\n// `Object.create` is declared as returning `any`, so pinning the result to\n// `typeof fs` is a claim no type guard can replace. The prototype link is the\n// whole point — see the note above — so rebuilding this with a spread, which\n// copies own properties and drops the chain, is not a substitute.\n/* oxlint-disable typescript/no-unsafe-type-assertion */\nconst atomicVolume = Object.create(fs, {\n promises: {\n value: Object.create(fs.promises, {\n writeFile: { value: writeFileAtomic },\n }) as typeof fs.promises,\n },\n writeFileSync: { value: writeFileSyncAtomic },\n}) as typeof fs\n/* oxlint-enable typescript/no-unsafe-type-assertion */\n\nexport const unpluginFactory: UnpluginFactory<\n undefined | UnpluginStyleDictionaryOptions,\n false\n> = (options = {}) => {\n const { silent = false } = options\n let root = process.cwd()\n\n // Helper to log if not silent\n const log = (\n message: string,\n type: 'error' | 'info' | 'success' = 'info',\n ) => {\n if (silent) return\n const prefix = '[unplugin-style-dictionary]'\n if (type === 'error') {\n console.error(`\\x1b[31m${prefix} ${message}\\x1b[0m`)\n } else if (type === 'success') {\n console.log(`\\x1b[32m${prefix} ${message}\\x1b[0m`)\n } else {\n console.log(`\\x1b[36m${prefix} ${message}\\x1b[0m`)\n }\n }\n\n // Resolve config file paths / objects\n const resolveConfigs = async (): Promise<\n Array<{ config: Config | string; dir: string; file?: string }>\n > => {\n let rawConfig = options.config\n\n // If config is not defined, look for default configuration files\n if (!rawConfig) {\n const defaults = [\n 'sd.config.json',\n 'config.json',\n 'sd.config.js',\n 'sd.config.mjs',\n ]\n for (const file of defaults) {\n const fullPath = path.resolve(root, file)\n if (fs.existsSync(fullPath)) {\n rawConfig = file\n break\n }\n }\n }\n\n if (!rawConfig) {\n log(\n 'No configuration specified and no default config file found. Style Dictionary will not compile.',\n 'error',\n )\n return []\n }\n\n // Evaluate function if provided\n if (typeof rawConfig === 'function') {\n rawConfig = await rawConfig()\n }\n\n const configs = Array.isArray(rawConfig) ? rawConfig : [rawConfig]\n\n return configs.map((conf) => {\n if (typeof conf === 'string') {\n const fullPath = path.resolve(root, conf)\n return {\n config: fullPath,\n dir: path.dirname(fullPath),\n file: fullPath,\n }\n } else {\n return {\n config: conf,\n dir: root,\n }\n }\n })\n }\n\n // Parse token files to watch\n const getWatchFiles = async (\n resolvedConfigs: Array<{\n config: Config | string\n dir: string\n file?: string\n }>,\n ): Promise<string[]> => {\n const filesToWatch = new Set<string>()\n\n for (const item of resolvedConfigs) {\n if (item.file) {\n filesToWatch.add(item.file.replace(/\\\\/g, '/'))\n }\n\n let configObj: Config | null = null\n\n if (typeof item.config === 'string') {\n try {\n let loaded: unknown\n\n if (item.config.endsWith('.json')) {\n loaded = JSON.parse(fs.readFileSync(item.config, 'utf-8'))\n } else {\n const fileUrl = pathToFileURL(item.config).href\n // Sequential on purpose: a config module runs arbitrary code at\n // import time — `registerFormat` and friends — and Style\n // Dictionary's registries are global, so importing several at\n // once would interleave those registrations.\n loaded = unwrapDefault(await import(`${fileUrl}?t=${Date.now()}`))\n }\n\n if (isConfig(loaded)) {\n configObj = loaded\n } else {\n log(\n `Config file did not resolve to a configuration object: ${item.config}`,\n 'error',\n )\n }\n } catch (err) {\n log(\n `Failed to parse config file: ${item.config}. Error: ${errorMessage(err)}`,\n 'error',\n )\n }\n } else {\n configObj = item.config\n }\n\n if (configObj) {\n const addPattern = (pattern: unknown) => {\n if (typeof pattern === 'string') {\n const absolutePattern = path.isAbsolute(pattern)\n ? pattern\n : path.resolve(item.dir, pattern)\n const normalized = absolutePattern.replace(/\\\\/g, '/')\n filesToWatch.add(normalized)\n }\n }\n\n if (configObj.source) {\n if (Array.isArray(configObj.source)) {\n configObj.source.forEach(addPattern)\n } else {\n addPattern(configObj.source)\n }\n }\n\n if (configObj.include) {\n if (Array.isArray(configObj.include)) {\n configObj.include.forEach(addPattern)\n } else {\n addPattern(configObj.include)\n }\n }\n }\n }\n\n // Add manually configured watch files\n if (options.watch) {\n const extraWatches = Array.isArray(options.watch)\n ? options.watch\n : [options.watch]\n for (const pattern of extraWatches) {\n const absolutePattern = path.isAbsolute(pattern)\n ? pattern\n : path.resolve(root, pattern)\n filesToWatch.add(absolutePattern.replace(/\\\\/g, '/'))\n }\n }\n\n return Array.from(filesToWatch)\n }\n\n // Compile design tokens\n const runBuilds = async (\n resolvedConfigs: Array<{ config: Config | string; dir: string }>,\n context?: string,\n ) => {\n const startTime = Date.now()\n try {\n if (!context) {\n log('Compiling design tokens...', 'info')\n }\n\n const generatedFiles = new Set<string>()\n\n // Configurations are built one after another rather than with\n // `Promise.all`, and that is load-bearing. Two configurations may name\n // the same destination file, and each instance gets the atomic volume\n // swapped onto it below — overlapping builds would interleave those\n // writes and hand a reader a file assembled from both.\n for (const item of resolvedConfigs) {\n const sd = new StyleDictionary(item.config)\n await sd.hasInitialized\n const silentSD = await sd.extend({\n log: {\n verbosity: 'silent',\n },\n })\n // Swap in the atomic volume only now that the instance has finished\n // reading its configs and token sources, so every write below lands\n // through `rename` while the read path stays exactly as it was.\n silentSD.volume = atomicVolume\n await silentSD.buildAllPlatforms()\n\n if (!context && !silent) {\n for (const platform of Object.values(silentSD.platforms)) {\n const buildPath = platform.buildPath ?? ''\n for (const file of platform.files ?? []) {\n if (file.destination) {\n const absoluteBuildPath = path.isAbsolute(buildPath)\n ? buildPath\n : path.resolve(root, buildPath)\n const absoluteDestination = path.isAbsolute(file.destination)\n ? file.destination\n : path.resolve(absoluteBuildPath, file.destination)\n generatedFiles.add(absoluteDestination)\n }\n }\n }\n }\n }\n\n const duration = Date.now() - startTime\n\n if (context) {\n log(\n `Rebuilt design tokens due to change in ${context} (${duration}ms)`,\n 'success',\n )\n } else {\n if (!silent && generatedFiles.size > 0) {\n const fileInfos: Array<{\n coloredPath: string\n gzipSizeStr: string\n relativeDisplayPath: string\n sizeStr: string\n }> = []\n\n for (const filePath of generatedFiles) {\n if (fs.existsSync(filePath)) {\n const displayPath = path\n .relative(root, filePath)\n .replace(/\\\\/g, '/')\n const dir = path.dirname(displayPath)\n const base = path.basename(displayPath)\n const coloredPath =\n dir === '.'\n ? `\\x1b[32m${base}\\x1b[0m`\n : `\\x1b[90m${dir}/\\x1b[0m\\x1b[32m${base}\\x1b[0m`\n\n try {\n const stats = fs.statSync(filePath)\n const bytes = stats.size\n const sizeStr = `${(bytes / 1024).toFixed(2)} kB`\n\n const content = fs.readFileSync(filePath)\n const gzipBytes = zlib.gzipSync(content).length\n const gzipSizeStr = `${(gzipBytes / 1024).toFixed(2)} kB`\n\n fileInfos.push({\n coloredPath,\n gzipSizeStr,\n relativeDisplayPath: displayPath,\n sizeStr,\n })\n } catch {\n // Ignore errors reading individual files\n }\n }\n }\n\n if (fileInfos.length > 0) {\n const longestPathLength = Math.max(\n ...fileInfos.map((f) => f.relativeDisplayPath.length),\n 0,\n )\n const longestSizeLength = Math.max(\n ...fileInfos.map((f) => f.sizeStr.length),\n 0,\n )\n\n for (const info of fileInfos) {\n const pathPadding = ' '.repeat(\n Math.max(\n 2,\n longestPathLength - info.relativeDisplayPath.length + 2,\n ),\n )\n const sizePadded = info.sizeStr.padStart(longestSizeLength)\n console.log(\n `${info.coloredPath}${pathPadding}\\x1b[90m${sizePadded} │ gzip: ${info.gzipSizeStr}\\x1b[0m`,\n )\n }\n }\n }\n\n log(`Compiled successfully! (${duration}ms)`, 'success')\n }\n } catch (err) {\n const duration = Date.now() - startTime\n log(\n `Compilation failed after ${duration}ms: ${errorMessage(err)}`,\n 'error',\n )\n }\n }\n\n return {\n async buildStart() {\n const resolved = await resolveConfigs()\n if (resolved.length === 0) return\n\n // Register token/config files with the host bundler's watch mode.\n // Works out of the box wherever the host runs a persistent watcher\n // (e.g. `rollup --watch`); Vite's dev server is additionally handled\n // below via the `vite.configureServer` escape hatch, since token\n // sources are plain JSON/JS files outside the module graph and\n // `watchChange` is not reliably invoked by Vite while serving.\n const watchFiles = await getWatchFiles(resolved)\n for (const file of watchFiles) {\n this.addWatchFile(file)\n }\n\n await runBuilds(resolved)\n },\n\n name: 'unplugin-style-dictionary',\n\n vite: {\n configResolved(config) {\n root = config.root || process.cwd()\n },\n\n async configureServer(server: ViteDevServer) {\n const resolved = await resolveConfigs()\n if (resolved.length === 0) return\n\n const filesToWatch = await getWatchFiles(resolved)\n\n // Watch configuration files and token files\n server.watcher.add(filesToWatch)\n\n // chokidar types its listener as returning void and does not await\n // what it is handed, so handing it an async function left every\n // rejection floating — `runBuilds` catches its own, but\n // `resolveConfigs` and `getWatchFiles` do not. Launching the work\n // explicitly and catching here is what keeps a bad config on disk\n // from surfacing as an unhandled rejection that kills the dev server.\n server.watcher.on('all', (_event, file) => {\n if (!matchesWatchedFile(file, filesToWatch)) return\n\n void (async () => {\n try {\n // Re-resolve configs to handle added/removed configs or changes\n // to config itself\n const currentResolved = await resolveConfigs()\n await runBuilds(currentResolved, path.basename(file))\n\n // Dynamically update the watch list in case the configurations\n // changed\n const newWatches = await getWatchFiles(currentResolved)\n server.watcher.add(newWatches)\n } catch (err) {\n log(`Rebuild failed: ${errorMessage(err)}`, 'error')\n }\n })()\n })\n },\n },\n\n // Rollup types `watchChange` as returning void, yet awaits it as a\n // sequential hook — and the work here is inherently asynchronous. The\n // signature is the thing that is wrong, so the rule is silenced rather\n // than the hook made to lie about finishing.\n // oxlint-disable-next-line typescript/no-misused-promises\n async watchChange(id) {\n const resolved = await resolveConfigs()\n if (resolved.length === 0) return\n\n const watchFiles = await getWatchFiles(resolved)\n // Without this check, watchChange fires for *any* changed file in the\n // host bundler's module graph — including our own generated output,\n // since consuming code imports it. Every regenerate is itself a\n // \"change\", so skipping non-matching files here is what keeps this\n // from rebuilding forever.\n if (!matchesWatchedFile(id, watchFiles)) return\n\n await runBuilds(resolved, path.basename(id))\n\n for (const file of watchFiles) {\n this.addWatchFile(file)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J,UAAAA,QAAK,SAAS,IAAI,CAAC;OAIpD,MAAM,aAAa,MAAM,cAAc,eAAe;OACtD,OAAO,QAAQ,IAAI,UAAU;MAC/B,SAAS,KAAK;OACZ,IAAI,mBAAmB,aAAa,GAAG,KAAK,OAAO;MACrD;KACF,EAAA,CAAG;IACL,CAAC;GACH;EACF;EAOA,MAAM,YAAY,IAAI;GACpB,MAAM,WAAW,MAAM,eAAe;GACtC,IAAI,SAAS,WAAW,GAAG;GAE3B,MAAM,aAAa,MAAM,cAAc,QAAQ;GAM/C,IAAI,CAAC,mBAAmB,IAAI,UAAU,GAAG;GAEzC,MAAM,UAAU,UAAUA,UAAAA,QAAK,SAAS,EAAE,CAAC;GAE3C,KAAK,MAAM,QAAQ,YACjB,KAAK,aAAa,IAAI;EAE1B;CACF;AACF;AAEA,MAAaK,aAA2B,iBAAA,GAAA,SAAA,eAAA,CAAe,eAAe"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { UnpluginStyleDictionaryOptions } from "./types.cjs";
|
|
2
|
+
import { UnpluginFactory } from "unplugin";
|
|
3
|
+
//#region src/index.d.ts
|
|
4
|
+
declare function matchesWatchedFile(file: string, patterns: string[]): boolean;
|
|
5
|
+
declare const unpluginFactory: UnpluginFactory<undefined | UnpluginStyleDictionaryOptions, false>;
|
|
6
|
+
declare const unplugin: import("unplugin").UnpluginInstance<UnpluginStyleDictionaryOptions | undefined, false>;
|
|
7
|
+
//#endregion
|
|
8
|
+
export { type UnpluginStyleDictionaryOptions, unplugin as default, unplugin, matchesWatchedFile, unpluginFactory };
|
|
9
|
+
//# sourceMappingURL=index.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rolldown.cjs","names":["unplugin"],"sources":["../../src/rolldown.ts"],"sourcesContent":["import { unplugin } from './index.js'\n\nexport default unplugin.rolldown\n"],"mappings":";AAEA,IAAA,wCAAeA,CAAAA,CAAAA,QAAS"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rollup.cjs","names":["unplugin"],"sources":["../../src/rollup.ts"],"sourcesContent":["import { unplugin } from './index.js'\n\nexport default unplugin.rollup\n"],"mappings":";AAEA,IAAA,sCAAeA,CAAAA,CAAAA,QAAS"}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { Config } from "style-dictionary";
|
|
2
|
+
//#region src/types.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Options for the Style Dictionary unplugin factory, shared across all bundler
|
|
5
|
+
* targets (Vite, Rolldown, Rollup, Webpack).
|
|
6
|
+
*
|
|
7
|
+
* Live rebuild-on-change is driven by the host bundler's watch mode. Vite's dev
|
|
8
|
+
* server is handled explicitly and is the best-supported case. Other targets
|
|
9
|
+
* rebuild on change only when the host bundler itself runs a persistent watch
|
|
10
|
+
* mode (e.g. `rollup --watch`), since token source files sit outside the module
|
|
11
|
+
* graph. A one-shot build (e.g. `tsdown`/`rolldown build` without `--watch`)
|
|
12
|
+
* only builds once, in `buildStart`.
|
|
13
|
+
*/
|
|
14
|
+
interface UnpluginStyleDictionaryOptions {
|
|
15
|
+
/**
|
|
16
|
+
* Style Dictionary configuration(s).
|
|
17
|
+
* Can be:
|
|
18
|
+
* - A file path string (e.g. 'sd.config.json')
|
|
19
|
+
* - An array of file path strings
|
|
20
|
+
* - A Style Dictionary configuration object
|
|
21
|
+
* - An array of Style Dictionary configuration objects
|
|
22
|
+
* - A function that returns a config or array of configs (or resolves to them).
|
|
23
|
+
* Useful for calling `StyleDictionary.registerFormat()` (or other `register*`
|
|
24
|
+
* methods) before returning a config that references the custom format by name.
|
|
25
|
+
*
|
|
26
|
+
* If not provided, it will look for 'sd.config.json' or 'config.json' in the root directory.
|
|
27
|
+
*/
|
|
28
|
+
config?: (() => Config | Config[] | Promise<Config | Config[]>) | Config | Config[] | string | string[];
|
|
29
|
+
/**
|
|
30
|
+
* Disable console logging.
|
|
31
|
+
* @default false
|
|
32
|
+
*/
|
|
33
|
+
silent?: boolean;
|
|
34
|
+
/**
|
|
35
|
+
* Additional files or glob patterns to watch.
|
|
36
|
+
* If config files are paths, those paths are watched automatically.
|
|
37
|
+
* By default, the plugin also parses 'source' and 'include' properties in configurations and watches them.
|
|
38
|
+
*/
|
|
39
|
+
watch?: string | string[];
|
|
40
|
+
}
|
|
41
|
+
//#endregion
|
|
42
|
+
export { UnpluginStyleDictionaryOptions };
|
|
43
|
+
//# sourceMappingURL=types.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"vite.cjs","names":["unplugin"],"sources":["../../src/vite.ts"],"sourcesContent":["import { unplugin } from './index.js'\n\nexport default unplugin.vite\n"],"mappings":";AAEA,IAAA,oCAAeA,CAAAA,CAAAA,QAAS"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"webpack.cjs","names":["unplugin"],"sources":["../../src/webpack.ts"],"sourcesContent":["import { unplugin } from './index.js'\n\nexport default unplugin.webpack\n"],"mappings":";AAEA,IAAA,uCAAeA,CAAAA,CAAAA,QAAS"}
|