@typestyles/vite 0.5.4 → 0.6.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 CHANGED
@@ -63,13 +63,13 @@ export default defineConfig({
63
63
  });
64
64
  ```
65
65
 
66
- **3. Link the CSS** in your HTML shell (optional — the plugin auto-injects this during dev and build when extraction is enabled):
66
+ **3. Link the CSS** in your HTML shell (optional — the plugin injects this during dev and build when extraction is enabled):
67
67
 
68
68
  ```html
69
69
  <link rel="stylesheet" href="/typestyles.css" />
70
70
  ```
71
71
 
72
- During `vite dev`, styles still inject at runtime and HMR works. During `vite build`, the plugin emits `typestyles.css`, defines `__TYPESTYLES_RUNTIME_DISABLED__`, and the browser loads one cacheable stylesheet.
72
+ During `vite dev`, styles still inject at runtime and HMR works, and the dev server serves that stable URL. During `vite build`, the plugin emits a content-hashed asset (Vite's `assetFileNames`, usually `assets/typestyles-<hash>.css`), rewrites the link to that href, and defines `__TYPESTYLES_RUNTIME_DISABLED__`. The hashed URL cache-busts on each deploy. Set `extract.fileName` to a literal such as `typestyles.css` to keep a fixed path.
73
73
 
74
74
  Example app: [`examples/vite-app`](../../examples/vite-app)
75
75
 
@@ -116,7 +116,13 @@ typestyles({
116
116
  extract?: {
117
117
  /** Explicit entry files relative to project root */
118
118
  modules?: string[];
119
- /** Output asset name. Default: 'typestyles.css' */
119
+ /**
120
+ * Production CSS path.
121
+ * Omitted: content-hashed asset (`assets/typestyles-<hash>.css`).
122
+ * A literal such as `'typestyles.css'` opts out of hashing.
123
+ * `[name]`, `[hash]`, `[hash:N]`, `[ext]`, and `[extname]` are expanded.
124
+ * Dev always serves the stable unhashed URL.
125
+ */
120
126
  fileName?: string;
121
127
  };
122
128
  });
@@ -130,7 +136,7 @@ Use when you have multiple entry files or non-standard paths:
130
136
  typestyles({
131
137
  extract: {
132
138
  modules: ['src/styles/tokens.ts', 'src/styles/components.ts'],
133
- fileName: 'assets/typestyles.css',
139
+ fileName: 'assets/typestyles-[hash].css',
134
140
  },
135
141
  });
136
142
  ```
@@ -147,7 +153,7 @@ Even with a convention entry present, this keeps `<style>` injection in producti
147
153
 
148
154
  **HMR:** On each `.ts`/`.tsx` module that registers typestyles APIs, the plugin injects `import.meta.hot` accept/dispose handlers. On dispose, it calls `invalidateKeys` from `typestyles/hmr` so stale rules are removed before the module re-executes. HMR code is only injected during `vite dev`, not in production bundles.
149
155
 
150
- **Extraction:** On `vite build`, matching entry modules are bundled and executed in Node via `@typestyles/build-runner`. The collected CSS is emitted as a static asset. In dev, the same extraction runs on demand when the browser requests `/typestyles.css` so your `<link>` href works without SPA fallback returning HTML.
156
+ **Extraction:** On `vite build`, matching entry modules are bundled and executed in Node via `@typestyles/build-runner`. The collected CSS is emitted as a content-hashed asset so a new deploy cannot be served with a cached copy of the previous stylesheet. In dev, extraction runs on demand when the browser requests `/typestyles.css` so your `<link>` href works without SPA fallback returning HTML.
151
157
 
152
158
  **Duplicate detection:** The plugin scans every source file for namespace strings (`recipe({ name: 'button' })` → `.button-`). Collisions across files fail the build with a clear error.
153
159
 
@@ -155,14 +161,14 @@ Even with a convention entry present, this keeps `<style>` injection in producti
155
161
 
156
162
  On `vite build`, the plugin fails if a local module reachable from the app calls `recipe()` and that file is missing from the extract entry. The error names the module and the recipe `name`. Import the module from the convention entry, or set `coverage: false` when the production CSS is meant to omit it.
157
163
 
158
- Tokens, themes, and `style()` calls are still execute-and-collect: anything the entry file does not run is omitted. After `vite build`, assert on the emitted file:
164
+ Tokens, themes, and `style()` calls are still execute-and-collect: anything the entry file does not run is omitted. The default build filename includes a content hash. Point `verifyTypestylesBuild` at that file, or set `extract.fileName` to a literal path first:
159
165
 
160
166
  ```ts
161
167
  import { verifyTypestylesBuild } from '@typestyles/build-runner';
162
168
 
163
169
  verifyTypestylesBuild({
164
170
  root: process.cwd(),
165
- cssFile: 'dist/typestyles.css',
171
+ cssFile: 'dist/assets/typestyles-<hash>.css',
166
172
  requiredCssSubstrings: ['.button-base'],
167
173
  });
168
174
  ```
package/dist/index.cjs CHANGED
@@ -2,18 +2,49 @@ Object.defineProperties(exports, {
2
2
  __esModule: { value: true },
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
+ let node_crypto = require("node:crypto");
5
6
  let node_path = require("node:path");
6
7
  let _typestyles_build_runner = require("@typestyles/build-runner");
7
8
  //#region src/index.ts
8
9
  function resolveExtractModulesForVite(root, extract) {
9
10
  return (0, _typestyles_build_runner.resolveExtractModules)(root, extract);
10
11
  }
11
- function resolveTypestylesCssHref(base, fileName) {
12
+ const DEFAULT_CSS_FILE_NAME = "typestyles.css";
13
+ const PARKED_CSS_HREF = "#__typestyles_css__";
14
+ function resolveTypestylesCssHref(base, fileName, htmlPath) {
12
15
  const normalizedFileName = fileName.replace(/^\//, "");
16
+ if (base.startsWith(".")) {
17
+ const fromDir = node_path.posix.dirname(`/${(htmlPath ?? "index.html").replace(/^\//, "")}`);
18
+ const relative = node_path.posix.relative(fromDir, `/${normalizedFileName}`);
19
+ return relative.startsWith(".") ? relative : `./${relative}`;
20
+ }
13
21
  const normalizedBase = base.replace(/\/$/, "") || "";
14
22
  if (normalizedBase === "" || normalizedBase === "/") return `/${normalizedFileName}`;
15
23
  return `${normalizedBase}/${normalizedFileName}`;
16
24
  }
25
+ function cssFileNameHasPlaceholder(fileName) {
26
+ return /\[(?:hash(?::\d+)?|name|extname|ext)\]/.test(fileName);
27
+ }
28
+ function stableDevCssFileName(fileName) {
29
+ if (!fileName) return DEFAULT_CSS_FILE_NAME;
30
+ const normalized = fileName.replace(/^\//, "");
31
+ if (!cssFileNameHasPlaceholder(normalized)) return normalized;
32
+ return normalized.replace(/-?\[hash(?::\d+)?\]/g, "").replace(/\[name\]/g, "typestyles").replace(/\[extname\]/g, ".css").replace(/\[ext\]/g, "css");
33
+ }
34
+ function renderCssFileName(pattern, source) {
35
+ const hash = (0, node_crypto.createHash)("sha256").update(source).digest("base64url");
36
+ return pattern.replace(/\[(hash(?::(\d+))?|name|extname|ext)\]/g, (_match, kind, size) => {
37
+ if (kind === "name") return "typestyles";
38
+ if (kind === "extname") return ".css";
39
+ if (kind === "ext") return "css";
40
+ const length = size ? Number(size) : 8;
41
+ const clamped = Math.min(Math.max(1, length), hash.length);
42
+ return hash.slice(0, clamped);
43
+ });
44
+ }
45
+ function isTypestylesStylesheetHref(href, cssHref, bareName) {
46
+ return href === cssHref || href.endsWith(`/${bareName}`) || href === bareName || href === `./${bareName}`;
47
+ }
17
48
  function htmlLinksTypestylesCss(html, cssHref, fileName) {
18
49
  const bareName = fileName.replace(/^\//, "");
19
50
  const linkPattern = /<link\b[^>]*\brel=["']stylesheet["'][^>]*>/gi;
@@ -21,10 +52,28 @@ function htmlLinksTypestylesCss(html, cssHref, fileName) {
21
52
  for (const match of html.matchAll(linkPattern)) {
22
53
  const href = match[0].match(hrefPattern)?.[1];
23
54
  if (!href) continue;
24
- if (href === cssHref || href.endsWith(`/${bareName}`) || href === bareName || href === `./${bareName}`) return true;
55
+ if (isTypestylesStylesheetHref(href, cssHref, bareName)) return true;
25
56
  }
26
57
  return false;
27
58
  }
59
+ function retargetTypestylesStylesheet(html, fileName, nextHref) {
60
+ const bareNames = [...new Set([fileName.replace(/^\//, ""), DEFAULT_CSS_FILE_NAME])];
61
+ return html.replace(/<link\b[^>]*>/gi, (tag) => {
62
+ if (!/\brel=["']stylesheet["']/i.test(tag)) return tag;
63
+ return tag.replace(/\bhref=(["'])([^"']+)\1/i, (attr, quote, href) => {
64
+ if (!bareNames.some((name) => isTypestylesStylesheetHref(href, `/${name}`, name))) return attr;
65
+ return `href=${quote}${nextHref}${quote}`;
66
+ });
67
+ });
68
+ }
69
+ function rebaseRelativeCssUrls(css, depth) {
70
+ if (depth <= 0) return css;
71
+ const up = "../".repeat(depth);
72
+ return css.replace(/url\(\s*(['"]?)([^'")]+?)\1\s*\)/g, (match, quote, url) => {
73
+ if (/^(?:[a-z][a-z0-9+.-]*:|\/|#)/i.test(url)) return match;
74
+ return `url(${quote}${up}${url.replace(/^\.\//, "")}${quote})`;
75
+ });
76
+ }
28
77
  function formatUnextractedRecipeError(missing, extractEntries) {
29
78
  const entries = extractEntries.map((entry) => entry.replace(/\\/g, "/")).join(", ");
30
79
  return [
@@ -48,6 +97,7 @@ function typestylesPlugin(options = {}) {
48
97
  const recipeModules = new Map();
49
98
  let devExtractCss = null;
50
99
  let devExtractInFlight = null;
100
+ let builtCssFileName = null;
51
101
  return {
52
102
  name: "typestyles",
53
103
  enforce: "pre",
@@ -68,7 +118,7 @@ function typestylesPlugin(options = {}) {
68
118
  configureServer(server) {
69
119
  if (resolvedExtractModules.length === 0) return;
70
120
  if (resolvedMode === "runtime") return;
71
- const fileName = extract?.fileName ?? "typestyles.css";
121
+ const fileName = stableDevCssFileName(extract?.fileName);
72
122
  const invalidateDevExtract = () => {
73
123
  devExtractCss = null;
74
124
  devExtractInFlight = null;
@@ -103,7 +153,8 @@ function typestylesPlugin(options = {}) {
103
153
  }
104
154
  if (!devExtractInFlight) devExtractInFlight = (0, _typestyles_build_runner.runTypestylesBuild)({
105
155
  root,
106
- modules: resolvedExtractModules
156
+ modules: resolvedExtractModules,
157
+ sourceComments: extract?.sourceComments
107
158
  }).then((css) => {
108
159
  devExtractCss = css;
109
160
  return css;
@@ -121,6 +172,13 @@ function typestylesPlugin(options = {}) {
121
172
  });
122
173
  },
123
174
  transform(code, id) {
175
+ if (isBuildCommand && resolvedMode !== "runtime" && resolvedExtractModules.length > 0 && id.split("?")[0]?.endsWith(".html")) {
176
+ const parked = retargetTypestylesStylesheet(code, stableDevCssFileName(extract?.fileName), PARKED_CSS_HREF);
177
+ if (parked !== code) return {
178
+ code: parked,
179
+ map: null
180
+ };
181
+ }
124
182
  if (!/\.[jt]sx?$/.test(id)) return null;
125
183
  if (id.includes("node_modules")) return null;
126
184
  const { keys, prefixes, recipeNames } = (0, _typestyles_build_runner.extractNamespaces)(code);
@@ -150,14 +208,30 @@ if (import.meta.hot) {
150
208
  };
151
209
  },
152
210
  transformIndexHtml: {
153
- order: "pre",
154
- handler(html) {
211
+ order: "post",
212
+ handler(html, ctx) {
155
213
  if (resolvedExtractModules.length === 0) return;
156
214
  if (resolvedMode === "runtime") return;
157
215
  if (!resolvedConfig) return;
158
- const fileName = extract?.fileName ?? "typestyles.css";
159
- const href = resolveTypestylesCssHref(resolvedConfig.base, fileName);
160
- if (htmlLinksTypestylesCss(html, href, fileName)) return;
216
+ const stableFileName = stableDevCssFileName(extract?.fileName);
217
+ if (!isBuildCommand) {
218
+ const href = resolveTypestylesCssHref(resolvedConfig.base, stableFileName);
219
+ if (htmlLinksTypestylesCss(html, href, stableFileName)) return;
220
+ return [{
221
+ tag: "link",
222
+ attrs: {
223
+ rel: "stylesheet",
224
+ href
225
+ },
226
+ injectTo: "head"
227
+ }];
228
+ }
229
+ if (!builtCssFileName) return;
230
+ const href = resolveTypestylesCssHref(resolvedConfig.base, builtCssFileName, ctx?.path);
231
+ if (html.includes(PARKED_CSS_HREF)) return html.split(PARKED_CSS_HREF).join(href);
232
+ if (htmlLinksTypestylesCss(html, href, builtCssFileName)) return;
233
+ const retargeted = retargetTypestylesStylesheet(html, stableFileName, href);
234
+ if (retargeted !== html) return retargeted;
161
235
  return [{
162
236
  tag: "link",
163
237
  attrs: {
@@ -168,13 +242,13 @@ if (import.meta.hot) {
168
242
  }];
169
243
  }
170
244
  },
171
- async generateBundle() {
245
+ async generateBundle(_options, bundle) {
172
246
  if (!isBuildCommand) return;
173
247
  if (resolvedMode === "runtime") return;
174
248
  if (!resolvedExtractModules.length) return;
175
249
  if (!resolvedConfig) return;
176
250
  const root = resolvedConfig.root ?? process.cwd();
177
- const fileName = extract?.fileName ?? "typestyles.css";
251
+ const requestedFileName = extract?.fileName?.replace(/^\//, "");
178
252
  if (coverage && recipeModules.size > 0) {
179
253
  let missing = [];
180
254
  try {
@@ -198,13 +272,33 @@ if (import.meta.hot) {
198
272
  try {
199
273
  const css = await (0, _typestyles_build_runner.runTypestylesBuild)({
200
274
  root,
201
- modules: resolvedExtractModules
202
- });
203
- this.emitFile({
204
- type: "asset",
205
- fileName,
206
- source: css
275
+ modules: resolvedExtractModules,
276
+ sourceComments: extract?.sourceComments
207
277
  });
278
+ if (requestedFileName && cssFileNameHasPlaceholder(requestedFileName)) {
279
+ builtCssFileName = renderCssFileName(requestedFileName, css);
280
+ this.emitFile({
281
+ type: "asset",
282
+ fileName: builtCssFileName,
283
+ source: css
284
+ });
285
+ } else if (requestedFileName) {
286
+ builtCssFileName = requestedFileName;
287
+ this.emitFile({
288
+ type: "asset",
289
+ fileName: requestedFileName,
290
+ source: css
291
+ });
292
+ } else {
293
+ const referenceId = this.emitFile({
294
+ type: "asset",
295
+ name: DEFAULT_CSS_FILE_NAME,
296
+ source: css
297
+ });
298
+ builtCssFileName = this.getFileName(referenceId);
299
+ const asset = bundle?.[builtCssFileName];
300
+ if (asset?.type === "asset" && typeof asset.source === "string") asset.source = rebaseRelativeCssUrls(asset.source, builtCssFileName.split("/").length - 1);
301
+ }
208
302
  } catch (err) {
209
303
  this.error(`[typestyles] Failed to extract CSS: ${err instanceof Error ? err.message : String(err)}`);
210
304
  }
package/dist/index.d.cts CHANGED
@@ -36,10 +36,11 @@ export interface TypestylesPluginOptions {
36
36
  *
37
37
  * When omitted and at least one extraction module is resolved (explicit `extract.modules`, or a
38
38
  * discovered convention entry file), defaults to `"build"`: `vite dev` keeps runtime
39
- * injection + HMR (runtime is only disabled during `vite build`), serves the same extracted CSS
40
- * at `extract.fileName` so `<link href="/typestyles.css">` is valid (avoids SPA fallback
41
- * returning HTML for that URL), and production emits the CSS file. If no modules are resolved,
42
- * defaults to `"runtime"`.
39
+ * injection + HMR (runtime is only disabled during `vite build`) and serves extracted CSS at a
40
+ * stable URL (`/typestyles.css`, unless `extract.fileName` sets another path) so
41
+ * `<link href="/typestyles.css">` is valid (avoids SPA fallback returning HTML for that URL).
42
+ * Production emits a content-hashed CSS asset and points the HTML link at it. If no modules
43
+ * are resolved, defaults to `"runtime"`.
43
44
  */
44
45
  mode?: TypestylesIntegrationMode;
45
46
  /**
@@ -51,7 +52,9 @@ export interface TypestylesPluginOptions {
51
52
  extract?: TypestylesExtractOptions;
52
53
  }
53
54
  /** Public URL path for the extracted CSS asset (respects Vite `base`). */
54
- export declare function resolveTypestylesCssHref(base: string, fileName: string): string;
55
+ export declare function resolveTypestylesCssHref(base: string, fileName: string,
56
+ /** Root-relative HTML path (e.g. `/nested/index.html`); only used when `base` is relative. */
57
+ htmlPath?: string): string;
55
58
  /** True when `html` already links the extracted stylesheet (avoids duplicate injection). */
56
59
  export declare function htmlLinksTypestylesCss(html: string, cssHref: string, fileName: string): boolean;
57
60
  /**
package/dist/index.d.ts CHANGED
@@ -36,10 +36,11 @@ export interface TypestylesPluginOptions {
36
36
  *
37
37
  * When omitted and at least one extraction module is resolved (explicit `extract.modules`, or a
38
38
  * discovered convention entry file), defaults to `"build"`: `vite dev` keeps runtime
39
- * injection + HMR (runtime is only disabled during `vite build`), serves the same extracted CSS
40
- * at `extract.fileName` so `<link href="/typestyles.css">` is valid (avoids SPA fallback
41
- * returning HTML for that URL), and production emits the CSS file. If no modules are resolved,
42
- * defaults to `"runtime"`.
39
+ * injection + HMR (runtime is only disabled during `vite build`) and serves extracted CSS at a
40
+ * stable URL (`/typestyles.css`, unless `extract.fileName` sets another path) so
41
+ * `<link href="/typestyles.css">` is valid (avoids SPA fallback returning HTML for that URL).
42
+ * Production emits a content-hashed CSS asset and points the HTML link at it. If no modules
43
+ * are resolved, defaults to `"runtime"`.
43
44
  */
44
45
  mode?: TypestylesIntegrationMode;
45
46
  /**
@@ -51,7 +52,9 @@ export interface TypestylesPluginOptions {
51
52
  extract?: TypestylesExtractOptions;
52
53
  }
53
54
  /** Public URL path for the extracted CSS asset (respects Vite `base`). */
54
- export declare function resolveTypestylesCssHref(base: string, fileName: string): string;
55
+ export declare function resolveTypestylesCssHref(base: string, fileName: string,
56
+ /** Root-relative HTML path (e.g. `/nested/index.html`); only used when `base` is relative. */
57
+ htmlPath?: string): string;
55
58
  /** True when `html` already links the extracted stylesheet (avoids duplicate injection). */
56
59
  export declare function htmlLinksTypestylesCss(html: string, cssHref: string, fileName: string): boolean;
57
60
  /**
package/dist/index.js CHANGED
@@ -1,15 +1,46 @@
1
- import { resolve } from "node:path";
1
+ import { createHash } from "node:crypto";
2
+ import { posix, resolve } from "node:path";
2
3
  import { DEFAULT_EXTRACT_MODULE_CANDIDATES, discoverDefaultExtractModules, extractNamespaces, findUnextractedRecipes, moduleNeedsOverrideHmr, moduleNeedsOverrideHmr as moduleNeedsOverrideHmr$1, reportDuplicateNamespaces, resolveExtractMode, resolveExtractModules, runTypestylesBuild } from "@typestyles/build-runner";
3
4
  //#region src/index.ts
4
5
  function resolveExtractModulesForVite(root, extract) {
5
6
  return resolveExtractModules(root, extract);
6
7
  }
7
- function resolveTypestylesCssHref(base, fileName) {
8
+ const DEFAULT_CSS_FILE_NAME = "typestyles.css";
9
+ const PARKED_CSS_HREF = "#__typestyles_css__";
10
+ function resolveTypestylesCssHref(base, fileName, htmlPath) {
8
11
  const normalizedFileName = fileName.replace(/^\//, "");
12
+ if (base.startsWith(".")) {
13
+ const fromDir = posix.dirname(`/${(htmlPath ?? "index.html").replace(/^\//, "")}`);
14
+ const relative = posix.relative(fromDir, `/${normalizedFileName}`);
15
+ return relative.startsWith(".") ? relative : `./${relative}`;
16
+ }
9
17
  const normalizedBase = base.replace(/\/$/, "") || "";
10
18
  if (normalizedBase === "" || normalizedBase === "/") return `/${normalizedFileName}`;
11
19
  return `${normalizedBase}/${normalizedFileName}`;
12
20
  }
21
+ function cssFileNameHasPlaceholder(fileName) {
22
+ return /\[(?:hash(?::\d+)?|name|extname|ext)\]/.test(fileName);
23
+ }
24
+ function stableDevCssFileName(fileName) {
25
+ if (!fileName) return DEFAULT_CSS_FILE_NAME;
26
+ const normalized = fileName.replace(/^\//, "");
27
+ if (!cssFileNameHasPlaceholder(normalized)) return normalized;
28
+ return normalized.replace(/-?\[hash(?::\d+)?\]/g, "").replace(/\[name\]/g, "typestyles").replace(/\[extname\]/g, ".css").replace(/\[ext\]/g, "css");
29
+ }
30
+ function renderCssFileName(pattern, source) {
31
+ const hash = createHash("sha256").update(source).digest("base64url");
32
+ return pattern.replace(/\[(hash(?::(\d+))?|name|extname|ext)\]/g, (_match, kind, size) => {
33
+ if (kind === "name") return "typestyles";
34
+ if (kind === "extname") return ".css";
35
+ if (kind === "ext") return "css";
36
+ const length = size ? Number(size) : 8;
37
+ const clamped = Math.min(Math.max(1, length), hash.length);
38
+ return hash.slice(0, clamped);
39
+ });
40
+ }
41
+ function isTypestylesStylesheetHref(href, cssHref, bareName) {
42
+ return href === cssHref || href.endsWith(`/${bareName}`) || href === bareName || href === `./${bareName}`;
43
+ }
13
44
  function htmlLinksTypestylesCss(html, cssHref, fileName) {
14
45
  const bareName = fileName.replace(/^\//, "");
15
46
  const linkPattern = /<link\b[^>]*\brel=["']stylesheet["'][^>]*>/gi;
@@ -17,10 +48,28 @@ function htmlLinksTypestylesCss(html, cssHref, fileName) {
17
48
  for (const match of html.matchAll(linkPattern)) {
18
49
  const href = match[0].match(hrefPattern)?.[1];
19
50
  if (!href) continue;
20
- if (href === cssHref || href.endsWith(`/${bareName}`) || href === bareName || href === `./${bareName}`) return true;
51
+ if (isTypestylesStylesheetHref(href, cssHref, bareName)) return true;
21
52
  }
22
53
  return false;
23
54
  }
55
+ function retargetTypestylesStylesheet(html, fileName, nextHref) {
56
+ const bareNames = [...new Set([fileName.replace(/^\//, ""), DEFAULT_CSS_FILE_NAME])];
57
+ return html.replace(/<link\b[^>]*>/gi, (tag) => {
58
+ if (!/\brel=["']stylesheet["']/i.test(tag)) return tag;
59
+ return tag.replace(/\bhref=(["'])([^"']+)\1/i, (attr, quote, href) => {
60
+ if (!bareNames.some((name) => isTypestylesStylesheetHref(href, `/${name}`, name))) return attr;
61
+ return `href=${quote}${nextHref}${quote}`;
62
+ });
63
+ });
64
+ }
65
+ function rebaseRelativeCssUrls(css, depth) {
66
+ if (depth <= 0) return css;
67
+ const up = "../".repeat(depth);
68
+ return css.replace(/url\(\s*(['"]?)([^'")]+?)\1\s*\)/g, (match, quote, url) => {
69
+ if (/^(?:[a-z][a-z0-9+.-]*:|\/|#)/i.test(url)) return match;
70
+ return `url(${quote}${up}${url.replace(/^\.\//, "")}${quote})`;
71
+ });
72
+ }
24
73
  function formatUnextractedRecipeError(missing, extractEntries) {
25
74
  const entries = extractEntries.map((entry) => entry.replace(/\\/g, "/")).join(", ");
26
75
  return [
@@ -44,6 +93,7 @@ function typestylesPlugin(options = {}) {
44
93
  const recipeModules = new Map();
45
94
  let devExtractCss = null;
46
95
  let devExtractInFlight = null;
96
+ let builtCssFileName = null;
47
97
  return {
48
98
  name: "typestyles",
49
99
  enforce: "pre",
@@ -64,7 +114,7 @@ function typestylesPlugin(options = {}) {
64
114
  configureServer(server) {
65
115
  if (resolvedExtractModules.length === 0) return;
66
116
  if (resolvedMode === "runtime") return;
67
- const fileName = extract?.fileName ?? "typestyles.css";
117
+ const fileName = stableDevCssFileName(extract?.fileName);
68
118
  const invalidateDevExtract = () => {
69
119
  devExtractCss = null;
70
120
  devExtractInFlight = null;
@@ -99,7 +149,8 @@ function typestylesPlugin(options = {}) {
99
149
  }
100
150
  if (!devExtractInFlight) devExtractInFlight = runTypestylesBuild({
101
151
  root,
102
- modules: resolvedExtractModules
152
+ modules: resolvedExtractModules,
153
+ sourceComments: extract?.sourceComments
103
154
  }).then((css) => {
104
155
  devExtractCss = css;
105
156
  return css;
@@ -117,6 +168,13 @@ function typestylesPlugin(options = {}) {
117
168
  });
118
169
  },
119
170
  transform(code, id) {
171
+ if (isBuildCommand && resolvedMode !== "runtime" && resolvedExtractModules.length > 0 && id.split("?")[0]?.endsWith(".html")) {
172
+ const parked = retargetTypestylesStylesheet(code, stableDevCssFileName(extract?.fileName), PARKED_CSS_HREF);
173
+ if (parked !== code) return {
174
+ code: parked,
175
+ map: null
176
+ };
177
+ }
120
178
  if (!/\.[jt]sx?$/.test(id)) return null;
121
179
  if (id.includes("node_modules")) return null;
122
180
  const { keys, prefixes, recipeNames } = extractNamespaces(code);
@@ -146,14 +204,30 @@ if (import.meta.hot) {
146
204
  };
147
205
  },
148
206
  transformIndexHtml: {
149
- order: "pre",
150
- handler(html) {
207
+ order: "post",
208
+ handler(html, ctx) {
151
209
  if (resolvedExtractModules.length === 0) return;
152
210
  if (resolvedMode === "runtime") return;
153
211
  if (!resolvedConfig) return;
154
- const fileName = extract?.fileName ?? "typestyles.css";
155
- const href = resolveTypestylesCssHref(resolvedConfig.base, fileName);
156
- if (htmlLinksTypestylesCss(html, href, fileName)) return;
212
+ const stableFileName = stableDevCssFileName(extract?.fileName);
213
+ if (!isBuildCommand) {
214
+ const href = resolveTypestylesCssHref(resolvedConfig.base, stableFileName);
215
+ if (htmlLinksTypestylesCss(html, href, stableFileName)) return;
216
+ return [{
217
+ tag: "link",
218
+ attrs: {
219
+ rel: "stylesheet",
220
+ href
221
+ },
222
+ injectTo: "head"
223
+ }];
224
+ }
225
+ if (!builtCssFileName) return;
226
+ const href = resolveTypestylesCssHref(resolvedConfig.base, builtCssFileName, ctx?.path);
227
+ if (html.includes(PARKED_CSS_HREF)) return html.split(PARKED_CSS_HREF).join(href);
228
+ if (htmlLinksTypestylesCss(html, href, builtCssFileName)) return;
229
+ const retargeted = retargetTypestylesStylesheet(html, stableFileName, href);
230
+ if (retargeted !== html) return retargeted;
157
231
  return [{
158
232
  tag: "link",
159
233
  attrs: {
@@ -164,13 +238,13 @@ if (import.meta.hot) {
164
238
  }];
165
239
  }
166
240
  },
167
- async generateBundle() {
241
+ async generateBundle(_options, bundle) {
168
242
  if (!isBuildCommand) return;
169
243
  if (resolvedMode === "runtime") return;
170
244
  if (!resolvedExtractModules.length) return;
171
245
  if (!resolvedConfig) return;
172
246
  const root = resolvedConfig.root ?? process.cwd();
173
- const fileName = extract?.fileName ?? "typestyles.css";
247
+ const requestedFileName = extract?.fileName?.replace(/^\//, "");
174
248
  if (coverage && recipeModules.size > 0) {
175
249
  let missing = [];
176
250
  try {
@@ -194,13 +268,33 @@ if (import.meta.hot) {
194
268
  try {
195
269
  const css = await runTypestylesBuild({
196
270
  root,
197
- modules: resolvedExtractModules
198
- });
199
- this.emitFile({
200
- type: "asset",
201
- fileName,
202
- source: css
271
+ modules: resolvedExtractModules,
272
+ sourceComments: extract?.sourceComments
203
273
  });
274
+ if (requestedFileName && cssFileNameHasPlaceholder(requestedFileName)) {
275
+ builtCssFileName = renderCssFileName(requestedFileName, css);
276
+ this.emitFile({
277
+ type: "asset",
278
+ fileName: builtCssFileName,
279
+ source: css
280
+ });
281
+ } else if (requestedFileName) {
282
+ builtCssFileName = requestedFileName;
283
+ this.emitFile({
284
+ type: "asset",
285
+ fileName: requestedFileName,
286
+ source: css
287
+ });
288
+ } else {
289
+ const referenceId = this.emitFile({
290
+ type: "asset",
291
+ name: DEFAULT_CSS_FILE_NAME,
292
+ source: css
293
+ });
294
+ builtCssFileName = this.getFileName(referenceId);
295
+ const asset = bundle?.[builtCssFileName];
296
+ if (asset?.type === "asset" && typeof asset.source === "string") asset.source = rebaseRelativeCssUrls(asset.source, builtCssFileName.split("/").length - 1);
297
+ }
204
298
  } catch (err) {
205
299
  this.error(`[typestyles] Failed to extract CSS: ${err instanceof Error ? err.message : String(err)}`);
206
300
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@typestyles/vite",
3
- "version": "0.5.4",
3
+ "version": "0.6.0",
4
4
  "description": "Vite plugin for typestyles HMR support",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -41,10 +41,10 @@
41
41
  "typescript": "^6.0.0",
42
42
  "vite": "npm:@voidzero-dev/vite-plus-core@1.3.0",
43
43
  "vite-plus": "1.3.0",
44
- "typestyles": "0.33.0"
44
+ "typestyles": "0.34.0"
45
45
  },
46
46
  "dependencies": {
47
- "@typestyles/build-runner": "0.6.4"
47
+ "@typestyles/build-runner": "0.7.0"
48
48
  },
49
49
  "scripts": {
50
50
  "build": "vp pack",