@visulima/packem 2.0.0-alpha.40 → 2.0.0-alpha.43

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 (103) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/LICENSE.md +1548 -1497
  3. package/dist/builder/typedoc/index.js +160 -3
  4. package/dist/cli/index.js +1377 -45
  5. package/dist/config/index.js +4 -1
  6. package/dist/config/preset/react.d.ts +59 -0
  7. package/dist/config/preset/react.js +43 -0
  8. package/dist/config/preset/solid.d.ts +101 -0
  9. package/dist/config/preset/solid.js +72 -0
  10. package/dist/config/preset/svelte.d.ts +71 -0
  11. package/dist/config/preset/svelte.js +44 -0
  12. package/dist/config/preset/vue.d.ts +53 -0
  13. package/dist/config/preset/vue.js +33 -0
  14. package/dist/index.js +30 -1
  15. package/dist/packem_shared/create-or-update-key-storage-Dd7b8-t1.js +36 -0
  16. package/dist/packem_shared/default-79SPobLI.js +12 -0
  17. package/dist/packem_shared/default-DWBYeUSC.js +210 -0
  18. package/dist/packem_shared/default-DaU6CQEi.js +28 -0
  19. package/dist/packem_shared/default-DavaZMwC.js +32 -0
  20. package/dist/packem_shared/default-DeYZ934H.js +32 -0
  21. package/dist/packem_shared/default-tUOOZ8w7.js +42 -0
  22. package/dist/packem_shared/default-wScAfTaq.js +27 -0
  23. package/dist/packem_shared/index-CTIRxV2x.js +63 -0
  24. package/dist/packem_shared/index-DzTDn4ad.js +9521 -0
  25. package/dist/rollup/plugins/css/loaders/less.js +1 -1
  26. package/dist/rollup/plugins/css/loaders/lightningcss.js +1 -1
  27. package/dist/rollup/plugins/css/loaders/postcss.js +1 -1
  28. package/dist/rollup/plugins/css/loaders/sass.js +1 -1
  29. package/dist/rollup/plugins/css/loaders/sourcemap.js +1 -1
  30. package/dist/rollup/plugins/css/loaders/stylus.js +1 -1
  31. package/dist/rollup/plugins/css/loaders/tailwindcss.js +1 -1
  32. package/dist/rollup/plugins/css/minifiers/cssnano.js +1 -1
  33. package/dist/rollup/plugins/css/minifiers/lightningcss.js +1 -1
  34. package/dist/rollup/plugins/esbuild/index.js +1 -1
  35. package/dist/rollup/plugins/oxc/isolated-declarations-oxc-transformer.js +1 -1
  36. package/dist/rollup/plugins/oxc/oxc-transformer.js +1 -1
  37. package/dist/rollup/plugins/sucrase/index.js +1 -1
  38. package/dist/rollup/plugins/swc/isolated-declarations-swc-transformer.js +1 -1
  39. package/dist/rollup/plugins/swc/swc-plugin.js +1 -1
  40. package/dist/rollup/plugins/typescript/isolated-declarations-typescript-transformer.js +1 -1
  41. package/dist/types.d.ts +2 -1
  42. package/package.json +143 -6
  43. package/dist/builder/typedoc/generate-reference-documentation.d.ts +0 -4
  44. package/dist/cli/commands/add.d.ts +0 -3
  45. package/dist/cli/commands/build.d.ts +0 -21
  46. package/dist/cli/commands/init.d.ts +0 -3
  47. package/dist/cli/commands/migrate.d.ts +0 -21
  48. package/dist/cli/commands/utils/css-loader-dependencies.d.ts +0 -2
  49. package/dist/config/preset/auto.d.ts +0 -3
  50. package/dist/config/preset/utils/infer-entries.d.ts +0 -12
  51. package/dist/config/preset/utils/overwrite-with-publish-config.d.ts +0 -4
  52. package/dist/config/utils/find-packem-file.d.ts +0 -2
  53. package/dist/config/utils/load-package-json.d.ts +0 -6
  54. package/dist/config/utils/load-packem-config.d.ts +0 -7
  55. package/dist/config/utils/load-preset.d.ts +0 -4
  56. package/dist/config/utils/load-tsconfig.d.ts +0 -5
  57. package/dist/config/utils/prepare-entries.d.ts +0 -4
  58. package/dist/jit/create-stub.d.ts +0 -4
  59. package/dist/packem/build.d.ts +0 -21
  60. package/dist/packem/index.d.ts +0 -25
  61. package/dist/packem/utils/brotli-size.d.ts +0 -2
  62. package/dist/packem/utils/group-by-keys.d.ts +0 -3
  63. package/dist/packem/utils/gzip-size.d.ts +0 -2
  64. package/dist/packem_shared/browserslistToEsbuild-C0IWmbNe-C6xPL1oW.js +0 -1
  65. package/dist/packem_shared/create-or-update-key-storage-GwAIWW7R.js +0 -3
  66. package/dist/packem_shared/default-B2EOH52z.js +0 -1
  67. package/dist/packem_shared/default-BYM_JvQL.js +0 -1
  68. package/dist/packem_shared/default-B_dUKZ_J.js +0 -1
  69. package/dist/packem_shared/default-Dego_fiC.js +0 -1
  70. package/dist/packem_shared/default-E4TiWfSK.js +0 -1
  71. package/dist/packem_shared/esbuildPlugin-DpLtQGuZ-Bny-e486.js +0 -3
  72. package/dist/packem_shared/index-CUp9WuCG.js +0 -1
  73. package/dist/packem_shared/index-DFigeRU2.js +0 -174
  74. package/dist/packem_shared/isolatedDeclarationsOxcTransformer-WbfE6cGu-NeZOx2Y7.js +0 -1
  75. package/dist/packem_shared/isolatedDeclarationsSwcTransformer-Ch2AgtWC-B-0lOgFf.js +0 -1
  76. package/dist/packem_shared/isolatedDeclarationsTypescriptTransformer-DkuEkofo-Cwe3ODMG.js +0 -3
  77. package/dist/packem_shared/oxcResolvePlugin-Ccef6pyL-D14z9S9i.js +0 -1
  78. package/dist/packem_shared/oxcTransformPlugin-DfVQouIB-Cpfv95eA.js +0 -4
  79. package/dist/packem_shared/resolveTypescriptMjsCtsPlugin-DcZrZTmM-3AmQC7y7.js +0 -6
  80. package/dist/packem_shared/swcPlugin-Boip4lWG-CwJ-HVJc.js +0 -1
  81. package/dist/rollup/build-types.d.ts +0 -5
  82. package/dist/rollup/build.d.ts +0 -5
  83. package/dist/rollup/get-rollup-options.d.ts +0 -5
  84. package/dist/rollup/utils/resolve-aliases.d.ts +0 -4
  85. package/dist/rollup/watch.d.ts +0 -5
  86. package/dist/utils/clean-distribution-directories.d.ts +0 -4
  87. package/dist/utils/create-or-update-key-storage.d.ts +0 -3
  88. package/dist/utils/extract-export-filenames.d.ts +0 -16
  89. package/dist/utils/find-alternatives.d.ts +0 -2
  90. package/dist/utils/get-package-side-effect.d.ts +0 -3
  91. package/dist/utils/infer-export-type.d.ts +0 -3
  92. package/dist/utils/kill-process.d.ts +0 -14
  93. package/dist/utils/log-build-errors.d.ts +0 -4
  94. package/dist/utils/remove-old-cache-folders.d.ts +0 -3
  95. package/dist/utils/warn-legacy-cjs.d.ts +0 -8
  96. package/dist/validator/attw.d.ts +0 -7
  97. package/dist/validator/package-json/index.d.ts +0 -4
  98. package/dist/validator/package-json/validate-dependencies.d.ts +0 -4
  99. package/dist/validator/package-json/validate-engines.d.ts +0 -4
  100. package/dist/validator/package-json/validate-package-entries.d.ts +0 -4
  101. package/dist/validator/package-json/validate-package-fields.d.ts +0 -4
  102. package/dist/validator/validate-alias-entries.d.ts +0 -3
  103. package/dist/validator/validate-bundle-size.d.ts +0 -4
package/dist/cli/index.js CHANGED
@@ -1,59 +1,1391 @@
1
1
  #!/usr/bin/env node
2
- var me=Object.defineProperty;var v=(t,s)=>me(t,"name",{value:s,configurable:!0});import{createCerebro as fe}from"@visulima/cerebro";import ge from"@visulima/cerebro/logger/pail";import{SimpleReporter as ye}from"@visulima/pail/reporter/simple";import P,{cwd as W,exit as be}from"node:process";import{installPackage as q}from"@antfu/install-pkg";import{spinner as U,select as j,multiselect as ie,confirm as h,intro as we,log as X,cancel as ve,outro as he}from"@clack/prompts";import{isAccessible as ke,readFile as $e,writeFile as je,isAccessibleSync as x,collectSync as Y,writeJsonSync as xe,writeFileSync as Se}from"@visulima/fs";import{join as C,resolve as E,extname as ne,toNamespacedPath as Ce}from"@visulima/path";import De from"magic-string";import{t as K,E as G,e as Ee,N as re,_ as Me,c as Pe}from"../packem_shared/index-CUp9WuCG.js";import{defu as Oe}from"defu";import{createJiti as Ie}from"jiti";import{cyan as Te,bold as V,gray as Ne}from"@visulima/colorize";import{e as Be,i as H,c as Le,x as Ae}from"../packem_shared/index-DFigeRU2.js";import Ke,{readFile as Fe,writeFile as Re}from"node:fs/promises";import Z from"node:path/posix";import{parsePackageJson as Je}from"@visulima/package/package-json";import{existsSync as ae}from"node:fs";import{createInterface as Ve}from"node:readline/promises";import __cjs_mod__ from "node:module"; // -- packem CommonJS require shim --
2
+ import { createCerebro } from '@visulima/cerebro';
3
+ import createPailLogger from '@visulima/cerebro/logger/pail';
4
+ import { SimpleReporter } from '@visulima/pail/reporter/simple';
5
+ import process, { cwd, exit } from 'node:process';
6
+ import { installPackage } from '@antfu/install-pkg';
7
+ import { spinner, confirm, cancel, select, multiselect, intro, log, outro } from '@clack/prompts';
8
+ import { isAccessible, readFile, writeFile, isAccessibleSync, writeJsonSync, writeFileSync } from '@visulima/fs';
9
+ import { parsePackageJson } from '@visulima/package/package-json';
10
+ import { join, resolve } from '@visulima/path';
11
+ import MagicString from 'magic-string';
12
+ import { exec } from 'tinyexec';
13
+ import { P as PRODUCTION_ENV, b as DEVELOPMENT_ENV } from '../packem_shared/index-CTIRxV2x.js';
14
+ import { defu } from 'defu';
15
+ import { createJiti } from 'jiti';
16
+ import { p as packem, a as autoPreset } from '../packem_shared/index-DzTDn4ad.js';
17
+ import { createReactPreset } from '../config/preset/react.js';
18
+ import { createSolidPreset } from '../config/preset/solid.js';
19
+ import { createSveltePreset } from '../config/preset/svelte.js';
20
+ import { createVuePreset } from '../config/preset/vue.js';
21
+ import { existsSync } from 'node:fs';
22
+ import { readFile as readFile$1, writeFile as writeFile$1 } from 'node:fs/promises';
23
+ import { createInterface } from 'node:readline/promises';
24
+
25
+ import __cjs_mod__ from "node:module"; // -- packem CommonJS require shim --
3
26
  const require = __cjs_mod__.createRequire(import.meta.url);
4
- var qe="@visulima/packem",ce="2.0.0-alpha.39";const Q={version:ce};var Ue=Object.defineProperty,Ge=v((t,s)=>Ue(t,"name",{value:s,configurable:!0}),"t$1");const le=Ge(async(t,s="")=>{let e=s;if(!e){const i=["packem.config.js","packem.config.mjs","packem.config.cjs","packem.config.ts","packem.config.cts","packem.config.mts"];for(const o of i)if(await ke(C(t,o))){e=`./${o}`;break}}if(!/\.(?:js|mjs|cjs|ts|cts|mts)$/.test(e))throw new Error("Invalid packem config file extension. Only .js, .mjs, .cjs, .ts, .cts and .mts extensions are allowed.");return e},"findPackemFile"),pe={less:["less"],lightningcss:["lightningcss"],"node-sass":["node-sass"],postcss:["postcss","postcss-load-config","postcss-modules-extract-imports","postcss-modules-local-by-default","postcss-modules-scope","postcss-modules-values","postcss-value-parser","@csstools/css-parser-algorithms","@csstools/css-tokenizer","@csstools/postcss-slow-plugins","icss-utils","@visulima/css-style-inject"],sass:["sass"],"sass-embedded":["sass-embedded"],stylus:["stylus"],tailwindcss:["@tailwindcss/node","@tailwindcss/oxide","tailwindcss"]};var ze=Object.defineProperty,ee=v((t,s)=>ze(t,"name",{value:s,configurable:!0}),"g");const We=["typedoc","typedoc-plugin-markdown","typedoc-plugin-rename-defaults"],_e=ee(t=>{t.addCommand({argument:{description:"Add a packem feature to your project",name:"feature",required:!0},description:"Add a optional packem feature to your project",execute:ee(async({argument:s,logger:e,options:i})=>{const o=U(),n=E(W(),i.dir??".");let l;try{l=await le(n,i.config)}catch{e.error("Could not find a packem config file, please run `packem init` first.");return}const r=await $e(l,{buffer:!1});let u="cjs";r.includes("import")&&(u="esm");const a=new De(r),m=" transformer,";let c=" transformer";if(r.includes(" transformer,")&&(c=" transformer,"),s.includes("typedoc")){if(r.includes("typedoc: typedocBuilder")||r.includes("@visulima/packem/builder/typedoc")){e.warn("Typedoc has already been added to the packem config.");return}u==="cjs"?a.prepend(`const typedocBuilder = require("@visulima/packem/builder/typedoc");
5
- `):a.prepend(`import typedocBuilder from "@visulima/packem/builder/typedoc";
6
- `),r.includes("builder: {")?a.replace("builder: {",`builder: {
27
+ var name = "@visulima/packem";
28
+ var version = "2.0.0-alpha.40";
29
+ const pkg = {
30
+ version: version};
31
+
32
+ const findPackemFile = async (rootDirectory, configPath = "") => {
33
+ let packemConfigFilePath = configPath;
34
+ if (!packemConfigFilePath) {
35
+ const packemConfigFiles = ["packem.config.js", "packem.config.mjs", "packem.config.cjs", "packem.config.ts", "packem.config.cts", "packem.config.mts"];
36
+ for (const file of packemConfigFiles) {
37
+ if (await isAccessible(join(rootDirectory, file))) {
38
+ packemConfigFilePath = `./${file}`;
39
+ break;
40
+ }
41
+ }
42
+ }
43
+ if (!/\.(?:js|mjs|cjs|ts|cts|mts)$/.test(packemConfigFilePath)) {
44
+ throw new Error("Invalid packem config file extension. Only .js, .mjs, .cjs, .ts, .cts and .mts extensions are allowed.");
45
+ }
46
+ return packemConfigFilePath;
47
+ };
48
+
49
+ const cssLoaderDependencies = {
50
+ less: ["less"],
51
+ lightningcss: ["lightningcss"],
52
+ "node-sass": ["node-sass"],
53
+ postcss: [
54
+ "postcss",
55
+ "postcss-load-config",
56
+ "postcss-modules-extract-imports",
57
+ "postcss-modules-local-by-default",
58
+ "postcss-modules-scope",
59
+ "postcss-modules-values",
60
+ "postcss-value-parser",
61
+ "@csstools/css-parser-algorithms",
62
+ "@csstools/css-tokenizer",
63
+ "@csstools/postcss-slow-plugins",
64
+ "icss-utils",
65
+ "@visulima/css-style-inject"
66
+ ],
67
+ sass: ["sass"],
68
+ "sass-embedded": ["sass-embedded"],
69
+ stylus: ["stylus"],
70
+ tailwindcss: ["@tailwindcss/node", "@tailwindcss/oxide", "tailwindcss"]
71
+ };
72
+
73
+ const typedocPackages = ["typedoc", "typedoc-plugin-markdown", "typedoc-plugin-rename-defaults"];
74
+ const reactDevDependencies = ["@babel/core", "@babel/preset-react"];
75
+ const reactDependencies = ["react", "react-dom"];
76
+ const solidDevDependencies = ["@babel/core", "babel-preset-solid"];
77
+ const solidDependencies = ["solid-js"];
78
+ const vueDevDependencies = ["unplugin-vue"];
79
+ const vueDependencies = ["vue"];
80
+ const svelteDevDependencies = ["rollup-plugin-svelte"];
81
+ const svelteDependencies = ["svelte"];
82
+ const checkPresetExists = (config, presetName, importName) => config.includes(`preset: '${presetName}'`) || config.includes(`preset: "${presetName}"`) || config.includes(`preset: '${presetName}',`) || config.includes(`preset: "${presetName}",`) || config.includes(importName) || config.includes(`@visulima/packem/config/preset/${presetName}`);
83
+ const insertPreset = (context, presetName) => {
84
+ const { logger, magic, packemConfig } = context;
85
+ const defineConfigMatch = packemConfig.match(/defineConfig\s*\(\s*\{/);
86
+ if (defineConfigMatch && defineConfigMatch.index !== void 0) {
87
+ const insertIndex = defineConfigMatch.index + defineConfigMatch[0].length;
88
+ if (packemConfig.includes("preset:")) {
89
+ const presetMatch = packemConfig.match(/preset:\s*['"]([^'"]+)['"]/);
90
+ if (presetMatch) {
91
+ magic.replace(presetMatch[0], `preset: '${presetName}'`);
92
+ } else {
93
+ logger.warn(`A preset already exists in the config. Please manually set it to '${presetName}'.`);
94
+ throw new Error("Preset exists but is not a string");
95
+ }
96
+ } else {
97
+ magic.appendLeft(insertIndex, `
98
+ preset: '${presetName}',`);
99
+ }
100
+ } else if (packemConfig.includes("transformer:")) {
101
+ magic.replace("transformer:", `preset: '${presetName}',
102
+ transformer:`);
103
+ } else {
104
+ const configStart = packemConfig.indexOf("{");
105
+ if (configStart !== -1) {
106
+ magic.appendLeft(configStart + 1, `
107
+ preset: '${presetName}',`);
108
+ }
109
+ }
110
+ };
111
+ const checkGitDirty = async (rootDirectory) => {
112
+ try {
113
+ const result = await exec("git", ["status", "--porcelain"], {
114
+ nodeOptions: {
115
+ cwd: rootDirectory,
116
+ stdio: ["pipe", "pipe", "pipe"]
117
+ }
118
+ });
119
+ return result.stdout?.trim().length > 0;
120
+ } catch {
121
+ return false;
122
+ }
123
+ };
124
+ const checkTypeScriptInstalled = async (rootDirectory) => {
125
+ const packageJsonPath = join(rootDirectory, "package.json");
126
+ const packageJson = await parsePackageJson(packageJsonPath, {
127
+ resolveCatalogs: true
128
+ });
129
+ return Boolean(packageJson.devDependencies?.typescript ?? packageJson.dependencies?.typescript);
130
+ };
131
+ const getReactTypeDependencies = async (rootDirectory) => {
132
+ const hasTypescript = await checkTypeScriptInstalled(rootDirectory);
133
+ const packages = [...reactDependencies];
134
+ const devPackages = [...reactDevDependencies];
135
+ if (hasTypescript) {
136
+ devPackages.push("@types/react", "@types/react-dom");
137
+ } else {
138
+ const useTypescript = await confirm({
139
+ initialValue: false,
140
+ message: "Do you want to use TypeScript?"
141
+ });
142
+ if (useTypescript) {
143
+ devPackages.push("typescript", "@types/react", "@types/react-dom");
144
+ }
145
+ }
146
+ return { devPackages, packages };
147
+ };
148
+ const installPackages = async (context, devPackages, packages) => {
149
+ const { rootDirectory, spinner: s } = context;
150
+ s.start("Installing packages");
151
+ await installPackage(packages, {
152
+ cwd: rootDirectory,
153
+ dev: false,
154
+ silent: true
155
+ });
156
+ await installPackage(devPackages, {
157
+ cwd: rootDirectory,
158
+ dev: true,
159
+ silent: true
160
+ });
161
+ s.stop("Installed packages");
162
+ };
163
+ const addTypedoc = async (context) => {
164
+ const { logger, magic, packemConfig, packemConfigFormat, rootDirectory, spinner: s, transformerReplaceKey, transformerSearchKey } = context;
165
+ if (packemConfig.includes("typedoc: typedocBuilder") || packemConfig.includes("@visulima/packem/builder/typedoc")) {
166
+ logger.warn("Typedoc has already been added to the packem config.");
167
+ return;
168
+ }
169
+ if (packemConfigFormat === "cjs") {
170
+ magic.prepend(`const typedocBuilder = require("@visulima/packem/builder/typedoc");
171
+ `);
172
+ } else {
173
+ magic.prepend(`import typedocBuilder from "@visulima/packem/builder/typedoc";
174
+ `);
175
+ }
176
+ if (packemConfig.includes("builder: {")) {
177
+ magic.replace("builder: {", `builder: {
7
178
  typedoc: typedocBuilder,
8
- `):a.replace(c,`${m}
179
+ `);
180
+ } else {
181
+ magic.replace(transformerSearchKey, `${transformerReplaceKey}
9
182
  builder: {
10
183
  typedoc: typedocBuilder,
11
- },`),e.info("Adding typedoc dependencies..."),o.start("Installing packages"),await q(We,{cwd:n,dev:!0,silent:!0}),o.stop("Installed packages"),e.success(`
12
- Typedoc added!`)}if(s.includes("css")){if(r.includes("css: {")||r.includes("@visulima/packem/css")){e.warn("Css loaders have already been added to the packem config.");return}const d=[],y=await j({message:"Pick a css loader",options:[{label:"PostCSS",value:"postcss"},{hint:"experimental",label:"Lightning CSS",value:"lightningcss"},{hint:"Tailwind Css Oxide",label:"Tailwind CSS",value:"tailwindcss"}]});if(d.push(y),y!=="tailwindcss"){let g=await ie({message:"Pick extra loaders",options:[{label:"Sass",value:"sass"},{label:"Stylus",value:"stylus"},{label:"Less",value:"less"}],required:!1});if(g.includes("sass")){const k=await j({message:"Pick a sass loader",options:[{hint:"recommended",label:"Sass embedded",value:"sass-embedded"},{label:"Sass",value:"sass"},{hint:"legacy",label:"Node Sass",value:"node-sass"}]});k!=="sass"&&(g=g.filter(D=>D!=="sass"),g.push(k))}d.push(...g)}const b=[];for(const g of d)b.push(...pe[g]);y!=="tailwindcss"&&d.push("sourceMap");for(let g of d)(g==="sass-embedded"||g==="node-sass")&&(g="sass"),u==="cjs"?a.prepend(`const ${g}Loader = require("@visulima/packem/css/loader/${g.toLowerCase()}");
13
- `):a.prepend(`import ${g}Loader from "@visulima/packem/css/loader/${g.toLowerCase()}";
14
- `);const f=await h({initialValue:!1,message:"Do you want to minify your css?"});let p;f&&(p=await j({message:"Pick a css minifier",options:[{label:"CSSNano",value:"cssnano"},{label:"Lightning CSS",value:"lightningcss"}]}),d.includes("lightningcss")||b.push(p),u==="cjs"?a.prepend(`const ${p}Minifier = require("@visulima/packem/css/minifier/${p.toLowerCase()}");
15
- `):a.prepend(`import ${p}Minifier from "@visulima/packem/css/minifier/${p.toLowerCase()}";
16
- `));const w=d.map(g=>((g==="sass-embedded"||g==="node-sass")&&(g="sass"),`${g}Loader`)).join(", ");r.includes("rollup: {")?a.replace("rollup: {",`rollup: {
17
- css: {${p?`
18
- minifier: ${p}Minifier,`:""}
19
- loaders: [${w}],
184
+ },`);
185
+ }
186
+ logger.info("Adding typedoc dependencies...");
187
+ s.start("Installing packages");
188
+ await installPackage(typedocPackages, {
189
+ cwd: rootDirectory,
190
+ dev: true,
191
+ silent: true
192
+ });
193
+ s.stop("Installed packages");
194
+ logger.success("\nTypedoc added!");
195
+ };
196
+ const addReact = async (context) => {
197
+ const { logger, packemConfig } = context;
198
+ if (checkPresetExists(packemConfig, "react", "createReactPreset")) {
199
+ logger.warn("React preset has already been added to the packem config.");
200
+ return;
201
+ }
202
+ insertPreset(context, "react");
203
+ const { devPackages, packages } = await getReactTypeDependencies(context.rootDirectory);
204
+ logger.info("Adding React dependencies...");
205
+ await installPackages(context, devPackages, packages);
206
+ logger.success("\nReact preset added!");
207
+ };
208
+ const addSolid = async (context) => {
209
+ const { logger, packemConfig } = context;
210
+ if (checkPresetExists(packemConfig, "solid", "createSolidPreset")) {
211
+ logger.warn("Solid preset has already been added to the packem config.");
212
+ return;
213
+ }
214
+ insertPreset(context, "solid");
215
+ logger.info("Adding Solid dependencies...");
216
+ await installPackages(context, solidDevDependencies, solidDependencies);
217
+ logger.success("\nSolid preset added!");
218
+ };
219
+ const addVue = async (context) => {
220
+ const { logger, packemConfig } = context;
221
+ if (checkPresetExists(packemConfig, "vue", "createVuePreset")) {
222
+ logger.warn("Vue preset has already been added to the packem config.");
223
+ return;
224
+ }
225
+ insertPreset(context, "vue");
226
+ logger.info("Adding Vue dependencies...");
227
+ await installPackages(context, vueDevDependencies, vueDependencies);
228
+ logger.success("\nVue preset added!");
229
+ };
230
+ const addSvelte = async (context) => {
231
+ const { logger, packemConfig } = context;
232
+ if (checkPresetExists(packemConfig, "svelte", "createSveltePreset")) {
233
+ logger.warn("Svelte preset has already been added to the packem config.");
234
+ return;
235
+ }
236
+ insertPreset(context, "svelte");
237
+ logger.info("Adding Svelte dependencies...");
238
+ await installPackages(context, svelteDevDependencies, svelteDependencies);
239
+ logger.success("\nSvelte preset added!");
240
+ };
241
+ const addCss = async (context) => {
242
+ const { logger, magic, packemConfig, packemConfigFormat, transformerReplaceKey, transformerSearchKey } = context;
243
+ if (packemConfig.includes("css: {") || packemConfig.includes("@visulima/packem/css")) {
244
+ logger.warn("Css loaders have already been added to the packem config.");
245
+ return;
246
+ }
247
+ const cssLoaders = [];
248
+ const mainCssLoader = await select({
249
+ message: "Pick a css loader",
250
+ options: [
251
+ { label: "PostCSS", value: "postcss" },
252
+ {
253
+ hint: "experimental",
254
+ label: "Lightning CSS",
255
+ value: "lightningcss"
256
+ },
257
+ {
258
+ hint: "Tailwind Css Oxide",
259
+ label: "Tailwind CSS",
260
+ value: "tailwindcss"
261
+ }
262
+ ]
263
+ });
264
+ cssLoaders.push(mainCssLoader);
265
+ if (mainCssLoader !== "tailwindcss") {
266
+ let extraCssLoaders = await multiselect({
267
+ message: "Pick extra loaders",
268
+ options: [
269
+ { label: "Sass", value: "sass" },
270
+ { label: "Stylus", value: "stylus" },
271
+ { label: "Less", value: "less" }
272
+ ],
273
+ required: false
274
+ });
275
+ if (extraCssLoaders.includes("sass")) {
276
+ const sassLoader = await select({
277
+ message: "Pick a sass loader",
278
+ options: [
279
+ {
280
+ hint: "recommended",
281
+ label: "Sass embedded",
282
+ value: "sass-embedded"
283
+ },
284
+ { label: "Sass", value: "sass" },
285
+ {
286
+ hint: "legacy",
287
+ label: "Node Sass",
288
+ value: "node-sass"
289
+ }
290
+ ]
291
+ });
292
+ if (sassLoader !== "sass") {
293
+ extraCssLoaders = extraCssLoaders.filter((loader) => loader !== "sass");
294
+ extraCssLoaders.push(sassLoader);
295
+ }
296
+ }
297
+ cssLoaders.push(...extraCssLoaders);
298
+ }
299
+ const packagesToInstall = [];
300
+ for (const loader of cssLoaders) {
301
+ packagesToInstall.push(...cssLoaderDependencies[loader]);
302
+ }
303
+ if (mainCssLoader !== "tailwindcss") {
304
+ cssLoaders.push("sourceMap");
305
+ }
306
+ for (const loader of cssLoaders) {
307
+ const normalizedLoader = loader === "sass-embedded" || loader === "node-sass" ? "sass" : loader;
308
+ if (packemConfigFormat === "cjs") {
309
+ magic.prepend(`const ${normalizedLoader}Loader = require("@visulima/packem/css/loader/${normalizedLoader.toLowerCase()}");
310
+ `);
311
+ } else {
312
+ magic.prepend(`import ${normalizedLoader}Loader from "@visulima/packem/css/loader/${normalizedLoader.toLowerCase()}";
313
+ `);
314
+ }
315
+ }
316
+ const useCssMinifier = await confirm({
317
+ initialValue: false,
318
+ message: "Do you want to minify your css?"
319
+ });
320
+ let cssMinifier;
321
+ if (useCssMinifier) {
322
+ cssMinifier = await select({
323
+ message: "Pick a css minifier",
324
+ options: [
325
+ { label: "CSSNano", value: "cssnano" },
326
+ { label: "Lightning CSS", value: "lightningcss" }
327
+ ]
328
+ });
329
+ if (!cssLoaders.includes("lightningcss")) {
330
+ packagesToInstall.push(cssMinifier);
331
+ }
332
+ if (packemConfigFormat === "cjs") {
333
+ magic.prepend(`const ${cssMinifier}Minifier = require("@visulima/packem/css/minifier/${cssMinifier.toLowerCase()}");
334
+ `);
335
+ } else {
336
+ magic.prepend(`import ${cssMinifier}Minifier from "@visulima/packem/css/minifier/${cssMinifier.toLowerCase()}";
337
+ `);
338
+ }
339
+ }
340
+ const stringCssLoaders = cssLoaders.map((loader) => {
341
+ if (loader === "sass-embedded" || loader === "node-sass") {
342
+ return "sass";
343
+ }
344
+ return `${loader}Loader`;
345
+ }).join(", ");
346
+ if (packemConfig.includes("rollup: {")) {
347
+ magic.replace(
348
+ "rollup: {",
349
+ `rollup: {
350
+ css: {${cssMinifier ? `
351
+ minifier: ${cssMinifier}Minifier,` : ""}
352
+ loaders: [${stringCssLoaders}],
20
353
  },
21
- `):a.replace(c,`${m}
354
+ `
355
+ );
356
+ } else {
357
+ magic.replace(
358
+ transformerSearchKey,
359
+ `${transformerReplaceKey}
22
360
  rollup: {
23
- css: {${p?`
24
- minifier: ${p}Minifier,`:""}
25
- loaders: [${w}],
361
+ css: {${cssMinifier ? `
362
+ minifier: ${cssMinifier}Minifier,` : ""}
363
+ loaders: [${stringCssLoaders}],
26
364
  },
27
- },`),o.start("Installing packages"),await q(b,{cwd:n,dev:!0,silent:!0}),o.stop("Installed packages"),e.success(`
28
- CSS loaders added!`)}await je(l,a.toString(),{overwrite:!0})},"execute"),name:"add",options:[{defaultValue:".",description:"The directory to build",name:"dir",type:String},{description:"Use a custom config file",name:"config",type:String}]})},"createAddCommand");var Xe=Object.defineProperty,Ye=v((t,s)=>Xe(t,"name",{value:s,configurable:!0}),"e$1");const He=Ye(async(t,s,e,i,o)=>{const n=await le(s,o);let l=await t.import(n,{default:!0,try:!0})||{};return typeof l=="function"&&(l=await l(e,i)),{config:l,path:n}},"loadPackemConfig");var Ze=Object.defineProperty,S=v((t,s)=>Ze(t,"name",{value:s,configurable:!0}),"u$1");const z=new Map,Qe=/\.[^./]+$/,et=S(async t=>{try{return await Ke.readdir(t,{withFileTypes:!0})}catch(s){const{code:e}=s;if(e==="ENOENT")return[];throw s}},"safeReaddir"),de=S(async(t,s)=>{const e=await et(t);return(await Promise.all(e.map(async i=>{const o=Z.join(t,i.name);return i.isDirectory()?de(o,s):i.isFile()?Z.relative(s,o):[]}))).flat()},"getDirectoryFilesRecursive"),tt=S(async t=>{let s=z.get(t);return s||(s=de(t,t),z.set(t,s)),s},"getDirectoryFiles"),st=S((t,s)=>{const e=t.replace(Qe,"");if(s==="*"){const l=e.split("/");return l.length>0?[l[0]]:null}const i=s.replaceAll(/[.+?^${}()|[\]\\]/g,String.raw`\$&`).replaceAll("*","(.*)"),o=new RegExp(`^${i}$`),n=e.match(o);return n?n.slice(1):null},"matchWildcardPattern"),ot=S((t,s)=>{let e=t;for(const i of s)e=e.replace("*",i);return e},"substituteWildcards"),it=S((t,s)=>t.key==="exports"&&t.subKey===K?K:t.key==="exports"&&t.subKey===G?G:s,"getEnvironment"),A=S((t,s,e,i,o,n,l)=>{const r=it(o,n.environment);let u=n.options.runtime;for(const c of Ee)if(o.file.includes(`.${c}.`)||o.subKey===c){u=c;break}let a=t.find(c=>c.input===s&&c.environment===r&&c.runtime===u);a===void 0?a=t[t.push({environment:r,exportKey:new Set([o.exportKey].filter(Boolean)),input:s,runtime:u})-1]:a.exportKey&&o.exportKey&&a.exportKey.add(o.exportKey),l&&(a.isGlob=!0),e&&(a.outDir=i),o.isExecutable?(a.executable=!0,a.declaration=!1,o.type==="cjs"?a.cjs=!0:o.type==="esm"&&(a.esm=!0)):(/\.d\.[mc]?ts$/.test(o.file)&&n.options.declaration!==!1&&(a.declaration=n.options.declaration),o.type==="cjs"?a.cjs=!0:o.type==="esm"&&(a.esm=!0));const m=o.file.replace(ne(o.file),"").replace(new RegExp(`^./${n.options.outDir.replace(/^\.\//,"")}/`),"");re.has(o.subKey)&&!s.includes(m)&&(a.fileAlias=m)},"createOrUpdateEntry");let te=!1;const se=S(t=>{if(t.pkg?.dependencies?.typescript===void 0&&t.pkg?.devDependencies?.typescript===void 0)throw new Error("You tried to use a `.ts`, `.cts` or `.mts` file but `typescript` was not found in your package.json.")},"validateIfTypescriptIsInstalled"),nt=S(async(t,s,e)=>{const i=t.types||t.typings;z.clear();const o=(e.options.outputExtensionMap?.cjs??"cjs").replaceAll(".",String.raw`\.`),n=(e.options.outputExtensionMap?.esm??"mjs").replaceAll(".",String.raw`\.`),l=[];s.sort((c,d)=>c.split("/").length-d.split("/").length);const r=t.type==="module"?"esm":"cjs";r==="esm"&&(e.options.emitESM=!0),r==="cjs"&&(e.options.emitCJS=!0);const u=e.options.emitCJS&&e.options.emitESM;e.options.declaration===void 0&&(e.options.declaration=u?"compatible":"node16");const a=Be(t.exports,r,e.options.declaration,[],e.options.ignoreExportKeys).filter(c=>!c.ignored);if(t.bin){const c=(typeof t.bin=="string"?[t.bin]:Object.values(t.bin)).filter(Boolean);for(const d of c){const y=H(d);if(y&&y!==r)throw new Error(`Exported file "${d}" has an extension that does not match the package.json type "${t.type??"commonjs"}".`);a.push({file:d,isExecutable:!0,key:"bin",type:y??r})}}t.main&&a.push({file:t.main,key:"main",type:H(t.main)??r}),t.module&&a.push({file:t.module,key:"module",type:"esm"}),i&&(se(e),(e.options.declaration===void 0||e.options.declaration==="node16")&&u&&(e.options.declaration="compatible"),a.push({file:t.types??t.typings,key:"types"}));const m=[];for await(const c of a){const d=ne(c.file);if(d!==""&&!Me.includes(d))continue;if(e.options.emitCJS===void 0&&c.type==="cjs"&&(e.options.emitCJS=!0),e.options.emitESM===void 0&&c.type==="esm"&&(e.options.emitESM=!0),e.options.declaration===void 0||e.options.declaration==="node16"){const $=e.options.emitCJS&&e.options.emitESM;e.options.declaration=$?"compatible":"node16"}const y=c.file.replace(new RegExp(String.raw`(?:\*[^/\\]|\.d\.[mc]?ts|\.\w+|${[`\\.${o}`,`\\.${n}`].join("|")})$`),""),b=y.endsWith("/");if(b&&["./","/"].includes(y))continue;const f=y.replace(new RegExp(`(./)?${e.options.outDir}`),e.options.sourceDir).replace("./",""),p="(?<=/|$)",w=b?"":String.raw`(\.d\.[cm]?ts|(\.[cm]?[tj]sx?)|${[`\\.${o}`,`\\.${n}`].join("|")})$`;if((c.file.includes("/*")||y.includes("*"))&&c.key==="exports"){te||(e.logger.debug("Private subfolders are not supported, if you need this feature please open an issue on GitHub."),te=!0);let $;c.exportKey?$=c.exportKey.startsWith("./")?c.exportKey.slice(2):c.exportKey:$=(c.file.startsWith("./")?c.file.slice(2):c.file).replace(/^dist\//,"");const N=c.file,F=e.options.sourceDir.replace(/^\.\//,""),_=E(e.options.rootDir,F),R=[],ue=await tt(_);for(const B of ue){const L=st(B,$);if(L){const J=ot(N,L);R.push({input:E(_,B),output:J})}}if(R.length===0){l.push(`Could not find entrypoints matching pattern \`${$}\` for output \`${N}\``);continue}for(const{input:B,output:L}of R){const J={...c,file:L};A(m,B,b,y,J,e,!0)}continue}const g=new RegExp(p+f+w);let k=s.find($=>g.test($));if(re.has(c.subKey)&&k===void 0){const $=f.replace(/^(.+?)\.[^.]*$/,"$1"),N=new RegExp(p+$+w);k=s.find(F=>N.test(F))}if(k===void 0){x(E(e.options.rootDir,c.file))||l.push(`Could not find entrypoint for \`${c.file}\``);continue}x(k)&&/\.[cm]?tsx?$/.test(k)&&se(e);const D=Ce(k.replace(Pe,""));x(`${D}.cts`)&&x(`${D}.mts`)?(A(m,`${D}.cts`,b,y,{...c,type:"cjs"},e,!1),A(m,`${D}.mts`,b,y,{...c,type:"esm"},e,!1)):A(m,k,b,y,c,e,!1)}return{entries:m,warnings:l}},"inferEntries");var rt=Object.defineProperty,at=v((t,s)=>rt(t,"name",{value:s,configurable:!0}),"o");const ct=at((t,s)=>{const{publishConfig:e}=t;return e&&(e.bin&&(typeof e.bin=="object"||typeof e.bin=="string")&&(t.bin=e.bin),e.type&&typeof e.type=="string"&&e.type!==""&&(t.type=e.type),e.main&&typeof e.main=="string"&&e.main!==""&&(t.main=e.main),e.module&&typeof e.module=="string"&&e.module!==""&&(t.module=e.module),s===void 0&&e.types&&typeof e.types=="string"&&e.types!==""?t.types=e.types:s===void 0&&e.typings&&typeof e.typings=="string"&&e.typings!==""&&(t.typings=e.typings),e.exports&&typeof e.exports=="object"&&(t.exports=e.exports)),t},"overwriteWithPublishConfig");var lt=Object.defineProperty,pt=v((t,s)=>lt(t,"name",{value:s,configurable:!0}),"p");const dt={hooks:{"build:prepare":pt(async function(t){if(t.options.unbundle){t.options.entries.length=0;const o=C(t.options.rootDir,t.options.sourceDir);if(!x(o))throw new Error("No 'src' directory found. Please provide entries manually.");const n=Y(o,{extensions:[],includeDirs:!1,includeSymlinks:!1,skip:[/.*\/node_modules\/.*/,/.*\/dist\/.*/]}).filter(l=>/\.(ts|tsx|js|jsx|mts|cts|mjs|cjs)$/.test(l)&&!l.endsWith(".d.ts"));for(const l of n){const r=l.replace(`${o}/`,"").replace(/\.(ts|tsx|js|jsx|mts|cts|mjs|cjs)$/,"").replaceAll("/","/");t.options.entries.push({input:l,name:r})}return}if(t.options.entries.length>0)return;const s=C(t.options.rootDir,t.options.sourceDir);if(!x(s))throw new Error("No 'src' directory found. Please provide entries manually.");const e=Y(s,{extensions:[],includeDirs:!1,includeSymlinks:!1,skip:[/.*\/node_modules\/.*/,/.*\/dist\/.*/]});if(e.length===0)throw new Error("No source files found in 'src' directory. Please provide entries manually.");let i={...t.pkg};if(i.publishConfig&&(t.logger.info(`Using publishConfig found in package.json, to override the default key-value pairs of "${Object.keys(i.publishConfig).join(", ")}".`),t.logger.debug(i.publishConfig),i=ct(i,t.options.declaration)),t.options.unbundle){t.logger.info("Unbundle mode detected, creating entries for all source files");const o=e.filter(n=>/\.(ts|tsx|js|jsx|mts|cts|mjs|cjs)$/.test(n)&&!n.endsWith(".d.ts"));t.logger.info(`Found ${o.length} code files for unbundle mode`);for(const n of o){const l=n.replace(`${s}/`,"").replace(/\.(ts|tsx|js|jsx|mts|cts|mjs|cjs)$/,"").replaceAll("/","/");t.logger.info(`Adding entry: ${l} -> ${n}`),t.options.entries.push({input:n,name:l})}}else{const o=await nt(i,e,t);for(const n of o.warnings)Le(t,n);t.options.entries.push(...o.entries)}if(t.options.entries.length===0)throw new Error("No entries detected. Please provide entries manually.");t.logger.info("Automatically detected entries:",Te(t.options.entries.map(o=>o.fileAlias?`${V(o.fileAlias)} => ${V(o.input.replace(`${t.options.rootDir}/`,"").replace(/\/$/,"/*"))}`:V(o.input.replace(`${t.options.rootDir}/`,"").replace(/\/$/,"/*"))).join(", ")),Ne([t.options.emitESM&&"esm",t.options.emitCJS&&"cjs",t.options.declaration&&"dts"].filter(Boolean).map(o=>`[${o}]`).join(" ")))},"build:prepare")}};var ut=Object.defineProperty,mt=v((t,s)=>ut(t,"name",{value:s,configurable:!0}),"t");const ft=mt(async(t,s)=>{if(t==="auto")t=dt;else{if(t==="none")return{};typeof t=="string"&&(t=await s.import(t)||{})}return typeof t=="function"&&(t=t()),t},"loadPreset");var gt=Object.defineProperty,O=v((t,s)=>gt(t,"name",{value:s,configurable:!0}),"r");const yt=O(t=>{t.addCommand({description:"Demonstrate options required",execute:O(async({logger:s,options:e})=>{let i="build";e.watch?i="watch":e.jit&&(i="jit");const o={};let n;if(e.env)for(const d of e.env)d.key==="NODE_ENV"?n=d.value:o[`process.env.${d.key}`]=JSON.stringify(d.value);n===void 0&&(e.production?n=K:e.development&&(n=G));const l=[];if(e.external)for(const d of e.external)l.push(d.split(","));const r=E(W(),e.dir??"."),u=Ie(r,{debug:e.debug}),{config:a,path:m}=await He(u,r,n,i,e.config??void 0);s.debug("Using packem config found at",m);const c=await ft(a.preset??"auto",u);e.minify&&e.sourcemap===void 0&&(e.sourcemap=!0);try{await Ae(r,i,n,s,e.debug,Oe(a,c,{analyze:e.analyze,cjsInterop:e.cjsInterop,clean:e.clean,dtsOnly:e.dtsOnly,externals:l,killSignal:e.killSignal,minify:e.minify===void 0?n===K:e.minify,onSuccess:e.onSuccess,rollup:{esbuild:{target:e.target},license:{path:e.license},metafile:e.metafile,replace:{values:o},resolveExternals:e.noExternal?{builtins:!1,deps:!1,devDeps:!1,optDeps:!1,peerDeps:!1}:{}},runtime:e.runtime,sourcemap:e.metafile||e.analyze||e.sourcemap,unbundle:e.unbundle,validation:e.validation===!1?!1:{},...e.typedoc?{typedoc:{format:"html"}}:{}}),e.tsconfig??void 0)}catch(d){s.error(d),be(1)}},"execute"),name:"build",options:[{defaultValue:".",description:"The directory to build",name:"dir",type:String},{alias:"t",description:"Environments to support. `target` in tsconfig.json is automatically added. Defaults to the current Node.js version.",name:"target"},{description:"Use a custom config file",name:"config",type:String},{description:"Path to the tsconfig.json file",name:"tsconfig",type:String},{description:"Minify the output",name:"minify",type:Boolean},{description:"Generate sourcemaps (experimental)",name:"sourcemap",type:Boolean},{conflicts:"jit",description:"Watch for changes",name:"watch",type:Boolean},{conflicts:"watch",description:"Stub the package for JIT compilation",name:"jit",type:Boolean},{description:"Compile-time environment variables (eg. --env.NODE_ENV=production)",multiple:!0,name:"env",type:O(s=>{const[e,i]=s.split("=");return{key:e,value:i}},"type")},{defaultValue:!1,description:"Generate meta file (experimental)",name:"metafile",type:Boolean},{description:"Path to the license file",name:"license",type:String},{conflicts:"watch",description:"Visualize and analyze the bundle",name:"analyze",type:Boolean},{description:"CJS interop mode, can export default and named export, (experimental).",name:"cjsInterop",type:Boolean},{conflicts:"development",description:"Run code in production environment",name:"production",type:Boolean},{conflicts:"production",description:"Run code in development environment",name:"development",type:Boolean},{description:"Do not clean the dist directory before building",name:"no-clean",type:Boolean},{description:"Only generate .d.ts files",name:"dts-only",type:Boolean},{description:"Disable the output validation",name:"no-validation",type:Boolean},{description:"Disable the cache",name:"no-cache",type:Boolean},{description:"Generate type documentation",name:"typedoc",type:Boolean},{description:"Execute command after successful build, specially useful for watch mode",name:"onSuccess",type:String},{description:'Signal to kill child process, "SIGTERM" or "SIGKILL"',name:"killSignal",type:O(s=>{if(s==="SIGTERM"||s==="SIGKILL")return s;throw new Error("Invalid kill signal. Use 'SIGTERM' or 'SIGKILL'.")},"type")},{description:"Specify an external dependency, separate by comma (eg. --external lodash,react,react-dom)",multiple:!0,name:"external",typeLabel:"string[]"},{description:"do not bundle external dependencies",name:"no-external",type:Boolean},{description:"Specify the build runtime (nodejs, browser).",name:"runtime",type:O(s=>{if(s==="node"||s==="browser")return s;throw new Error("Invalid runtime. Use 'node' or 'browser'.")},"type")},{description:"Enable unbundle mode to preserve source file structure instead of bundling into a single file",name:"unbundle",type:Boolean}]})},"createBuildCommand");var bt=Object.defineProperty,I=v((t,s)=>bt(t,"name",{value:s,configurable:!0}),"f");const wt=I(t=>{t.addCommand({description:"Initialize packem configuration",execute:I(async({logger:s,options:e})=>{if(we("Welcome to packem setup"),x(C(e.dir,"packem.config.mjs"))){s.info("Packem project already initialized, you can use `packem build` to build your project");return}const i=E(W(),e.dir??"."),o=C(i,"package.json");if(!x(o))throw new Error("No package.json found in the directory");const n=await Je(o,{resolveCatalogs:!0}),l=[];n.dependencies&&l.push(...Object.keys(n.dependencies)),n.devDependencies&&l.push(...Object.keys(n.devDependencies));const r=!!(n.devDependencies?.typescript??n.dependencies?.typescript),u=[];if(e.typescript===void 0&&!r?(e.typescript=await h({message:"Do you want to install TypeScript?"}),e.typescript&&u.push("typescript@latest")):X.message(`TypeScript version ${n.devDependencies?.typescript??n.dependencies?.typescript} is already installed`),!x(C(i,"tsconfig.json"))){const f=await h({message:"Do you want to use generate a tsconfig.json?"}),p=await h({message:"Do you want to run your code in the DOM?"});if(f){const w=U();w.start("Generating tsconfig.json"),xe(C(i,"tsconfig.json"),{compilerOptions:{esModuleInterop:!0,skipLibCheck:!0,target:"es2022",allowJs:!0,resolveJsonModule:!0,moduleDetection:"force",isolatedModules:!0,verbatimModuleSyntax:!0,strict:!0,noUncheckedIndexedAccess:!0,noImplicitOverride:!0,module:"NodeNext",outDir:"dist",sourceMap:!0,declaration:!0,lib:p?["es2022","dom","dom.iterable"]:["es2022"]}}),w.stop("")}}if(e.runtime===void 0&&(e.runtime=await j({message:"Pick a build runtime",options:[{label:"Node",value:"node"},{label:"Browser",value:"browser"}]})),l.includes("esbuild")?e.transformer="esbuild":l.includes("@swc/core")?e.transformer="swc":l.includes("sucrase")&&(e.transformer="sucrase"),e.transformer===void 0?(e.transformer=await j({message:"Pick a transformer",options:[{label:"esbuild",value:"esbuild"},{label:"swc",value:"swc"},{label:"Sucrase",value:"sucrase"},{label:"OXC",value:"oxc"}]}),e.transformer&&e.transformer!=="oxc"&&!l.includes(e.transformer)&&await h({message:`Do you want to install ${e.transformer}?`})&&u.push(e.transformer==="swc"?"@swc/core":e.transformer)):X.message(`Transformer ${e.transformer} is already installed.`),e.isolatedDeclarationTransformer===void 0&&(e.isolatedDeclarationTransformer=await h({message:"Do you want to use an isolated declaration types?",initialValue:!1})),e.isolatedDeclarationTransformer===void 0&&(e.isolatedDeclarationTransformer=await j({message:"Pick a isolated declaration transformer",options:[{label:"Typescript",value:"typescript"},{label:"swc",value:"swc"},{label:"OXC",value:"oxc"},{label:"None",value:void 0}]}),e.isolatedDeclarationTransformer!==void 0)){let f;switch(e.isolatedDeclarationTransformer){case"oxc":{f="oxc-transform";break}case"swc":{f="@swc/core";break}case"typescript":{f="typescript";break}default:ve("Invalid isolated declaration transformer")}f!==void 0&&!l.includes(f)&&await h({message:`Do you want to install ${f}?`})&&u.push(f)}e.css===void 0&&(e.css=await h({message:"Do you want to use css in your project?",initialValue:!1}));const a=[];if(e.css){const f=await j({message:"Pick a css loader",options:[{label:"PostCSS",value:"postcss"},{hint:"experimental",label:"Lightning CSS",value:"lightningcss"}]});a.push(f);let p=await ie({message:"Pick your loaders",options:[{label:"Sass",value:"sass"},{label:"Stylus",value:"stylus"},{label:"Less",value:"less"}],required:!1});if(p.includes("sass")){const w=await j({message:"Pick a sass loader",options:[{label:"Sass embedded",value:"sass-embedded",hint:"recommended"},{label:"Sass",value:"sass"},{label:"Node Sass",value:"node-sass",hint:"legacy"}]});w!=="sass"&&(p=p.filter(g=>g!=="sass"),p.push(w))}if(a.push(...p),await h({message:`Do you want to install "${a.join('", "')}"?`}))for(const w of a)u.push(...pe[w]);a.push("sourceMap")}e.cssMinifier===void 0&&(e.cssMinifier=await h({message:"Do you want to minify your css?",initialValue:!1}));let m;e.cssMinifier&&(m=await j({message:"Pick a css minifier",options:[{label:"CSSNano",value:"cssnano"},{label:"Lightning CSS",value:"lightningcss"}]}),a.includes("lightningcss")||await h({message:`Do you want to install "${m}"?`})&&u.push(m));let c="",d="";if(e.isolatedDeclarationTransformer&&(d+=`,
29
- isolatedDeclarationTransformer`),(e.css||e.cssMinifier)&&(d+=`,
30
- rollup: {
31
- css: {`),e.css){const f=a.map(p=>((p==="sass-embedded"||p==="node-sass")&&(p="sass"),`${p}Loader`)).join(", ");d+=`
32
- loaders: [${f}],`}if(e.cssMinifier&&m&&(d+=`
33
- minifier: ${m}Minifier,`),(e.css||e.cssMinifier)&&(d+=`
34
- }
35
- }`),r||n.type==="module"){let f="";if(e.isolatedDeclarationTransformer&&(f+=`import isolatedDeclarationTransformer from "@visulima/packem/dts/isolated/transformer/${e.isolatedDeclarationTransformer}";
36
- `),e.css)for(let p of a)(p==="sass-embedded"||p==="node-sass")&&(p="sass"),f+=`import ${p}Loader from "@visulima/packem/css/loader/${p.toLowerCase()}";
37
- `;e.cssMinifier&&m&&(f+=`import ${m}Minifier from "@visulima/packem/css/minifier/${m.toLowerCase()}";
38
- `),c=`import { defineConfig } from "@visulima/packem/config";
39
- import transformer from "@visulima/packem/transformer/${e.transformer}";
40
- ${f}
365
+ },`
366
+ );
367
+ }
368
+ context.spinner.start("Installing packages");
369
+ await installPackage(packagesToInstall, {
370
+ cwd: context.rootDirectory,
371
+ dev: true,
372
+ silent: true
373
+ });
374
+ context.spinner.stop("Installed packages");
375
+ logger.success("\nCSS loaders added!");
376
+ };
377
+ const createAddCommand = (cli) => {
378
+ cli.addCommand({
379
+ argument: {
380
+ description: "Add a packem feature to your project",
381
+ name: "feature",
382
+ required: true
383
+ },
384
+ description: "Add a optional packem feature to your project",
385
+ execute: async ({ argument, logger, options }) => {
386
+ const s = spinner();
387
+ const rootDirectory = resolve(cwd(), options.dir ?? ".");
388
+ let packemConfigFilePath;
389
+ try {
390
+ packemConfigFilePath = await findPackemFile(rootDirectory, options.config);
391
+ } catch {
392
+ logger.error("Could not find a packem config file, please run `packem init` first.");
393
+ return;
394
+ }
395
+ const isGitDirty = await checkGitDirty(rootDirectory);
396
+ if (isGitDirty) {
397
+ const proceed = await confirm({
398
+ initialValue: false,
399
+ message: "Git repository has uncommitted changes. Do you want to proceed?"
400
+ });
401
+ if (!proceed) {
402
+ cancel("Operation cancelled.");
403
+ return;
404
+ }
405
+ }
406
+ const packemConfig = await readFile(packemConfigFilePath, {
407
+ buffer: false
408
+ });
409
+ const packemConfigFormat = packemConfig.includes("import") ? "esm" : "cjs";
410
+ const magic = new MagicString(packemConfig);
411
+ const transformerReplaceKey = " transformer,";
412
+ const transformerSearchKey = packemConfig.includes(" transformer,") ? " transformer," : " transformer";
413
+ const context = {
414
+ logger,
415
+ magic,
416
+ packemConfig,
417
+ packemConfigFormat,
418
+ rootDirectory,
419
+ spinner: s,
420
+ transformerReplaceKey,
421
+ transformerSearchKey
422
+ };
423
+ if (argument.includes("typedoc")) {
424
+ await addTypedoc(context);
425
+ }
426
+ if (argument.includes("react")) {
427
+ await addReact(context);
428
+ }
429
+ if (argument.includes("solid")) {
430
+ await addSolid(context);
431
+ }
432
+ if (argument.includes("vue")) {
433
+ await addVue(context);
434
+ }
435
+ if (argument.includes("svelte")) {
436
+ await addSvelte(context);
437
+ }
438
+ if (argument.includes("css")) {
439
+ await addCss(context);
440
+ }
441
+ await writeFile(packemConfigFilePath, magic.toString(), {
442
+ overwrite: true
443
+ });
444
+ },
445
+ name: "add",
446
+ options: [
447
+ {
448
+ defaultValue: ".",
449
+ description: "The directory to build",
450
+ name: "dir",
451
+ type: String
452
+ },
453
+ {
454
+ description: "Use a custom config file",
455
+ name: "config",
456
+ type: String
457
+ }
458
+ ]
459
+ });
460
+ };
461
+
462
+ const loadPackemConfig = async (jiti, rootDirectory, environment, mode, configPath) => {
463
+ const packemConfigFilePath = await findPackemFile(rootDirectory, configPath);
464
+ let buildConfig = await jiti.import(packemConfigFilePath, {
465
+ default: true,
466
+ try: true
467
+ }) || {};
468
+ if (typeof buildConfig === "function") {
469
+ buildConfig = await buildConfig(environment, mode);
470
+ }
471
+ return {
472
+ config: buildConfig,
473
+ path: packemConfigFilePath
474
+ };
475
+ };
476
+
477
+ const loadPreset = async (preset, jiti) => {
478
+ switch (preset) {
479
+ case "none": {
480
+ return {};
481
+ }
482
+ case "react": {
483
+ preset = createReactPreset();
484
+ break;
485
+ }
486
+ case "solid": {
487
+ preset = createSolidPreset();
488
+ break;
489
+ }
490
+ case "svelte": {
491
+ preset = createSveltePreset();
492
+ break;
493
+ }
494
+ case "vue": {
495
+ preset = createVuePreset();
496
+ break;
497
+ }
498
+ default: {
499
+ if (typeof preset === "string") {
500
+ preset = await jiti.import(preset) || {};
501
+ }
502
+ }
503
+ }
504
+ if (typeof preset === "function") {
505
+ preset = preset();
506
+ }
507
+ return preset;
508
+ };
509
+
510
+ const createBuildCommand = (cli) => {
511
+ cli.addCommand({
512
+ description: "Demonstrate options required",
513
+ // eslint-disable-next-line sonarjs/cognitive-complexity
514
+ execute: async ({ logger, options }) => {
515
+ let mode = "build";
516
+ if (options.watch) {
517
+ mode = "watch";
518
+ } else if (options.jit) {
519
+ mode = "jit";
520
+ }
521
+ const environments = {};
522
+ let nodeEnvironment;
523
+ if (options.env) {
524
+ for (const environment of options.env) {
525
+ if (environment.key === "NODE_ENV") {
526
+ nodeEnvironment = environment.value;
527
+ } else {
528
+ environments[`process.env.${environment.key}`] = JSON.stringify(environment.value);
529
+ }
530
+ }
531
+ }
532
+ if (nodeEnvironment === void 0) {
533
+ if (options.production) {
534
+ nodeEnvironment = PRODUCTION_ENV;
535
+ } else if (options.development) {
536
+ nodeEnvironment = DEVELOPMENT_ENV;
537
+ }
538
+ }
539
+ const externals = [];
540
+ if (options.external) {
541
+ for (const extension of options.external) {
542
+ externals.push(extension.split(","));
543
+ }
544
+ }
545
+ const rootPath = resolve(cwd(), options.dir ?? ".");
546
+ const jiti = createJiti(rootPath, { debug: options.debug });
547
+ const { config: buildConfig, path: buildConfigPath } = await loadPackemConfig(
548
+ jiti,
549
+ rootPath,
550
+ nodeEnvironment,
551
+ mode,
552
+ options.config ?? void 0
553
+ );
554
+ logger.debug("Using packem config found at", buildConfigPath);
555
+ const preset = await loadPreset(buildConfig.preset ?? "none", jiti);
556
+ if (options.minify && options.sourcemap === void 0) {
557
+ options.sourcemap = true;
558
+ }
559
+ try {
560
+ await packem(
561
+ rootPath,
562
+ mode,
563
+ nodeEnvironment,
564
+ logger,
565
+ options.debug,
566
+ defu(buildConfig, autoPreset, preset, {
567
+ analyze: options.analyze,
568
+ cjsInterop: options.cjsInterop,
569
+ clean: options.clean,
570
+ dtsOnly: options.dtsOnly,
571
+ externals,
572
+ killSignal: options.killSignal,
573
+ minify: options.minify === void 0 ? nodeEnvironment === PRODUCTION_ENV : options.minify,
574
+ onSuccess: options.onSuccess,
575
+ rollup: {
576
+ esbuild: {
577
+ target: options.target
578
+ },
579
+ license: {
580
+ path: options.license
581
+ },
582
+ metafile: options.metafile,
583
+ replace: {
584
+ values: environments
585
+ },
586
+ resolveExternals: options.noExternal ? {
587
+ builtins: false,
588
+ deps: false,
589
+ devDeps: false,
590
+ optDeps: false,
591
+ peerDeps: false
592
+ } : {}
593
+ },
594
+ runtime: options.runtime,
595
+ sourcemap: options.metafile || options.analyze || options.sourcemap,
596
+ unbundle: options.unbundle,
597
+ // validation will take the default values
598
+ validation: options.validation === false ? false : {},
599
+ ...options.typedoc ? {
600
+ typedoc: {
601
+ format: "html"
602
+ }
603
+ } : {}
604
+ }),
605
+ options.tsconfig ?? void 0
606
+ );
607
+ } catch (error) {
608
+ logger.error(error);
609
+ exit(1);
610
+ }
611
+ },
612
+ name: "build",
613
+ options: [
614
+ {
615
+ defaultValue: ".",
616
+ description: "The directory to build",
617
+ name: "dir",
618
+ type: String
619
+ },
620
+ {
621
+ alias: "t",
622
+ description: "Environments to support. `target` in tsconfig.json is automatically added. Defaults to the current Node.js version.",
623
+ name: "target"
624
+ },
625
+ {
626
+ description: "Use a custom config file",
627
+ name: "config",
628
+ type: String
629
+ },
630
+ {
631
+ description: "Path to the tsconfig.json file",
632
+ name: "tsconfig",
633
+ type: String
634
+ },
635
+ {
636
+ description: "Minify the output",
637
+ name: "minify",
638
+ type: Boolean
639
+ },
640
+ {
641
+ description: "Generate sourcemaps (experimental)",
642
+ name: "sourcemap",
643
+ type: Boolean
644
+ },
645
+ {
646
+ conflicts: "jit",
647
+ description: "Watch for changes",
648
+ name: "watch",
649
+ type: Boolean
650
+ },
651
+ {
652
+ conflicts: "watch",
653
+ description: "Stub the package for JIT compilation",
654
+ name: "jit",
655
+ type: Boolean
656
+ },
657
+ {
658
+ description: "Compile-time environment variables (eg. --env.NODE_ENV=production)",
659
+ multiple: true,
660
+ name: "env",
661
+ type: (input) => {
662
+ const [key, value] = input.split("=");
663
+ return {
664
+ key,
665
+ value
666
+ };
667
+ }
668
+ },
669
+ {
670
+ defaultValue: false,
671
+ description: "Generate meta file (experimental)",
672
+ name: "metafile",
673
+ type: Boolean
674
+ },
675
+ {
676
+ description: "Path to the license file",
677
+ name: "license",
678
+ type: String
679
+ },
680
+ {
681
+ conflicts: "watch",
682
+ description: "Visualize and analyze the bundle",
683
+ name: "analyze",
684
+ type: Boolean
685
+ },
686
+ {
687
+ description: "CJS interop mode, can export default and named export, (experimental).",
688
+ name: "cjsInterop",
689
+ type: Boolean
690
+ },
691
+ {
692
+ conflicts: "development",
693
+ description: "Run code in production environment",
694
+ name: "production",
695
+ type: Boolean
696
+ },
697
+ {
698
+ conflicts: "production",
699
+ description: "Run code in development environment",
700
+ name: "development",
701
+ type: Boolean
702
+ },
703
+ {
704
+ description: "Do not clean the dist directory before building",
705
+ name: "no-clean",
706
+ type: Boolean
707
+ },
708
+ {
709
+ description: "Only generate .d.ts files",
710
+ name: "dts-only",
711
+ type: Boolean
712
+ },
713
+ {
714
+ description: "Disable the output validation",
715
+ name: "no-validation",
716
+ type: Boolean
717
+ },
718
+ {
719
+ description: "Disable the cache",
720
+ name: "no-cache",
721
+ type: Boolean
722
+ },
723
+ {
724
+ description: "Generate type documentation",
725
+ name: "typedoc",
726
+ type: Boolean
727
+ },
728
+ {
729
+ description: "Execute command after successful build, specially useful for watch mode",
730
+ name: "onSuccess",
731
+ type: String
732
+ },
733
+ {
734
+ description: 'Signal to kill child process, "SIGTERM" or "SIGKILL"',
735
+ name: "killSignal",
736
+ type: (input) => {
737
+ if (input === "SIGTERM" || input === "SIGKILL") {
738
+ return input;
739
+ }
740
+ throw new Error("Invalid kill signal. Use 'SIGTERM' or 'SIGKILL'.");
741
+ }
742
+ },
743
+ {
744
+ description: "Specify an external dependency, separate by comma (eg. --external lodash,react,react-dom)",
745
+ multiple: true,
746
+ name: "external",
747
+ typeLabel: "string[]"
748
+ },
749
+ {
750
+ description: "do not bundle external dependencies",
751
+ name: "no-external",
752
+ type: Boolean
753
+ },
754
+ {
755
+ // defaultValue: "browser",
756
+ description: "Specify the build runtime (nodejs, browser).",
757
+ name: "runtime",
758
+ type: (input) => {
759
+ if (input === "node" || input === "browser") {
760
+ return input;
761
+ }
762
+ throw new Error("Invalid runtime. Use 'node' or 'browser'.");
763
+ }
764
+ },
765
+ {
766
+ description: "Enable unbundle mode to preserve source file structure instead of bundling into a single file",
767
+ name: "unbundle",
768
+ type: Boolean
769
+ }
770
+ ]
771
+ });
772
+ };
773
+
774
+ const createInitCommand = (cli) => {
775
+ cli.addCommand({
776
+ description: "Initialize packem configuration",
777
+ // eslint-disable-next-line sonarjs/cognitive-complexity
778
+ execute: async ({ logger, options }) => {
779
+ intro("Welcome to packem setup");
780
+ if (isAccessibleSync(join(options.dir, "packem.config.ts"))) {
781
+ logger.info("Packem project already initialized, you can use `packem build` to build your project");
782
+ return;
783
+ }
784
+ const rootDirectory = resolve(cwd(), options.dir ?? ".");
785
+ const packageJsonPath = join(rootDirectory, "package.json");
786
+ if (!isAccessibleSync(packageJsonPath)) {
787
+ throw new Error("No package.json found in the directory");
788
+ }
789
+ const packageJson = await parsePackageJson(packageJsonPath, {
790
+ resolveCatalogs: true
791
+ });
792
+ const packages = [];
793
+ if (packageJson.dependencies) {
794
+ packages.push(...Object.keys(packageJson.dependencies));
795
+ }
796
+ if (packageJson.devDependencies) {
797
+ packages.push(...Object.keys(packageJson.devDependencies));
798
+ }
799
+ const hasTypescript = Boolean(packageJson.devDependencies?.typescript ?? packageJson.dependencies?.typescript);
800
+ const packagesToInstall = [];
801
+ if (options.typescript === void 0 && !hasTypescript) {
802
+ options.typescript = await confirm({
803
+ message: "Do you want to install TypeScript?"
804
+ });
805
+ if (options.typescript) {
806
+ packagesToInstall.push("typescript@latest");
807
+ }
808
+ } else {
809
+ log.message(`TypeScript version ${packageJson.devDependencies?.typescript ?? packageJson.dependencies?.typescript} is already installed`);
810
+ }
811
+ if (!isAccessibleSync(join(rootDirectory, "tsconfig.json"))) {
812
+ const shouldGenerate = await confirm({
813
+ message: "Do you want to use generate a tsconfig.json?"
814
+ });
815
+ const runInDom = await confirm({
816
+ message: "Do you want to run your code in the DOM?"
817
+ });
818
+ if (shouldGenerate) {
819
+ const s2 = spinner();
820
+ s2.start("Generating tsconfig.json");
821
+ writeJsonSync(join(rootDirectory, "tsconfig.json"), {
822
+ compilerOptions: {
823
+ esModuleInterop: true,
824
+ skipLibCheck: true,
825
+ target: "es2022",
826
+ allowJs: true,
827
+ resolveJsonModule: true,
828
+ moduleDetection: "force",
829
+ isolatedModules: true,
830
+ verbatimModuleSyntax: true,
831
+ strict: true,
832
+ noUncheckedIndexedAccess: true,
833
+ noImplicitOverride: true,
834
+ module: "NodeNext",
835
+ outDir: "dist",
836
+ sourceMap: true,
837
+ declaration: true,
838
+ lib: runInDom ? ["es2022", "dom", "dom.iterable"] : ["es2022"]
839
+ }
840
+ });
841
+ s2.stop("");
842
+ }
843
+ }
844
+ if (options.runtime === void 0) {
845
+ options.runtime = await select({
846
+ message: "Pick a build runtime",
847
+ options: [
848
+ { label: "Node", value: "node" },
849
+ { label: "Browser", value: "browser" }
850
+ ]
851
+ });
852
+ }
853
+ if (packages.includes("esbuild")) {
854
+ options.transformer = "esbuild";
855
+ } else if (packages.includes("@swc/core")) {
856
+ options.transformer = "swc";
857
+ } else if (packages.includes("sucrase")) {
858
+ options.transformer = "sucrase";
859
+ }
860
+ if (options.transformer === void 0) {
861
+ options.transformer = await select({
862
+ message: "Pick a transformer",
863
+ options: [
864
+ { label: "esbuild", value: "esbuild" },
865
+ { label: "swc", value: "swc" },
866
+ { label: "Sucrase", value: "sucrase" },
867
+ { label: "OXC", value: "oxc" }
868
+ ]
869
+ });
870
+ if (options.transformer && options.transformer !== "oxc" && !packages.includes(options.transformer)) {
871
+ const shouldInstall = await confirm({
872
+ message: `Do you want to install ${options.transformer}?`
873
+ });
874
+ if (shouldInstall) {
875
+ packagesToInstall.push(options.transformer === "swc" ? "@swc/core" : options.transformer);
876
+ }
877
+ }
878
+ } else {
879
+ log.message(`Transformer ${options.transformer} is already installed.`);
880
+ }
881
+ if (options.isolatedDeclarationTransformer === void 0) {
882
+ options.isolatedDeclarationTransformer = await confirm({
883
+ message: "Do you want to use an isolated declaration types?",
884
+ initialValue: false
885
+ });
886
+ }
887
+ if (options.isolatedDeclarationTransformer === void 0) {
888
+ options.isolatedDeclarationTransformer = await select({
889
+ message: "Pick a isolated declaration transformer",
890
+ options: [
891
+ { label: "Typescript", value: "typescript" },
892
+ { label: "swc", value: "swc" },
893
+ { label: "OXC", value: "oxc" },
894
+ { label: "None", value: void 0 }
895
+ ]
896
+ });
897
+ if (options.isolatedDeclarationTransformer !== void 0) {
898
+ let packageName;
899
+ switch (options.isolatedDeclarationTransformer) {
900
+ case "oxc": {
901
+ packageName = "oxc-transform";
902
+ break;
903
+ }
904
+ case "swc": {
905
+ packageName = "@swc/core";
906
+ break;
907
+ }
908
+ case "typescript": {
909
+ packageName = "typescript";
910
+ break;
911
+ }
912
+ default: {
913
+ cancel("Invalid isolated declaration transformer");
914
+ }
915
+ }
916
+ if (packageName !== void 0 && !packages.includes(packageName)) {
917
+ const shouldInstall = await confirm({
918
+ message: `Do you want to install ${packageName}?`
919
+ });
920
+ if (shouldInstall) {
921
+ packagesToInstall.push(packageName);
922
+ }
923
+ }
924
+ }
925
+ }
926
+ if (options.css === void 0) {
927
+ options.css = await confirm({
928
+ message: "Do you want to use css in your project?",
929
+ initialValue: false
930
+ });
931
+ }
932
+ const cssLoaders = [];
933
+ if (options.css) {
934
+ const mainCssLoader = await select({
935
+ message: "Pick a css loader",
936
+ options: [
937
+ { label: "PostCSS", value: "postcss" },
938
+ {
939
+ hint: "experimental",
940
+ label: "Lightning CSS",
941
+ value: "lightningcss"
942
+ }
943
+ ]
944
+ });
945
+ cssLoaders.push(mainCssLoader);
946
+ let extraCssLoaders = await multiselect({
947
+ message: "Pick your loaders",
948
+ options: [
949
+ { label: "Sass", value: "sass" },
950
+ { label: "Stylus", value: "stylus" },
951
+ { label: "Less", value: "less" }
952
+ ],
953
+ required: false
954
+ });
955
+ if (extraCssLoaders.includes("sass")) {
956
+ const sassLoader = await select({
957
+ message: "Pick a sass loader",
958
+ options: [
959
+ {
960
+ label: "Sass embedded",
961
+ value: "sass-embedded",
962
+ hint: "recommended"
963
+ },
964
+ { label: "Sass", value: "sass" },
965
+ {
966
+ label: "Node Sass",
967
+ value: "node-sass",
968
+ hint: "legacy"
969
+ }
970
+ ]
971
+ });
972
+ if (sassLoader !== "sass") {
973
+ extraCssLoaders = extraCssLoaders.filter((loader) => loader !== "sass");
974
+ extraCssLoaders.push(sassLoader);
975
+ }
976
+ }
977
+ cssLoaders.push(...extraCssLoaders);
978
+ const shouldInstall = await confirm({
979
+ message: `Do you want to install "${cssLoaders.join('", "')}"?`
980
+ });
981
+ if (shouldInstall) {
982
+ for (const loader of cssLoaders) {
983
+ packagesToInstall.push(...cssLoaderDependencies[loader]);
984
+ }
985
+ }
986
+ cssLoaders.push("sourceMap");
987
+ }
988
+ if (options.cssMinifier === void 0) {
989
+ options.cssMinifier = await confirm({
990
+ message: "Do you want to minify your css?",
991
+ initialValue: false
992
+ });
993
+ }
994
+ let cssMinifier;
995
+ if (options.cssMinifier) {
996
+ cssMinifier = await select({
997
+ message: "Pick a css minifier",
998
+ options: [
999
+ { label: "CSSNano", value: "cssnano" },
1000
+ { label: "Lightning CSS", value: "lightningcss" }
1001
+ ]
1002
+ });
1003
+ if (!cssLoaders.includes("lightningcss")) {
1004
+ const shouldInstall = await confirm({
1005
+ message: `Do you want to install "${cssMinifier}"?`
1006
+ });
1007
+ if (shouldInstall) {
1008
+ packagesToInstall.push(cssMinifier);
1009
+ }
1010
+ }
1011
+ }
1012
+ let template = "";
1013
+ let packemConfig = "";
1014
+ if (options.isolatedDeclarationTransformer) {
1015
+ packemConfig += ",\n isolatedDeclarationTransformer";
1016
+ }
1017
+ if (options.css || options.cssMinifier) {
1018
+ packemConfig += ",\n rollup: {\n css: {";
1019
+ }
1020
+ if (options.css) {
1021
+ const stringCssLoaders = cssLoaders.map((loader) => {
1022
+ if (loader === "sass-embedded" || loader === "node-sass") {
1023
+ loader = "sass";
1024
+ }
1025
+ return `${loader}Loader`;
1026
+ }).join(", ");
1027
+ packemConfig += `
1028
+ loaders: [${stringCssLoaders}],`;
1029
+ }
1030
+ if (options.cssMinifier && cssMinifier) {
1031
+ packemConfig += `
1032
+ minifier: ${cssMinifier}Minifier,`;
1033
+ }
1034
+ if (options.css || options.cssMinifier) {
1035
+ packemConfig += "\n }\n }";
1036
+ }
1037
+ if (hasTypescript || packageJson.type === "module") {
1038
+ let imports = "";
1039
+ if (options.isolatedDeclarationTransformer) {
1040
+ imports += `import isolatedDeclarationTransformer from "@visulima/packem/dts/isolated/transformer/${options.isolatedDeclarationTransformer}";
1041
+ `;
1042
+ }
1043
+ if (options.css) {
1044
+ for (let loader of cssLoaders) {
1045
+ if (loader === "sass-embedded" || loader === "node-sass") {
1046
+ loader = "sass";
1047
+ }
1048
+ imports += `import ${loader}Loader from "@visulima/packem/css/loader/${loader.toLowerCase()}";
1049
+ `;
1050
+ }
1051
+ }
1052
+ if (options.cssMinifier && cssMinifier) {
1053
+ imports += `import ${cssMinifier}Minifier from "@visulima/packem/css/minifier/${cssMinifier.toLowerCase()}";
1054
+ `;
1055
+ }
1056
+ template = `import { defineConfig } from "@visulima/packem/config";
1057
+ import transformer from "@visulima/packem/transformer/${options.transformer}";
1058
+ ${imports}
41
1059
  export default defineConfig({
42
- runtime: "${e.runtime}",
43
- transformer${d}
1060
+ runtime: "${options.runtime}",
1061
+ transformer${packemConfig}
44
1062
  });
45
- `}else{let f="";if(e.isolatedDeclarationTransformer&&(f+=`const isolatedDeclarationTransformer = require("@visulima/packem/dts/isolated/transformer/${e.isolatedDeclarationTransformer}");
46
- `),e.css)for(let p of a)(p==="sass-embedded"||p==="node-sass")&&(p="sass"),f+=`const ${p}Loader = require("@visulima/packem/css/loader/${p.toLowerCase()}");
47
- `;e.cssMinifier&&m&&(f+=`const ${m}Minifier = require("@visulima/packem/css/minifier/${m.toLowerCase()}");
48
- `),c=`const { defineConfig } = require("@visulima/packem/config");
49
- const transformer = require("@visulima/packem/transformer/${e.transformer}");
50
- ${f}
1063
+ `;
1064
+ } else {
1065
+ let imports = "";
1066
+ if (options.isolatedDeclarationTransformer) {
1067
+ imports += `const isolatedDeclarationTransformer = require("@visulima/packem/dts/isolated/transformer/${options.isolatedDeclarationTransformer}");
1068
+ `;
1069
+ }
1070
+ if (options.css) {
1071
+ for (let loader of cssLoaders) {
1072
+ if (loader === "sass-embedded" || loader === "node-sass") {
1073
+ loader = "sass";
1074
+ }
1075
+ imports += `const ${loader}Loader = require("@visulima/packem/css/loader/${loader.toLowerCase()}");
1076
+ `;
1077
+ }
1078
+ }
1079
+ if (options.cssMinifier && cssMinifier) {
1080
+ imports += `const ${cssMinifier}Minifier = require("@visulima/packem/css/minifier/${cssMinifier.toLowerCase()}");
1081
+ `;
1082
+ }
1083
+ template = `const { defineConfig } = require("@visulima/packem/config");
1084
+ const transformer = require("@visulima/packem/transformer/${options.transformer}");
1085
+ ${imports}
51
1086
  module.exports = defineConfig({
52
- runtime: ${e.runtime},
53
- transformer${d}
1087
+ runtime: ${options.runtime},
1088
+ transformer${packemConfig}
54
1089
  });
55
- `}const y=U(),b=r?"ts":"js";u.length>0&&(y.start("Installing packages"),await q(u,{cwd:i,dev:!0,silent:!0}),y.stop("Installed packages")),y.start(`Creating packem.config.${b}`),Se(C(i,`packem.config.${b}`),c),y.stop(`Created packem.config.${b}`),he("Now you can run `packem build` to build your project")},"execute"),name:"init",options:[{defaultValue:".",description:"The directory to initialize",name:"dir",type:String},{description:"Choose a transformer",name:"transformer",type:I(s=>{if(typeof s=="string"&&["esbuild","sucrase","swc"].includes(s))return s;throw new Error("Invalid transformer, please choose one of 'swc', 'sucrase' or 'esbuild'")},"type")},{description:"Choose a isolated declaration transformer",name:"isolated-declaration-transformer",type:I(s=>{if(typeof s=="string"&&["none","oxc","swc","typescript"].includes(s))return s;throw new Error("Invalid isolated declaration isolated declaration, please choose one of 'none', 'oxc', 'swc' or 'typescript'")},"type")},{description:"Use CSS",name:"css",type:Boolean},{description:"Use CSS minifier",name:"css-minifier",type:Boolean},{Description:"Use TypeScript",name:"typescript",type:Boolean},{description:"Specify the build runtime (nodejs, browser).",name:"runtime",type:I(s=>{if(s==="node"||s==="browser")return s;throw new Error("Invalid runtime. Use 'node' or 'browser'.")},"type")}]})},"createInitCommand");var vt=Object.defineProperty,M=v((t,s)=>vt(t,"name",{value:s,configurable:!0}),"a");const ht=M(async({cwd:t,dryRun:s,logger:e})=>{if(s)e.info("Dry run enabled. No changes will be made.");else{const o=Ve({input:P.stdin,output:P.stdout});e.warn(`
1090
+ `;
1091
+ }
1092
+ const s = spinner();
1093
+ const extension = hasTypescript ? "ts" : "js";
1094
+ if (packagesToInstall.length > 0) {
1095
+ s.start("Installing packages");
1096
+ await installPackage(packagesToInstall, {
1097
+ cwd: rootDirectory,
1098
+ dev: true,
1099
+ silent: true
1100
+ });
1101
+ s.stop("Installed packages");
1102
+ }
1103
+ s.start(`Creating packem.config.${extension}`);
1104
+ writeFileSync(join(rootDirectory, `packem.config.${extension}`), template);
1105
+ s.stop(`Created packem.config.${extension}`);
1106
+ outro("Now you can run `packem build` to build your project");
1107
+ },
1108
+ name: "init",
1109
+ options: [
1110
+ {
1111
+ defaultValue: ".",
1112
+ description: "The directory to initialize",
1113
+ name: "dir",
1114
+ type: String
1115
+ },
1116
+ {
1117
+ description: "Choose a transformer",
1118
+ name: "transformer",
1119
+ type: (value) => {
1120
+ if (typeof value === "string" && ["esbuild", "sucrase", "swc"].includes(value)) {
1121
+ return value;
1122
+ }
1123
+ throw new Error("Invalid transformer, please choose one of 'swc', 'sucrase' or 'esbuild'");
1124
+ }
1125
+ },
1126
+ {
1127
+ description: "Choose a isolated declaration transformer",
1128
+ name: "isolated-declaration-transformer",
1129
+ type: (value) => {
1130
+ if (typeof value === "string" && ["none", "oxc", "swc", "typescript"].includes(value)) {
1131
+ return value;
1132
+ }
1133
+ throw new Error("Invalid isolated declaration isolated declaration, please choose one of 'none', 'oxc', 'swc' or 'typescript'");
1134
+ }
1135
+ },
1136
+ {
1137
+ description: "Use CSS",
1138
+ name: "css",
1139
+ type: Boolean
1140
+ },
1141
+ {
1142
+ description: "Use CSS minifier",
1143
+ name: "css-minifier",
1144
+ type: Boolean
1145
+ },
1146
+ {
1147
+ Description: "Use TypeScript",
1148
+ name: "typescript",
1149
+ type: Boolean
1150
+ },
1151
+ {
1152
+ // defaultValue: "browser",
1153
+ description: "Specify the build runtime (nodejs, browser).",
1154
+ name: "runtime",
1155
+ type: (input) => {
1156
+ if (input === "node" || input === "browser") {
1157
+ return input;
1158
+ }
1159
+ throw new Error("Invalid runtime. Use 'node' or 'browser'.");
1160
+ }
1161
+ }
1162
+ ]
1163
+ });
1164
+ };
1165
+
1166
+ const migrate = async ({ cwd, dryRun, logger }) => {
1167
+ if (dryRun) {
1168
+ logger.info("Dry run enabled. No changes will be made.");
1169
+ } else {
1170
+ const rl = createInterface({
1171
+ input: process.stdin,
1172
+ output: process.stdout
1173
+ });
1174
+ logger.warn(
1175
+ `
56
1176
 
57
1177
  Before proceeding, review the migration guide at https://www.visulima.com/docs/package/packem, as this process will modify your files.
58
- Uncommitted changes will be lost. Use the --dry-run flag to preview changes without applying them.`);const n=await o.question("Continue? (Y/n) ");if(o.close(),!(n.toLowerCase()==="y"||n==="")){e.error("Migration cancelled."),P.exitCode=1;return}}t&&P.chdir(t);let i=!1;await $t(s,e)&&(i=!0),await xt(s,e)&&(i=!0),i?e.success("Migration completed. Remember to run install command with your package manager."):(e.error("No migration performed."),P.exitCode=1)},"migrate"),oe={bunchee:"@visulima/packem",tsup:"@visulima/packem","tsup-node":"@visulima/packem",unbuild:"@visulima/packem"},kt={dependencies:`^${Q.version}`,devDependencies:`^${Q.version}`,peerDependencies:"*"},$t=M(async(t,s)=>{if(!ae("package.json"))return s.error("No package.json found"),!1;const e=await Fe("package.json","utf8"),i=JSON.parse(e);let o=!1;for(const[r,u]of Object.entries(kt))for(const[a,m]of Object.entries(oe))i[r]?.[a]&&(s.info(`Migrating \`${r}\` from ${a} to ${m}.`),o=!0,i[r]=St(i[r],a,m,u));if(i.scripts)for(const r of Object.keys(i.scripts)){for(const[u,a]of Object.entries(oe))i.scripts[r].includes(u)&&(s.info(`Migrating \`${r}\` script from ${u} to packem`),o=!0,i.scripts[r]=i.scripts[r].replaceAll(new RegExp(`\\b${u}\\b`,"g"),"packem").replaceAll(new RegExp(`\\b${u}-node\\b`,"g"),"packem"));i.scripts[r].includes("tsup")&&(s.info(`Migrating \`${r}\` script from tsup to packem`),o=!0,i.scripts[r]=i.scripts[r].replaceAll(/\btsup(?:-node)?/g,"packem build").replaceAll(/\bbuild\b/g,"build")),i.scripts[r].includes("unbuild")&&(s.info(`Migrating \`${r}\` script from unbuild to packem`),o=!0,i.scripts[r]=i.scripts[r].replaceAll(/\bunbuild\b/g,"packem build")),i.scripts[r].includes("bunchee")&&(s.info(`Migrating \`${r}\` script from bunchee to packem`),o=!0,i.scripts[r]=i.scripts[r].replaceAll(/\bbunchee\b/g,"packem build"))}const n=["tsup","unbuild","bunchee"];for(const r of n)i[r]&&s.info(`Found \`${r}\` config field in package.json. Consider moving to packem.config.ts`);if(!o)return s.warn("No migratable bundler dependencies found in package.json"),!1;const l=`${JSON.stringify(i,null,e.includes(" ")?" ":2)}
59
- `;return t?(s.info("[dry-run] package.json changes:"),s.info("Old content:"),console.info(e),s.info("New content:"),console.info(l)):(await Re("package.json",l),s.success("Migrated `package.json`")),!0},"migratePackageJson"),jt=["tsup.config.ts","tsup.config.cts","tsup.config.mts","tsup.config.js","tsup.config.cjs","tsup.config.mjs","tsup.config.json","build.config.ts","build.config.cts","build.config.mts","build.config.js","build.config.cjs","build.config.mjs","bunchee.config.ts","bunchee.config.cts","bunchee.config.mts","bunchee.config.js","bunchee.config.cjs","bunchee.config.mjs"],xt=M(async(t,s)=>{let e=!1;for(const i of jt)ae(i)&&(s.info(`Found config file \`${i}\`. Consider creating packem.config.ts instead.`),s.warn("Manual migration required for config files. See https://www.visulima.com/docs/package/packem"),e=!0);return e||s.warn("No bundler config files found"),e},"migrateConfigFiles"),St=M((t,s,e,i)=>{const o={};for(const n of Object.keys(t))n===s?o[e]=i||t[s]:o[n]=t[n];return o},"renameKey"),Ct=M(t=>{t.addCommand({description:"Migrate from other bundlers (tsup, unbuild, bunchee, etc.) to packem",execute:M(async({logger:s,options:e})=>{await ht({cwd:e.cwd,dryRun:e.dryRun,logger:s})},"execute"),name:"migrate",options:[{defaultValue:".",description:"The directory to migrate",name:"cwd",type:String},{description:"Preview changes without applying them",name:"dry-run",type:Boolean}]})},"createMigrateCommand");try{require("node:module")?.enableCompileCache?.()||require("v8-compile-cache")}catch{}const T=fe("packem",{logger:await ge({reporters:[new ye({error:{hideErrorCauseCodeView:!0,hideErrorCodeView:!0,hideErrorErrorsCodeView:!0}})],scope:"packem"}),packageName:qe,packageVersion:ce});wt(T);yt(T);_e(T);Ct(T);T.run({shouldExitProcess:!1});
1178
+ Uncommitted changes will be lost. Use the --dry-run flag to preview changes without applying them.`
1179
+ );
1180
+ const input = await rl.question(`Continue? (Y/n) `);
1181
+ rl.close();
1182
+ const confirm = input.toLowerCase() === "y" || input === "";
1183
+ if (!confirm) {
1184
+ logger.error("Migration cancelled.");
1185
+ process.exitCode = 1;
1186
+ return;
1187
+ }
1188
+ }
1189
+ if (cwd)
1190
+ process.chdir(cwd);
1191
+ let migrated = false;
1192
+ if (await migratePackageJson(dryRun, logger)) {
1193
+ migrated = true;
1194
+ }
1195
+ if (await migrateConfigFiles(dryRun, logger)) {
1196
+ migrated = true;
1197
+ }
1198
+ if (migrated) {
1199
+ logger.success("Migration completed. Remember to run install command with your package manager.");
1200
+ } else {
1201
+ logger.error("No migration performed.");
1202
+ process.exitCode = 1;
1203
+ }
1204
+ };
1205
+ const DEP_MIGRATIONS = {
1206
+ // From bunchee
1207
+ bunchee: "@visulima/packem",
1208
+ // From tsup
1209
+ tsup: "@visulima/packem",
1210
+ "tsup-node": "@visulima/packem",
1211
+ // From unbuild
1212
+ unbuild: "@visulima/packem"
1213
+ // Add more bundlers as needed
1214
+ };
1215
+ const DEP_FIELDS = {
1216
+ dependencies: `^${pkg.version}`,
1217
+ devDependencies: `^${pkg.version}`,
1218
+ peerDependencies: "*"
1219
+ };
1220
+ const migratePackageJson = async (dryRun, logger) => {
1221
+ if (!existsSync("package.json")) {
1222
+ logger.error("No package.json found");
1223
+ return false;
1224
+ }
1225
+ const pkgRaw = await readFile$1("package.json", "utf8");
1226
+ const pkg2 = JSON.parse(pkgRaw);
1227
+ let found = false;
1228
+ for (const [field, semver] of Object.entries(DEP_FIELDS)) {
1229
+ for (const [oldDep, newDep] of Object.entries(DEP_MIGRATIONS)) {
1230
+ if (pkg2[field]?.[oldDep]) {
1231
+ logger.info(`Migrating \`${field}\` from ${oldDep} to ${newDep}.`);
1232
+ found = true;
1233
+ pkg2[field] = renameKey(pkg2[field], oldDep, newDep, semver);
1234
+ }
1235
+ }
1236
+ }
1237
+ if (pkg2.scripts) {
1238
+ for (const key of Object.keys(pkg2.scripts)) {
1239
+ for (const [oldCmd, newCmd] of Object.entries(DEP_MIGRATIONS)) {
1240
+ if (pkg2.scripts[key].includes(oldCmd)) {
1241
+ logger.info(`Migrating \`${key}\` script from ${oldCmd} to packem`);
1242
+ found = true;
1243
+ pkg2.scripts[key] = pkg2.scripts[key].replaceAll(new RegExp(String.raw`\b${oldCmd}\b`, "g"), "packem").replaceAll(new RegExp(String.raw`\b${oldCmd}-node\b`, "g"), "packem");
1244
+ }
1245
+ }
1246
+ if (pkg2.scripts[key].includes("tsup")) {
1247
+ logger.info(`Migrating \`${key}\` script from tsup to packem`);
1248
+ found = true;
1249
+ pkg2.scripts[key] = pkg2.scripts[key].replaceAll(/\btsup(?:-node)?/g, "packem build").replaceAll(/\bbuild\b/g, "build");
1250
+ }
1251
+ if (pkg2.scripts[key].includes("unbuild")) {
1252
+ logger.info(`Migrating \`${key}\` script from unbuild to packem`);
1253
+ found = true;
1254
+ pkg2.scripts[key] = pkg2.scripts[key].replaceAll(/\bunbuild\b/g, "packem build");
1255
+ }
1256
+ if (pkg2.scripts[key].includes("bunchee")) {
1257
+ logger.info(`Migrating \`${key}\` script from bunchee to packem`);
1258
+ found = true;
1259
+ pkg2.scripts[key] = pkg2.scripts[key].replaceAll(/\bbunchee\b/g, "packem build");
1260
+ }
1261
+ }
1262
+ }
1263
+ const configFields = ["tsup", "unbuild", "bunchee"];
1264
+ for (const field of configFields) {
1265
+ if (pkg2[field]) {
1266
+ logger.info(`Found \`${field}\` config field in package.json. Consider moving to packem.config.ts`);
1267
+ }
1268
+ }
1269
+ if (!found) {
1270
+ logger.warn("No migratable bundler dependencies found in package.json");
1271
+ return false;
1272
+ }
1273
+ const pkgString = `${JSON.stringify(pkg2, null, pkgRaw.includes(" ") ? " " : 2)}
1274
+ `;
1275
+ if (dryRun) {
1276
+ logger.info("[dry-run] package.json changes:");
1277
+ logger.info("Old content:");
1278
+ console.info(pkgRaw);
1279
+ logger.info("New content:");
1280
+ console.info(pkgString);
1281
+ } else {
1282
+ await writeFile$1("package.json", pkgString);
1283
+ logger.success("Migrated `package.json`");
1284
+ }
1285
+ return true;
1286
+ };
1287
+ const CONFIG_FILES = [
1288
+ // tsup configs
1289
+ "tsup.config.ts",
1290
+ "tsup.config.cts",
1291
+ "tsup.config.mts",
1292
+ "tsup.config.js",
1293
+ "tsup.config.cjs",
1294
+ "tsup.config.mjs",
1295
+ "tsup.config.json",
1296
+ // unbuild configs
1297
+ "build.config.ts",
1298
+ "build.config.cts",
1299
+ "build.config.mts",
1300
+ "build.config.js",
1301
+ "build.config.cjs",
1302
+ "build.config.mjs",
1303
+ // bunchee configs
1304
+ "bunchee.config.ts",
1305
+ "bunchee.config.cts",
1306
+ "bunchee.config.mts",
1307
+ "bunchee.config.js",
1308
+ "bunchee.config.cjs",
1309
+ "bunchee.config.mjs"
1310
+ ];
1311
+ const migrateConfigFiles = async (dryRun, logger) => {
1312
+ let found = false;
1313
+ for (const file of CONFIG_FILES) {
1314
+ if (!existsSync(file))
1315
+ continue;
1316
+ logger.info(`Found config file \`${file}\`. Consider creating packem.config.ts instead.`);
1317
+ logger.warn(`Manual migration required for config files. See https://www.visulima.com/docs/package/packem`);
1318
+ found = true;
1319
+ }
1320
+ if (!found) {
1321
+ logger.warn("No bundler config files found");
1322
+ }
1323
+ return found;
1324
+ };
1325
+ const renameKey = (object, oldKey, newKey, newValue) => {
1326
+ const newObject = {};
1327
+ for (const key of Object.keys(object)) {
1328
+ if (key === oldKey) {
1329
+ newObject[newKey] = newValue || object[oldKey];
1330
+ } else {
1331
+ newObject[key] = object[key];
1332
+ }
1333
+ }
1334
+ return newObject;
1335
+ };
1336
+ const createMigrateCommand = (cli) => {
1337
+ cli.addCommand({
1338
+ description: "Migrate from other bundlers (tsup, unbuild, bunchee, etc.) to packem",
1339
+ execute: async ({ logger, options }) => {
1340
+ await migrate({
1341
+ cwd: options.cwd,
1342
+ dryRun: options.dryRun,
1343
+ logger
1344
+ });
1345
+ },
1346
+ name: "migrate",
1347
+ options: [
1348
+ {
1349
+ defaultValue: ".",
1350
+ description: "The directory to migrate",
1351
+ name: "cwd",
1352
+ type: String
1353
+ },
1354
+ {
1355
+ description: "Preview changes without applying them",
1356
+ name: "dry-run",
1357
+ type: Boolean
1358
+ }
1359
+ ]
1360
+ });
1361
+ };
1362
+
1363
+ try {
1364
+ if (!require("node:module")?.enableCompileCache?.()) {
1365
+ require("v8-compile-cache");
1366
+ }
1367
+ } catch {
1368
+ }
1369
+ const index = createCerebro("packem", {
1370
+ logger: await createPailLogger({
1371
+ reporters: [
1372
+ new SimpleReporter({
1373
+ error: {
1374
+ hideErrorCauseCodeView: true,
1375
+ hideErrorCodeView: true,
1376
+ hideErrorErrorsCodeView: true
1377
+ }
1378
+ })
1379
+ ],
1380
+ scope: "packem"
1381
+ }),
1382
+ packageName: name,
1383
+ packageVersion: version
1384
+ });
1385
+ createInitCommand(index);
1386
+ createBuildCommand(index);
1387
+ createAddCommand(index);
1388
+ createMigrateCommand(index);
1389
+ void index.run({
1390
+ shouldExitProcess: false
1391
+ });