@typestyles/next 0.0.0-unstable.247bf362710f → 0.0.0-unstable.28a3f8233b47

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
@@ -128,24 +128,43 @@ export default function RootLayout({ children }) {
128
128
  }
129
129
  ```
130
130
 
131
- ### Option 3: Metadata API
131
+ ### Option 3: Collecting from a specific component tree
132
132
 
133
- For static generation, you can collect styles in `generateMetadata`:
133
+ `getTypestylesMetadata` (alias of `collectStylesFromComponent`) renders a React element on the server and returns the CSS registered during that render. Use it when you need CSS scoped to a subtree rather than the whole app. For App Router pages, injecting the result still belongs in `layout.tsx` / `<head>` (Next.js `Metadata` does not provide a supported hook for arbitrary `<style>` payloads).
134
134
 
135
135
  ```tsx
136
- // app/layout.tsx
137
- import { generateMetadata } from 'next';
138
136
  import { getTypestylesMetadata } from '@typestyles/next/server';
139
137
  import { Home } from './Home';
140
138
 
141
- export async function generateMetadata() {
142
- const css = await getTypestylesMetadata(<Home />);
143
- return {
144
- styles: [{ cssText: css, id: 'typestyles' }],
145
- };
146
- }
139
+ const css = await getTypestylesMetadata(<Home />);
140
+ // Pass `css` into your layout <style> or streaming head pipeline.
147
141
  ```
148
142
 
143
+ ## Build-time CSS + Turbopack
144
+
145
+ To ship a static stylesheet and avoid client-side `<style>` injection (uses `typestyles/build` under the hood):
146
+
147
+ 1. Run **`buildTypestylesForNext({ root })`** before `next build`. It discovers the same **convention entry** as `@typestyles/vite` (see `DEFAULT_EXTRACT_MODULE_CANDIDATES` from `@typestyles/build-runner`) and by default writes **`app/typestyles.css`** plus **`app/typestyles.manifest.json`** (override paths or pass explicit `modules` when needed).
148
+ 2. Import that CSS from your root layout (e.g. `import './typestyles.css'`).
149
+ 3. Wrap config with **`withTypestyles`** from `@typestyles/next/build` — in **production**, if a convention entry exists, it applies **`withTypestylesExtract`**; in **development** it leaves your config unchanged so the runtime stays on.
150
+
151
+ `withTypestylesExtract` sets **`NEXT_PUBLIC_TYPESTYLES_RUNTIME_DISABLED`** via `next.config` `env` (works with **webpack and Turbopack**) and adds webpack **`DefinePlugin`** for `__TYPESTYLES_RUNTIME_DISABLED__` on client bundles when webpack runs. Example app: `examples/next-app`.
152
+
153
+ ### Runtime in development, zero-runtime in production
154
+
155
+ During `next dev`, keeping the client runtime **enabled** avoids tying every style tweak to a pre-build extraction step. In production, disable injection so the browser loads one cacheable stylesheet.
156
+
157
+ ```js
158
+ // next.config.mjs
159
+ import { withTypestyles } from '@typestyles/next/build';
160
+
161
+ export default withTypestyles({
162
+ transpilePackages: ['typestyles', '@typestyles/next'],
163
+ });
164
+ ```
165
+
166
+ You still typically run extraction before production builds (CI or `prebuild`). For full manual control, **`withTypestylesExtract`** remains available.
167
+
149
168
  ## API Reference
150
169
 
151
170
  ### getRegisteredCss
@@ -171,7 +190,7 @@ const css = await collectStylesFromComponent(<YourComponent />);
171
190
 
172
191
  ### getTypestylesMetadata
173
192
 
174
- Generate CSS for use in Next.js metadata API. Collects styles by rendering the component server-side.
193
+ Same as `collectStylesFromComponent` — renders the given element on the server and returns registered CSS. Use when you want a dedicated name for “CSS for this subtree.”
175
194
 
176
195
  ```tsx
177
196
  import { getTypestylesMetadata } from '@typestyles/next/server';
@@ -200,7 +219,7 @@ import { TypestylesStylesheet } from '@typestyles/next';
200
219
  // app/page.tsx
201
220
  import { styles } from 'typestyles';
202
221
 
203
- const button = styles.create('button', {
222
+ const button = styles.component('button', {
204
223
  base: {
205
224
  padding: '12px 24px',
206
225
  backgroundColor: '#0066ff',
@@ -214,7 +233,7 @@ const button = styles.create('button', {
214
233
  export default function Home() {
215
234
  return (
216
235
  <main>
217
- <button className={button('base')}>Click me</button>
236
+ <button className={button()}>Click me</button>
218
237
  </main>
219
238
  );
220
239
  }
@@ -241,7 +260,7 @@ export const spacing = tokens.create('space', {
241
260
  import { styles } from 'typestyles';
242
261
  import { colors, spacing } from './tokens';
243
262
 
244
- const card = styles.create('card', {
263
+ const card = styles.component('card', {
245
264
  base: {
246
265
  padding: spacing.md,
247
266
  backgroundColor: colors.primary,
@@ -250,7 +269,7 @@ const card = styles.create('card', {
250
269
  });
251
270
 
252
271
  export default function Page() {
253
- return <div className={card('base')}>Hello World</div>;
272
+ return <div className={card()}>Hello World</div>;
254
273
  }
255
274
  ```
256
275
 
@@ -262,9 +281,11 @@ import { tokens } from 'typestyles';
262
281
  import { getRegisteredCss } from '@typestyles/next';
263
282
 
264
283
  const darkTheme = tokens.createTheme('dark', {
265
- color: {
266
- background: '#1a1a1a',
267
- text: '#ffffff',
284
+ base: {
285
+ color: {
286
+ background: '#1a1a1a',
287
+ text: '#ffffff',
288
+ },
268
289
  },
269
290
  });
270
291
 
@@ -272,7 +293,7 @@ export default function RootLayout({ children }) {
272
293
  const css = getRegisteredCss();
273
294
 
274
295
  return (
275
- <html className={darkTheme}>
296
+ <html className={darkTheme.className}>
276
297
  <head>{css && <style dangerouslySetInnerHTML={{ __html: css }} />}</head>
277
298
  <body>{children}</body>
278
299
  </html>
@@ -280,6 +301,14 @@ export default function RootLayout({ children }) {
280
301
  }
281
302
  ```
282
303
 
304
+ ## Fonts and local files
305
+
306
+ `global.fontFace()` registers `@font-face` like any other TypeStyles global. For **Next’s pre-build extraction** (`buildTypestylesForNext`), prefer fonts under **`public/fonts/`** and a root-relative `url('/fonts/…')` in `src` so Node does not need to resolve binary imports.
307
+
308
+ For **Vite**, you can use `import file from './font.woff2?url'` and `url(\`${file}\`) format('woff2')` so production CSS points at hashed assets.
309
+
310
+ See the **Fonts** guide in the TypeStyles docs (`docs/content/docs/fonts.md`, route `/docs/fonts` on the docs site).
311
+
283
312
  ## Troubleshooting
284
313
 
285
314
  ### Flash of Unstyled Content (FOUC)
package/dist/build.cjs ADDED
@@ -0,0 +1,126 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/build.ts
21
+ var build_exports = {};
22
+ __export(build_exports, {
23
+ DEFAULT_EXTRACT_MODULE_CANDIDATES: () => import_build_runner.DEFAULT_EXTRACT_MODULE_CANDIDATES,
24
+ buildTypestylesForNext: () => buildTypestylesForNext,
25
+ discoverDefaultExtractModules: () => import_build_runner.discoverDefaultExtractModules,
26
+ withTypestyles: () => withTypestyles,
27
+ withTypestylesExtract: () => withTypestylesExtract
28
+ });
29
+ module.exports = __toCommonJS(build_exports);
30
+ var import_promises = require("fs/promises");
31
+ var import_node_module = require("module");
32
+ var import_node_path = require("path");
33
+ var import_node_url = require("url");
34
+ var import_build_runner = require("@typestyles/build-runner");
35
+ var import_build = require("typestyles/build");
36
+ function resolveExtractModulesForNext(root, modules) {
37
+ if (modules !== void 0) {
38
+ return modules;
39
+ }
40
+ const found = (0, import_build_runner.discoverDefaultExtractModules)(root);
41
+ if (found.length === 0) {
42
+ throw new Error(
43
+ `[typestyles] No extraction entry found under ${root}. Add a convention file (see DEFAULT_EXTRACT_MODULE_CANDIDATES from @typestyles/build-runner) or pass modules to buildTypestylesForNext.`
44
+ );
45
+ }
46
+ return found;
47
+ }
48
+ async function buildTypestylesForNext(options) {
49
+ const {
50
+ root,
51
+ modules,
52
+ cssOutFile = "app/typestyles.css",
53
+ manifestOutFile,
54
+ manifestCssPath
55
+ } = options;
56
+ const resolvedModules = resolveExtractModulesForNext(root, modules);
57
+ const loaders = resolvedModules.map((mod) => {
58
+ const abs = (0, import_node_path.resolve)(root, mod);
59
+ const href = (0, import_node_url.pathToFileURL)(abs).href;
60
+ return () => import(href);
61
+ });
62
+ const css = await (0, import_build.collectStylesFromModules)(loaders);
63
+ const outAbs = (0, import_node_path.resolve)(root, cssOutFile);
64
+ await (0, import_promises.mkdir)((0, import_node_path.dirname)(outAbs), { recursive: true });
65
+ await (0, import_promises.writeFile)(outAbs, css, "utf8");
66
+ const manifestRel = manifestOutFile === false ? void 0 : manifestOutFile ?? "app/typestyles.manifest.json";
67
+ if (manifestRel) {
68
+ const manifest = {
69
+ version: 1,
70
+ css: manifestCssPath ?? cssOutFile
71
+ };
72
+ const manAbs = (0, import_node_path.resolve)(root, manifestRel);
73
+ await (0, import_promises.mkdir)((0, import_node_path.dirname)(manAbs), { recursive: true });
74
+ await (0, import_promises.writeFile)(manAbs, `${JSON.stringify(manifest, null, 2)}
75
+ `, "utf8");
76
+ }
77
+ }
78
+ function withTypestyles(nextConfig = {}, options = {}) {
79
+ const projectRoot = options.root ?? process.cwd();
80
+ const hasConventionEntry = (0, import_build_runner.discoverDefaultExtractModules)(projectRoot).length > 0;
81
+ const prod = process.env.NODE_ENV === "production";
82
+ if (!prod || !hasConventionEntry) {
83
+ return nextConfig;
84
+ }
85
+ return withTypestylesExtract(nextConfig, options);
86
+ }
87
+ function withTypestylesExtract(nextConfig = {}, options = {}) {
88
+ const disableClientRuntime = options.disableClientRuntime !== false;
89
+ const projectRoot = options.root ?? process.cwd();
90
+ return {
91
+ ...nextConfig,
92
+ ...disableClientRuntime ? {
93
+ env: {
94
+ ...typeof nextConfig.env === "object" && nextConfig.env !== null && !Array.isArray(nextConfig.env) ? nextConfig.env : {},
95
+ NEXT_PUBLIC_TYPESTYLES_RUNTIME_DISABLED: "true"
96
+ }
97
+ } : {},
98
+ webpack(config, context) {
99
+ const nextWebpack = typeof nextConfig.webpack === "function" ? nextConfig.webpack(config, context) : config;
100
+ if (disableClientRuntime && !context.isServer) {
101
+ try {
102
+ const require2 = (0, import_node_module.createRequire)((0, import_node_path.join)(projectRoot, "package.json"));
103
+ const webpackLib = require2("webpack");
104
+ nextWebpack.plugins.push(
105
+ new webpackLib.DefinePlugin({
106
+ __TYPESTYLES_RUNTIME_DISABLED__: JSON.stringify("true")
107
+ })
108
+ );
109
+ } catch {
110
+ console.warn(
111
+ "[@typestyles/next/build] Could not load webpack; client bundles may still inject <style>."
112
+ );
113
+ }
114
+ }
115
+ return nextWebpack;
116
+ }
117
+ };
118
+ }
119
+ // Annotate the CommonJS export names for ESM import in node:
120
+ 0 && (module.exports = {
121
+ DEFAULT_EXTRACT_MODULE_CANDIDATES,
122
+ buildTypestylesForNext,
123
+ discoverDefaultExtractModules,
124
+ withTypestyles,
125
+ withTypestylesExtract
126
+ });
package/dist/build.js ADDED
@@ -0,0 +1,100 @@
1
+ // src/build.ts
2
+ import { mkdir, writeFile } from "fs/promises";
3
+ import { createRequire } from "module";
4
+ import { dirname, join, resolve } from "path";
5
+ import { pathToFileURL } from "url";
6
+ import {
7
+ DEFAULT_EXTRACT_MODULE_CANDIDATES,
8
+ discoverDefaultExtractModules
9
+ } from "@typestyles/build-runner";
10
+ import { collectStylesFromModules } from "typestyles/build";
11
+ function resolveExtractModulesForNext(root, modules) {
12
+ if (modules !== void 0) {
13
+ return modules;
14
+ }
15
+ const found = discoverDefaultExtractModules(root);
16
+ if (found.length === 0) {
17
+ throw new Error(
18
+ `[typestyles] No extraction entry found under ${root}. Add a convention file (see DEFAULT_EXTRACT_MODULE_CANDIDATES from @typestyles/build-runner) or pass modules to buildTypestylesForNext.`
19
+ );
20
+ }
21
+ return found;
22
+ }
23
+ async function buildTypestylesForNext(options) {
24
+ const {
25
+ root,
26
+ modules,
27
+ cssOutFile = "app/typestyles.css",
28
+ manifestOutFile,
29
+ manifestCssPath
30
+ } = options;
31
+ const resolvedModules = resolveExtractModulesForNext(root, modules);
32
+ const loaders = resolvedModules.map((mod) => {
33
+ const abs = resolve(root, mod);
34
+ const href = pathToFileURL(abs).href;
35
+ return () => import(href);
36
+ });
37
+ const css = await collectStylesFromModules(loaders);
38
+ const outAbs = resolve(root, cssOutFile);
39
+ await mkdir(dirname(outAbs), { recursive: true });
40
+ await writeFile(outAbs, css, "utf8");
41
+ const manifestRel = manifestOutFile === false ? void 0 : manifestOutFile ?? "app/typestyles.manifest.json";
42
+ if (manifestRel) {
43
+ const manifest = {
44
+ version: 1,
45
+ css: manifestCssPath ?? cssOutFile
46
+ };
47
+ const manAbs = resolve(root, manifestRel);
48
+ await mkdir(dirname(manAbs), { recursive: true });
49
+ await writeFile(manAbs, `${JSON.stringify(manifest, null, 2)}
50
+ `, "utf8");
51
+ }
52
+ }
53
+ function withTypestyles(nextConfig = {}, options = {}) {
54
+ const projectRoot = options.root ?? process.cwd();
55
+ const hasConventionEntry = discoverDefaultExtractModules(projectRoot).length > 0;
56
+ const prod = process.env.NODE_ENV === "production";
57
+ if (!prod || !hasConventionEntry) {
58
+ return nextConfig;
59
+ }
60
+ return withTypestylesExtract(nextConfig, options);
61
+ }
62
+ function withTypestylesExtract(nextConfig = {}, options = {}) {
63
+ const disableClientRuntime = options.disableClientRuntime !== false;
64
+ const projectRoot = options.root ?? process.cwd();
65
+ return {
66
+ ...nextConfig,
67
+ ...disableClientRuntime ? {
68
+ env: {
69
+ ...typeof nextConfig.env === "object" && nextConfig.env !== null && !Array.isArray(nextConfig.env) ? nextConfig.env : {},
70
+ NEXT_PUBLIC_TYPESTYLES_RUNTIME_DISABLED: "true"
71
+ }
72
+ } : {},
73
+ webpack(config, context) {
74
+ const nextWebpack = typeof nextConfig.webpack === "function" ? nextConfig.webpack(config, context) : config;
75
+ if (disableClientRuntime && !context.isServer) {
76
+ try {
77
+ const require2 = createRequire(join(projectRoot, "package.json"));
78
+ const webpackLib = require2("webpack");
79
+ nextWebpack.plugins.push(
80
+ new webpackLib.DefinePlugin({
81
+ __TYPESTYLES_RUNTIME_DISABLED__: JSON.stringify("true")
82
+ })
83
+ );
84
+ } catch {
85
+ console.warn(
86
+ "[@typestyles/next/build] Could not load webpack; client bundles may still inject <style>."
87
+ );
88
+ }
89
+ }
90
+ return nextWebpack;
91
+ }
92
+ };
93
+ }
94
+ export {
95
+ DEFAULT_EXTRACT_MODULE_CANDIDATES,
96
+ buildTypestylesForNext,
97
+ discoverDefaultExtractModules,
98
+ withTypestyles,
99
+ withTypestylesExtract
100
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@typestyles/next",
3
- "version": "0.0.0-unstable.247bf362710f",
3
+ "version": "0.0.0-unstable.28a3f8233b47",
4
4
  "description": "Next.js integration for typestyles SSR",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -22,6 +22,11 @@
22
22
  "import": "./dist/client.js",
23
23
  "require": "./dist/client.cjs",
24
24
  "default": "./dist/client.js"
25
+ },
26
+ "./build": {
27
+ "types": "./src/build.d.ts",
28
+ "import": "./dist/build.js",
29
+ "require": "./dist/build.cjs"
25
30
  }
26
31
  },
27
32
  "files": [
@@ -45,7 +50,8 @@
45
50
  "next": ">=13.0.0",
46
51
  "react": ">=18.0.0",
47
52
  "react-dom": ">=18.0.0",
48
- "typestyles": ">=0.1.0"
53
+ "typestyles": ">=0.1.0",
54
+ "webpack": ">=5.0.0"
49
55
  },
50
56
  "peerDependenciesMeta": {
51
57
  "next": {
@@ -56,19 +62,32 @@
56
62
  },
57
63
  "react-dom": {
58
64
  "optional": false
65
+ },
66
+ "webpack": {
67
+ "optional": true
59
68
  }
60
69
  },
70
+ "dependencies": {
71
+ "@typestyles/build-runner": "0.0.0-unstable.28a3f8233b47"
72
+ },
61
73
  "devDependencies": {
74
+ "eslint": "^9.39.2",
75
+ "vitest": "^3.0.0",
62
76
  "@types/node": "^25.2.1",
63
- "@types/react": "^18.0.0",
64
- "@types/react-dom": "^18.0.0",
77
+ "@types/react": "^18.3.12",
78
+ "@types/react-dom": "^18.3.1",
65
79
  "next": "^14.0.0",
66
80
  "react": "^18.0.0",
67
81
  "react-dom": "^18.0.0",
68
82
  "tsup": "^8.0.0",
69
- "typescript": "^5.4.0"
83
+ "typestyles": "0.0.0-unstable.28a3f8233b47",
84
+ "typescript": "^5.4.0",
85
+ "webpack": "^5.97.1"
70
86
  },
71
87
  "scripts": {
72
- "build": "tsup"
88
+ "build": "tsup",
89
+ "test": "vitest run",
90
+ "lint": "eslint .",
91
+ "typecheck": "tsc --noEmit"
73
92
  }
74
93
  }
package/src/build.d.ts ADDED
@@ -0,0 +1,41 @@
1
+ import type { NextConfig } from 'next';
2
+
3
+ export interface TypestylesExtractManifestV1 {
4
+ version: 1;
5
+ css: string;
6
+ }
7
+
8
+ export declare const DEFAULT_EXTRACT_MODULE_CANDIDATES: readonly string[];
9
+
10
+ export declare function discoverDefaultExtractModules(root: string): string[];
11
+
12
+ export interface BuildTypestylesForNextOptions {
13
+ root: string;
14
+ modules?: string[];
15
+ cssOutFile?: string;
16
+ manifestOutFile?: string | false;
17
+ manifestCssPath?: string;
18
+ }
19
+
20
+ export declare function buildTypestylesForNext(
21
+ options: BuildTypestylesForNextOptions,
22
+ ): Promise<void>;
23
+
24
+ export interface WithTypestylesExtractOptions {
25
+ disableClientRuntime?: boolean;
26
+ root?: string;
27
+ }
28
+
29
+ export interface WithTypestylesOptions extends WithTypestylesExtractOptions {
30
+ root?: string;
31
+ }
32
+
33
+ export declare function withTypestyles(
34
+ nextConfig?: NextConfig,
35
+ options?: WithTypestylesOptions,
36
+ ): NextConfig;
37
+
38
+ export declare function withTypestylesExtract(
39
+ nextConfig?: NextConfig,
40
+ options?: WithTypestylesExtractOptions,
41
+ ): NextConfig;
@@ -0,0 +1,96 @@
1
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { tmpdir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { describe, it, expect, vi } from 'vitest';
5
+ import type { NextConfig } from 'next';
6
+ import type { Configuration } from 'webpack';
7
+ import { withTypestyles, withTypestylesExtract } from './build';
8
+
9
+ type WebpackContext = Parameters<NonNullable<NextConfig['webpack']>>[1];
10
+
11
+ describe('withTypestylesExtract', () => {
12
+ it('merges NEXT_PUBLIC_TYPESTYLES_RUNTIME_DISABLED into env for Turbopack + webpack', () => {
13
+ const merged = withTypestylesExtract({ env: { CUSTOM: 'x' } }, { disableClientRuntime: true });
14
+ expect(merged.env).toEqual({
15
+ CUSTOM: 'x',
16
+ NEXT_PUBLIC_TYPESTYLES_RUNTIME_DISABLED: 'true',
17
+ });
18
+ });
19
+
20
+ it('does not override env when disableClientRuntime is false', () => {
21
+ const merged = withTypestylesExtract({ env: { CUSTOM: 'x' } }, { disableClientRuntime: false });
22
+ expect(merged.env).toEqual({ CUSTOM: 'x' });
23
+ });
24
+
25
+ it('chains user webpack() and adds DefinePlugin on the client', async () => {
26
+ const webpackMod = await import('webpack');
27
+ const userWebpack = vi.fn((cfg: { plugins: unknown[] }) => {
28
+ cfg.plugins.push('user-marker');
29
+ return cfg;
30
+ });
31
+ const merged = withTypestylesExtract({ webpack: userWebpack });
32
+ const config = { plugins: [] as unknown[] };
33
+ const result = merged.webpack!(
34
+ config as Configuration,
35
+ {
36
+ isServer: false,
37
+ } as WebpackContext,
38
+ );
39
+ expect(userWebpack).toHaveBeenCalled();
40
+ const hasDefine = result.plugins?.some(
41
+ (p: unknown) => p instanceof webpackMod.default.DefinePlugin,
42
+ );
43
+ expect(hasDefine).toBe(true);
44
+ });
45
+
46
+ it('applies extract in production when a convention entry exists under root', () => {
47
+ const dir = mkdtempSync(join(tmpdir(), 'typestyles-next-cwd-'));
48
+ mkdirSync(join(dir, 'styles'), { recursive: true });
49
+ writeFileSync(join(dir, 'styles/typestyles-entry.ts'), 'export {}\n');
50
+
51
+ vi.stubEnv('NODE_ENV', 'production');
52
+ try {
53
+ const merged = withTypestyles({ env: { CUSTOM: 'y' } }, { root: dir });
54
+ expect(merged.env).toEqual({
55
+ CUSTOM: 'y',
56
+ NEXT_PUBLIC_TYPESTYLES_RUNTIME_DISABLED: 'true',
57
+ });
58
+ } finally {
59
+ vi.unstubAllEnvs();
60
+ }
61
+
62
+ rmSync(dir, { recursive: true, force: true });
63
+ });
64
+
65
+ it('does not apply extract in development even when a convention entry exists', () => {
66
+ const dir = mkdtempSync(join(tmpdir(), 'typestyles-next-dev-'));
67
+ mkdirSync(join(dir, 'styles'), { recursive: true });
68
+ writeFileSync(join(dir, 'styles/typestyles-entry.ts'), 'export {}\n');
69
+
70
+ vi.stubEnv('NODE_ENV', 'development');
71
+ try {
72
+ const merged = withTypestyles({ env: { CUSTOM: 'y' } }, { root: dir });
73
+ expect(merged.env).toEqual({ CUSTOM: 'y' });
74
+ } finally {
75
+ vi.unstubAllEnvs();
76
+ }
77
+
78
+ rmSync(dir, { recursive: true, force: true });
79
+ });
80
+
81
+ it('does not add DefinePlugin for server bundles', async () => {
82
+ const webpackMod = await import('webpack');
83
+ const merged = withTypestylesExtract({});
84
+ const config = { plugins: [] as unknown[] };
85
+ const result = merged.webpack!(
86
+ config as Configuration,
87
+ {
88
+ isServer: true,
89
+ } as WebpackContext,
90
+ );
91
+ const hasDefine = result.plugins?.some(
92
+ (p: unknown) => p instanceof webpackMod.default.DefinePlugin,
93
+ );
94
+ expect(hasDefine).toBe(false);
95
+ });
96
+ });
package/src/build.ts ADDED
@@ -0,0 +1,192 @@
1
+ import { mkdir, writeFile } from 'node:fs/promises';
2
+ import { createRequire } from 'node:module';
3
+ import { dirname, join, resolve } from 'node:path';
4
+ import { pathToFileURL } from 'node:url';
5
+ import {
6
+ DEFAULT_EXTRACT_MODULE_CANDIDATES,
7
+ discoverDefaultExtractModules,
8
+ } from '@typestyles/build-runner';
9
+ import { collectStylesFromModules } from 'typestyles/build';
10
+ import type { NextConfig } from 'next';
11
+
12
+ /** Re-export shared convention paths (aligned with `@typestyles/vite`). */
13
+ export { DEFAULT_EXTRACT_MODULE_CANDIDATES, discoverDefaultExtractModules };
14
+
15
+ /** Manifest shape written next to extracted CSS (optional). */
16
+ export interface TypestylesExtractManifestV1 {
17
+ version: 1;
18
+ css: string;
19
+ }
20
+
21
+ /** Shape of `require('webpack')` for `DefinePlugin` only (webpack is an optional peer). */
22
+ type WebpackWithDefinePlugin = {
23
+ DefinePlugin: new (definitions: Record<string, string>) => unknown;
24
+ };
25
+
26
+ export interface BuildTypestylesForNextOptions {
27
+ root: string;
28
+ /**
29
+ * Style entry modules relative to `root`. When omitted, uses the same convention discovery as
30
+ * `@typestyles/vite` (see {@link discoverDefaultExtractModules}).
31
+ */
32
+ modules?: string[];
33
+ /** Output CSS path relative to `root`. Defaults to `app/typestyles.css`. */
34
+ cssOutFile?: string;
35
+ /**
36
+ * Manifest path relative to `root`. Defaults to `app/typestyles.manifest.json`.
37
+ * Pass `false` to skip writing a manifest.
38
+ */
39
+ manifestOutFile?: string | false;
40
+ /** Value stored in the manifest `css` field. Defaults to `cssOutFile`. */
41
+ manifestCssPath?: string;
42
+ }
43
+
44
+ function resolveExtractModulesForNext(root: string, modules?: string[]): string[] {
45
+ if (modules !== undefined) {
46
+ return modules;
47
+ }
48
+ const found = discoverDefaultExtractModules(root);
49
+ if (found.length === 0) {
50
+ throw new Error(
51
+ `[typestyles] No extraction entry found under ${root}. Add a convention file (see DEFAULT_EXTRACT_MODULE_CANDIDATES from @typestyles/build-runner) or pass modules to buildTypestylesForNext.`,
52
+ );
53
+ }
54
+ return found;
55
+ }
56
+
57
+ /**
58
+ * Extract TypeStyles CSS for a Next.js app (run from a script before `next build`, or in CI).
59
+ * Loads each module path (relative to `root`) so side-effect registrations run, then writes CSS.
60
+ *
61
+ * Defaults mirror `@typestyles/vite`: discovers a convention entry when `modules` is omitted,
62
+ * writes `app/typestyles.css` and `app/typestyles.manifest.json` unless overridden.
63
+ */
64
+ export async function buildTypestylesForNext(
65
+ options: BuildTypestylesForNextOptions,
66
+ ): Promise<void> {
67
+ const {
68
+ root,
69
+ modules,
70
+ cssOutFile = 'app/typestyles.css',
71
+ manifestOutFile,
72
+ manifestCssPath,
73
+ } = options;
74
+
75
+ const resolvedModules = resolveExtractModulesForNext(root, modules);
76
+
77
+ const loaders = resolvedModules.map((mod) => {
78
+ const abs = resolve(root, mod);
79
+ const href = pathToFileURL(abs).href;
80
+ return () => import(href);
81
+ });
82
+ const css = await collectStylesFromModules(loaders);
83
+ const outAbs = resolve(root, cssOutFile);
84
+ await mkdir(dirname(outAbs), { recursive: true });
85
+ await writeFile(outAbs, css, 'utf8');
86
+
87
+ const manifestRel =
88
+ manifestOutFile === false ? undefined : (manifestOutFile ?? 'app/typestyles.manifest.json');
89
+
90
+ if (manifestRel) {
91
+ const manifest: TypestylesExtractManifestV1 = {
92
+ version: 1,
93
+ css: manifestCssPath ?? cssOutFile,
94
+ };
95
+ const manAbs = resolve(root, manifestRel);
96
+ await mkdir(dirname(manAbs), { recursive: true });
97
+ await writeFile(manAbs, `${JSON.stringify(manifest, null, 2)}\n`, 'utf8');
98
+ }
99
+ }
100
+
101
+ export interface WithTypestylesExtractOptions {
102
+ /**
103
+ * When true (default), client bundles skip DOM style injection (`__TYPESTYLES_RUNTIME_DISABLED__`).
104
+ * Pair with a global stylesheet from {@link buildTypestylesForNext}.
105
+ */
106
+ disableClientRuntime?: boolean;
107
+ /**
108
+ * Project root used for module resolution (e.g. loading `webpack`). Defaults to `process.cwd()`.
109
+ */
110
+ root?: string;
111
+ }
112
+
113
+ export interface WithTypestylesOptions extends WithTypestylesExtractOptions {
114
+ /**
115
+ * Project root for convention discovery. Defaults to `process.cwd()` (the directory Next runs from).
116
+ */
117
+ root?: string;
118
+ }
119
+
120
+ /**
121
+ * Production Next.js config helper aligned with `@typestyles/vite`: when `NODE_ENV === 'production'`
122
+ * and a convention entry file exists under `root`, applies {@link withTypestylesExtract}; otherwise
123
+ * returns `nextConfig` unchanged (development keeps runtime injection).
124
+ */
125
+ export function withTypestyles(
126
+ nextConfig: NextConfig = {},
127
+ options: WithTypestylesOptions = {},
128
+ ): NextConfig {
129
+ const projectRoot = options.root ?? process.cwd();
130
+ const hasConventionEntry = discoverDefaultExtractModules(projectRoot).length > 0;
131
+ const prod = process.env.NODE_ENV === 'production';
132
+
133
+ if (!prod || !hasConventionEntry) {
134
+ return nextConfig;
135
+ }
136
+
137
+ return withTypestylesExtract(nextConfig, options);
138
+ }
139
+
140
+ /**
141
+ * Merge Next.js config so client bundles use pre-extracted CSS only (no runtime `<style>` injection).
142
+ *
143
+ * - **Webpack**: adds `DefinePlugin` for `__TYPESTYLES_RUNTIME_DISABLED__` on client bundles.
144
+ * - **Turbopack** (`next dev --turbo` / Turbopack production): webpack hooks do not run; the same
145
+ * `next.config` `env` entry `NEXT_PUBLIC_TYPESTYLES_RUNTIME_DISABLED` is merged so the client
146
+ * bundle still disables runtime insertion (see `typestyles` `sheet` implementation).
147
+ */
148
+ export function withTypestylesExtract(
149
+ nextConfig: NextConfig = {},
150
+ options: WithTypestylesExtractOptions = {},
151
+ ): NextConfig {
152
+ const disableClientRuntime = options.disableClientRuntime !== false;
153
+ const projectRoot = options.root ?? process.cwd();
154
+
155
+ return {
156
+ ...nextConfig,
157
+ ...(disableClientRuntime
158
+ ? {
159
+ env: {
160
+ ...(typeof nextConfig.env === 'object' &&
161
+ nextConfig.env !== null &&
162
+ !Array.isArray(nextConfig.env)
163
+ ? (nextConfig.env as Record<string, string>)
164
+ : {}),
165
+ NEXT_PUBLIC_TYPESTYLES_RUNTIME_DISABLED: 'true',
166
+ },
167
+ }
168
+ : {}),
169
+ webpack(config, context) {
170
+ const nextWebpack =
171
+ typeof nextConfig.webpack === 'function' ? nextConfig.webpack(config, context) : config;
172
+
173
+ if (disableClientRuntime && !context.isServer) {
174
+ try {
175
+ const require = createRequire(join(projectRoot, 'package.json'));
176
+ const webpackLib = require('webpack') as WebpackWithDefinePlugin;
177
+ nextWebpack.plugins.push(
178
+ new webpackLib.DefinePlugin({
179
+ __TYPESTYLES_RUNTIME_DISABLED__: JSON.stringify('true'),
180
+ }),
181
+ );
182
+ } catch {
183
+ console.warn(
184
+ '[@typestyles/next/build] Could not load webpack; client bundles may still inject <style>.',
185
+ );
186
+ }
187
+ }
188
+
189
+ return nextWebpack;
190
+ },
191
+ };
192
+ }
package/src/client.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type * as React from 'react';
2
- import type { useSyncExternalStore, useServerInsertedHTML } from 'react';
2
+ import type { useSyncExternalStore } from 'react';
3
3
 
4
4
  /**
5
5
  * Subscribe to typestyles CSS changes. Use this in client components
@@ -8,9 +8,10 @@ import type { useSyncExternalStore, useServerInsertedHTML } from 'react';
8
8
  export function useTypestyles(): ReturnType<typeof useSyncExternalStore<string>>;
9
9
 
10
10
  /**
11
- * Collect styles during server rendering for App Router.
11
+ * Re-export of React’s `useServerInsertedHTML` (App Router / streaming SSR).
12
+ * Declared here so consumers get a stable signature even when their `@types/react` predates the hook.
12
13
  */
13
- export { useServerInsertedHTML };
14
+ export function useServerInsertedHTML(callback: () => React.ReactNode | null): void;
14
15
 
15
16
  /**
16
17
  * Props for the TypestylesStylesheet component.
@@ -22,9 +23,7 @@ export interface TypestylesStylesheetProps {
22
23
  /**
23
24
  * A React component that renders typestyles CSS.
24
25
  */
25
- export function TypestylesStylesheet(
26
- props: TypestylesStylesheetProps,
27
- ): React.JSX.Element | null;
26
+ export function TypestylesStylesheet(props: TypestylesStylesheetProps): React.JSX.Element | null;
28
27
 
29
28
  /**
30
29
  * Create a Next.js layout export that includes typestyles.
package/src/index.d.ts CHANGED
@@ -1,13 +1,15 @@
1
+ import type { ReactElement, ReactNode } from 'react';
2
+
1
3
  export { getRegisteredCss } from 'typestyles/server';
2
4
 
3
5
  export interface TypestylesStylesheetProps {
4
- children?: React.ReactNode;
6
+ children?: ReactNode;
5
7
  }
6
8
 
7
9
  export function TypestylesStylesheet(props: TypestylesStylesheetProps): React.JSX.Element;
8
10
 
9
- export function collectStylesFromComponent(component: React.ReactElement): Promise<string>;
11
+ export function collectStylesFromComponent(component: ReactElement): Promise<string>;
10
12
 
11
- export function createTypestylesLayout<P extends { children?: React.ReactNode }>(
12
- layout: (props: P) => React.ReactNode,
13
+ export function createTypestylesLayout<P extends { children?: ReactNode }>(
14
+ layout: (props: P) => ReactNode,
13
15
  ): (props: P) => React.JSX.Element;
@@ -0,0 +1,13 @@
1
+ /**
2
+ * `useServerInsertedHTML` exists at runtime in Next.js App Router / React 18.3+ client builds,
3
+ * but some `@types/react` releases omit it. Augment `react` so local `tsc` and tooling match runtime.
4
+ *
5
+ * @see https://react.dev/reference/react-dom/server/useServerInsertedHTML
6
+ */
7
+ import type { ReactNode } from 'react';
8
+
9
+ declare module 'react' {
10
+ export function useServerInsertedHTML(callback: () => ReactNode | null): void;
11
+ }
12
+
13
+ export {};
@@ -0,0 +1,7 @@
1
+ import type { ReactElement } from 'react';
2
+
3
+ export { getRegisteredCss } from 'typestyles/server';
4
+
5
+ export declare function collectStylesFromComponent(component: ReactElement): Promise<string>;
6
+
7
+ export declare function getTypestylesMetadata(component: ReactElement): Promise<string>;
package/src/server.ts CHANGED
@@ -28,24 +28,25 @@ export async function collectStylesFromComponent(component: React.ReactElement):
28
28
  }
29
29
 
30
30
  /**
31
- * Generate CSS for use in Next.js metadata API.
32
- * Call this in your layout or page to get CSS for the head.
31
+ * Collect CSS by rendering a React element on the server (alias for {@link collectStylesFromComponent}).
32
+ * Use when you need styles for a specific subtree; inject the returned string in `<head>` / layout as needed.
33
33
  *
34
- * Note: This only captures CSS registered during the synchronous render.
34
+ * Next.js `metadata` / `generateMetadata` does not support injecting arbitrary `<style>` payloads; prefer
35
+ * {@link getRegisteredCss} in root `layout.tsx` or pipe this string into your own head/streaming pipeline.
36
+ *
37
+ * Note: This only captures CSS registered during that render.
35
38
  * For dynamic styles that may be registered client-side, use TypestylesStylesheet.
36
39
  *
37
40
  * @example
38
41
  * ```tsx
39
- * // app/layout.tsx
40
- * import { generateMetadata } from 'next/metadata';
42
+ * // app/some-route/head-styles.tsx (Server Component)
41
43
  * import { getTypestylesMetadata } from '@typestyles/next/server';
42
- * import { Home } from './Home';
44
+ * import { ProductPage } from './ProductPage';
43
45
  *
44
- * export async function generateMetadata() {
45
- * const css = await getTypestylesMetadata(<Home />);
46
- * return {
47
- * styles: [{ cssText: css }],
48
- * };
46
+ * export async function ProductPageStyles() {
47
+ * const css = await getTypestylesMetadata(<ProductPage />);
48
+ * if (!css) return null;
49
+ * return <style id="typestyles-product" dangerouslySetInnerHTML={{ __html: css }} />;
49
50
  * }
50
51
  * ```
51
52
  */