@typestyles/build-runner 0.0.0-unstable.439960c19a5a → 0.0.0-unstable.4b1f40dade83

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/dist/index.cjs CHANGED
@@ -20,12 +20,549 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
- runTypestylesBuild: () => runTypestylesBuild
23
+ DEFAULT_EXTRACT_MODULE_CANDIDATES: () => DEFAULT_EXTRACT_MODULE_CANDIDATES,
24
+ TYPESTYLES_IMPORT_RE: () => TYPESTYLES_IMPORT_RE,
25
+ VerifyTypestylesBuildError: () => VerifyTypestylesBuildError,
26
+ buildManifestV2: () => buildManifestV2,
27
+ collectAndWriteRouteCss: () => collectAndWriteRouteCss,
28
+ createModuleLoader: () => createModuleLoader,
29
+ discoverDefaultExtractModules: () => discoverDefaultExtractModules,
30
+ discoverNextAppRoutes: () => discoverNextAppRoutes,
31
+ extractNamespaces: () => extractNamespaces,
32
+ getRouteCss: () => getRouteCss,
33
+ isManifestV2: () => isManifestV2,
34
+ moduleNeedsOverrideHmr: () => moduleNeedsOverrideHmr,
35
+ normalizeRoutePath: () => normalizeRoutePath,
36
+ pageRelPathToRoutePath: () => pageRelPathToRoutePath,
37
+ readCssFile: () => readCssFile,
38
+ readTypestylesManifest: () => readTypestylesManifest,
39
+ reportDuplicateNamespaces: () => reportDuplicateNamespaces,
40
+ resolveExtractMode: () => resolveExtractMode,
41
+ resolveExtractModules: () => resolveExtractModules,
42
+ runTypestylesBuild: () => runTypestylesBuild,
43
+ traceTypestylesModules: () => traceTypestylesModules,
44
+ verifyTypestylesBuild: () => verifyTypestylesBuild
24
45
  });
25
46
  module.exports = __toCommonJS(index_exports);
26
- var import_esbuild = require("esbuild");
47
+
48
+ // src/discover.ts
27
49
  var import_node_fs = require("fs");
28
50
  var import_node_path = require("path");
51
+ var DEFAULT_EXTRACT_MODULE_BASES = [
52
+ "src/typestyles-entry",
53
+ "src/typestyles",
54
+ "src/styles/index",
55
+ "src/styles",
56
+ "styles/typestyles-entry",
57
+ "styles/typestyles"
58
+ ];
59
+ var DISCOVERY_EXTENSIONS = [".ts", ".tsx", ".js", ".mjs"];
60
+ var DEFAULT_EXTRACT_MODULE_CANDIDATES = DEFAULT_EXTRACT_MODULE_BASES.map(
61
+ (base) => `${base}.ts`
62
+ );
63
+ function discoverDefaultExtractModules(root) {
64
+ const absRoot = (0, import_node_path.resolve)(root);
65
+ for (const base of DEFAULT_EXTRACT_MODULE_BASES) {
66
+ for (const ext of DISCOVERY_EXTENSIONS) {
67
+ const rel = `${base}${ext}`;
68
+ if ((0, import_node_fs.existsSync)((0, import_node_path.resolve)(absRoot, rel))) {
69
+ return [rel.replace(/\\/g, "/")];
70
+ }
71
+ }
72
+ }
73
+ return [];
74
+ }
75
+
76
+ // src/namespaces.ts
77
+ var STYLES_COMPONENT_RE = /styles\.component\(\s*['"]([^'"]+)['"]/g;
78
+ var STYLES_CLASS_RE = /styles\.class\(\s*['"]([^'"]+)['"]/g;
79
+ var TOKENS_CREATE_RE = /tokens\.create\(\s*['"]([^'"]+)['"]/g;
80
+ var CREATE_THEME_RE = /(?:tokens\.)?createTheme\(\s*['"]([^'"]+)['"]/g;
81
+ var KEYFRAMES_CREATE_RE = /keyframes\.create\(\s*['"]([^'"]+)['"]/g;
82
+ var GLOBAL_STYLE_RE = /global\.style\(\s*['"]([^'"]+)['"]/g;
83
+ var GLOBAL_FONT_FACE_RE = /global\.fontFace\(\s*['"]([^'"]+)['"]/g;
84
+ var OVERRIDE_HMR_EXPORT_NAMES = /* @__PURE__ */ new Set(["createDesignTheme", "overrideComponent"]);
85
+ var TYPESTYLES_IMPORT_RE = /(?:from\s+|import\s+|require\s*\(\s*)['"]typestyles['"]/;
86
+ function stripCommentsForHmrScan(code) {
87
+ return code.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:])\/\/.*$/gm, "$1");
88
+ }
89
+ function collectOverrideHmrCallTargets(code) {
90
+ const locals = new Set(OVERRIDE_HMR_EXPORT_NAMES);
91
+ const namespaces = /* @__PURE__ */ new Set();
92
+ for (const match of code.matchAll(/import\s*{([^}]+)}\s*from\s*['"][^'"]+['"]/g)) {
93
+ for (const rawPart of match[1].split(",")) {
94
+ const part = rawPart.trim();
95
+ if (!part || part.startsWith("type ")) continue;
96
+ const asMatch = part.match(/^(\w+)\s+as\s+(\w+)$/);
97
+ if (asMatch) {
98
+ if (OVERRIDE_HMR_EXPORT_NAMES.has(asMatch[1])) {
99
+ locals.add(asMatch[2]);
100
+ }
101
+ continue;
102
+ }
103
+ const name = part.match(/^(\w+)$/)?.[1];
104
+ if (name && OVERRIDE_HMR_EXPORT_NAMES.has(name)) {
105
+ locals.add(name);
106
+ }
107
+ }
108
+ }
109
+ for (const match of code.matchAll(/import\s*\*\s*as\s+(\w+)\s*from\s*['"][^'"]+['"]/g)) {
110
+ namespaces.add(match[1]);
111
+ }
112
+ return { locals, namespaces };
113
+ }
114
+ function moduleNeedsOverrideHmr(code) {
115
+ const scan = stripCommentsForHmrScan(code);
116
+ if (/\bstyles\.override\s*\(/.test(scan)) return true;
117
+ const { locals, namespaces } = collectOverrideHmrCallTargets(scan);
118
+ for (const name of locals) {
119
+ if (new RegExp(`\\b${name}\\s*\\(`).test(scan)) return true;
120
+ }
121
+ for (const ns of namespaces) {
122
+ if (new RegExp(`\\b${ns}\\.(?:createDesignTheme|overrideComponent)\\s*\\(`).test(scan)) {
123
+ return true;
124
+ }
125
+ }
126
+ return false;
127
+ }
128
+ function extractNamespaces(code) {
129
+ const keys = [];
130
+ const prefixes = [];
131
+ for (const match of code.matchAll(STYLES_COMPONENT_RE)) {
132
+ prefixes.push(`.${match[1]}-`);
133
+ }
134
+ for (const match of code.matchAll(STYLES_CLASS_RE)) {
135
+ prefixes.push(`.${match[1]}-`);
136
+ }
137
+ for (const match of code.matchAll(TOKENS_CREATE_RE)) {
138
+ keys.push(`tokens:${match[1]}`);
139
+ }
140
+ for (const match of code.matchAll(CREATE_THEME_RE)) {
141
+ keys.push(`theme:${match[1]}`);
142
+ }
143
+ for (const match of code.matchAll(KEYFRAMES_CREATE_RE)) {
144
+ keys.push(`keyframes:${match[1]}`);
145
+ }
146
+ for (const match of code.matchAll(GLOBAL_STYLE_RE)) {
147
+ prefixes.push(match[1]);
148
+ }
149
+ for (const match of code.matchAll(GLOBAL_FONT_FACE_RE)) {
150
+ prefixes.push(`font-face:${match[1]}`);
151
+ }
152
+ return { keys, prefixes };
153
+ }
154
+ function reportDuplicateNamespaces(moduleNamespaces, id, prefixes, reporter) {
155
+ for (const [otherId, other] of moduleNamespaces) {
156
+ if (otherId === id) continue;
157
+ for (const prefix of prefixes) {
158
+ if (other.prefixes.includes(prefix)) {
159
+ const ns = prefix.slice(1, -1);
160
+ reporter.error(
161
+ `[typestyles] Style namespace "${ns}" is also used in ${otherId}. Duplicate namespaces cause class name collisions. Use a distinct name or isolate with createStyles({ scopeId: fileScopeId(import.meta) }).`
162
+ );
163
+ }
164
+ }
165
+ }
166
+ }
167
+
168
+ // src/resolve-extract.ts
169
+ function resolveExtractModules(root, extract) {
170
+ if (extract?.modules !== void 0) {
171
+ return extract.modules;
172
+ }
173
+ return discoverDefaultExtractModules(root);
174
+ }
175
+ function resolveExtractMode(explicitMode, resolvedModules) {
176
+ return explicitMode ?? (resolvedModules.length > 0 ? "build" : "runtime");
177
+ }
178
+
179
+ // src/verify.ts
180
+ var import_node_fs2 = require("fs");
181
+ var import_node_path2 = require("path");
182
+
183
+ // src/manifest.ts
184
+ function isManifestV2(manifest) {
185
+ return manifest.version === 2;
186
+ }
187
+ function normalizeRoutePath(routePath) {
188
+ if (!routePath || routePath === "/") return "/";
189
+ const trimmed = routePath.replace(/\/+$/, "");
190
+ return trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
191
+ }
192
+
193
+ // src/verify.ts
194
+ var VerifyTypestylesBuildError = class extends Error {
195
+ constructor(message, code) {
196
+ super(`[typestyles:verify] ${message}`);
197
+ this.name = "VerifyTypestylesBuildError";
198
+ this.code = code;
199
+ }
200
+ };
201
+ function fail(message, code) {
202
+ throw new VerifyTypestylesBuildError(message, code);
203
+ }
204
+ function readManifest(path) {
205
+ let parsed;
206
+ try {
207
+ parsed = JSON.parse((0, import_node_fs2.readFileSync)(path, "utf8"));
208
+ } catch {
209
+ fail(`Invalid JSON in ${path}.`, "manifest-invalid-json");
210
+ }
211
+ if (typeof parsed !== "object" || parsed === null || !("version" in parsed) || !("css" in parsed)) {
212
+ fail(`Manifest at ${path} is missing required fields.`, "manifest-invalid-shape");
213
+ }
214
+ const version = parsed.version;
215
+ if (version !== 1 && version !== 2) {
216
+ fail(`Unsupported manifest version ${String(version)}.`, "manifest-version-unsupported");
217
+ }
218
+ const manifest = parsed;
219
+ if (isManifestV2(manifest) && typeof manifest.routes !== "object") {
220
+ fail(`Manifest v2 at ${path} is missing routes.`, "manifest-invalid-shape");
221
+ }
222
+ return manifest;
223
+ }
224
+ function verifyTypestylesBuild(options) {
225
+ const {
226
+ root,
227
+ cssFile,
228
+ manifestFile,
229
+ manifestCssPath,
230
+ manifestVersion = 1,
231
+ minBytes,
232
+ requiredCssSubstrings = [],
233
+ minRouteEntries
234
+ } = options;
235
+ const cssPath = (0, import_node_path2.resolve)(root, cssFile);
236
+ if (!(0, import_node_fs2.existsSync)(cssPath)) {
237
+ fail(`Missing ${cssPath} \u2014 run your TypeStyles build step first.`, "css-missing");
238
+ }
239
+ const css = (0, import_node_fs2.readFileSync)(cssPath, "utf8");
240
+ const cssBytes = Buffer.byteLength(css, "utf8");
241
+ const min = minBytes ?? 1;
242
+ if (cssBytes < min) {
243
+ fail(
244
+ `CSS file unexpectedly small (${cssBytes} bytes, expected at least ${min}).`,
245
+ "css-too-small"
246
+ );
247
+ }
248
+ for (const substring of requiredCssSubstrings) {
249
+ if (!css.includes(substring)) {
250
+ fail(`Expected CSS to contain ${JSON.stringify(substring)}.`, "css-missing-substring");
251
+ }
252
+ }
253
+ const manifestRel = manifestFile === false ? void 0 : manifestFile;
254
+ if (!manifestRel) {
255
+ return { cssPath, cssBytes };
256
+ }
257
+ const manifestPath = (0, import_node_path2.resolve)(root, manifestRel);
258
+ if (!(0, import_node_fs2.existsSync)(manifestPath)) {
259
+ fail(`Missing ${manifestPath}.`, "manifest-missing");
260
+ }
261
+ const manifest = readManifest(manifestPath);
262
+ if (manifest.version !== manifestVersion) {
263
+ fail(
264
+ `Expected manifest version ${manifestVersion}, got ${manifest.version}.`,
265
+ "manifest-version-mismatch"
266
+ );
267
+ }
268
+ const expectedCssPath = manifestCssPath ?? cssFile;
269
+ if (manifest.css !== expectedCssPath) {
270
+ fail(
271
+ `Expected manifest.css ${JSON.stringify(expectedCssPath)}, got ${JSON.stringify(manifest.css)}.`,
272
+ "manifest-css-mismatch"
273
+ );
274
+ }
275
+ if (isManifestV2(manifest)) {
276
+ const routeCount = Object.keys(manifest.routes).length;
277
+ if (minRouteEntries !== void 0 && routeCount < minRouteEntries) {
278
+ fail(
279
+ `Expected at least ${minRouteEntries} route CSS entries, got ${routeCount}.`,
280
+ "manifest-routes-too-few"
281
+ );
282
+ }
283
+ for (const [routePath, entry] of Object.entries(manifest.routes)) {
284
+ const routeCssPath = (0, import_node_path2.resolve)(root, entry.css);
285
+ if (!(0, import_node_fs2.existsSync)(routeCssPath)) {
286
+ fail(`Missing route CSS for ${routePath} at ${routeCssPath}.`, "route-css-missing");
287
+ }
288
+ if (Buffer.byteLength((0, import_node_fs2.readFileSync)(routeCssPath, "utf8"), "utf8") < 1) {
289
+ fail(`Route CSS for ${routePath} is empty.`, "route-css-empty");
290
+ }
291
+ }
292
+ }
293
+ return {
294
+ cssPath,
295
+ cssBytes,
296
+ manifestPath,
297
+ manifestVersion: manifest.version
298
+ };
299
+ }
300
+
301
+ // src/next-routes.ts
302
+ var import_node_fs3 = require("fs");
303
+ var import_node_path3 = require("path");
304
+ var PAGE_BASENAMES = /* @__PURE__ */ new Set(["page.tsx", "page.ts", "page.jsx", "page.js"]);
305
+ var LAYOUT_BASENAMES = /* @__PURE__ */ new Set(["layout.tsx", "layout.ts", "layout.jsx", "layout.js"]);
306
+ function normalizeRelPath(root, absPath) {
307
+ return (0, import_node_path3.relative)(root, absPath).replace(/\\/g, "/");
308
+ }
309
+ function isRouteGroupSegment(segment) {
310
+ return segment.startsWith("(") && segment.endsWith(")");
311
+ }
312
+ function pageRelPathToRoutePath(pageRelPath) {
313
+ const dir = (0, import_node_path3.dirname)(pageRelPath).replace(/\\/g, "/");
314
+ if (dir === "." || dir === "") return "/";
315
+ const segments = dir.split("/").filter((segment) => segment.length > 0 && !isRouteGroupSegment(segment));
316
+ return segments.length === 0 ? "/" : `/${segments.join("/")}`;
317
+ }
318
+ function walkForPages(appAbs, currentRel, pages) {
319
+ const currentAbs = (0, import_node_path3.join)(appAbs, currentRel);
320
+ let entries;
321
+ try {
322
+ entries = (0, import_node_fs3.readdirSync)(currentAbs);
323
+ } catch {
324
+ return;
325
+ }
326
+ for (const entry of entries) {
327
+ const entryRel = currentRel ? (0, import_node_path3.join)(currentRel, entry) : entry;
328
+ const entryAbs = (0, import_node_path3.join)(appAbs, entryRel);
329
+ let stat;
330
+ try {
331
+ stat = (0, import_node_fs3.statSync)(entryAbs);
332
+ } catch {
333
+ continue;
334
+ }
335
+ if (stat.isDirectory()) {
336
+ walkForPages(appAbs, entryRel, pages);
337
+ continue;
338
+ }
339
+ if (PAGE_BASENAMES.has(entry)) {
340
+ pages.push(entryRel.replace(/\\/g, "/"));
341
+ }
342
+ }
343
+ }
344
+ function collectLayoutChain(appAbs, pageRelPath) {
345
+ const layouts = [];
346
+ const segments = (0, import_node_path3.dirname)(pageRelPath).replace(/\\/g, "/").split("/");
347
+ const chainDirs = [""];
348
+ for (const segment of segments) {
349
+ if (!segment || segment === ".") continue;
350
+ const parent = chainDirs[chainDirs.length - 1];
351
+ chainDirs.push(parent ? `${parent}/${segment}` : segment);
352
+ }
353
+ for (const dir of chainDirs) {
354
+ const dirAbs = dir ? (0, import_node_path3.join)(appAbs, dir) : appAbs;
355
+ for (const layoutName of LAYOUT_BASENAMES) {
356
+ const layoutAbs = (0, import_node_path3.join)(dirAbs, layoutName);
357
+ if ((0, import_node_fs3.existsSync)(layoutAbs)) {
358
+ layouts.push((0, import_node_path3.join)(dir, layoutName).replace(/\\/g, "/"));
359
+ break;
360
+ }
361
+ }
362
+ }
363
+ return layouts;
364
+ }
365
+ function discoverNextAppRoutes(root, appDir = "app") {
366
+ const appAbs = (0, import_node_path3.resolve)(root, appDir);
367
+ if (!(0, import_node_fs3.existsSync)(appAbs)) return [];
368
+ const pageRelPaths = [];
369
+ walkForPages(appAbs, "", pageRelPaths);
370
+ return pageRelPaths.map((pageRelPath) => {
371
+ const pageFile = normalizeRelPath(root, (0, import_node_path3.join)(appAbs, pageRelPath));
372
+ const layoutFiles = collectLayoutChain(appAbs, pageRelPath).map(
373
+ (layoutRel) => normalizeRelPath(root, (0, import_node_path3.join)(appAbs, layoutRel))
374
+ );
375
+ return {
376
+ routePath: pageRelPathToRoutePath(pageRelPath),
377
+ pageFile,
378
+ layoutFiles
379
+ };
380
+ }).sort((a, b) => a.routePath.localeCompare(b.routePath));
381
+ }
382
+
383
+ // src/trace-imports.ts
384
+ var import_esbuild = require("esbuild");
385
+ var import_node_fs4 = require("fs");
386
+ var import_node_path4 = require("path");
387
+ var import_node_url = require("url");
388
+ var EXTERNAL_PREFIXES = [
389
+ "react",
390
+ "react-dom",
391
+ "react/",
392
+ "react-dom/",
393
+ "next",
394
+ "next/",
395
+ "server-only",
396
+ "client-only",
397
+ "typestyles",
398
+ "typestyles/"
399
+ ];
400
+ function isExternalBareImport(specifier) {
401
+ if (specifier.startsWith("node:")) return true;
402
+ return EXTERNAL_PREFIXES.some(
403
+ (prefix) => specifier === prefix || specifier.startsWith(`${prefix}/`)
404
+ );
405
+ }
406
+ function isExternalAssetPath(path, importer, namespace) {
407
+ if (path.endsWith(".css")) return true;
408
+ const fromCss = namespace === "css" || importer.endsWith(".css");
409
+ if (fromCss && path.startsWith("/") && !path.startsWith("//")) {
410
+ return true;
411
+ }
412
+ return false;
413
+ }
414
+ function fileImportsTypestyles(absPath) {
415
+ if (!(0, import_node_fs4.existsSync)(absPath)) return false;
416
+ try {
417
+ return TYPESTYLES_IMPORT_RE.test((0, import_node_fs4.readFileSync)(absPath, "utf8"));
418
+ } catch {
419
+ return false;
420
+ }
421
+ }
422
+ async function traceTypestylesModules(root, entryFiles) {
423
+ const absEntries = entryFiles.map((file) => (0, import_node_path4.resolve)(root, file));
424
+ const missing = absEntries.filter((file) => !(0, import_node_fs4.existsSync)(file));
425
+ if (missing.length > 0) {
426
+ throw new Error(
427
+ `[typestyles] Cannot trace imports; missing entry file(s): ${missing.join(", ")}`
428
+ );
429
+ }
430
+ const tsconfigPath = (0, import_node_path4.join)(root, "tsconfig.json");
431
+ const result = await (0, import_esbuild.build)({
432
+ entryPoints: absEntries,
433
+ bundle: true,
434
+ write: false,
435
+ outdir: root,
436
+ metafile: true,
437
+ platform: "neutral",
438
+ format: "esm",
439
+ logLevel: "silent",
440
+ absWorkingDir: root,
441
+ ...(0, import_node_fs4.existsSync)(tsconfigPath) ? { tsconfig: tsconfigPath } : {},
442
+ plugins: [
443
+ {
444
+ name: "typestyles-trace-imports",
445
+ setup(build) {
446
+ build.onResolve({ filter: /.*/ }, (args) => {
447
+ if (isExternalAssetPath(args.path, args.importer, args.namespace)) {
448
+ return { path: args.path, external: true };
449
+ }
450
+ if (args.path.startsWith(".")) {
451
+ return null;
452
+ }
453
+ if (isExternalBareImport(args.path)) {
454
+ return { path: args.path, external: true };
455
+ }
456
+ return null;
457
+ });
458
+ }
459
+ }
460
+ ]
461
+ });
462
+ const inputs = result.metafile?.inputs ?? {};
463
+ const traced = /* @__PURE__ */ new Set();
464
+ for (const inputPath of Object.keys(inputs)) {
465
+ const absPath = (0, import_node_path4.resolve)(root, inputPath);
466
+ if (!fileImportsTypestyles(absPath)) continue;
467
+ traced.add(inputPath.replace(/\\/g, "/"));
468
+ }
469
+ return [...traced].sort();
470
+ }
471
+ function createModuleLoader(root, modulePath) {
472
+ const abs = (0, import_node_path4.resolve)(root, modulePath);
473
+ const href = (0, import_node_url.pathToFileURL)(abs).href;
474
+ return () => import(href);
475
+ }
476
+
477
+ // src/route-css.ts
478
+ var import_promises = require("fs/promises");
479
+ var import_node_path5 = require("path");
480
+ function routePathToCssFile(routePath) {
481
+ if (routePath === "/") return "index.css";
482
+ const slug = routePath.slice(1).replace(/^\[|\]$/g, "").replace(/[^\w.-]+/g, "-");
483
+ return `${slug || "route"}.css`;
484
+ }
485
+ function uniqueModules(...groups) {
486
+ return [...new Set(groups.flat())].sort();
487
+ }
488
+ async function collectAndWriteRouteCss(options) {
489
+ const {
490
+ root,
491
+ sharedModules,
492
+ appDir = "app",
493
+ routeCssOutDir = "app/_typestyles/routes",
494
+ collectCss
495
+ } = options;
496
+ const routes = discoverNextAppRoutes(root, appDir);
497
+ if (routes.length === 0) {
498
+ return { routes: {} };
499
+ }
500
+ const manifestRoutes = {};
501
+ for (const route of routes) {
502
+ const entryFiles = uniqueModules(route.layoutFiles, [route.pageFile]);
503
+ const routeModules = await traceTypestylesModules(root, entryFiles);
504
+ const modules = uniqueModules(sharedModules, routeModules);
505
+ const loaders = modules.map((mod) => createModuleLoader(root, mod));
506
+ const css = await collectCss(loaders);
507
+ const cssFileName = routePathToCssFile(route.routePath);
508
+ const cssRel = `${routeCssOutDir.replace(/\\/g, "/")}/${cssFileName}`;
509
+ const cssAbs = (0, import_node_path5.resolve)(root, cssRel);
510
+ await (0, import_promises.mkdir)((0, import_node_path5.dirname)(cssAbs), { recursive: true });
511
+ await (0, import_promises.writeFile)(cssAbs, css, "utf8");
512
+ manifestRoutes[route.routePath] = { css: cssRel };
513
+ }
514
+ return { routes: manifestRoutes };
515
+ }
516
+ function buildManifestV2(cssOutFile, routeEntries) {
517
+ return {
518
+ version: 2,
519
+ css: cssOutFile,
520
+ routes: routeEntries
521
+ };
522
+ }
523
+
524
+ // src/route-css-read.ts
525
+ var import_node_fs5 = require("fs");
526
+ var import_node_path6 = require("path");
527
+ function readTypestylesManifest(root, manifestFile = "app/typestyles.manifest.json") {
528
+ const manifestPath = (0, import_node_path6.resolve)(root, manifestFile);
529
+ if (!(0, import_node_fs5.existsSync)(manifestPath)) {
530
+ throw new Error(`[typestyles] Missing manifest at ${manifestPath}.`);
531
+ }
532
+ let parsed;
533
+ try {
534
+ parsed = JSON.parse((0, import_node_fs5.readFileSync)(manifestPath, "utf8"));
535
+ } catch {
536
+ throw new Error(`[typestyles] Invalid JSON in ${manifestPath}.`);
537
+ }
538
+ if (typeof parsed !== "object" || parsed === null || !("version" in parsed) || !("css" in parsed)) {
539
+ throw new Error(`[typestyles] Manifest at ${manifestPath} is missing required fields.`);
540
+ }
541
+ return parsed;
542
+ }
543
+ function readCssFile(root, cssRelPath) {
544
+ const cssPath = (0, import_node_path6.resolve)(root, cssRelPath);
545
+ if (!(0, import_node_fs5.existsSync)(cssPath)) {
546
+ throw new Error(`[typestyles] Missing CSS file at ${cssPath}.`);
547
+ }
548
+ return (0, import_node_fs5.readFileSync)(cssPath, "utf8");
549
+ }
550
+ function getRouteCss(routePath, options) {
551
+ const manifest = readTypestylesManifest(options.root, options.manifestFile);
552
+ const normalized = normalizeRoutePath(routePath);
553
+ if (isManifestV2(manifest)) {
554
+ const routeEntry = manifest.routes[normalized];
555
+ if (routeEntry) {
556
+ return readCssFile(options.root, routeEntry.css);
557
+ }
558
+ }
559
+ return readCssFile(options.root, manifest.css);
560
+ }
561
+
562
+ // src/index.ts
563
+ var import_esbuild2 = require("esbuild");
564
+ var import_node_fs6 = require("fs");
565
+ var import_node_path7 = require("path");
29
566
  var import_node_child_process = require("child_process");
30
567
  function toImportPath(modulePath) {
31
568
  const normalized = modulePath.replace(/\\/g, "/");
@@ -40,13 +577,32 @@ async function runTypestylesBuild({
40
577
  }) {
41
578
  if (!modules.length) return "";
42
579
  const importLines = modules.map((mod) => `import ${JSON.stringify(toImportPath(mod))};`).join("\n");
43
- const bundleResult = await (0, import_esbuild.build)({
580
+ const bundleResult = await (0, import_esbuild2.build)({
44
581
  write: false,
45
582
  bundle: true,
46
583
  platform: "node",
47
584
  format: "cjs",
48
585
  target: "node18",
49
586
  external: ["typestyles"],
587
+ // Style registration calls (styles.component/class, createTypeStyles) are
588
+ // side-effect-only: the CSS they register into the global registry is the
589
+ // point, regardless of whether the returned classname function is ever
590
+ // read. esbuild's default tree shaking doesn't know that, so any
591
+ // consumer module reached only through an unread namespace/barrel import
592
+ // (or a package marked "sideEffects": false) can have its registration
593
+ // calls silently dropped as "unused". Disable tree shaking here so every
594
+ // registration in the extraction graph survives.
595
+ treeShaking: false,
596
+ // `treeShaking: false` only stops esbuild from pruning declarations
597
+ // *within* an already-included module. It's a separate esbuild behavior
598
+ // by the treeShaking option — that drops a plain bare import entirely
599
+ // (`import './some-lib'` with no binding at all) when it resolves to a
600
+ // module/package marked "sideEffects": false, before that module is ever
601
+ // considered for inclusion. A real extraction entry is exactly this
602
+ // shape: several side-effect-only imports, any one of which may point at
603
+ // a (correctly) tree-shakeable component library. Ignore both kinds of
604
+ // annotation so every import in the extraction graph is included.
605
+ ignoreAnnotations: true,
50
606
  stdin: {
51
607
  contents: importLines,
52
608
  resolveDir: root,
@@ -58,12 +614,12 @@ async function runTypestylesBuild({
58
614
  if (!bundledCode) {
59
615
  throw new Error("[typestyles] Failed to produce extraction bundle.");
60
616
  }
61
- const scriptPath = (0, import_node_path.resolve)(root, `.typestyles-extract-${process.pid}.cjs`);
617
+ const scriptPath = (0, import_node_path7.resolve)(root, `.typestyles-extract-${process.pid}.cjs`);
62
618
  const script = `${bundledCode}
63
619
  process.stdout.write(require('typestyles').getRegisteredCss());
64
620
  `;
65
621
  try {
66
- (0, import_node_fs.writeFileSync)(scriptPath, script, "utf8");
622
+ (0, import_node_fs6.writeFileSync)(scriptPath, script, "utf8");
67
623
  const result = (0, import_node_child_process.spawnSync)(process.execPath, [scriptPath], {
68
624
  cwd: root,
69
625
  encoding: "utf8",
@@ -80,9 +636,9 @@ ${result.stderr || result.stdout || "unknown error"}`
80
636
  }
81
637
  return result.stdout ?? "";
82
638
  } finally {
83
- if ((0, import_node_fs.existsSync)(scriptPath)) {
639
+ if ((0, import_node_fs6.existsSync)(scriptPath)) {
84
640
  try {
85
- (0, import_node_fs.unlinkSync)(scriptPath);
641
+ (0, import_node_fs6.unlinkSync)(scriptPath);
86
642
  } catch {
87
643
  }
88
644
  }
@@ -90,5 +646,26 @@ ${result.stderr || result.stdout || "unknown error"}`
90
646
  }
91
647
  // Annotate the CommonJS export names for ESM import in node:
92
648
  0 && (module.exports = {
93
- runTypestylesBuild
649
+ DEFAULT_EXTRACT_MODULE_CANDIDATES,
650
+ TYPESTYLES_IMPORT_RE,
651
+ VerifyTypestylesBuildError,
652
+ buildManifestV2,
653
+ collectAndWriteRouteCss,
654
+ createModuleLoader,
655
+ discoverDefaultExtractModules,
656
+ discoverNextAppRoutes,
657
+ extractNamespaces,
658
+ getRouteCss,
659
+ isManifestV2,
660
+ moduleNeedsOverrideHmr,
661
+ normalizeRoutePath,
662
+ pageRelPathToRoutePath,
663
+ readCssFile,
664
+ readTypestylesManifest,
665
+ reportDuplicateNamespaces,
666
+ resolveExtractMode,
667
+ resolveExtractModules,
668
+ runTypestylesBuild,
669
+ traceTypestylesModules,
670
+ verifyTypestylesBuild
94
671
  });