balm-core 6.0.0-alpha.2 → 6.0.0-alpha.3

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 (55) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/index.cjs +395 -111
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.cts +21 -3
  5. package/dist/index.d.ts +21 -3
  6. package/dist/index.js +381 -97
  7. package/dist/index.js.map +1 -1
  8. package/package.json +38 -1
  9. package/src/balm.ts +0 -107
  10. package/src/bundler/esbuild.ts +0 -48
  11. package/src/bundler/index.ts +0 -3
  12. package/src/bundler/rollup.ts +0 -46
  13. package/src/bundler/webpack.ts +0 -125
  14. package/src/config/constants.ts +0 -12
  15. package/src/config/defaults.ts +0 -212
  16. package/src/config/index.ts +0 -112
  17. package/src/hooks/index.ts +0 -224
  18. package/src/index.ts +0 -16
  19. package/src/pipeline/file.ts +0 -69
  20. package/src/pipeline/index.ts +0 -10
  21. package/src/pipeline/pipeline.ts +0 -135
  22. package/src/pipeline/transforms/cache.ts +0 -147
  23. package/src/pipeline/transforms/htmlmin.ts +0 -18
  24. package/src/pipeline/transforms/less.ts +0 -75
  25. package/src/pipeline/transforms/postcss.ts +0 -43
  26. package/src/pipeline/transforms/rename.ts +0 -38
  27. package/src/pipeline/transforms/replace.ts +0 -30
  28. package/src/pipeline/transforms/sass.ts +0 -106
  29. package/src/pipeline/transforms/terser.ts +0 -20
  30. package/src/runner/dag.ts +0 -77
  31. package/src/runner/task.ts +0 -38
  32. package/src/shims.d.ts +0 -5
  33. package/src/tasks/cache.ts +0 -84
  34. package/src/tasks/clean.ts +0 -21
  35. package/src/tasks/copy.ts +0 -36
  36. package/src/tasks/ftp.ts +0 -90
  37. package/src/tasks/html.ts +0 -290
  38. package/src/tasks/index.ts +0 -14
  39. package/src/tasks/publish.ts +0 -71
  40. package/src/tasks/pwa.ts +0 -86
  41. package/src/tasks/remove.ts +0 -24
  42. package/src/tasks/replace.ts +0 -34
  43. package/src/tasks/script.ts +0 -28
  44. package/src/tasks/server.ts +0 -218
  45. package/src/tasks/static.ts +0 -77
  46. package/src/tasks/style.ts +0 -57
  47. package/src/tasks/zip.ts +0 -77
  48. package/src/types/index.ts +0 -225
  49. package/src/utilities/file.ts +0 -140
  50. package/src/utilities/logger.ts +0 -63
  51. package/src/utilities/utils.ts +0 -46
  52. package/src/utilities/workspace.ts +0 -38
  53. package/src/watcher/index.ts +0 -100
  54. package/tsconfig.json +0 -8
  55. package/tsup.config.ts +0 -12
@@ -1,147 +0,0 @@
1
- import path from 'node:path';
2
- import picomatch from 'picomatch';
3
- import { VirtualFile } from '../file.js';
4
- import { file as fsUtil } from '../../utilities/file.js';
5
-
6
- export interface CacheTransformOptions {
7
- fileNameManifest?: string;
8
- dontRenameFile?: (string | RegExp)[];
9
- dontUpdateReference?: (string | RegExp)[];
10
- hashLength?: number;
11
- [key: string]: any;
12
- }
13
-
14
- function matchesAny(filePath: string, rules?: (string | RegExp)[]): boolean {
15
- if (!rules || !rules.length) return false;
16
- const normalized = filePath.replace(/\\/g, '/');
17
- const baseName = path.basename(normalized);
18
- for (const rawRule of rules) {
19
- if (typeof rawRule === 'string') {
20
- const rule = rawRule.replace(/\\/g, '/');
21
- const cleanRule = rule.replace(/^dist\//, '').replace(/^\.\/dist\//, '');
22
- if (
23
- normalized.endsWith(rule) ||
24
- normalized.endsWith(cleanRule) ||
25
- baseName === rule ||
26
- baseName === cleanRule ||
27
- baseName.endsWith(rule) ||
28
- picomatch.isMatch(normalized, rule) ||
29
- picomatch.isMatch(normalized, cleanRule) ||
30
- picomatch.isMatch(normalized, `**/${cleanRule}`) ||
31
- picomatch.isMatch(baseName, rule) ||
32
- picomatch.isMatch(baseName, cleanRule)
33
- ) {
34
- return true;
35
- }
36
- } else if (rawRule instanceof RegExp) {
37
- if (rawRule.test(normalized) || rawRule.test(baseName)) return true;
38
- }
39
- }
40
- return false;
41
- }
42
-
43
- export class AssetRevisioner {
44
- private options: CacheTransformOptions;
45
- private manifest: Record<string, string> = {};
46
-
47
- constructor(options: CacheTransformOptions = {}) {
48
- const baseDontRename = [
49
- '.html',
50
- 'favicon.ico',
51
- 'manifest.json',
52
- '*.webmanifest',
53
- 'robots.txt',
54
- '*.ico',
55
- 'workbox-sw.js',
56
- 'workbox-sw.js.map',
57
- 'service-worker.js',
58
- 'sw.js'
59
- ];
60
- this.options = {
61
- fileNameManifest: 'rev-manifest.json',
62
- dontRenameFile: baseDontRename,
63
- dontUpdateReference: [],
64
- hashLength: 8,
65
- ...options
66
- };
67
- if (options.dontRenameFile) {
68
- this.options.dontRenameFile = [
69
- ...baseDontRename,
70
- ...options.dontRenameFile
71
- ];
72
- }
73
- }
74
-
75
- process(files: VirtualFile[]): VirtualFile[] {
76
- const hashLength = this.options.hashLength || 8;
77
- const outputFiles: VirtualFile[] = [];
78
-
79
- // Phase 1: Calculate hashes and renames
80
- for (const file of files) {
81
- const origRelative = file.relative;
82
- file.revPathOriginal = file.path;
83
-
84
- // Check if file is already hashed (e.g. app.0e94aeee.js or chunk.22810145.js)
85
- const alreadyHashed = /\.[a-f0-9]{8}$/i.test(file.stem);
86
-
87
- const shouldRename =
88
- !alreadyHashed &&
89
- !matchesAny(file.path, this.options.dontRenameFile) &&
90
- !matchesAny(file.relative, this.options.dontRenameFile);
91
-
92
- if (shouldRename) {
93
- const fileHash = fsUtil.hash(file.contents, hashLength);
94
- const dir = path.dirname(file.path);
95
- const newFilename = `${file.stem}.${fileHash}${file.extname}`;
96
- file.path = path.join(dir, newFilename);
97
- }
98
-
99
- if (alreadyHashed) {
100
- const unhashedRelative = file.relative.replace(/\.[a-f0-9]{8}(\.[^.]+)$/i, '$1');
101
- this.manifest[unhashedRelative] = file.relative;
102
- }
103
- this.manifest[origRelative] = file.relative;
104
- outputFiles.push(file);
105
- }
106
-
107
- // Phase 2: Rewrite references
108
- const manifestEntries = Object.entries(this.manifest)
109
- .filter(([orig, reved]) => orig !== reved)
110
- .sort((a, b) => b[0].length - a[0].length);
111
-
112
- for (const file of outputFiles) {
113
- const shouldUpdate =
114
- !matchesAny(file.path, this.options.dontUpdateReference) &&
115
- !matchesAny(file.relative, this.options.dontUpdateReference);
116
-
117
- if (shouldUpdate && /\.(html|css|js)$/i.test(file.extname)) {
118
- let content = file.toString();
119
- for (const [orig, reved] of manifestEntries) {
120
- // Replace full relative path first
121
- content = content.replaceAll(orig, reved);
122
-
123
- // Replace basename with boundary check to avoid substring collision (e.g. .woff matching .woff2)
124
- const origBase = path.basename(orig);
125
- const revedBase = path.basename(reved);
126
- const escapedBase = origBase.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
127
- const baseRegex = new RegExp(`${escapedBase}(?![a-zA-Z0-9_])`, 'g');
128
- content = content.replace(baseRegex, revedBase);
129
- }
130
- file.contents = Buffer.from(content);
131
- }
132
- }
133
-
134
- // Phase 3: Add manifest file
135
- const manifestName = this.options.fileNameManifest || 'rev-manifest.json';
136
- const firstBase = files[0]?.base || process.cwd();
137
- const manifestFile = new VirtualFile({
138
- cwd: files[0]?.cwd || process.cwd(),
139
- base: firstBase,
140
- path: path.join(firstBase, manifestName),
141
- contents: JSON.stringify(this.manifest, null, 2)
142
- });
143
- outputFiles.push(manifestFile);
144
-
145
- return outputFiles;
146
- }
147
- }
@@ -1,18 +0,0 @@
1
- import { minify } from 'html-minifier-terser';
2
- import { TransformFn } from '../pipeline.js';
3
- import { logger } from '../../utilities/logger.js';
4
-
5
- export function transformHtmlmin(options: Record<string, any> = {}): TransformFn {
6
- return async (file) => {
7
- if (!/\.html$/i.test(file.extname)) return file;
8
-
9
- try {
10
- const minified = await minify(file.toString(), options);
11
- file.contents = Buffer.from(minified);
12
- return file;
13
- } catch (err: any) {
14
- logger.error('htmlmin', `Error minifying ${file.path}: ${err.message}`);
15
- throw err;
16
- }
17
- };
18
- }
@@ -1,75 +0,0 @@
1
- import less from 'less';
2
- import path from 'node:path';
3
- import { TransformFn } from '../pipeline.js';
4
- import { logger } from '../../utilities/logger.js';
5
-
6
- export interface LessTransformOptions {
7
- paths?: string[];
8
- alias?: Record<string, string>;
9
- [key: string]: any;
10
- }
11
-
12
- class AliasFileManager extends less.FileManager {
13
- private alias: Record<string, string>;
14
-
15
- constructor(alias: Record<string, string> = {}) {
16
- super();
17
- this.alias = alias;
18
- }
19
-
20
- supports(filename: string): boolean {
21
- const clean = filename.startsWith('~') ? filename.slice(1) : filename;
22
- return Object.keys(this.alias).some((k) => clean === k || clean.startsWith(`${k}/`));
23
- }
24
-
25
- loadFile(filename: string, currentDirectory: string, options: any, environment: any): Promise<any> {
26
- const clean = filename.startsWith('~') ? filename.slice(1) : filename;
27
- for (const [k, v] of Object.entries(this.alias)) {
28
- if (clean === k) {
29
- return super.loadFile(v, currentDirectory, options, environment);
30
- } else if (clean.startsWith(`${k}/`)) {
31
- const sub = clean.slice(k.length + 1);
32
- return super.loadFile(path.join(v, sub), currentDirectory, options, environment);
33
- }
34
- }
35
- return super.loadFile(filename, currentDirectory, options, environment);
36
- }
37
- }
38
-
39
- export function transformLess(options: LessTransformOptions = {}): TransformFn {
40
- return async (file) => {
41
- if (!/\.less$/i.test(file.extname)) return file;
42
- if (path.basename(file.path).startsWith('_')) return null;
43
-
44
- try {
45
- const paths = [
46
- path.dirname(file.path),
47
- path.resolve(file.cwd, 'node_modules'),
48
- ...(options.paths || [])
49
- ];
50
-
51
- const plugins = [...(options.plugins || [])];
52
- if (options.alias && Object.keys(options.alias).length > 0) {
53
- plugins.push({
54
- install: (lessInstance: any, pluginManager: any) => {
55
- pluginManager.addFileManager(new AliasFileManager(options.alias));
56
- }
57
- });
58
- }
59
-
60
- const result = await less.render(file.toString(), {
61
- filename: file.path,
62
- paths,
63
- ...options,
64
- plugins
65
- });
66
-
67
- file.contents = Buffer.from(result.css);
68
- file.extname = '.css';
69
- return file;
70
- } catch (err: any) {
71
- logger.error('less', `Error compiling ${file.path}: ${err.message}`);
72
- throw err;
73
- }
74
- };
75
- }
@@ -1,43 +0,0 @@
1
- import postcss, { AcceptedPlugin } from 'postcss';
2
- import autoprefixer from 'autoprefixer';
3
- import postcssPresetEnv from 'postcss-preset-env';
4
- import cssnano from 'cssnano';
5
- import { TransformFn } from '../pipeline.js';
6
- import { logger } from '../../utilities/logger.js';
7
-
8
- export interface PostcssTransformOptions {
9
- plugins?: AcceptedPlugin[];
10
- minify?: boolean;
11
- [key: string]: any;
12
- }
13
-
14
- export function transformPostcss(options: PostcssTransformOptions = {}): TransformFn {
15
- const plugins: AcceptedPlugin[] = [
16
- ...(options.plugins || []),
17
- autoprefixer(),
18
- postcssPresetEnv()
19
- ];
20
-
21
- if (options.minify) {
22
- plugins.push(cssnano({ preset: 'default' }));
23
- }
24
-
25
- const processor = postcss(plugins);
26
-
27
- return async (file) => {
28
- if (!/\.css$/i.test(file.extname)) return file;
29
-
30
- try {
31
- const result = await processor.process(file.toString(), {
32
- from: file.path,
33
- to: file.path
34
- });
35
-
36
- file.contents = Buffer.from(result.css);
37
- return file;
38
- } catch (err: any) {
39
- logger.error('postcss', `Error processing ${file.path}: ${err.message}`);
40
- throw err;
41
- }
42
- };
43
- }
@@ -1,38 +0,0 @@
1
- import path from 'node:path';
2
- import { TransformFn } from '../pipeline.js';
3
- import { RenameOptions } from '../../types/index.js';
4
-
5
- export function transformRename(
6
- options: string | Function | RenameOptions = {}
7
- ): TransformFn {
8
- return async (file) => {
9
- if (typeof options === 'string') {
10
- file.path = path.resolve(path.dirname(file.path), options);
11
- return file;
12
- }
13
-
14
- if (typeof options === 'function') {
15
- const parsed = {
16
- dirname: path.dirname(file.path),
17
- basename: file.stem,
18
- extname: file.extname
19
- };
20
- const result = options(parsed);
21
- if (result) {
22
- if (result.dirname) file.path = path.join(result.dirname, path.basename(file.path));
23
- if (result.basename) file.stem = result.basename;
24
- if (result.extname) file.extname = result.extname;
25
- }
26
- return file;
27
- }
28
-
29
- const { dirname, prefix = '', basename, suffix = '', extname } = options;
30
- const currentDir = dirname ? path.resolve(file.cwd, dirname) : path.dirname(file.path);
31
- const base = basename !== undefined ? basename : file.stem;
32
- const ext = extname !== undefined ? extname : file.extname;
33
- const dotExt = ext ? (ext.startsWith('.') ? ext : `.${ext}`) : '';
34
-
35
- file.path = path.join(currentDir, `${prefix}${base}${suffix}${dotExt}`);
36
- return file;
37
- };
38
- }
@@ -1,30 +0,0 @@
1
- import { TransformFn } from '../pipeline.js';
2
- import { ReplaceOptions } from '../../types/index.js';
3
-
4
- export function transformReplace(
5
- options: ReplaceOptions | ReplaceOptions[] | string | RegExp,
6
- replacement?: string | ((substring: string, ...args: any[]) => string)
7
- ): TransformFn {
8
- let rules: ReplaceOptions[] = [];
9
-
10
- if (Array.isArray(options)) {
11
- rules = options;
12
- } else if (typeof options === 'object' && 'substr' in options) {
13
- rules = [options];
14
- } else if (typeof options === 'string' || options instanceof RegExp) {
15
- rules = [{ substr: options, replacement: replacement || '' }];
16
- }
17
-
18
- return async (file) => {
19
- let content = file.toString();
20
- for (const rule of rules) {
21
- if (typeof rule.replacement === 'function') {
22
- content = content.replace(rule.substr, rule.replacement as any);
23
- } else {
24
- content = content.replace(rule.substr, rule.replacement);
25
- }
26
- }
27
- file.contents = Buffer.from(content);
28
- return file;
29
- };
30
- }
@@ -1,106 +0,0 @@
1
- import * as sass from 'sass';
2
- import path from 'node:path';
3
- import fs from 'node:fs';
4
- import { TransformFn } from '../pipeline.js';
5
- import { logger } from '../../utilities/logger.js';
6
-
7
- export interface SassTransformOptions {
8
- includePaths?: string[];
9
- alias?: Record<string, string>;
10
- style?: 'expanded' | 'compressed';
11
- sourceMap?: boolean;
12
- [key: string]: any;
13
- }
14
-
15
- function resolveFile(baseDir: string, url: string): string | null {
16
- const possiblePaths = [
17
- path.resolve(baseDir, url),
18
- path.resolve(baseDir, `${url}.scss`),
19
- path.resolve(baseDir, `${url}.sass`),
20
- path.resolve(baseDir, `${url}.css`),
21
- path.resolve(baseDir, path.dirname(url), `_${path.basename(url)}.scss`),
22
- path.resolve(baseDir, path.dirname(url), `_${path.basename(url)}.sass`),
23
- path.resolve(baseDir, url, '_index.scss'),
24
- path.resolve(baseDir, url, '_index.sass'),
25
- path.resolve(baseDir, url, 'index.scss'),
26
- path.resolve(baseDir, url, 'index.sass')
27
- ];
28
-
29
- for (const p of possiblePaths) {
30
- try {
31
- if (fs.existsSync(p) && fs.statSync(p).isFile()) {
32
- return p;
33
- }
34
- } catch {
35
- // ignore
36
- }
37
- }
38
- return null;
39
- }
40
-
41
- export function transformSass(options: SassTransformOptions = {}): TransformFn {
42
- return async (file) => {
43
- // Only process .scss / .sass files
44
- if (!/\.(scss|sass)$/i.test(file.extname)) return file;
45
- // Skip partials starting with '_'
46
- if (path.basename(file.path).startsWith('_')) return null;
47
-
48
- try {
49
- const searchDirs = [
50
- path.dirname(file.path),
51
- path.resolve(file.cwd, 'node_modules'),
52
- path.resolve(process.cwd(), 'node_modules'),
53
- path.resolve(process.cwd(), '..', 'node_modules'),
54
- ...(options.includePaths || [])
55
- ];
56
-
57
- const customImporter: sass.FileImporter<'async'> = {
58
- findFileUrl(url) {
59
- let cleanUrl = url;
60
- if (cleanUrl.startsWith('~')) {
61
- cleanUrl = cleanUrl.slice(1);
62
- }
63
-
64
- // 1. Check alias resolution
65
- if (options.alias) {
66
- for (const [aliasKey, aliasTarget] of Object.entries(options.alias)) {
67
- if (cleanUrl === aliasKey) {
68
- const resolved = resolveFile(path.dirname(aliasTarget), path.basename(aliasTarget));
69
- if (resolved) return new URL(`file://${resolved}`);
70
- } else if (cleanUrl.startsWith(`${aliasKey}/`)) {
71
- const subPath = cleanUrl.slice(aliasKey.length + 1);
72
- const resolved = resolveFile(aliasTarget, subPath);
73
- if (resolved) return new URL(`file://${resolved}`);
74
- }
75
- }
76
- }
77
-
78
- // 2. Check searchDirs
79
- for (const dir of searchDirs) {
80
- const resolved = resolveFile(dir, cleanUrl);
81
- if (resolved) {
82
- return new URL(`file://${resolved}`);
83
- }
84
- }
85
- return null;
86
- }
87
- };
88
-
89
- const result = await sass.compileStringAsync(file.toString(), {
90
- url: new URL(`file://${file.path}`),
91
- syntax: file.extname === '.sass' ? 'indented' : 'scss',
92
- loadPaths: searchDirs,
93
- importers: [customImporter, new sass.NodePackageImporter(file.cwd || process.cwd())],
94
- style: options.style || 'expanded',
95
- sourceMap: options.sourceMap || false
96
- });
97
-
98
- file.contents = Buffer.from(result.css);
99
- file.extname = '.css';
100
- return file;
101
- } catch (err: any) {
102
- logger.error('sass', `Error compiling ${file.path}: ${err.message}`);
103
- throw err;
104
- }
105
- };
106
- }
@@ -1,20 +0,0 @@
1
- import { minify, MinifyOptions } from 'terser';
2
- import { TransformFn } from '../pipeline.js';
3
- import { logger } from '../../utilities/logger.js';
4
-
5
- export function transformTerser(options: MinifyOptions = {}): TransformFn {
6
- return async (file) => {
7
- if (!/\.js$/i.test(file.extname)) return file;
8
-
9
- try {
10
- const result = await minify(file.toString(), options);
11
- if (result.code) {
12
- file.contents = Buffer.from(result.code);
13
- }
14
- return file;
15
- } catch (err: any) {
16
- logger.error('terser', `Error minifying ${file.path}: ${err.message}`);
17
- throw err;
18
- }
19
- };
20
- }
package/src/runner/dag.ts DELETED
@@ -1,77 +0,0 @@
1
- import { BaseTask } from './task.js';
2
- import { BalmConfig } from '../types/index.js';
3
- import { logger } from '../utilities/logger.js';
4
- import pc from 'picocolors';
5
-
6
- export class TaskDAG {
7
- private tasks = new Map<string, BaseTask>();
8
-
9
- registerTask(task: BaseTask): void {
10
- this.tasks.set(task.name, task);
11
- }
12
-
13
- getTask(name: string): BaseTask | undefined {
14
- return this.tasks.get(name);
15
- }
16
-
17
- hasTask(name: string): boolean {
18
- return this.tasks.has(name);
19
- }
20
-
21
- clear(): void {
22
- this.tasks.clear();
23
- }
24
-
25
- /**
26
- * Run a list of tasks in strict series
27
- */
28
- async runSeries(taskNames: string[], config: BalmConfig): Promise<void> {
29
- for (const name of taskNames) {
30
- await this.executeTask(name, config);
31
- }
32
- }
33
-
34
- /**
35
- * Run a list of tasks in parallel
36
- */
37
- async runParallel(taskNames: string[], config: BalmConfig): Promise<void> {
38
- await Promise.all(taskNames.map((name) => this.executeTask(name, config)));
39
- }
40
-
41
- /**
42
- * Execute a single task resolving its dependencies first
43
- */
44
- async executeTask(
45
- taskName: string,
46
- config: BalmConfig,
47
- executed = new Set<string>()
48
- ): Promise<void> {
49
- if (executed.has(taskName)) return;
50
-
51
- const task = this.tasks.get(taskName);
52
- if (!task) {
53
- logger.warn('task', `Task ${pc.bold(taskName)} not found, skipping.`);
54
- return;
55
- }
56
-
57
- // Execute dependencies first
58
- if (task.deps && task.deps.length > 0) {
59
- for (const dep of task.deps) {
60
- await this.executeTask(dep, config, executed);
61
- }
62
- }
63
-
64
- const start = performance.now();
65
- try {
66
- await task.run(config);
67
- executed.add(taskName);
68
- const duration = (performance.now() - start).toFixed(1);
69
- if (!task.hidden) {
70
- logger.info('task', `${pc.cyan(task.name)} finished in ${pc.bold(duration + 'ms')}`);
71
- }
72
- } catch (error: any) {
73
- logger.error('task', `Task ${pc.bold(task.name)} failed: ${error?.message || error}`);
74
- throw error;
75
- }
76
- }
77
- }
@@ -1,38 +0,0 @@
1
- import { BalmConfig } from '../types/index.js';
2
- import { logger } from '../utilities/logger.js';
3
-
4
- export interface TaskOptions {
5
- name: string;
6
- deps?: string[];
7
- description?: string;
8
- hidden?: boolean;
9
- }
10
-
11
- export abstract class BaseTask {
12
- name: string;
13
- deps: string[];
14
- description?: string;
15
- hidden: boolean;
16
-
17
- constructor(options: TaskOptions) {
18
- this.name = options.name;
19
- this.deps = options.deps || [];
20
- this.description = options.description;
21
- this.hidden = options.hidden || false;
22
- }
23
-
24
- abstract run(config: BalmConfig): Promise<void> | void;
25
- }
26
-
27
- export class FunctionTask extends BaseTask {
28
- private fn: (config: BalmConfig) => Promise<void> | void;
29
-
30
- constructor(name: string, fn: (config: BalmConfig) => Promise<void> | void, deps: string[] = []) {
31
- super({ name, deps });
32
- this.fn = fn;
33
- }
34
-
35
- async run(config: BalmConfig): Promise<void> {
36
- await this.fn(config);
37
- }
38
- }
package/src/shims.d.ts DELETED
@@ -1,5 +0,0 @@
1
- declare module 'postcss-preset-env';
2
- declare module 'connect';
3
- declare module 'serve-static';
4
- declare module 'html-minifier-terser';
5
-
@@ -1,84 +0,0 @@
1
- import path from 'node:path';
2
- import fg from 'fast-glob';
3
- import fs from 'node:fs/promises';
4
- import { BaseTask } from '../runner/task.js';
5
- import { BalmConfig } from '../types/index.js';
6
- import { VirtualFile } from '../pipeline/file.js';
7
- import { AssetRevisioner } from '../pipeline/transforms/cache.js';
8
- import { file as fsUtil } from '../utilities/file.js';
9
- import { logger } from '../utilities/logger.js';
10
-
11
- export class CacheTask extends BaseTask {
12
- constructor() {
13
- super({ name: 'cache', description: 'Revision assets and generate manifest' });
14
- }
15
-
16
- async run(config: BalmConfig): Promise<void> {
17
- const destDir = config.dest.base;
18
- const assetGlobs = [
19
- `${config.paths.target.css}/**/*`,
20
- `${config.paths.target.js}/**/*`,
21
- `${config.paths.target.img}/**/*`,
22
- `${config.paths.target.font}/**/*`,
23
- `${config.paths.target.media}/**/*`,
24
- '*.html'
25
- ];
26
- const filesToRev = await fg(assetGlobs, {
27
- cwd: destDir,
28
- absolute: true,
29
- onlyFiles: true
30
- });
31
-
32
- if (!filesToRev.length) {
33
- logger.warn('cache', 'No files found to cache');
34
- return;
35
- }
36
-
37
- const virtualFiles = await Promise.all(
38
- filesToRev.map(async (filePath) => {
39
- const buffer = await fs.readFile(filePath);
40
- return new VirtualFile({
41
- cwd: config.workspace,
42
- base: destDir,
43
- path: filePath,
44
- contents: buffer
45
- });
46
- })
47
- );
48
-
49
- const cacheOptions = {
50
- ...config.assets.options,
51
- dontRenameFile: [
52
- '.html',
53
- 'favicon.ico',
54
- 'manifest.json',
55
- '*.webmanifest',
56
- 'robots.txt',
57
- '*.ico',
58
- 'icons/*',
59
- '**/icons/**',
60
- 'sw.js',
61
- 'service-worker.js',
62
- 'workbox-sw.js',
63
- ...(config.assets.excludes || []),
64
- ...(config.assets.options?.dontRenameFile || [])
65
- ]
66
- };
67
- const revisioner = new AssetRevisioner(cacheOptions);
68
- const resultFiles = revisioner.process(virtualFiles);
69
-
70
- // Remove old files that have been renamed
71
- for (const vFile of resultFiles) {
72
- if (vFile.revPathOriginal && vFile.revPathOriginal !== vFile.path) {
73
- await fsUtil.remove(vFile.revPathOriginal);
74
- }
75
- }
76
-
77
- // Write new / updated files
78
- for (const vFile of resultFiles) {
79
- await fsUtil.writeFile(vFile.path, vFile.contents);
80
- }
81
-
82
- logger.success('cache', 'Asset revisioning and rev-manifest.json completed');
83
- }
84
- }