@withstudiocms/buildkit 0.1.0-beta.1

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 (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +69 -0
  3. package/index.js +207 -0
  4. package/package.json +41 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 withStudioCMS
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,69 @@
1
+ # `@withstudiocms/buildkit`
2
+
3
+ This is an esbuild based CLI kit for building Astro Integrations
4
+
5
+ ## Usage
6
+
7
+ ### Installation
8
+
9
+ Install the package in the root of the repo:
10
+
11
+ 1. Install the required dependencies
12
+
13
+ ```bash
14
+ pnpm add @withstudiocms/buildkit
15
+ ```
16
+
17
+ ```bash
18
+ npm install @withstudiocms/buildkit
19
+ ```
20
+
21
+ ```bash
22
+ yarn add @withstudiocms/buildkit
23
+ ```
24
+
25
+ ### Usage
26
+
27
+ Once you install the buildkit package you now have access to a `buildkit` CLI utility, add the following to your integration scripts:
28
+
29
+ ```json
30
+ {
31
+ "scripts": {
32
+ "build": "buildkit build 'src/**/*.{ts,astro,css}'",
33
+ "dev": "buildkit dev 'src/**/*.{ts,astro,css}'"
34
+ }
35
+ }
36
+ ```
37
+
38
+ The command pattern is `buildkit <command> 'path/to/file or glob/**/**.{ts}' [flags]`
39
+
40
+ #### Available Flags (All are optional)
41
+
42
+ - `--no-clean-dist`: Do not clean the dist output during build.
43
+ - `--bundle`: Enable bundling.
44
+ - `--force-cjs`: Force CJS output.
45
+ - `--tsconfig=tsconfig.json`: Allows setting custom tsconfig for build time.
46
+ - `--outdir=dist`: Allows settings the output directory.
47
+
48
+ #### Files considered Assets
49
+
50
+ The following file extensions will be copied from their src to their respective outputs and not transformed as if they are static assets.
51
+
52
+ - `.astro`
53
+ - `.d.ts`
54
+ - `.json`
55
+ - `.gif`
56
+ - `.jpeg`
57
+ - `.jpg`
58
+ - `.png`
59
+ - `.tiff`
60
+ - `.webp`
61
+ - `.avif`
62
+ - `.svg`
63
+
64
+ For other content types and how to use them see [The esBuild Docs](https://esbuild.github.io/content-types/)
65
+
66
+ ## Licensing
67
+
68
+ -[MIT Licensed](https://github.com/withstudiocms/cachedfetch/blob/main/LICENSE).
69
+ +[MIT Licensed](https://github.com/withstudiocms/studiocms/blob/main/LICENSE).
package/index.js ADDED
@@ -0,0 +1,207 @@
1
+ #!/usr/bin/env node
2
+ import { execSync } from 'node:child_process';
3
+ import fs from 'node:fs/promises';
4
+ import esbuild from 'esbuild';
5
+ import glob from 'fast-glob';
6
+ import { dim, gray, green, red, yellow } from 'kleur/colors';
7
+
8
+ /** @type {import('esbuild').BuildOptions} */
9
+ const defaultConfig = {
10
+ minify: false,
11
+ format: 'esm',
12
+ platform: 'node',
13
+ target: 'node18',
14
+ sourcemap: false,
15
+ sourcesContent: false,
16
+ loader: {
17
+ '.astro': 'copy',
18
+ '.d.ts': 'copy',
19
+ '.json': 'copy',
20
+ '.gif': 'copy',
21
+ '.jpeg': 'copy',
22
+ '.jpg': 'copy',
23
+ '.png': 'copy',
24
+ '.tiff': 'copy',
25
+ '.webp': 'copy',
26
+ '.avif': 'copy',
27
+ '.svg': 'copy',
28
+ },
29
+ };
30
+
31
+ const dt = new Intl.DateTimeFormat('en-us', {
32
+ hour: '2-digit',
33
+ minute: '2-digit',
34
+ });
35
+
36
+ const dtsGen = (buildTsConfig, outdir) => ({
37
+ name: 'TypeScriptDeclarationsPlugin',
38
+ setup(build) {
39
+ build.onEnd((result) => {
40
+ if (result.errors.length > 0) return;
41
+ const date = dt.format(new Date());
42
+ console.log(`${dim(`[${date}]`)} Generating TypeScript declarations...`);
43
+ try {
44
+ const res = execSync(`tsc --emitDeclarationOnly -p ${buildTsConfig} --outDir ./${outdir}`);
45
+ console.log(res.toString());
46
+ console.log(dim(`[${date}] `) + green('√ Generated TypeScript declarations'));
47
+ } catch (error) {
48
+ console.error(dim(`[${date}] `) + red(`${error}\n\n${error.stdout.toString()}`));
49
+ }
50
+ });
51
+ },
52
+ });
53
+
54
+ export default async function run() {
55
+ const [cmd, ...args] = process.argv.slice(2);
56
+ const config = Object.assign({}, defaultConfig);
57
+ const patterns = args
58
+ .filter((f) => !!f) // remove empty args
59
+ .map((f) => f.replace(/^'/, '').replace(/'$/, '')); // Needed for Windows: glob strings contain surrounding string chars??? remove these
60
+ const entryPoints = [].concat(
61
+ ...(await Promise.all(
62
+ patterns.map((pattern) => glob(pattern, { filesOnly: true, absolute: true }))
63
+ ))
64
+ );
65
+ const date = dt.format(new Date());
66
+
67
+ const noClean = args.includes('--no-clean-dist');
68
+ const bundle = args.includes('--bundle');
69
+ const forceCJS = args.includes('--force-cjs');
70
+ const buildTsConfig =
71
+ args.find((arg) => arg.startsWith('--tsconfig='))?.split('=')[1] || 'tsconfig.json';
72
+ const outdir = args.find((arg) => arg.startsWith('--outdir='))?.split('=')[1] || 'dist';
73
+
74
+ const { type = 'module', dependencies = {} } = await readPackageJSON('./package.json');
75
+
76
+ const format = type === 'module' && !forceCJS ? 'esm' : 'cjs';
77
+
78
+ switch (cmd) {
79
+ case 'dev': {
80
+ if (!noClean) {
81
+ console.log(
82
+ `${dim(`[${date}]`)} Cleaning ${outdir} directory... ${dim(`(${entryPoints.length} files found)`)}`
83
+ );
84
+ await clean(outdir, date, [`!${outdir}/**/*.d.ts`]);
85
+ }
86
+
87
+ const rebuildPlugin = {
88
+ name: 'dev:rebuild',
89
+ setup(build) {
90
+ build.onEnd(async (result) => {
91
+ const date = dt.format(new Date());
92
+ if (result?.errors.length) {
93
+ const errMsg = result.errors.join('\n');
94
+ console.error(dim(`[${date}] `) + red(errMsg));
95
+ } else {
96
+ if (result.warnings.length) {
97
+ console.info(
98
+ dim(`[${date}] `) +
99
+ yellow(`! updated with warnings:\n${result.warnings.join('\n')}`)
100
+ );
101
+ }
102
+ console.info(dim(`[${date}] `) + green('√ updated'));
103
+ }
104
+ });
105
+ },
106
+ };
107
+
108
+ const builder = await esbuild.context({
109
+ ...config,
110
+ entryPoints,
111
+ outdir,
112
+ format,
113
+ sourcemap: 'linked',
114
+ plugins: [rebuildPlugin],
115
+ });
116
+
117
+ console.log(
118
+ `${dim(`[${date}] `) + gray('Watching for changes...')} ${dim(`(${entryPoints.length} files found)`)}`
119
+ );
120
+ await builder.watch();
121
+
122
+ process.on('beforeExit', () => {
123
+ builder.stop?.();
124
+ });
125
+ break;
126
+ }
127
+ case 'build': {
128
+ if (!noClean) {
129
+ console.log(
130
+ `${dim(`[${date}]`)} Cleaning ${outdir} directory... ${dim(`(${entryPoints.length} files found)`)}`
131
+ );
132
+ await clean(outdir, date, [`!${outdir}/**/*.d.ts`]);
133
+ }
134
+ console.log(
135
+ `${dim(`[${date}]`)} Building...${bundle ? '(Bundling)' : ''} ${dim(`(${entryPoints.length} files found)`)}`
136
+ );
137
+ await esbuild.build({
138
+ ...config,
139
+ bundle,
140
+ external: bundle ? Object.keys(dependencies) : undefined,
141
+ entryPoints,
142
+ outdir,
143
+ outExtension: forceCJS ? { '.js': '.cjs' } : {},
144
+ format,
145
+ plugins: [dtsGen(buildTsConfig, outdir)],
146
+ });
147
+ console.log(dim(`[${date}] `) + green('√ Build Complete'));
148
+ break;
149
+ }
150
+ case 'help': {
151
+ showHelp();
152
+ break;
153
+ }
154
+ default: {
155
+ showHelp();
156
+ break;
157
+ }
158
+ }
159
+ }
160
+
161
+ function showHelp() {
162
+ console.log(`
163
+ ${green('StudioCMS Buildkit')} - Build tool for StudioCMS packages
164
+
165
+ ${yellow('Usage:')}
166
+ buildkit <command> [...files] [...options]
167
+
168
+ ${yellow('Commands:')}
169
+ dev Watch files and rebuild on changes
170
+ build Perform a one-time build
171
+ help Show this help message
172
+
173
+ ${yellow('Options:')}
174
+ --no-clean-dist Skip cleaning the dist directory
175
+ --bundle Enable bundling mode
176
+ --force-cjs Force CommonJS output format
177
+ --tsconfig=<path> Specify TypeScript config file (default: tsconfig.json)
178
+ --outdir=<path> Specify output directory (default: dist)
179
+
180
+ ${yellow('Examples:')}
181
+ buildkit build "src/**/*.ts"
182
+ buildkit dev "src/**/*.ts" --no-clean-dist
183
+ buildkit build "src/**/*.ts" --bundle --force-cjs
184
+ `);
185
+ }
186
+
187
+ async function clean(outdir, date, skip = []) {
188
+ const files = await glob([`${outdir}/**`, ...skip], { filesOnly: true });
189
+ console.log(dim(`[${date}] `) + dim(`Cleaning ${files.length} files from ${outdir}`));
190
+ await Promise.all(files.map((file) => fs.rm(file, { force: true })));
191
+ }
192
+
193
+ async function readPackageJSON(path) {
194
+ try {
195
+ const content = await fs.readFile(path, { encoding: 'utf8' });
196
+ try {
197
+ return JSON.parse(content);
198
+ } catch (parseError) {
199
+ throw new Error(`Invalid JSON in ${path}: ${parseError.message}`);
200
+ }
201
+ } catch (readError) {
202
+ throw new Error(`Failed to read ${path}: ${readError.message}`);
203
+ }
204
+ }
205
+
206
+ // THIS IS THE ENTRY POINT FOR THE CLI - DO NOT REMOVE
207
+ run();
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@withstudiocms/buildkit",
3
+ "version": "0.1.0-beta.1",
4
+ "description": "Build kit based on esbuild for the withstudiocms github org",
5
+ "author": {
6
+ "name": "Adam Matthiesen | Jacob Jenkins | Paul Valladares",
7
+ "url": "https://studiocms.dev"
8
+ },
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/withstudiocms/studiocms.git",
12
+ "directory": "packages/withstudiocms_buildkit"
13
+ },
14
+ "license": "MIT",
15
+ "files": [
16
+ "index.js",
17
+ "cmd"
18
+ ],
19
+ "type": "module",
20
+ "main": "./index.js",
21
+ "publishConfig": {
22
+ "access": "public",
23
+ "provenance": true
24
+ },
25
+ "bin": {
26
+ "buildkit": "./index.js"
27
+ },
28
+ "dependencies": {
29
+ "esbuild": "^0.25.0",
30
+ "fast-glob": "^3.3.3",
31
+ "kleur": "^4.1.5"
32
+ },
33
+ "devDependencies": {
34
+ "vitest": "^3.1.1",
35
+ "strip-ansi": "^7.1.0"
36
+ },
37
+ "scripts": {
38
+ "test": "vitest run",
39
+ "test:watch": "vitest"
40
+ }
41
+ }