cssints 0.0.0-stage → 0.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.
Files changed (51) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +178 -2
  3. package/dist/author-types-C1AhsnrT.d.mts +80 -0
  4. package/dist/check.d.mts +22 -0
  5. package/dist/check.mjs +37 -0
  6. package/dist/color-BYIxVLlS.mjs +29 -0
  7. package/dist/color-C8OzjAeg.mjs +2 -0
  8. package/dist/contrast-BUKVao74.mjs +83 -0
  9. package/dist/derived.d.mts +14 -0
  10. package/dist/derived.mjs +391 -0
  11. package/dist/errors-D4ZbcwRo.d.mts +32 -0
  12. package/dist/frame-BoBKjgBB.mjs +92 -0
  13. package/dist/frame.d.mts +72 -0
  14. package/dist/frame.mjs +2 -0
  15. package/dist/index.d.mts +34 -0
  16. package/dist/index.mjs +1132 -0
  17. package/dist/instrument-Bdtk2INz.mjs +172 -0
  18. package/dist/lib-2OEIfPAE.d.mts +9 -0
  19. package/dist/lowered-CeoXbm0P.mjs +28 -0
  20. package/dist/node-CdhAGmF3.d.mts +229 -0
  21. package/dist/parent-vars.d.mts +13 -0
  22. package/dist/parent-vars.mjs +65 -0
  23. package/dist/plugin-types.d.mts +377 -0
  24. package/dist/plugin.d.mts +3 -0
  25. package/dist/plugin.mjs +30 -0
  26. package/dist/registry-n9JCX4pl.mjs +72 -0
  27. package/dist/runtime-CTvuM-Hm.d.mts +5 -0
  28. package/dist/runtime.d.mts +18 -0
  29. package/dist/runtime.mjs +21 -0
  30. package/dist/scope-oWEaWE9n.d.mts +2095 -0
  31. package/dist/sheet-CO7a-mdA.mjs +756 -0
  32. package/dist/surface.d.mts +228 -0
  33. package/dist/surface.mjs +101 -0
  34. package/dist/theme-BGEbFAYh.mjs +906 -0
  35. package/dist/theme-types-DHdtTZhz.d.mts +1803 -0
  36. package/dist/trace-otlp-CbKFDsn9.mjs +14 -0
  37. package/dist/tui-types.d.mts +181 -0
  38. package/dist/tui.d.mts +30 -0
  39. package/dist/tui.mjs +399 -0
  40. package/dist/types.d.mts +2 -0
  41. package/dist/vite.d.mts +118 -0
  42. package/dist/vite.mjs +980 -0
  43. package/docs/API.md +1148 -0
  44. package/package.json +81 -4
  45. package/skills/cssints/SKILL.md +200 -0
  46. package/skills/cssints/references/errors.md +85 -0
  47. package/skills/cssints/references/plugins.md +91 -0
  48. package/skills/cssints/references/tokens.md +91 -0
  49. package/skills/cssints-plugin/SKILL.md +177 -0
  50. package/skills/cssints-plugin/references/table.md +124 -0
  51. package/skills/cssints-plugin/references/testing.md +122 -0
package/dist/vite.mjs ADDED
@@ -0,0 +1,980 @@
1
+ import { c as EvalError, d as MacroError, f as MemberError, i as forgetWarnings, l as HookError, n as forget, p as SiteMissingError, t as Registry } from "./registry-n9JCX4pl.mjs";
2
+ import { C as fallbackEntries, T as runtimeNames, a as closeNames, b as DERIVED, c as layerEntries, f as themedEntries, l as layerStatements, m as usesDerived, n as addGlobal, o as globalEntries, r as addLayers, s as globalNames, t as LAYERS, u as renderSheet, v as kernelEntries, w as runtimeModule, x as RUNTIME_ID } from "./sheet-CO7a-mdA.mjs";
3
+ import { i as keptImport, n as RUNTIME, r as instrument } from "./instrument-Bdtk2INz.mjs";
4
+ import { r as verifyChecks } from "./contrast-BUKVao74.mjs";
5
+ import { createRequire } from "node:module";
6
+ import { targets as targets$1, useTargets } from "@cssints/css-grammar/support";
7
+ import { Cause, Clock, Config, Data, Effect, Exit, Formatter, Option, Predicate, Result, Schema, Semaphore } from "effect";
8
+ import { createHash } from "node:crypto";
9
+ import { basename, join, relative, resolve, sep } from "node:path";
10
+ import { browserslistToTargets } from "lightningcss";
11
+ import MagicString from "magic-string";
12
+ import { existsSync, readFileSync } from "node:fs";
13
+ import { readFile } from "node:fs/promises";
14
+ import { browsers as browsers$1 } from "@cssints/css-grammar/browsers";
15
+ import { createFilter, createServer, createServerModuleRunner, normalizePath, transformWithOxc } from "vite";
16
+ import { fileURLToPath } from "node:url";
17
+ import { Window } from "happy-dom";
18
+ import { ESModulesEvaluator, ssrModuleExportsKey } from "vite/module-runner";
19
+ import { gzipSync } from "node:zlib";
20
+ //#region src/evaluate.ts
21
+ var DomEvaluator = class extends ESModulesEvaluator {
22
+ win = Object.assign(new Window(), { __jsx: () => null });
23
+ names = Object.getOwnPropertyNames(this.win).filter((k) => !Reflect.has(globalThis, k));
24
+ async runInlinedModule(context, code) {
25
+ const keys = Object.keys(context);
26
+ const fn = new Function(...this.names, `return async function (${keys.join(",")}) {"use strict";\n${code}\n}`);
27
+ const globals = this.win;
28
+ const values = context;
29
+ await fn(...this.names.map((k) => globals[k]))(...keys.map((k) => values[k]));
30
+ Object.seal(context[ssrModuleExportsKey]);
31
+ }
32
+ };
33
+ const evalLock = Semaphore.makeUnsafe(1);
34
+ const LIB = fileURLToPath(new URL("./index.ts", import.meta.url));
35
+ const clearApp = ({ idToModuleMap, urlToIdModuleMap, fileToModulesMap }) => {
36
+ const lib = /* @__PURE__ */ new Set();
37
+ const walk = (m) => {
38
+ if (!m || lib.has(m)) return;
39
+ lib.add(m);
40
+ m.imports.forEach((id) => walk(idToModuleMap.get(id)));
41
+ };
42
+ walk(idToModuleMap.get(LIB));
43
+ for (const map of [idToModuleMap, urlToIdModuleMap]) for (const [k, m] of map) if (!lib.has(m)) map.delete(k);
44
+ for (const [k, ms] of fileToModulesMap) for (const m of ms) if (!lib.has(m) && ms.delete(m) && !ms.size) fileToModulesMap.delete(k);
45
+ };
46
+ const isMacroError = (e) => Predicate.isTagged(e, "MacroError");
47
+ const isMemberError = (e) => Predicate.isTagged(e, "MemberError");
48
+ const failureOf = (id, registry) => (e) => {
49
+ if (isMacroError(e)) return new MacroError({
50
+ message: e.message,
51
+ file: e.file,
52
+ site: e.site,
53
+ offset: e.offset,
54
+ cause: e.cause
55
+ });
56
+ if (isMemberError(e)) return new MemberError({
57
+ message: e.message,
58
+ pluginName: e.pluginName,
59
+ file: e.file,
60
+ site: e.site,
61
+ offset: e.offset,
62
+ cause: e.cause
63
+ });
64
+ const at = registry.at;
65
+ const message = e instanceof Error ? e.message : String(e);
66
+ if (!at) return new EvalError({
67
+ file: id,
68
+ message,
69
+ cause: e
70
+ });
71
+ const m = e instanceof ReferenceError ? /^(?:(\S+) is not defined|Cannot access '(\S+)' before initialization)$/.exec(e.message) : null;
72
+ const name = m?.[1] ?? m?.[2];
73
+ return new MacroError({
74
+ message: name ? `cssints: css arguments must be known at build time: \`${name}\` is not defined where the call is evaluated (a parameter, a prop or state). Use cx(on && p(4)), a cv variant, or a token in a style prop` : message,
75
+ cause: e,
76
+ ...at
77
+ });
78
+ };
79
+ const evaluateModule = Effect.fnUntraced(function* (runner, id, targets) {
80
+ const registry = yield* Registry;
81
+ useTargets(targets);
82
+ registry.sites.delete(id);
83
+ forget(id);
84
+ registry.at = void 0;
85
+ registry.files.clear();
86
+ registry.gen++;
87
+ clearApp(runner.evaluatedModules);
88
+ yield* Effect.tryPromise({
89
+ try: () => runner.import(id).then((m) => m.__cssints_hoisted?.()),
90
+ catch: failureOf(id, registry)
91
+ }).pipe(Effect.withSpan("cssints.runner.import", { attributes: { file: id } }), Effect.timeoutOrElse({
92
+ duration: "30 seconds",
93
+ orElse: () => Effect.fail(new EvalError({
94
+ file: id,
95
+ message: `cssints: evaluating ${id} took more than 30 seconds`
96
+ }))
97
+ }));
98
+ yield* verifyChecks((c) => c.gen === registry.gen);
99
+ return registry.sites.get(id) ?? /* @__PURE__ */ new Map();
100
+ });
101
+ /**
102
+ * Evaluates `id` for the browser `targets` (default: those of process.cwd()) and runs `whileLocked` on its sites before
103
+ * the next evaluation may start (runner.qnt `rules`).
104
+ */
105
+ const evaluate = Effect.fn("cssints.evaluate")(function* (runner, id, whileLocked, targets) {
106
+ return yield* evalLock.withPermit(evaluateModule(runner, id, targets).pipe(Effect.flatMap(whileLocked)));
107
+ });
108
+ //#endregion
109
+ //#region src/devtools-server.ts
110
+ const DEVTOOLS_ID = "virtual:cssints/devtools";
111
+ const RESOLVED = `\0${DEVTOOLS_ID}`;
112
+ const SHEET$1 = "\0virtual:cssints.css";
113
+ const GROUP = /^_g(-[\w-]+)?$/;
114
+ const table = Effect.fn("cssints.devtoolsTable")(function* (root, usedBy, callsOf) {
115
+ const { rules, kernels, defs, scopes, layers } = yield* Registry;
116
+ const entries = [...new Set([...usedBy.values()].flatMap((s) => s.split("\n")))];
117
+ const sheet = yield* renderSheet(entries);
118
+ const classes = {};
119
+ for (const cls of entries) {
120
+ const r = rules.get(cls);
121
+ if (!r) continue;
122
+ const scope = r.prop.startsWith("--") ? [...scopes.keys()].find((s) => r.prop.startsWith(`--${s}-`)) : void 0;
123
+ classes[cls] = {
124
+ kind: "class",
125
+ layer: r.layer,
126
+ wrap: r.wrap,
127
+ prop: r.prop,
128
+ css: r.css,
129
+ tokens: r.tokens ?? [],
130
+ ...scope ? { plugin: scope } : {},
131
+ sites: []
132
+ };
133
+ }
134
+ for (const [key, k] of kernels) for (const m of k.markers) classes[m] = {
135
+ kind: "marker",
136
+ layer: "_.k",
137
+ wrap: [],
138
+ prop: "",
139
+ css: k.kernel.css,
140
+ tokens: [],
141
+ plugin: key,
142
+ sites: []
143
+ };
144
+ const sites = [];
145
+ for (const [file, calls] of callsOf) {
146
+ if (!usedBy.has(file)) continue;
147
+ for (const call of calls) {
148
+ const known = call.classes.filter((c) => {
149
+ if (!classes[c] && GROUP.test(c)) classes[c] = {
150
+ kind: "group",
151
+ layer: "",
152
+ wrap: [],
153
+ prop: "",
154
+ css: "",
155
+ tokens: [],
156
+ sites: []
157
+ };
158
+ return !!classes[c];
159
+ });
160
+ if (!known.length) continue;
161
+ const n = sites.push({
162
+ ...call,
163
+ file,
164
+ classes: known
165
+ }) - 1;
166
+ for (const c of known) classes[c].sites.push(n);
167
+ }
168
+ }
169
+ const tokens = {};
170
+ for (const [name, d] of defs) tokens[name] = {
171
+ path: d.path,
172
+ value: d.value
173
+ };
174
+ const statements = (before) => layerStatements([...layers.values()].flatMap((l) => l.before === before ? [l.names] : []));
175
+ const engine = LAYERS.slice(7, -1).split(", ");
176
+ const order = [
177
+ ...statements(true).flat(),
178
+ ...engine,
179
+ ...statements(false).flat()
180
+ ];
181
+ return {
182
+ root,
183
+ sheet,
184
+ layers: [...new Set(order)],
185
+ classes,
186
+ sites,
187
+ tokens
188
+ };
189
+ });
190
+ const ASK = "cssints:devtools:ask";
191
+ const ASKED = "cssints:devtools:asked";
192
+ const MAX_PROMPT = 16e3;
193
+ const Asking = Schema.Struct({
194
+ ref: Schema.Finite,
195
+ prompt: Schema.String
196
+ });
197
+ var OpenCodeError = class extends Data.TaggedError("OpenCodeError") {};
198
+ const workspace = (root) => root.split(sep).map((_, i, parts) => parts.slice(0, parts.length - i).join(sep) || sep).find((dir) => existsSync(join(dir, ".git"))) ?? root;
199
+ const connect = Effect.fn("cssints.opencodeConnect")(function* () {
200
+ const unavailable = (message) => () => new OpenCodeError({
201
+ status: "unavailable",
202
+ message
203
+ });
204
+ const { OpenCode } = yield* Effect.tryPromise({
205
+ try: () => import("@opencode/client"),
206
+ catch: unavailable("opencode is on, but @opencode/client is not installed: add it to the devDependencies of the app")
207
+ });
208
+ const { Service } = yield* Effect.tryPromise({
209
+ try: () => import("@opencode/client/service"),
210
+ catch: unavailable("opencode is on, but @opencode/client is not installed: add it to the devDependencies of the app")
211
+ });
212
+ const service = yield* Effect.tryPromise({
213
+ try: () => Service.discover(),
214
+ catch: (e) => unavailable(Predicate.isError(e) ? e.message : String(e))()
215
+ });
216
+ if (!service) return yield* new OpenCodeError({
217
+ status: "unavailable",
218
+ message: "No OpenCode service is running. Start OpenCode (or `opencode serve --service`) and send again."
219
+ });
220
+ return OpenCode.make({
221
+ baseUrl: service.url,
222
+ headers: Service.headers(service)
223
+ });
224
+ });
225
+ const ask = Effect.fn("cssints.opencodeAsk")(function* (root, options, ref, prompt, say) {
226
+ const client = yield* connect();
227
+ const call = (f) => Effect.tryPromise({
228
+ try: f,
229
+ catch: (e) => new OpenCodeError({
230
+ status: "failed",
231
+ message: Predicate.isError(e) ? e.message : String(e)
232
+ })
233
+ });
234
+ const { id } = yield* call(() => client.session.create({
235
+ title: "cssints devtools: UI change",
236
+ ...options.agent ? { agent: options.agent } : {},
237
+ location: { directory: workspace(root) }
238
+ }));
239
+ say({
240
+ ref,
241
+ status: "running",
242
+ id
243
+ });
244
+ yield* call(() => client.session.prompt({
245
+ sessionID: id,
246
+ text: prompt.slice(0, MAX_PROMPT),
247
+ ...options.skills?.length ? { skills: options.skills.map((s) => ({ id: s })) } : {}
248
+ }));
249
+ yield* call(() => client.session.wait({ sessionID: id }));
250
+ const { outcome } = yield* call(() => client.session.get({ sessionID: id }));
251
+ say({
252
+ ref,
253
+ status: outcome === "succeeded" ? "completed" : outcome ?? "failed",
254
+ id
255
+ });
256
+ });
257
+ const entryModule = (overlay, root, opencode) => overlay ? `import { mount } from ${Formatter.formatJson(overlay)};
258
+ const hot = import.meta.hot;
259
+ mount({
260
+ root: ${Formatter.formatJson(root)},
261
+ request: () => hot.send("cssints:devtools:get"),
262
+ on: (event, listener) => hot.on(event, listener),${opencode ? `\n ask: (ref, prompt) => hot.send("${ASK}", { ref, prompt }),` : ""}
263
+ });
264
+ ` : `console.warn("cssints: devtools is on, but @cssints/devtools/overlay is not installed (or not built): add @cssints/devtools to the devDependencies of the app");\n`;
265
+ /**
266
+ * The dev-only plugin of `cssints({ devtools: true })`: the overlay's entry in every HTML page, and the table on request.
267
+ * `apply: "serve"`, so a build has none of it.
268
+ * @param {Map<string, string>} usedBy the entries of each client module (plugin.ts)
269
+ * @param {Map<string, DevSite[]>} callsOf the sites of each client module
270
+ * @param {OpenCodeOptions | undefined} opencode set: the overlay's prompt box starts OpenCode sessions through this server
271
+ * @returns {Plugin} the plugin
272
+ */
273
+ const devtoolsPlugin = (usedBy, callsOf, opencode) => {
274
+ let server;
275
+ const stale = () => Effect.sync(() => server?.environments.client.hot.send("cssints:devtools:stale"));
276
+ const entry = Effect.fn("cssints.devtoolsEntry")(function* (resolve) {
277
+ const overlay = yield* Effect.tryPromise(resolve).pipe(Effect.orElseSucceed(() => null));
278
+ return entryModule(overlay?.id, server?.config.root ?? "", !!opencode);
279
+ });
280
+ return {
281
+ name: "cssints:devtools",
282
+ apply: "serve",
283
+ configureServer(s) {
284
+ server = s;
285
+ s.environments.client.hot.on("cssints:devtools:get", (_, client) => client.send("cssints:devtools", Effect.runSync(table(s.config.root, usedBy, callsOf))));
286
+ if (opencode) s.environments.client.hot.on(ASK, (data) => {
287
+ const asking = Schema.decodeUnknownOption(Asking)(data);
288
+ if (Option.isNone(asking)) return;
289
+ const { ref, prompt } = asking.value;
290
+ const say = (asked) => s.environments.client.hot.send(ASKED, asked);
291
+ Effect.runFork(ask(s.config.root, opencode, ref, prompt, say).pipe(Effect.catchTag("OpenCodeError", (e) => Effect.sync(() => say({
292
+ ref,
293
+ status: e.status,
294
+ message: e.message
295
+ })))));
296
+ });
297
+ },
298
+ transformIndexHtml: () => [{
299
+ tag: "script",
300
+ attrs: {
301
+ type: "module",
302
+ src: `/@id/${DEVTOOLS_ID}`
303
+ },
304
+ injectTo: "body"
305
+ }],
306
+ resolveId(id) {
307
+ if (id === "virtual:cssints/devtools") return RESOLVED;
308
+ },
309
+ load(id) {
310
+ if (id !== RESOLVED) return;
311
+ return Effect.runPromise(entry(() => this.resolve("@cssints/devtools/overlay", void 0, { skipSelf: true })));
312
+ },
313
+ transform: {
314
+ order: "post",
315
+ handler(_, id) {
316
+ if (this.environment.name === "client" && (id === SHEET$1 || callsOf.has(id))) Effect.runSync(stale());
317
+ }
318
+ }
319
+ };
320
+ };
321
+ const TABLE_FILE = "__CSSINTS_DEVTOOLS_TABLE__";
322
+ const loaderModule = (overlay, base) => `const key = (e) => {
323
+ if (e.altKey && e.shiftKey && e.code === "KeyC") {
324
+ e.preventDefault();
325
+ open();
326
+ }
327
+ };
328
+ const button = document.createElement("button");
329
+ button.textContent = "cssints";
330
+ button.title = "cssints devtools (Alt+Shift+C)";
331
+ button.style.cssText = "position:fixed;right:12px;bottom:12px;z-index:2147483647;padding:4px 8px;border:1px solid #374151;border-radius:999px;background:#111827;color:#e5e7eb;font:11px ui-monospace,monospace;cursor:pointer;opacity:.75";
332
+ button.onclick = () => open();
333
+ const open = () => {
334
+ button.remove();
335
+ removeEventListener("keydown", key, true);
336
+ import(${Formatter.formatJson(overlay)}).then(({ mount }) => {
337
+ const listeners = {};
338
+ mount({
339
+ root: "",
340
+ build: true,
341
+ request: () => fetch(new URL(${Formatter.formatJson(base)} + "${TABLE_FILE}", document.baseURI))
342
+ .then((r) => r.json())
343
+ .then((table) => listeners["cssints:devtools"]?.(table)),
344
+ on: (event, listener) => { listeners[event] = listener; },
345
+ });
346
+ });
347
+ };
348
+ addEventListener("keydown", key, true);
349
+ document.body.append(button);
350
+ `;
351
+ const kb = (n) => `${(n / 1024).toFixed(1)} kB`;
352
+ /**
353
+ * The build side of `cssints({ devtools: "build" })`: the overlay in every page behind a button, the table as a JSON asset.
354
+ * Nothing loads until the first open. The files of the sites are relative to the root, so the asset holds no path of this machine.
355
+ * @param {Map<string, string>} usedBy the entries of each client module (plugin.ts)
356
+ * @param {Map<string, DevSite[]>} callsOf the sites of each client module
357
+ * @returns {Plugin} the plugin
358
+ */
359
+ const devtoolsBuildPlugin = (usedBy, callsOf) => ({
360
+ name: "cssints:devtools-build",
361
+ apply: "build",
362
+ transformIndexHtml: {
363
+ order: "pre",
364
+ handler: () => [{
365
+ tag: "script",
366
+ attrs: {
367
+ type: "module",
368
+ src: DEVTOOLS_ID
369
+ },
370
+ injectTo: "body"
371
+ }]
372
+ },
373
+ resolveId(id) {
374
+ if (id === "virtual:cssints/devtools") return RESOLVED;
375
+ },
376
+ load(id) {
377
+ if (id !== RESOLVED) return;
378
+ return Effect.runPromise(Effect.tryPromise(() => this.resolve("@cssints/devtools/overlay", void 0, { skipSelf: true })).pipe(Effect.orElseSucceed(() => null), Effect.map((overlay) => overlay ? loaderModule(overlay.id, this.environment.config.base) : `console.warn("cssints: devtools is on, but @cssints/devtools/overlay is not installed: add @cssints/devtools to the devDependencies of the app");\n`)));
379
+ },
380
+ generateBundle(_, bundle) {
381
+ if (this.environment.name !== "client") return;
382
+ const chunks = Object.values(bundle).flatMap((f) => f.type === "chunk" ? [f] : []);
383
+ const loader = chunks.find((c) => c.code.includes(TABLE_FILE));
384
+ if (!loader) return;
385
+ const { root } = this.environment.config;
386
+ const t = Effect.runSync(table(root, usedBy, callsOf));
387
+ const json = Formatter.formatJson({
388
+ ...t,
389
+ root: "",
390
+ sites: t.sites.map((s) => ({
391
+ ...s,
392
+ file: relative(root, s.file)
393
+ }))
394
+ });
395
+ const ref = this.emitFile({
396
+ type: "asset",
397
+ name: "cssints-devtools.json",
398
+ source: json
399
+ });
400
+ const file = this.getFileName(ref);
401
+ loader.code = loader.code.replace(TABLE_FILE, () => file);
402
+ const overlay = chunks.find((c) => c.isDynamicEntry && c.code.includes("cssints-devtools"));
403
+ this.info(`devtools: ${file} ${kb(Buffer.byteLength(json))} (${kb(gzipSync(json).length)} gzip)` + (overlay ? `, ${overlay.fileName} ${kb(Buffer.byteLength(overlay.code))} (${kb(gzipSync(overlay.code).length)} gzip), loaded on the first open` : ""));
404
+ }
405
+ });
406
+ //#endregion
407
+ //#region src/entries.ts
408
+ const moduleEntries = Effect.fnUntraced(function* (id, sites) {
409
+ const registry = yield* Registry;
410
+ const { rules, properties, themed } = registry;
411
+ const texts = [...sites.values()];
412
+ const classes = texts.flatMap((r) => [...r.matchAll(/"(_[\w-]+(?: _[\w-]+)*)"/g)].flatMap((m) => m[1].split(" ")));
413
+ const kernels = kernelEntries(registry, id);
414
+ const names = new Set([...texts, ...kernels].flatMap((r) => r.match(/--[\w-]+/g) ?? []));
415
+ globalNames(themed, id).forEach((n) => names.add(n));
416
+ for (const c of classes) rules.get(c)?.tokens?.forEach((n) => names.add(n));
417
+ closeNames(names, registry.defs, themed);
418
+ const entries = [
419
+ ...classes,
420
+ ...[...names].flatMap((n) => properties.get(n)?.css ?? []),
421
+ ...themedEntries(themed, id, names),
422
+ ...kernels,
423
+ ...globalEntries(registry, id),
424
+ ...layerEntries(registry, id),
425
+ ...yield* fallbackEntries(registry, id)
426
+ ];
427
+ const runtimes = runtimeNames(registry, id);
428
+ if (!runtimes.includes("derived") && usesDerived(registry, names)) runtimes.push(DERIVED);
429
+ return {
430
+ entries,
431
+ runtimes
432
+ };
433
+ });
434
+ //#endregion
435
+ //#region src/trace.ts
436
+ const mode = /^otlp(?::(.+))?$/.exec(Effect.runSync(Config.String("CSSINTS_TRACE").pipe(Config.withDefault(""))));
437
+ const otlp = mode ? await import("./trace-otlp-CbKFDsn9.mjs").then((m) => m.start(mode[1] ?? "http://localhost:4318")) : void 0;
438
+ let runtime = otlp;
439
+ const runSync = otlp ? (e) => runtime ? runtime.runSync(e) : Effect.runSync(e) : Effect.runSync;
440
+ const runPromiseExit = otlp ? (e, o) => runtime ? runtime.runPromiseExit(e, o) : Effect.runPromiseExit(e, o) : Effect.runPromiseExit;
441
+ /**
442
+ * Sends what is buffered and stops the exporter, whose timer would keep Node alive (the end of a build, `server.close()`;
443
+ * a script that exits itself calls it first). Later hooks run untraced. A no-op when off.
444
+ * @returns {Promise<void>} resolved when the exporter has stopped
445
+ */
446
+ const closeTrace = () => {
447
+ const r = runtime;
448
+ runtime = void 0;
449
+ return r ? r.dispose() : Promise.resolve();
450
+ };
451
+ const note = (e) => Effect.flatMap(Effect.all([Effect.currentSpan, Clock.currentTimeNanos]), ([span, now]) => Effect.sync(() => {
452
+ span.event("cssints.error", now, {
453
+ message: e.message,
454
+ file: e.file,
455
+ offset: e.offset
456
+ });
457
+ Object.assign(e, {
458
+ traceId: span.traceId,
459
+ spanId: span.spanId,
460
+ message: `${e.message} (trace ${span.traceId})`
461
+ });
462
+ })).pipe(Effect.ignore);
463
+ const hook = otlp ? (name, file, program, environment) => program.pipe(Effect.tapCause((cause) => {
464
+ const e = Cause.squash(cause);
465
+ return Predicate.hasProperty(e, "message") ? note(e) : Effect.void;
466
+ }), Effect.withSpan(name, {
467
+ root: true,
468
+ attributes: {
469
+ file,
470
+ environment
471
+ }
472
+ })) : (_name, _file, program) => program;
473
+ const warned = otlp ? (ws, file) => Effect.flatMap(Effect.all([Effect.currentSpan, Clock.currentTimeNanos]), ([span, now]) => Effect.sync(() => ws.forEach((message) => span.event("cssints.warning", now, {
474
+ message,
475
+ file
476
+ })))).pipe(Effect.ignore) : () => Effect.void;
477
+ //#endregion
478
+ //#region src/plugin.ts
479
+ const FILE_RE = /\.(ts|tsx|js|jsx|mts|mjs)$/;
480
+ const VERSION = /[?&]v=\w+$/;
481
+ const SHEET_IMPORT = "virtual:cssints.css";
482
+ const SHEET = `\0${SHEET_IMPORT}`;
483
+ const ATTRIBUTE = /type\s*:\s*["']cssints["']/;
484
+ const marked = (code, id) => code.includes("cssints") && (!id.includes("node_modules") || ATTRIBUTE.test(code));
485
+ const Deps = Schema.optional(Schema.Record(Schema.String, Schema.String));
486
+ const Manifest = Schema.fromJsonString(Schema.Struct({
487
+ dependencies: Deps,
488
+ devDependencies: Deps,
489
+ peerDependencies: Deps
490
+ }));
491
+ const decodeManifest = Schema.decodeUnknownOption(Manifest);
492
+ const packagesOnCssints = (root) => Effect.sync(() => {
493
+ const read = (file) => Option.getOrUndefined(Option.flatMap(Result.getSuccess(Result.try(() => readFileSync(file, "utf8"))), decodeManifest));
494
+ const app = read(join(root, "package.json"));
495
+ const lookup = createRequire(join(root, "package.json")).resolve.paths("cssints") ?? [];
496
+ return Object.keys({
497
+ ...app?.dependencies,
498
+ ...app?.devDependencies
499
+ }).filter((name) => {
500
+ const m = lookup.map((dir) => read(join(dir, name, "package.json"))).find(Boolean);
501
+ return !!m && Object.hasOwn({
502
+ ...m.dependencies,
503
+ ...m.peerDependencies
504
+ }, "cssints");
505
+ });
506
+ });
507
+ const hash = (s) => createHash("sha1").update(s).digest("hex").slice(0, 8);
508
+ /**
509
+ * LightningCSS targets (css.lightningcss.targets) from the browserslist config of process.cwd(), read when vite.config.ts
510
+ * imports this module: the support warnings read the one of the Vite root, the same unless the root is elsewhere.
511
+ */
512
+ const targets = browserslistToTargets(Effect.runSync(browsers$1()));
513
+ const ESBUILD = {
514
+ ios_saf: "ios",
515
+ ie: "ie",
516
+ opera: "opera",
517
+ edge: "edge",
518
+ chrome: "chrome",
519
+ firefox: "firefox",
520
+ safari: "safari"
521
+ };
522
+ /** `build: { cssTarget }`, the browserslist query of `targets`, so a minified build keeps `firstThatWorks` fallbacks. */
523
+ const cssTarget = Effect.runSync(browsers$1()).flatMap((t) => {
524
+ const [agent, version] = t.split(" ");
525
+ return ESBUILD[agent] && /^\d/.test(version) ? [`${ESBUILD[agent]}${version.split("-")[0]}`] : [];
526
+ });
527
+ const run = (program) => runPromiseExit(program).then((exit) => {
528
+ if (Exit.isSuccess(exit)) return exit.value;
529
+ throw Cause.squash(exit.cause);
530
+ });
531
+ const lineCol = (text, offset) => {
532
+ let line = 1;
533
+ let lineStart = 0;
534
+ for (let i = text.indexOf("\n"); i !== -1 && i < offset; i = text.indexOf("\n", i + 1)) {
535
+ line++;
536
+ lineStart = i + 1;
537
+ }
538
+ return {
539
+ line,
540
+ column: offset - lineStart
541
+ };
542
+ };
543
+ const B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
544
+ const vlq = (n) => {
545
+ let v = n < 0 ? -n << 1 | 1 : n << 1;
546
+ let s = "";
547
+ do {
548
+ const d = v & 31;
549
+ v >>>= 5;
550
+ s += B64[v ? d | 32 : d];
551
+ } while (v);
552
+ return s;
553
+ };
554
+ const sheetMap = (text, siteOf, source = (file) => file) => {
555
+ const first = /* @__PURE__ */ new Map();
556
+ for (const [file, at] of [...siteOf].sort(([a], [b]) => a < b ? -1 : 1)) for (const [cls, loc] of at) if (!first.has(cls)) first.set(cls, [file, loc]);
557
+ const sources = [];
558
+ let prev = [
559
+ 0,
560
+ 0,
561
+ 0
562
+ ];
563
+ return {
564
+ version: 3,
565
+ sources,
566
+ names: [],
567
+ mappings: text.split("\n").map((l) => {
568
+ const segs = [];
569
+ let col = 0;
570
+ let mapped = false;
571
+ for (const m of l.matchAll(/(?<=^|[{};])\s*([^{};\s][^{};]*)(?=\{)/g)) {
572
+ const at = m.index + m[0].length - m[1].length;
573
+ const hit = [...m[1].matchAll(/\.(_[\w-]+)/g)].map((c) => first.get(c[1])).find(Boolean);
574
+ if (!hit && !mapped) continue;
575
+ let out = vlq(at - col);
576
+ if (hit) {
577
+ const [file, { line, column }] = hit;
578
+ const name = source(file);
579
+ const seg = [
580
+ sources.includes(name) ? sources.indexOf(name) : sources.push(name) - 1,
581
+ line - 1,
582
+ column
583
+ ];
584
+ out += seg.map((x, i) => vlq(x - prev[i])).join("");
585
+ prev = seg;
586
+ }
587
+ segs.push(out);
588
+ col = at;
589
+ mapped = !!hit;
590
+ }
591
+ return segs.join(",");
592
+ }).join(";")
593
+ };
594
+ };
595
+ const locate = Effect.fn("cssints.locate")(function* (e, code, id) {
596
+ const file = Predicate.hasProperty(e, "file") && e.file ? e.file : id;
597
+ if (Predicate.hasProperty(e, "offset") && e.offset !== void 0) {
598
+ const text = file === id ? code : yield* Effect.tryPromise(() => readFile(file, "utf8")).pipe(Effect.orElseSucceed(() => void 0));
599
+ if (text !== void 0) Object.assign(e, {
600
+ id: file,
601
+ loc: {
602
+ file,
603
+ ...lineCol(text, e.offset)
604
+ }
605
+ });
606
+ }
607
+ return yield* e;
608
+ });
609
+ function cssints({ inner = false, exclude, devtools = false, opencode = false } = {}) {
610
+ const excluded = [exclude ?? []].flat().length ? createFilter(exclude) : () => false;
611
+ let server;
612
+ let ownServer = false;
613
+ let runner;
614
+ let build = false;
615
+ let root = process.cwd();
616
+ let rootTargets;
617
+ let cssPlugins = [];
618
+ let resolveOf = {};
619
+ const usedBy = /* @__PURE__ */ new Map();
620
+ const depsOf = /* @__PURE__ */ new Map();
621
+ const inflight = /* @__PURE__ */ new Set();
622
+ const siteOf = /* @__PURE__ */ new Map();
623
+ let buildMap = false;
624
+ const callsOf = /* @__PURE__ */ new Map();
625
+ const sheet = Effect.fnUntraced(function* (ids = [...usedBy.keys()]) {
626
+ return yield* renderSheet(ids.flatMap((id) => usedBy.get(id)?.split("\n") ?? []));
627
+ });
628
+ const reloadSheet = Effect.fnUntraced(function* () {
629
+ yield* Effect.sync(() => {
630
+ const env = server?.environments.client;
631
+ const mod = env?.moduleGraph.getModuleById(SHEET);
632
+ if (!env || !mod) return;
633
+ env.moduleGraph.invalidateModule(mod);
634
+ env.reloadModule(mod);
635
+ });
636
+ });
637
+ const record = Effect.fnUntraced(function* (id, classes) {
638
+ const s = [...new Set(classes)].sort().join("\n");
639
+ if (usedBy.get(id) === s) return;
640
+ usedBy.set(id, s);
641
+ yield* reloadSheet();
642
+ });
643
+ const drop = Effect.fnUntraced(function* (id) {
644
+ if (!usedBy.delete(id)) return;
645
+ forget(id);
646
+ siteOf.delete(id);
647
+ callsOf.delete(id);
648
+ yield* reloadSheet();
649
+ });
650
+ const runnerDeps = (env, id, out = /* @__PURE__ */ new Set(), seen = /* @__PURE__ */ new Set()) => {
651
+ const mod = env.moduleGraph.getModuleById(id);
652
+ if (!mod || seen.has(id)) return out;
653
+ seen.add(id);
654
+ for (const dep of mod.importedModules) {
655
+ if (!dep.file || dep.file.includes("node_modules")) continue;
656
+ out.add(dep.file);
657
+ runnerDeps(env, dep.id ?? "", out, seen);
658
+ }
659
+ return out;
660
+ };
661
+ const flushWarnings = Effect.fnUntraced(function* (warn, id, code) {
662
+ const { warnings } = yield* Registry;
663
+ const ws = warnings.splice(0);
664
+ for (const { message, at } of ws) {
665
+ const file = at?.file ?? id;
666
+ const text = at === void 0 ? void 0 : at.file === id ? code : yield* Effect.tryPromise(() => readFile(at.file, "utf8")).pipe(Effect.orElseSucceed(() => void 0));
667
+ const loc = at && text !== void 0 ? {
668
+ file: at.file,
669
+ ...lineCol(text, at.offset)
670
+ } : void 0;
671
+ yield* Effect.sync(() => warn({
672
+ message,
673
+ ...file && { id: file },
674
+ ...loc && { loc }
675
+ }));
676
+ }
677
+ yield* warned(ws.map((w) => w.message), id);
678
+ });
679
+ const clientTransform = Effect.fn("cssints.clientTransform")(function* (code, id, parsed, env, warn, watch) {
680
+ const recorded = Effect.fnUntraced(function* (sites) {
681
+ let runtimes = [];
682
+ const files = parsed.sites.length ? [...(yield* Registry).files] : [];
683
+ if (parsed.sites.every((_, n) => sites.has(n))) {
684
+ const made = yield* moduleEntries(id, sites);
685
+ yield* record(id, made.entries);
686
+ runtimes = made.runtimes;
687
+ }
688
+ return {
689
+ sites,
690
+ runtimes,
691
+ files
692
+ };
693
+ });
694
+ const { sites, runtimes, files } = parsed.sites.length ? yield* evaluate(runner, id, recorded, rootTargets).pipe(Effect.ensuring(flushWarnings(warn, id, code))) : yield* Effect.sync(() => forget(id)).pipe(Effect.andThen(recorded(/* @__PURE__ */ new Map())));
695
+ if (!build || buildMap || devtools === "build") {
696
+ const at = /* @__PURE__ */ new Map();
697
+ for (const [n, s] of parsed.sites.entries()) {
698
+ const loc = lineCol(code, s.start);
699
+ for (const m of sites.get(n)?.matchAll(/_[\w-]+/g) ?? []) if (!at.has(m[0])) at.set(m[0], loc);
700
+ }
701
+ siteOf.set(id, at);
702
+ if (devtools) callsOf.set(id, parsed.sites.map((s, n) => ({
703
+ ...lineCol(code, s.start),
704
+ classes: sites.get(n)?.match(/_[\w-]+/g) ?? [],
705
+ text: code.slice(s.start, s.end)
706
+ })));
707
+ }
708
+ const ms = new MagicString(code);
709
+ if (runtimes.length) ms.prepend(runtimes.map((n) => `import ${Formatter.formatJson(RUNTIME_ID + n)};\n`).join(""));
710
+ if ([...sites.values()].some((r) => r.startsWith("__cv("))) ms.prepend(`import { _cv as __cv } from ${Formatter.formatJson(RUNTIME)};\n`);
711
+ for (const [n, s] of parsed.sites.entries()) {
712
+ const replacement = sites.get(n);
713
+ if (replacement === void 0) return yield* new SiteMissingError({
714
+ message: `cssints: site ${n} in ${id} was not evaluated`,
715
+ file: id,
716
+ site: n,
717
+ offset: s.start
718
+ });
719
+ ms.overwrite(s.start, s.end, replacement);
720
+ }
721
+ for (const decl of parsed.imp.decls) {
722
+ const kept = keptImport(decl, code);
723
+ if (kept) ms.overwrite(decl.start, decl.end, kept);
724
+ else ms.remove(decl.start, decl.end);
725
+ }
726
+ for (const dep of runnerDeps(env, id)) (depsOf.get(dep) ?? depsOf.set(dep, /* @__PURE__ */ new Set()).get(dep)).add(id);
727
+ for (const file of files) {
728
+ const dep = normalizePath(resolve(file));
729
+ (depsOf.get(dep) ?? depsOf.set(dep, /* @__PURE__ */ new Set()).get(dep)).add(id);
730
+ yield* Effect.sync(() => watch(dep));
731
+ }
732
+ return {
733
+ code: ms.toString(),
734
+ map: ms.generateMap({
735
+ hires: true,
736
+ source: id,
737
+ includeContent: true
738
+ })
739
+ };
740
+ });
741
+ const inertJsx = Effect.fn("cssints.inertJsx")(function* (code, id) {
742
+ const jsx = {
743
+ runtime: "classic",
744
+ pragma: "__jsx",
745
+ pragmaFrag: "__jsx"
746
+ };
747
+ return yield* Effect.tryPromise({
748
+ try: () => transformWithOxc(code, id, { jsx }).then((r) => r.code),
749
+ catch: (cause) => new HookError({
750
+ hook: "transform",
751
+ message: `cssints: ${String(cause)}`,
752
+ cause
753
+ })
754
+ });
755
+ });
756
+ const transform = Effect.fn("cssints.transform")(function* (ctx, code, url) {
757
+ const id = url.replace(VERSION, "");
758
+ if (!FILE_RE.test(id) || excluded(id)) return void 0;
759
+ if (!marked(code, id)) {
760
+ if (ctx.environment.name === "client") yield* drop(id);
761
+ return ctx.environment.name === "ssr" && (inner || !build) && /[jt]sx$/.test(id) && !id.includes("node_modules") ? yield* inertJsx(code, id) : void 0;
762
+ }
763
+ if (ctx.environment.name === "ssr" && (inner || !build)) {
764
+ const out = yield* instrument(code, id, false);
765
+ return out && /x$/.test(id) ? yield* inertJsx(out.code, id) : out?.code;
766
+ }
767
+ if (inner) return void 0;
768
+ const parsed = yield* instrument(code, id);
769
+ if (!parsed) return void 0;
770
+ const env = server.environments.ssr;
771
+ runner ??= createServerModuleRunner(env, {
772
+ hmr: false,
773
+ sourcemapInterceptor: "prepareStackTrace",
774
+ evaluator: new DomEvaluator()
775
+ });
776
+ inflight.add(id);
777
+ const watch = (file) => build ? ctx.addWatchFile(file) : void server.watcher.add(file);
778
+ return yield* clientTransform(code, id, parsed, env, (w) => ctx.warn(w), watch).pipe(Effect.ensuring(Effect.sync(() => inflight.delete(id))));
779
+ });
780
+ const startServer = Effect.fn("cssints.buildStart")(function* () {
781
+ server = yield* Effect.tryPromise({
782
+ try: () => createServer({
783
+ configFile: false,
784
+ root,
785
+ logLevel: "warn",
786
+ server: {
787
+ middlewareMode: true,
788
+ watch: null,
789
+ hmr: false
790
+ },
791
+ optimizeDeps: { noDiscovery: true },
792
+ ...resolveOf,
793
+ plugins: [cssints({
794
+ inner: true,
795
+ exclude
796
+ })]
797
+ }),
798
+ catch: (cause) => new HookError({
799
+ hook: "buildStart",
800
+ message: `cssints: could not start the evaluation server: ${String(cause)}`,
801
+ cause
802
+ })
803
+ });
804
+ ownServer = true;
805
+ });
806
+ const stopServer = Effect.fn("cssints.closeBundle")(function* () {
807
+ if (!ownServer || !server) return;
808
+ const s = server;
809
+ yield* Effect.tryPromise({
810
+ try: () => s.close(),
811
+ catch: (cause) => new HookError({
812
+ hook: "closeBundle",
813
+ message: `cssints: could not stop the evaluation server: ${String(cause)}`,
814
+ cause
815
+ })
816
+ });
817
+ server = runner = void 0;
818
+ ownServer = false;
819
+ });
820
+ const renderChunk = Effect.fn("cssints.renderChunk")(function* (ctx, chunk) {
821
+ if (inner || !Object.hasOwn(chunk.modules, SHEET)) return null;
822
+ const [css, cssPost] = cssPlugins;
823
+ const text = yield* sheet();
824
+ const via = (plugin, code) => Effect.tryPromise({
825
+ try: () => callTransform(plugin, ctx, code),
826
+ catch: (cause) => new HookError({
827
+ hook: "renderChunk",
828
+ message: `cssints: the sheet failed in Vite's CSS pipeline: ${String(cause)}`,
829
+ cause
830
+ })
831
+ });
832
+ yield* via(cssPost, (yield* via(css, text).pipe(Effect.withSpan("cssints.lightningcss")))?.code ?? text).pipe(Effect.withSpan("cssints.cssPost"));
833
+ return null;
834
+ });
835
+ const emitMaps = Effect.fn("cssints.generateBundle")(function* (ctx, bundle, dir) {
836
+ for (const asset of Object.values(bundle)) {
837
+ if (asset.type !== "asset" || !asset.fileName.endsWith(".css")) continue;
838
+ const text = Predicate.isString(asset.source) ? asset.source : new TextDecoder().decode(asset.source);
839
+ const at = resolve(dir, asset.fileName, "..");
840
+ const map = {
841
+ ...sheetMap(text, siteOf, (file) => relative(at, file.replace(/\?.*/, ""))),
842
+ file: basename(asset.fileName)
843
+ };
844
+ if (!map.sources.length) continue;
845
+ const json = Formatter.formatJson(map);
846
+ const url = buildMap === "inline" ? `data:application/json;base64,${Buffer.from(json).toString("base64")}` : `${map.file}.map`;
847
+ if (buildMap !== "inline") yield* Effect.sync(() => ctx.emitFile({
848
+ type: "asset",
849
+ fileName: `${asset.fileName}.map`,
850
+ source: json
851
+ }));
852
+ if (buildMap !== "hidden") asset.source = `${text}\n/*# sourceMappingURL=${url} */`;
853
+ }
854
+ });
855
+ const buildEnd = Effect.fn("cssints.buildEnd")(function* (warn) {
856
+ yield* verifyChecks(() => true).pipe(Effect.catch((e) => locate(e, "", "")), Effect.ensuring(flushWarnings(warn)));
857
+ });
858
+ const hotUpdate = Effect.fn("cssints.hotUpdate")(function* (env, file, modules) {
859
+ if (env.name !== "client") return void 0;
860
+ yield* Effect.sync(() => forgetWarnings([file]));
861
+ const graph = env.moduleGraph;
862
+ const affected = [.../* @__PURE__ */ new Set([...depsOf.get(file) ?? [], ...inflight])].flatMap((id) => graph.getModuleById(id) ?? []);
863
+ yield* Effect.sync(() => affected.forEach((m) => {
864
+ graph.invalidateModule(m);
865
+ if (m.id) forget(m.id);
866
+ }));
867
+ return [...modules, ...affected];
868
+ });
869
+ const main = {
870
+ name: "cssints",
871
+ enforce: "pre",
872
+ config(user) {
873
+ const names = Effect.runSync(packagesOnCssints(resolve(user.root ?? process.cwd())));
874
+ return {
875
+ optimizeDeps: { exclude: names },
876
+ ssr: { noExternal: names }
877
+ };
878
+ },
879
+ api: {
880
+ sheet: (ids) => Effect.runSync(sheet(ids)),
881
+ forgetWarnings: (files) => forgetWarnings(files)
882
+ },
883
+ configResolved(config) {
884
+ build = config.command === "build";
885
+ buildMap = build && !inner && config.build.sourcemap;
886
+ root = config.root;
887
+ if (!inner) rootTargets = Effect.runSync(targets$1(void 0, root));
888
+ const ssr = config.environments.ssr?.resolve;
889
+ resolveOf = {
890
+ resolve: { alias: config.resolve.alias },
891
+ ...ssr && { environments: { ssr: { resolve: {
892
+ conditions: ssr.conditions,
893
+ externalConditions: ssr.externalConditions
894
+ } } } }
895
+ };
896
+ cssPlugins = ["vite:css", "vite:css-post"].map((n) => config.plugins.find((p) => p.name === n));
897
+ },
898
+ configureServer(s) {
899
+ server = s;
900
+ if (inner) return;
901
+ s.environments.client.hot.on("cssints:sheet", (v) => {
902
+ if (!s.environments.client.moduleGraph.getModuleById(SHEET)?.transformResult?.code.includes(v)) Effect.runSync(reloadSheet());
903
+ });
904
+ },
905
+ buildStart() {
906
+ if (inner) return;
907
+ if (build) forgetWarnings();
908
+ if (server) return;
909
+ return run(hook("vite.buildStart", root, startServer()));
910
+ },
911
+ buildEnd() {
912
+ if (build && !inner) return run(hook("vite.buildEnd", root, buildEnd((w) => this.warn(w))));
913
+ },
914
+ closeBundle() {
915
+ return run(hook("vite.closeBundle", root, stopServer())).then(() => inner ? void 0 : closeTrace());
916
+ },
917
+ resolveId(id) {
918
+ if (id === SHEET_IMPORT) return SHEET;
919
+ if (id.startsWith("virtual:cssints/runtime/")) return `\0${id}`;
920
+ },
921
+ load(id) {
922
+ if (id === SHEET) {
923
+ if (build) return LAYERS;
924
+ const code = runSync(hook("vite.load", id, sheet()));
925
+ return {
926
+ code,
927
+ map: sheetMap(code, siteOf)
928
+ };
929
+ }
930
+ if (id.startsWith(`\0virtual:cssints/runtime/`)) return runSync(runtimeModule(id.slice(RUNTIME_ID.length + 1)));
931
+ },
932
+ renderChunk(_, chunk) {
933
+ return run(hook("vite.renderChunk", chunk.fileName, renderChunk(this, chunk)));
934
+ },
935
+ generateBundle: {
936
+ order: "post",
937
+ handler(out, bundle) {
938
+ if (buildMap) runSync(hook("vite.generateBundle", root, emitMaps(this, bundle, resolve(root, out.dir ?? "dist"))));
939
+ }
940
+ },
941
+ transform: {
942
+ order: "pre",
943
+ handler(code, id) {
944
+ return run(hook("vite.transform", id, transform(this, code, id).pipe(Effect.catch((e) => locate(e, code, id))), this.environment.name));
945
+ }
946
+ },
947
+ hotUpdate({ file, modules }) {
948
+ return runSync(hook("vite.hotUpdate", file, hotUpdate(this.environment, file, modules)));
949
+ }
950
+ };
951
+ const version = {
952
+ name: "cssints:sheet-version",
953
+ apply: "serve",
954
+ transform: {
955
+ order: "post",
956
+ handler(code, id) {
957
+ if (id === SHEET && this.environment.name === "client") return `${code}\nimport.meta.hot.send("cssints:sheet", ${Formatter.formatJson(hash(code))});`;
958
+ }
959
+ }
960
+ };
961
+ if (!devtools || inner) return [main, version];
962
+ const dev = devtoolsPlugin(usedBy, callsOf, opencode ? opencode === true ? {} : opencode : void 0);
963
+ return devtools === "build" ? [
964
+ main,
965
+ version,
966
+ dev,
967
+ devtoolsBuildPlugin(usedBy, callsOf)
968
+ ] : [
969
+ main,
970
+ version,
971
+ dev
972
+ ];
973
+ }
974
+ const callTransform = (plugin, ctx, code) => {
975
+ const t = plugin?.transform;
976
+ const handler = typeof t === "function" ? t : t?.handler;
977
+ return Promise.resolve(handler?.call(ctx, code, SHEET));
978
+ };
979
+ //#endregion
980
+ export { addGlobal, addLayers, cssTarget, cssints as default, globalEntries, instrument, layerEntries, renderSheet, targets };