@flamingo-stack/openframe-frontend-core 0.0.814 → 0.0.815

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 (52) hide show
  1. package/README.md +26 -5
  2. package/dist/build/next-styles.cjs +170 -0
  3. package/dist/build/next-styles.d.ts +21 -0
  4. package/dist/build/style-sources.cjs +262 -0
  5. package/dist/build/style-sources.d.ts +12 -0
  6. package/dist/{chunk-ZNZ6453J.cjs → chunk-3E4FIJAM.cjs} +5 -5
  7. package/dist/{chunk-UTRRECPV.cjs → chunk-3ELDGEM2.cjs} +41 -41
  8. package/dist/{chunk-ILV243HM.cjs → chunk-53JJLHJM.cjs} +3 -3
  9. package/dist/{chunk-M6VLEXN3.cjs → chunk-5TUR7O7H.cjs} +42 -42
  10. package/dist/{chunk-WJPEDREU.cjs → chunk-633NTKO2.cjs} +2 -2
  11. package/dist/{chunk-2H7XPKKT.cjs → chunk-7NYWHEQM.cjs} +2 -2
  12. package/dist/{chunk-D23VVC3K.cjs → chunk-EB7YAUER.cjs} +11 -11
  13. package/dist/{chunk-E5VF3IXO.cjs → chunk-EJCUAADF.cjs} +2 -2
  14. package/dist/{chunk-IDEOLXY6.cjs → chunk-FUEK43FL.cjs} +79 -79
  15. package/dist/{chunk-AYMKG55T.cjs → chunk-JH65CEO4.cjs} +13 -13
  16. package/dist/{chunk-LUR2ED43.cjs → chunk-JOOZTRXQ.cjs} +4 -4
  17. package/dist/{chunk-IBYT5I7K.cjs → chunk-L7W4455K.cjs} +3 -3
  18. package/dist/{chunk-G5CCYMCU.cjs → chunk-O6VWD2SB.cjs} +3 -3
  19. package/dist/{chunk-KNGULKOU.cjs → chunk-RYJJHSHV.cjs} +10 -10
  20. package/dist/{chunk-CVPHODOE.cjs → chunk-SWBLTIN4.cjs} +28 -28
  21. package/dist/{chunk-KINBPFAC.cjs → chunk-VDXI26G7.cjs} +4 -0
  22. package/dist/{chunk-G2B6EA4J.cjs → chunk-ZAWHRYJZ.cjs} +35 -35
  23. package/dist/{cloud-tenants-JSH6AQMZ.cjs → cloud-tenants-SRTX2FZC.cjs} +3 -3
  24. package/dist/components/case-studies/index.cjs +12 -12
  25. package/dist/components/chat/embeddable-chat.d.ts +6 -0
  26. package/dist/components/chat/embeddable-chat.d.ts.map +1 -1
  27. package/dist/components/chat/index.cjs +2 -2
  28. package/dist/components/chat/index.d.ts.map +1 -1
  29. package/dist/components/chat/index.js +4 -0
  30. package/dist/components/contact/index.cjs +4 -4
  31. package/dist/components/docs/index.cjs +7 -7
  32. package/dist/components/embeds/index.cjs +4 -4
  33. package/dist/components/faq/index.cjs +5 -5
  34. package/dist/components/features/index.cjs +3 -3
  35. package/dist/components/help-center-pages/index.cjs +58 -58
  36. package/dist/components/index.cjs +33 -33
  37. package/dist/components/meeting-scheduler/index.cjs +26 -26
  38. package/dist/components/navigation/index.cjs +6 -6
  39. package/dist/components/onboarding-guides/index.cjs +5 -5
  40. package/dist/components/product-demo/index.cjs +12 -12
  41. package/dist/components/tickets/index.cjs +8 -8
  42. package/dist/components/ui/index.cjs +3 -3
  43. package/dist/{devices-OCEOO6OW.cjs → devices-DL4YU64N.cjs} +4 -4
  44. package/dist/index.cjs +7 -7
  45. package/dist/{knowledge-3GEE4LPY.cjs → knowledge-VQW5JL2Z.cjs} +3 -3
  46. package/dist/{logs-7GGUZSDB.cjs → logs-IY3WBLMW.cjs} +11 -11
  47. package/dist/{policies-S74WTNL4.cjs → policies-IXWTWMJO.cjs} +7 -7
  48. package/dist/{scripts-G4QAT4NZ.cjs → scripts-D5CLO5EG.cjs} +8 -8
  49. package/dist/{software-update-IYHJABLP.cjs → software-update-ULNP6CKJ.cjs} +6 -6
  50. package/package.json +17 -2
  51. package/src/components/chat/embeddable-chat.tsx +6 -0
  52. package/src/components/chat/index.ts +6 -1
package/README.md CHANGED
@@ -43,16 +43,35 @@ Extend the shared Tailwind config in your project:
43
43
 
44
44
  ```ts
45
45
  import designSystemConfig from '@flamingo-stack/openframe-frontend-core/tailwind.config.ts'
46
+ import { appStyleSources } from '@flamingo-stack/openframe-frontend-core/style-sources'
46
47
 
47
48
  export default {
48
- ...designSystemConfig,
49
- content: [
50
- './src/**/*.{js,ts,jsx,tsx}',
51
- './node_modules/@flamingo-stack/openframe-frontend-core/src/**/*.{js,ts,jsx,tsx}'
52
- ]
49
+ presets: [designSystemConfig],
50
+ // The files your App Router routes import, yours and this library's: never this library's whole
51
+ // `dist` or `src`, which puts every component's classes in the stylesheet every page blocks on.
52
+ content: appStyleSources({ root: __dirname, appDir: 'src/app' }),
53
53
  }
54
54
  ```
55
55
 
56
+ `appStyleSources` (`scripts/style-sources.cjs`) walks the import graph from the route files, tree-shaken
57
+ as your bundler does. A host can leave the lazily loaded chat out of the page's stylesheet with
58
+ `firstPaint: true`, and give `EmbeddableChat` a `loadStyles` that loads a full stylesheet built
59
+ without it (see the file's header).
60
+
61
+ Then send the stylesheet inside each page's HTML, so a page never waits on a second request to paint,
62
+ and hold its size to a budget in your checks (`scripts/next-styles.cjs` says why and what it costs):
63
+
64
+ ```js
65
+ // next.config.mjs
66
+ import { withInlineStyles } from '@flamingo-stack/openframe-frontend-core/next-styles'
67
+ export default withInlineStyles(nextConfig)
68
+ ```
69
+
70
+ ```bash
71
+ node node_modules/@flamingo-stack/openframe-frontend-core/dist/build/next-styles.cjs budget \
72
+ --input src/app/globals.css --config tailwind.config.ts --budget 31500
73
+ ```
74
+
56
75
  ## Package Exports
57
76
 
58
77
  | Export Path | Description |
@@ -67,6 +86,8 @@ export default {
67
86
  | `./utils` | Utilities (cn, formatDate, formatPrice, getPlatformUrl, platform-config) |
68
87
  | `./types` | TypeScript type definitions |
69
88
  | `./styles` | CSS styles and ODS design tokens |
89
+ | `./style-sources` | Tailwind `content` for an app: the files its routes import (`appStyleSources`) |
90
+ | `./next-styles` | The stylesheet inside each page's HTML (`withInlineStyles`) and its size gate (`measureStylesheet`, `budget` command) |
70
91
  | `./nats` | NATS WebSocket utilities |
71
92
  | `./fonts` | Font configuration |
72
93
 
@@ -0,0 +1,170 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * How a Next.js app that uses this library ships its stylesheet: inside the page, and measured.
4
+ *
5
+ * const { withInlineStyles } = require('<package>/next-styles')
6
+ * export default withInlineStyles(nextConfig) // next.config
7
+ *
8
+ * next-styles budget --budget 31500 // the build gate (package.json script)
9
+ *
10
+ * `budget` finds the app's stylesheet (`src/app/globals.css`, else `app/globals.css`) and Tailwind config
11
+ * (`tailwind.config.{ts,js,cjs,mjs}`) itself and is named after the app's package; `--input`, `--config`
12
+ * and `--name` say otherwise.
13
+ *
14
+ * WHY. A page cannot paint before its stylesheet arrives, and a stylesheet in a file of its own is
15
+ * requested only once the HTML names it: one more round trip after the HTML, whatever the file weighs.
16
+ * Measured on flamingo.run (CU-17tkuw617h7, Lighthouse mobile, slow 4G): the 44 KB sheet took 856 ms
17
+ * from request to last byte, a 1 KB sheet beside it 570 ms, and the page painted 65 ms after the large
18
+ * one landed. Cutting the sheet by a quarter moved LCP by nothing measurable; sending the sheet inside
19
+ * the HTML moved the home page's LCP from 1.50 s to 0.93 s and a blog post's from 1.60 s to 0.95 s.
20
+ *
21
+ * WHAT. `withInlineStyles` turns on Next's `experimental.inlineCss`: every stylesheet a route links is
22
+ * written into its HTML as a `<style>` tag instead (production builds, `output: 'export'` included;
23
+ * `next dev` keeps its links). The price is paid in the HTML: the sheet arrives with every page and is
24
+ * not cached apart from it, and Next sends it twice on a first load (the tag and the page's data).
25
+ * That is a good trade only while the sheet is small, so it comes with its gate: `measureStylesheet`
26
+ * builds the app's stylesheet the way its build does (Tailwind, minified) and reports its size
27
+ * brotli-compressed, as a CDN serves it, and the `budget` command fails past a stated size. Keep the
28
+ * sheet small with `appStyleSources` (`./style-sources`): Tailwind content from what the routes import.
29
+ *
30
+ * Per page: a sheet cut per route from the import graph was measured too, and saved 10% (26.4 KB
31
+ * against 29.3 KB brotli on flamingo): a site's shared layout reaches most of the design system, so a
32
+ * page's sheet is mostly its layout's. Inlining removes the wait; a smaller sheet only makes it cheap.
33
+ */
34
+ const { execFile } = require('node:child_process');
35
+ const { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } = require('node:fs');
36
+ const { tmpdir } = require('node:os');
37
+ const { dirname, isAbsolute, join, resolve } = require('node:path');
38
+ const { promisify } = require('node:util');
39
+ const { brotliCompressSync, constants } = require('node:zlib');
40
+
41
+ /** `nextConfig` with every route's stylesheets written into its HTML. Composes with a config function. */
42
+ function withInlineStyles(nextConfig) {
43
+ const apply = config => ({ ...config, experimental: { ...config.experimental, inlineCss: true } });
44
+ if (typeof nextConfig === 'function') {
45
+ return async (...args) => apply(await nextConfig(...args));
46
+ }
47
+ return apply(nextConfig);
48
+ }
49
+
50
+ /**
51
+ * The stylesheet `input` with each `@import` made an absolute path: the Tailwind CLI resolves an import
52
+ * by path only, never through a package's `exports` (`@import '<package>/styles'`), which a bundler does.
53
+ */
54
+ function resolveImports(input, root) {
55
+ const from = dirname(input);
56
+ return readFileSync(input, 'utf8').replace(/@import\s+(['"])([^'"]+)\1\s*;/g, (statement, _quote, specifier) => {
57
+ if (/^(https?:)?\/\//.test(specifier)) return statement;
58
+ const file =
59
+ specifier.startsWith('.') || isAbsolute(specifier)
60
+ ? resolve(from, specifier)
61
+ : require.resolve(specifier, { paths: [root, from] });
62
+ return `@import "${file}";`;
63
+ });
64
+ }
65
+
66
+ /**
67
+ * Builds `input` with Tailwind and `config` the way the app's build does, minified, and measures it.
68
+ *
69
+ * root the app's directory (absolute); `input` and `config` are relative to it.
70
+ * input the stylesheet the root layout imports ('src/app/globals.css').
71
+ * config the Tailwind config that builds it ('tailwind.config.ts').
72
+ * env variables the config reads (an app that builds one site per `NEXT_PUBLIC_APP_TYPE`).
73
+ *
74
+ * Resolves to `{ css, raw, brotli }`: the minified stylesheet, its bytes, and its bytes brotli-compressed
75
+ * at the quality a CDN serves static files with.
76
+ */
77
+ async function measureStylesheet({ root, input, config, env = {} }) {
78
+ if (!isAbsolute(root)) throw new Error('measureStylesheet: root must be an absolute path');
79
+ const file = resolve(root, input);
80
+ const dir = mkdtempSync(join(tmpdir(), 'next-styles-'));
81
+ try {
82
+ // The copy lives in the temp folder, never beside the input (a file watcher or linter there would see
83
+ // it). A stylesheet's own `@config` is relative to ITS folder and Tailwind refuses an absolute one, so
84
+ // it is dropped: `config` is what the sheet is built with, as the app's build states it.
85
+ const source = join(dir, 'input.css');
86
+ const output = join(dir, 'output.css');
87
+ writeFileSync(source, resolveImports(file, root).replace(/^\s*@config\s+(['"])[^'"]+\1\s*;\s*$/gm, ''));
88
+ // The app's own Tailwind, the one its build runs; this package's where the app has none of its own.
89
+ const cli = require.resolve('tailwindcss/lib/cli.js', { paths: [root, __dirname] });
90
+ await promisify(execFile)(
91
+ process.execPath,
92
+ [cli, '-c', resolve(root, config), '-i', source, '-o', output, '--minify'],
93
+ {
94
+ cwd: root,
95
+ env: { ...process.env, ...env },
96
+ maxBuffer: 64 * 1024 * 1024,
97
+ },
98
+ );
99
+ const css = readFileSync(output, 'utf8');
100
+ const brotli = brotliCompressSync(Buffer.from(css), {
101
+ params: { [constants.BROTLI_PARAM_QUALITY]: constants.BROTLI_MAX_QUALITY },
102
+ }).length;
103
+ return { css, raw: Buffer.byteLength(css), brotli };
104
+ } finally {
105
+ rmSync(dir, { recursive: true, force: true });
106
+ }
107
+ }
108
+
109
+ const kb = bytes => `${(bytes / 1024).toFixed(1)} KB`;
110
+
111
+ /** `--name value` pairs of the command line; `--env KEY=VALUE` may repeat. */
112
+ function parseArgs(argv) {
113
+ const args = { env: {} };
114
+ for (let i = 0; i < argv.length; i += 2) {
115
+ const [name, value] = [argv[i], argv[i + 1]];
116
+ if (!name.startsWith('--') || value === undefined) throw new Error(`next-styles: bad argument ${name}`);
117
+ if (name === '--env') {
118
+ const at = value.indexOf('=');
119
+ args.env[value.slice(0, at)] = value.slice(at + 1);
120
+ } else {
121
+ args[name.slice(2)] = value;
122
+ }
123
+ }
124
+ return args;
125
+ }
126
+
127
+ /** The first of `candidates` (relative to `root`) that exists. */
128
+ const firstExisting = (root, candidates) => candidates.find(file => existsSync(resolve(root, file)));
129
+
130
+ /** `budget --budget <brotli bytes> [--input <css>] [--config <tailwind config>] [--name <label>] [--env K=V]` */
131
+ async function budgetCommand(argv) {
132
+ const root = process.cwd();
133
+ const args = parseArgs(argv);
134
+ const budget = Number(args.budget);
135
+ const input = args.input ?? firstExisting(root, ['src/app/globals.css', 'app/globals.css']);
136
+ const config =
137
+ args.config ??
138
+ firstExisting(
139
+ root,
140
+ ['ts', 'js', 'cjs', 'mjs'].map(ext => `tailwind.config.${ext}`),
141
+ );
142
+ if (!input || !config || !Number.isInteger(budget) || budget <= 0) {
143
+ throw new Error('usage: next-styles budget --budget <brotli bytes> [--input <css>] [--config <tailwind config>]');
144
+ }
145
+ const name = args.name ?? (existsSync(join(root, 'package.json')) ? require(join(root, 'package.json')).name : input);
146
+ const { raw, brotli } = await measureStylesheet({ root, input, config, env: args.env });
147
+ console.log(`[css-budget] ${name}: ${kb(raw)} raw, ${kb(brotli)} brotli (budget ${kb(budget)})`);
148
+ if (brotli > budget) {
149
+ console.error(
150
+ `[css-budget] FAIL: ${name} is over its budget. Every page carries this stylesheet in its HTML: find what a ` +
151
+ 'route now imports that it does not render, or raise the budget with the reason.',
152
+ );
153
+ process.exitCode = 1;
154
+ }
155
+ }
156
+
157
+ if (require.main === module) {
158
+ const [command, ...rest] = process.argv.slice(2);
159
+ Promise.resolve()
160
+ .then(() => {
161
+ if (command !== 'budget') throw new Error(`next-styles: unknown command ${command ?? '(none)'}; try "budget"`);
162
+ return budgetCommand(rest);
163
+ })
164
+ .catch(error => {
165
+ console.error(`[css-budget] ${error.message}`);
166
+ process.exitCode = 1;
167
+ });
168
+ }
169
+
170
+ module.exports = { withInlineStyles, measureStylesheet, resolveImports };
@@ -0,0 +1,21 @@
1
+ /** `nextConfig` (an object, or a config function) with every route's stylesheets written into its HTML. */
2
+ export function withInlineStyles<A extends unknown[], T extends object>(
3
+ nextConfig: (...args: A) => T | Promise<T>,
4
+ ): (...args: A) => Promise<T & { experimental: { inlineCss: true } }>;
5
+ export function withInlineStyles<T extends object>(nextConfig: T): T & { experimental: { inlineCss: true } };
6
+
7
+ /** Options of {@link measureStylesheet}; each is described in `next-styles.cjs`. */
8
+ export interface MeasureStylesheetOptions {
9
+ root: string;
10
+ input: string;
11
+ config: string;
12
+ env?: Record<string, string>;
13
+ }
14
+
15
+ /** The app's stylesheet built as its build builds it, minified: its bytes raw and brotli-compressed. */
16
+ export function measureStylesheet(
17
+ options: MeasureStylesheetOptions,
18
+ ): Promise<{ css: string; raw: number; brotli: number }>;
19
+
20
+ /** The stylesheet at `input` with each `@import` resolved to an absolute path (packages through their `exports`). */
21
+ export function resolveImports(input: string, root: string): string;
@@ -0,0 +1,262 @@
1
+ /**
2
+ * The files a Next.js app's pages really reach, for Tailwind's `content`.
3
+ *
4
+ * const { appStyleSources } = require('<package>/style-sources')
5
+ * content: appStyleSources({ root: __dirname, appDir: 'app', firstPaint: true }) // the page's sheet
6
+ * content: appStyleSources({ root: __dirname, appDir: 'app' }) // the full sheet
7
+ *
8
+ * WHY. Tailwind writes one rule for every class name it finds in `content`, and an app that lists
9
+ * this library's whole `dist` gets a rule for every class of every component the library ships:
10
+ * the chat, the markdown editor, the admin tables, whether or not a page renders them. On the hub
11
+ * that was 299 KB of a 366 KB stylesheet, and the stylesheet blocks every page's first paint.
12
+ *
13
+ * WHAT. Every route file of the App Router (`page`, `layout`, `template`, `loading`, `error`,
14
+ * `not-found`, `default`) is an entry, and the import graph is walked from them the way the app's
15
+ * bundler walks it (esbuild, in memory, nothing written): the app's own modules and this library's
16
+ * per-module ESM build, tree-shaken, so a barrel's unused re-exports are left out exactly as the
17
+ * app's bundle leaves them out (the library declares no side effects but its CSS). Every other
18
+ * package is external: it ships no Tailwind classes of the app's. What is not imported is not
19
+ * scanned, so a new page, component or library module is in the stylesheet the moment something
20
+ * imports it, with no list to keep.
21
+ *
22
+ * The library resolves from `node_modules`, the way a production build resolves it: a tsconfig
23
+ * `paths` alias that points the package at a source checkout is ignored here.
24
+ *
25
+ * Options:
26
+ * root the app's directory (absolute).
27
+ * appDir the App Router directory, relative to root ('app', 'src/app').
28
+ * exclude route directories under appDir whose files are not entries ('admin'): their own
29
+ * layout imports their own stylesheet.
30
+ * routes which routes this build serves, for an app that builds several sites from one tree:
31
+ * { module, export, args } names a function of the app's (`(…args, path) => boolean`),
32
+ * called with each page's path ('/blog/x' for 'app/blog/[slug]/page.tsx'). A page it
33
+ * refuses is not an entry, nor is a layout or loading file with no served page under it.
34
+ * alias bare specifier → file relative to root, for build-time aliases the bundler config
35
+ * states (Turbopack's resolveAlias).
36
+ * firstPaint true for the stylesheet a page BLOCKS on: the library's lazily loaded panels
37
+ * (`LAZY_STYLED`) are not followed, because each loads the app's full stylesheet itself
38
+ * when it opens (`EmbeddableChat`'s `loadStyles`). The full stylesheet is the same call
39
+ * without `firstPaint` and without `exclude`: it holds every class the first-paint one
40
+ * holds, so whichever of the two a page loads last, every element keeps Tailwind's order.
41
+ *
42
+ * A static list of files is what Tailwind's `content` takes, so in `next dev` a NEW file is in the
43
+ * stylesheet after the dev server restarts; edits to a file already listed are picked up live.
44
+ *
45
+ * Tailwind loads its config synchronously and esbuild runs plugins only in its asynchronous API, so
46
+ * the walk runs in a child process this call waits for (a few seconds, once per process).
47
+ */
48
+ const { execFileSync } = require('node:child_process');
49
+ const { existsSync, readdirSync, realpathSync, rmSync, statSync } = require('node:fs');
50
+ const { dirname, isAbsolute, join, relative, resolve, sep } = require('node:path');
51
+
52
+ /** This package's directory: the nearest package.json up from here (`scripts/` in the repo, `dist/build/` installed). */
53
+ function packageDir() {
54
+ for (let dir = __dirname; ; dir = dirname(dir)) {
55
+ if (existsSync(join(dir, 'package.json'))) return dir;
56
+ if (dirname(dir) === dir) throw new Error('style-sources: no package.json above this file');
57
+ }
58
+ }
59
+ const PACKAGE_DIR = packageDir();
60
+ const PACKAGE = require(join(PACKAGE_DIR, 'package.json')).name;
61
+ const ROUTE_FILE =
62
+ /^(page|layout|template|loading|error|not-found|default|global-error|global-not-found)\.[cm]?[jt]sx?$/;
63
+ /**
64
+ * The library's modules that load on their own, after the page, and call the host's `loadStyles`
65
+ * when they do. Only these leave the first-paint stylesheet: a lazily loaded module that does not
66
+ * bring the full stylesheet with it must keep its classes in the one the page loads.
67
+ */
68
+ const LAZY_STYLED = ['dist/components/chat/embeddable-chat.js'];
69
+ /** What the walk reads: code (and JSON, which code imports). Every other import (a stylesheet, an image, a
70
+ * font) holds no class name and is loaded as an empty module, so nothing has to name its extension. */
71
+ const CODE = /\.(?:[cm]?[jt]sx?|json)$/;
72
+ const codeOnly = {
73
+ name: 'code-only',
74
+ setup(builder) {
75
+ builder.onLoad({ filter: /.*/ }, args => (CODE.test(args.path) ? undefined : { contents: '', loader: 'empty' }));
76
+ },
77
+ };
78
+
79
+ /** Route files under `dir`, skipping private folders (`_x`), API routes and the excluded directories. */
80
+ function routeFiles(appRoot, dir, exclude, out) {
81
+ for (const name of readdirSync(dir)) {
82
+ const path = join(dir, name);
83
+ if (statSync(path).isDirectory()) {
84
+ const rel = relative(appRoot, path).split(sep).join('/');
85
+ if (name.startsWith('_') || name === 'api' || exclude.includes(rel)) continue;
86
+ routeFiles(appRoot, path, exclude, out);
87
+ } else if (ROUTE_FILE.test(name)) {
88
+ out.push(path);
89
+ }
90
+ }
91
+ return out;
92
+ }
93
+
94
+ /**
95
+ * The paths a route directory answers, as the filter is asked about them: a sample path with each
96
+ * dynamic segment filled ('/blog/x'), and for a dynamic route the static part before its first
97
+ * dynamic segment ('/blog', '/' for 'app/(landing)/[slug]'), because a dynamic route serves every path
98
+ * under it and a filter that lists exact paths ('/ai-copilots-for-msps') knows none of them as '/x'.
99
+ */
100
+ function routePaths(appRoot, dir) {
101
+ const segments = relative(appRoot, dir)
102
+ .split(sep)
103
+ .filter(segment => segment && !/^\(.*\)$/.test(segment) && !segment.startsWith('@'));
104
+ const firstDynamic = segments.findIndex(segment => segment.startsWith('['));
105
+ const sample = `/${segments.map(segment => (segment.startsWith('[') ? 'x' : segment)).join('/')}`;
106
+ if (firstDynamic === -1) return [sample];
107
+ return [sample, `/${segments.slice(0, firstDynamic).join('/')}`];
108
+ }
109
+
110
+ const isPage = file => /^page\.[cm]?[jt]sx?$/.test(file.slice(file.lastIndexOf(sep) + 1));
111
+
112
+ /**
113
+ * The route files this build serves: every page the filter accepts at one of its paths (`routePaths`),
114
+ * and every other route file (layout, loading, error, …) that sits on the path to one. When in doubt a
115
+ * page is kept: a page kept for nothing costs bytes, a page dropped costs its styles.
116
+ */
117
+ function servedRouteFiles(appRoot, files, isServed) {
118
+ const pages = files.filter(file => isPage(file) && routePaths(appRoot, dirname(file)).some(isServed));
119
+ const dirs = pages.map(page => `${dirname(page)}${sep}`);
120
+ return files.filter(file =>
121
+ isPage(file) ? pages.includes(file) : dirs.some(dir => dir.startsWith(`${dirname(file)}${sep}`)),
122
+ );
123
+ }
124
+
125
+ /** The app's route filter, bundled from its source (its own aliases resolved) and loaded in this process. */
126
+ async function loadRouteFilter(build, root, tsconfigRaw, routes) {
127
+ // Beside the app's own packages, so the bundle's external imports resolve as the app's do.
128
+ const outfile = join(root, 'node_modules', '.cache', 'style-sources', `routes-${process.pid}.cjs`);
129
+ await build({
130
+ absWorkingDir: root,
131
+ entryPoints: [resolve(root, routes.module)],
132
+ bundle: true,
133
+ outfile,
134
+ format: 'cjs',
135
+ platform: 'node',
136
+ packages: 'external',
137
+ jsx: 'automatic',
138
+ logLevel: 'silent',
139
+ tsconfigRaw,
140
+ plugins: [codeOnly],
141
+ });
142
+ try {
143
+ const filter = require(outfile)[routes.export];
144
+ if (typeof filter !== 'function') throw new Error(`${routes.module} exports no function ${routes.export}`);
145
+ return path => filter(...(routes.args ?? []), path);
146
+ } finally {
147
+ rmSync(outfile, { force: true });
148
+ }
149
+ }
150
+
151
+ /** The project's tsconfig `paths`, minus any that point this package somewhere other than node_modules. */
152
+ function projectPaths(root) {
153
+ let ts;
154
+ try {
155
+ ts = require(require.resolve('typescript', { paths: [root] }));
156
+ } catch {
157
+ return { baseUrl: root, paths: {} };
158
+ }
159
+ const file = ts.findConfigFile(root, ts.sys.fileExists);
160
+ const parsed = file
161
+ ? ts.getParsedCommandLineOfConfigFile(file, {}, { ...ts.sys, onUnRecoverableConfigFileDiagnostic() {} })
162
+ : null;
163
+ const paths = Object.fromEntries(
164
+ Object.entries(parsed?.options.paths ?? {}).filter(([key]) => key !== PACKAGE && !key.startsWith(`${PACKAGE}/`)),
165
+ );
166
+ return { baseUrl: parsed?.options.baseUrl ?? parsed?.options.pathsBasePath ?? root, paths };
167
+ }
168
+
169
+ const memo = new Map();
170
+
171
+ function appStyleSources({ root, appDir = 'app', exclude = [], routes = null, alias = {}, firstPaint = false }) {
172
+ if (!isAbsolute(root)) throw new Error('appStyleSources: root must be an absolute path');
173
+ const options = { root, appDir, exclude, routes, alias, firstPaint };
174
+ const key = JSON.stringify(options);
175
+ if (!memo.has(key)) {
176
+ const output = execFileSync(process.execPath, [__filename], {
177
+ input: key,
178
+ maxBuffer: 64 * 1024 * 1024,
179
+ stdio: ['pipe', 'pipe', 'inherit'],
180
+ });
181
+ memo.set(key, JSON.parse(output.toString()));
182
+ }
183
+ return memo.get(key);
184
+ }
185
+
186
+ /** The walk itself, run in the child process. */
187
+ async function walk({ root, appDir, exclude, routes, alias, firstPaint }) {
188
+ const { build } = require(require.resolve('esbuild', { paths: [root, __dirname] }));
189
+ const appRoot = resolve(root, appDir);
190
+ const packageRoot = realpathSync(PACKAGE_DIR);
191
+ const deferred = firstPaint ? LAZY_STYLED.map(file => join(packageRoot, file)) : [];
192
+ const isDeferred = path => deferred.includes(path);
193
+ const { baseUrl, paths } = projectPaths(root);
194
+ const tsconfigRaw = { compilerOptions: { baseUrl, paths, jsx: 'react-jsx' } };
195
+ const allRouteFiles = routeFiles(appRoot, appRoot, exclude, []);
196
+ const entryPoints = routes
197
+ ? servedRouteFiles(appRoot, allRouteFiles, await loadRouteFilter(build, root, tsconfigRaw, routes))
198
+ : allRouteFiles;
199
+ const isPathAlias = specifier =>
200
+ Object.keys(paths).some(key => specifier === key || (key.endsWith('*') && specifier.startsWith(key.slice(0, -1))));
201
+
202
+ const graph = {
203
+ name: 'style-sources',
204
+ setup(builder) {
205
+ builder.onResolve({ filter: /.*/ }, args => {
206
+ if (args.kind === 'entry-point') return undefined;
207
+ const specifier = args.path;
208
+ if (Object.prototype.hasOwnProperty.call(alias, specifier)) return { path: resolve(root, alias[specifier]) };
209
+ if (specifier.startsWith('.') || isAbsolute(specifier) || isPathAlias(specifier)) return undefined;
210
+ if (specifier === PACKAGE || specifier.startsWith(`${PACKAGE}/`)) return undefined;
211
+ return { path: specifier, external: true };
212
+ });
213
+ builder.onLoad({ filter: /\.[cm]?[jt]sx?$/ }, args =>
214
+ isDeferred(realpathSync(args.path)) ? { contents: '', loader: 'js' } : undefined,
215
+ );
216
+ },
217
+ };
218
+
219
+ const result = await build({
220
+ absWorkingDir: root,
221
+ entryPoints,
222
+ bundle: true,
223
+ splitting: true,
224
+ write: false,
225
+ metafile: true,
226
+ outdir: join(root, '.style-sources'),
227
+ format: 'esm',
228
+ platform: 'node',
229
+ conditions: ['import', 'module', 'default'],
230
+ jsx: 'automatic',
231
+ treeShaking: true,
232
+ logLevel: 'silent',
233
+ tsconfigRaw,
234
+ plugins: [graph, codeOnly],
235
+ });
236
+
237
+ // A module is scanned when the tree-shaken bundle keeps any of it, as the app's own bundle does.
238
+ const files = new Set();
239
+ for (const output of Object.values(result.metafile.outputs)) {
240
+ for (const [file, { bytesInOutput }] of Object.entries(output.inputs)) {
241
+ const path = resolve(root, file);
242
+ if (bytesInOutput > 0) files.add(path);
243
+ }
244
+ }
245
+ return [...files].sort();
246
+ }
247
+
248
+ if (require.main === module) {
249
+ let input = '';
250
+ process.stdin.on('data', chunk => (input += chunk));
251
+ process.stdin.on('end', () =>
252
+ walk(JSON.parse(input)).then(
253
+ files => process.stdout.write(JSON.stringify(files)),
254
+ error => {
255
+ console.error(`[style-sources] ${error.message}`);
256
+ process.exit(1);
257
+ },
258
+ ),
259
+ );
260
+ }
261
+
262
+ module.exports = { appStyleSources, routePaths, servedRouteFiles, LAZY_STYLED };
@@ -0,0 +1,12 @@
1
+ /** Options of {@link appStyleSources}; each is described in `style-sources.cjs`. */
2
+ export interface AppStyleSourcesOptions {
3
+ root: string;
4
+ appDir?: string;
5
+ exclude?: string[];
6
+ routes?: { module: string; export: string; args?: unknown[] } | null;
7
+ alias?: Record<string, string>;
8
+ firstPaint?: boolean;
9
+ }
10
+
11
+ /** The files a Next.js app's served routes import, for Tailwind's `content`. */
12
+ export function appStyleSources(options: AppStyleSourcesOptions): string[];
@@ -2,7 +2,7 @@
2
2
 
3
3
 
4
4
 
5
- var _chunkIDEOLXY6cjs = require('./chunk-IDEOLXY6.cjs');
5
+ var _chunkFUEK43FLcjs = require('./chunk-FUEK43FL.cjs');
6
6
 
7
7
 
8
8
 
@@ -17,7 +17,7 @@ var _chunkIJCSQFLDcjs = require('./chunk-IJCSQFLD.cjs');
17
17
  var _chunk7O7EX7HQcjs = require('./chunk-7O7EX7HQ.cjs');
18
18
 
19
19
 
20
- var _chunkKINBPFACcjs = require('./chunk-KINBPFAC.cjs');
20
+ var _chunkVDXI26G7cjs = require('./chunk-VDXI26G7.cjs');
21
21
 
22
22
 
23
23
 
@@ -203,13 +203,13 @@ function ContactForm({
203
203
  );
204
204
  }),
205
205
  className: "flex flex-grow flex-col space-y-4 content-md:space-y-6",
206
- ..._chunkKINBPFACcjs.HUBSPOT_DO_NOT_COLLECT_FORM_PROPS,
206
+ ..._chunkVDXI26G7cjs.HUBSPOT_DO_NOT_COLLECT_FORM_PROPS,
207
207
  children: [
208
208
  !showName && /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "input", { type: "hidden", ...register("name") }),
209
209
  !showEmail && /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "input", { type: "hidden", ...register("email") }),
210
210
  !showHelpCategory && /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "input", { type: "hidden", ...register("helpCategory") }),
211
211
  !showMessage && /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "input", { type: "hidden", ...register("message") }),
212
- /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _chunkIDEOLXY6cjs.HoneypotField, { ...honeypotInputProps }),
212
+ /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _chunkFUEK43FLcjs.HoneypotField, { ...honeypotInputProps }),
213
213
  extraTopField,
214
214
  showNameEmailRow && /* @__PURE__ */ _jsxruntime.jsxs.call(void 0, "div", { className: "grid grid-cols-1 gap-4 content-md:grid-cols-2 content-md:gap-6", children: [
215
215
  showName && /* @__PURE__ */ _jsxruntime.jsxs.call(void 0, "div", { className: "flex flex-col", children: [
@@ -334,7 +334,7 @@ function ContactForm({
334
334
  /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _chunkSWF6TNZ3cjs.RequiredMark, {})
335
335
  ] }),
336
336
  /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
337
- _chunkIDEOLXY6cjs.Textarea,
337
+ _chunkFUEK43FLcjs.Textarea,
338
338
  {
339
339
  id: "message",
340
340
  ...register("message"),