|
| 1 | +import { MacroTransformer } from 'use-macro'; |
| 2 | +import { cacheDirectivePlugin } from './use-cache.mjs'; |
| 3 | +import { readFile } from 'node:fs/promises'; |
| 4 | + |
| 5 | +const defaultConfig = { |
| 6 | + 'use-macro': true, |
| 7 | + 'use-cache': true, |
| 8 | +}; |
| 9 | + |
| 10 | +/** |
| 11 | + * @typedef {Object} CommandKitEsbuildPluginConfig |
| 12 | + * @property {boolean} [use-macro] |
| 13 | + * @property {boolean} [use-cache] |
| 14 | + */ |
| 15 | + |
| 16 | +/** |
| 17 | + * @param {CommandKitEsbuildPluginConfig} [config] |
| 18 | + */ |
| 19 | +export const commandkitPlugin = (config) => { |
| 20 | + config = Object.assign({}, defaultConfig, config); |
| 21 | + |
| 22 | + const plugins = [ |
| 23 | + { |
| 24 | + name: 'use-macro', |
| 25 | + plugin: async (content, args) => { |
| 26 | + const transformer = new MacroTransformer(); |
| 27 | + const { contents } = await transformer.transform(content, args.path); |
| 28 | + return contents; |
| 29 | + }, |
| 30 | + }, |
| 31 | + { |
| 32 | + name: 'use-cache', |
| 33 | + plugin: async (content, args) => { |
| 34 | + const { contents } = await cacheDirectivePlugin(content, args); |
| 35 | + return contents; |
| 36 | + }, |
| 37 | + }, |
| 38 | + ].filter((p) => { |
| 39 | + return !!config[p.name]; |
| 40 | + }); |
| 41 | + |
| 42 | + return { |
| 43 | + name: 'commandkit-transformer-plugin', |
| 44 | + setup(build) { |
| 45 | + if (!plugins.length) return; |
| 46 | + |
| 47 | + const fileFilter = /\.(c|m)?(t|j)sx?$/; |
| 48 | + |
| 49 | + build.onLoad({ filter: fileFilter }, async (args) => { |
| 50 | + const source = await readFile(args.path, 'utf8'); |
| 51 | + const loader = args.path.split('.').pop(); |
| 52 | + |
| 53 | + let contents = source; |
| 54 | + |
| 55 | + for (const _plugin of plugins) { |
| 56 | + const { plugin, name } = _plugin; |
| 57 | + try { |
| 58 | + contents = await plugin(contents, args); |
| 59 | + } catch (e) { |
| 60 | + const err = new Error(`Plugin ${name} failed with ${e}`); |
| 61 | + err.stack = e.stack; |
| 62 | + |
| 63 | + throw err; |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + return { |
| 68 | + contents, |
| 69 | + loader, |
| 70 | + }; |
| 71 | + }); |
| 72 | + }, |
| 73 | + }; |
| 74 | +}; |
0 commit comments