Repository navigation
Expand file tree
/
Copy pathrollup.config.ts
More file actions
190 lines (178 loc) · 6.11 KB
/
Copy pathrollup.config.ts
File metadata and controls
190 lines (178 loc) · 6.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
/**
* Rollup build configuration for library, CLI entrypoint, and bundled types.
* Externalizes production dependencies; emits ESM outputs; best-effort doc copy.
* @module
*/
import aliasPlugin, { type Alias } from '@rollup/plugin-alias';
import commonjsPlugin from '@rollup/plugin-commonjs';
import jsonPlugin from '@rollup/plugin-json';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import terserPlugin from '@rollup/plugin-terser';
import typescriptPlugin from '@rollup/plugin-typescript';
import fs from 'fs-extra';
import path from 'node:path';
import { builtinModules } from 'node:module';
import { fileURLToPath } from 'node:url';
import type {
InputOptions,
OutputOptions,
Plugin,
RollupOptions,
} from 'rollup';
import dtsPlugin from 'rollup-plugin-dts';
import { createRequire } from 'node:module';
const outputPath = 'dist';
// Path alias @ -> <abs>/src
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const srcAbs = path.resolve(__dirname, 'src');
const aliases: Alias[] = [{ find: '@', replacement: srcAbs }];
const alias = aliasPlugin({ entries: aliases });
// Externalize all production dependencies to avoid bundling issues (assets, singletons, __filename)
// and to keep the distribution size small (relying on node_modules).
const pkg = JSON.parse(
fs.readFileSync(path.resolve(__dirname, 'package.json'), 'utf8'),
) as { dependencies?: Record<string, string> };
const externalPkgs = new Set([
...(pkg.dependencies ? Object.keys(pkg.dependencies) : []),
// Explicit additions if needed (e.g. peer deps or optionals not in dependencies)
'clipboardy',
'fs-extra',
'typescript',
]);
// Treat Node built-ins and node: specifiers as external.
const nodeExternals = new Set([
...builtinModules,
...builtinModules.map((m) => `node:${m}`),
]);
const copyDocsPlugin = (dest: string): Plugin => {
return {
name: 'stan-copy-docs',
async writeBundle() {
const fromSystem = path.resolve(__dirname, '.stan', 'system');
const candidates = [
{
src: path.join(fromSystem, 'stan.system.md'),
dest: path.join(dest, 'stan.system.md'),
},
];
try {
await fs.ensureDir(dest);
for (const c of candidates) {
if (await fs.pathExists(c.src)) await fs.copyFile(c.src, c.dest);
}
} catch {
// best-effort
}
},
};
};
const makePlugins = (minify: boolean, extras: Plugin[] = []): Plugin[] => {
const base: Plugin[] = [
alias,
nodeResolve({ exportConditions: ['node', 'module', 'default'] }),
commonjsPlugin(),
jsonPlugin(),
typescriptPlugin(),
...extras,
];
return minify
? [...base, terserPlugin({ format: { comments: false } })]
: base;
};
const commonInputOptions = (
minify: boolean,
extras: Plugin[] = [],
): InputOptions => ({
plugins: makePlugins(minify, extras),
onwarn(warning, defaultHandler) {
// CI build guard: fail on new circular dependencies introduced in this package.
// Allow cycles originating from node_modules (e.g., zod), but treat project cycles as errors.
if (warning.code === 'CIRCULAR_DEPENDENCY') {
const msg = String((warning as { message?: string }).message ?? '');
const ids =
((warning as unknown as { ids?: string[] }).ids as
| string[]
| undefined) ?? [];
const fromNodeModules =
(Array.isArray(ids) && ids.some((p) => p.includes('node_modules'))) ||
/node_modules/.test(msg);
if (!fromNodeModules) {
// Treat as a hard error to surface regressions early in CI.
throw new Error(`Circular dependency detected: ${msg}`);
}
}
defaultHandler(warning);
},
external: (id) =>
nodeExternals.has(id) ||
externalPkgs.has(id) ||
// also treat deep subpath imports as external (e.g., clipboardy/fallbacks/...)
Array.from(externalPkgs).some((p) => id === p || id.startsWith(`${p}/`)),
});
/**
* Rollup options to build the public library entrypoint (`src/index.ts`) into an
* ESM-only output folder.
*
* @param dest - Destination directory where Rollup should write the library output.
* @returns Rollup configuration for the library build.
*/
export const buildLibrary = (dest: string): RollupOptions => ({
input: 'src/index.ts',
output: [{ dir: dest, format: 'esm', sourcemap: false }],
...commonInputOptions(
true,
// Copy docs once from library config
[copyDocsPlugin(dest)],
),
});
const discoverCliEntries = (): string[] => {
const candidates = [
'src/cli/bin/stan.ts', // preferred: single bootstrap
'src/cli/stan.ts', // legacy fallback (should not exist post‑cleanup)
'src/cli/index.ts', // last resort (library factory only)
];
const found = candidates.filter((p) => fs.existsSync(p));
// Prefer a single CLI entry to avoid duplicate bundles.
return found.length ? [found[0]!] : [];
};
/**
* Rollup options to build the CLI entrypoint (preferring `src/cli/bin/stan.ts`)
* into a Node-executable ESM bundle with a shebang banner.
*
* @param dest - Destination directory where Rollup should write the CLI output.
* @returns Rollup configuration for the CLI build.
*/
export const buildCli = (dest: string): RollupOptions => ({
input: discoverCliEntries(),
output: [
{
dir: `${dest}/cli`,
format: 'esm',
sourcemap: false,
banner: '#!/usr/bin/env node',
},
],
...commonInputOptions(false),
});
/**
* Rollup options to bundle TypeScript declaration files for the library
* entrypoint (`src/index.ts`).
*
* @param dest - Destination directory where Rollup should write the generated types.
* @returns Rollup configuration for the declaration build.
*/
export const buildTypes = (dest: string): RollupOptions => ({
input: 'src/index.ts',
output: [{ dir: `${dest}/types`, format: 'esm' }],
// Ensure alias resolution works during type bundling to avoid unresolved "@/..." warnings.
plugins: [alias, dtsPlugin()],
});
/**
* Default Rollup configuration (library build, CLI build, and bundled types).
*/
export default [
buildLibrary(outputPath),
buildCli(outputPath),
buildTypes(outputPath),
];