@visulima/packem 2.0.0-alpha.9 → 2.0.0-alpha.91
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.
- package/CHANGELOG.md +1288 -3
- package/LICENSE.md +3812 -2243
- package/README.md +92 -34
- package/dist/babel-runtime/packem_shared/transform-code-KNtowoK1.js +1 -0
- package/dist/babel-runtime/plugins/babel/worker.js +1 -0
- package/dist/builder/typedoc/index.d.ts +11 -23
- package/dist/builder/typedoc/index.js +3 -3
- package/dist/cli/index.js +69 -41
- package/dist/config/index.d.ts +55 -24
- package/dist/config/index.js +1 -1
- package/dist/config/preset/preact.d.ts +31 -0
- package/dist/config/preset/preact.js +2 -0
- package/dist/config/preset/react.d.ts +72 -0
- package/dist/config/preset/react.js +1 -0
- package/dist/config/preset/solid.d.ts +114 -0
- package/dist/config/preset/solid.js +1 -0
- package/dist/config/preset/svelte.d.ts +84 -0
- package/dist/config/preset/svelte.js +1 -0
- package/dist/config/preset/vue.d.ts +66 -0
- package/dist/config/preset/vue.js +1 -0
- package/dist/css/loaders/less.d.ts +1 -0
- package/dist/css/loaders/less.js +1 -0
- package/dist/css/loaders/lightningcss.d.ts +1 -0
- package/dist/css/loaders/lightningcss.js +1 -0
- package/dist/css/loaders/postcss.d.ts +1 -0
- package/dist/css/loaders/postcss.js +1 -0
- package/dist/css/loaders/sass.d.ts +1 -0
- package/dist/css/loaders/sass.js +1 -0
- package/dist/css/loaders/sourcemap.d.ts +1 -0
- package/dist/css/loaders/sourcemap.js +1 -0
- package/dist/css/loaders/stylus.d.ts +1 -0
- package/dist/css/loaders/stylus.js +1 -0
- package/dist/{rollup/plugins/css/minifiers/lightningcss.js → css/loaders/tailwindcss.d.ts} +1 -1
- package/dist/css/loaders/tailwindcss.js +1 -0
- package/dist/css/minifiers/cssnano.d.ts +1 -0
- package/dist/css/minifiers/cssnano.js +1 -0
- package/dist/css/minifiers/lightningcss.d.ts +1 -0
- package/dist/css/minifiers/lightningcss.js +1 -0
- package/dist/index.d.ts +55 -30
- package/dist/index.js +45 -1
- package/dist/packem_shared/create-or-update-key-storage-DHOKZmnD.js +28 -0
- package/dist/packem_shared/default-mHB0zin0.js +1 -0
- package/dist/packem_shared/index-UxllEEEe.js +249 -0
- package/dist/packem_shared/oxcTransformPlugin-Dwvbw2jE-BsmmBg7q.js +177 -0
- package/dist/packem_shared/types.d-BkLP91NJ.d.ts +464 -0
- package/dist/packem_shared/utils-Bsoe7qJG.js +1 -0
- package/dist/rollup/plugins/esbuild/index.d.ts +1 -24
- package/dist/rollup/plugins/esbuild/index.js +1 -1
- package/dist/rollup/plugins/oxc/oxc-transformer.d.ts +1 -20
- package/dist/rollup/plugins/oxc/oxc-transformer.js +1 -1
- package/dist/rollup/plugins/sucrase/index.d.ts +1 -19
- package/dist/rollup/plugins/sucrase/index.js +1 -1
- package/dist/rollup/plugins/swc/swc-plugin.d.ts +1 -26
- package/dist/rollup/plugins/swc/swc-plugin.js +1 -1
- package/files.d.ts +37 -0
- package/package.json +113 -78
- package/dist/packem_shared/browserslistToEsbuild-C0IWmbNe-C6xPL1oW.js +0 -1
- package/dist/packem_shared/create-or-update-key-storage-GwAIWW7R.js +0 -3
- package/dist/packem_shared/default-B6X7-Lx3.js +0 -1
- package/dist/packem_shared/default-BYM_JvQL.js +0 -1
- package/dist/packem_shared/default-B_dUKZ_J.js +0 -1
- package/dist/packem_shared/default-DjNIGH2Y.js +0 -1
- package/dist/packem_shared/default-DqRcOUe1.js +0 -1
- package/dist/packem_shared/esbuildPlugin-BAwyhG6L-yty60jMl.js +0 -3
- package/dist/packem_shared/index-CSyJAz0_.js +0 -139
- package/dist/packem_shared/index-CUp9WuCG.js +0 -1
- package/dist/packem_shared/index-DvyuEcZZ.d.ts +0 -5235
- package/dist/packem_shared/isolatedDeclarationsOxcTransformer-WbfE6cGu-NeZOx2Y7.js +0 -1
- package/dist/packem_shared/isolatedDeclarationsSwcTransformer-Ch2AgtWC-B-0lOgFf.js +0 -1
- package/dist/packem_shared/isolatedDeclarationsTypescriptTransformer-DkuEkofo-Cwe3ODMG.js +0 -3
- package/dist/packem_shared/oxcResolvePlugin-BJpi-eSG-BsYx9cDO.js +0 -1
- package/dist/packem_shared/oxcTransformPlugin-DfVQouIB-Cpfv95eA.js +0 -4
- package/dist/packem_shared/resolveTypescriptMjsCtsPlugin-DcZrZTmM-BEkYWTsH.js +0 -6
- package/dist/packem_shared/swcPlugin-Boip4lWG-CwJ-HVJc.js +0 -1
- package/dist/packem_shared/types-0XfKu6f9.d.ts +0 -163
- package/dist/rollup/plugins/css/loaders/less.d.ts +0 -1
- package/dist/rollup/plugins/css/loaders/less.js +0 -1
- package/dist/rollup/plugins/css/loaders/lightningcss.d.ts +0 -1
- package/dist/rollup/plugins/css/loaders/lightningcss.js +0 -1
- package/dist/rollup/plugins/css/loaders/postcss.d.ts +0 -1
- package/dist/rollup/plugins/css/loaders/postcss.js +0 -1
- package/dist/rollup/plugins/css/loaders/sass.d.ts +0 -1
- package/dist/rollup/plugins/css/loaders/sass.js +0 -1
- package/dist/rollup/plugins/css/loaders/sourcemap.d.ts +0 -9
- package/dist/rollup/plugins/css/loaders/sourcemap.js +0 -1
- package/dist/rollup/plugins/css/loaders/stylus.d.ts +0 -1
- package/dist/rollup/plugins/css/loaders/stylus.js +0 -1
- package/dist/rollup/plugins/css/loaders/tailwindcss.d.ts +0 -1
- package/dist/rollup/plugins/css/loaders/tailwindcss.js +0 -1
- package/dist/rollup/plugins/css/minifiers/cssnano.d.ts +0 -1
- package/dist/rollup/plugins/css/minifiers/cssnano.js +0 -1
- package/dist/rollup/plugins/css/minifiers/lightningcss.d.ts +0 -1
- package/dist/rollup/plugins/oxc/isolated-declarations-oxc-transformer.d.ts +0 -25
- package/dist/rollup/plugins/oxc/isolated-declarations-oxc-transformer.js +0 -1
- package/dist/rollup/plugins/swc/isolated-declarations-swc-transformer.d.ts +0 -20
- package/dist/rollup/plugins/swc/isolated-declarations-swc-transformer.js +0 -1
- package/dist/rollup/plugins/typescript/isolated-declarations-typescript-transformer.d.ts +0 -24
- package/dist/rollup/plugins/typescript/isolated-declarations-typescript-transformer.js +0 -1
package/README.md
CHANGED
|
@@ -35,6 +35,8 @@ It enables you to generate multiple bundles (CommonJS or ESModule) simultaneousl
|
|
|
35
35
|
|
|
36
36
|
It uses the `exports` configuration in `package.json` and recognizes entry file conventions to match your exports and build them into bundles.
|
|
37
37
|
|
|
38
|
+
Rollup is the default and full-featured backend. An experimental [Rolldown](https://rolldown.rs) backend is also selectable via the `bundler` option (or `--bundler` CLI flag) — see [Rolldown backend (experimental)](#rolldown-backend-experimental).
|
|
39
|
+
|
|
38
40
|
## Features
|
|
39
41
|
|
|
40
42
|
- ✅ package.json#exports, package.json#main, package.json#module to define entry-points
|
|
@@ -53,9 +55,10 @@ It uses the `exports` configuration in `package.json` and recognizes entry file
|
|
|
53
55
|
- ✅ Supports react server and client components
|
|
54
56
|
- ✅ Supports shared modules
|
|
55
57
|
- ✅ Supports dynamic import
|
|
56
|
-
- ✅ Supports `tsconfig.json` paths and `package.json` imports resolution
|
|
58
|
+
- ✅ Supports `tsconfig.json` paths and `package.json`, `package.yml`, `package.yaml` and `package.json5` imports resolution
|
|
57
59
|
- ✅ ESM ⇄ CJS interoperability
|
|
58
60
|
- ✅ Supports isolated declaration types (experimental) (Typescript version 5.5 or higher)
|
|
61
|
+
- ✅ Selectable bundler backend: Rollup (default) or [Rolldown](https://rolldown.rs) (experimental)
|
|
59
62
|
- ✅ Supports wasm [WebAssembly modules](http://webassembly.org)
|
|
60
63
|
- ✅ Supports css, [sass](https://github.com/sass/sass), [less](https://github.com/less/less.js), [stylus](https://github.com/stylus/stylus) and Up-to-date [CSS Modules](https://github.com/css-modules/css-modules) (experimental)
|
|
61
64
|
- ✅ [TypeDoc](https://github.com/TypeStrong/TypeDoc) documentation generation
|
|
@@ -163,13 +166,9 @@ Enable the automatic `node 10` typesVersions generation in packem.config.js:
|
|
|
163
166
|
```js
|
|
164
167
|
export default defineConfig({
|
|
165
168
|
// ...
|
|
166
|
-
|
|
167
|
-
//
|
|
168
|
-
|
|
169
|
-
typeScriptVersion: ">=5.0", // Chose the version of TypeScript you want to support
|
|
170
|
-
writeToPackageJson: true,
|
|
171
|
-
},
|
|
172
|
-
// ...
|
|
169
|
+
node10Compatibility: {
|
|
170
|
+
typeScriptVersion: ">=5.0", // Chose the version of TypeScript you want to support
|
|
171
|
+
writeToPackageJson: true,
|
|
173
172
|
},
|
|
174
173
|
transformer,
|
|
175
174
|
});
|
|
@@ -454,13 +453,13 @@ Native Node.js import mapping supports conditional imports (eg. resolving differ
|
|
|
454
453
|
{
|
|
455
454
|
// ...
|
|
456
455
|
|
|
457
|
-
|
|
456
|
+
imports: {
|
|
458
457
|
// Mapping '~utils' to './src/utils.js'
|
|
459
458
|
"~utils": "./src/utils.js",
|
|
460
459
|
|
|
461
460
|
// Native Node.js import mapping (can't reference ./src)
|
|
462
|
-
"#internal-package": "./vendors/package/index.js"
|
|
463
|
-
}
|
|
461
|
+
"#internal-package": "./vendors/package/index.js",
|
|
462
|
+
},
|
|
464
463
|
}
|
|
465
464
|
```
|
|
466
465
|
|
|
@@ -499,6 +498,48 @@ This will replace all instances of `process.env.NODE_ENV` with `'production'` an
|
|
|
499
498
|
packem build --env.NODE_ENV=production
|
|
500
499
|
```
|
|
501
500
|
|
|
501
|
+
#### Loading from .env files
|
|
502
|
+
|
|
503
|
+
You can also load environment variables from `.env` files using the `--env-file` option:
|
|
504
|
+
|
|
505
|
+
```sh
|
|
506
|
+
# Load from .env file with default prefix (PACKEM_)
|
|
507
|
+
packem build --env-file .env
|
|
508
|
+
|
|
509
|
+
# Load from custom .env file with custom prefix
|
|
510
|
+
packem build --env-file .env.production --env-prefix BUILD_
|
|
511
|
+
|
|
512
|
+
# Combine .env file with CLI variables (CLI vars override .env vars)
|
|
513
|
+
packem build --env-file .env --env.API_URL=https://api.example.com
|
|
514
|
+
```
|
|
515
|
+
|
|
516
|
+
**Configuration file:**
|
|
517
|
+
|
|
518
|
+
You can also configure this in your `packem.config.ts`:
|
|
519
|
+
|
|
520
|
+
```typescript
|
|
521
|
+
export default defineConfig({
|
|
522
|
+
envFile: ".env",
|
|
523
|
+
envPrefix: "PACKEM_", // default: "PACKEM_"
|
|
524
|
+
// ...
|
|
525
|
+
});
|
|
526
|
+
```
|
|
527
|
+
|
|
528
|
+
**How it works:**
|
|
529
|
+
|
|
530
|
+
- Variables from `.env` files are loaded first
|
|
531
|
+
- CLI `--env.*` variables override `.env` file variables
|
|
532
|
+
- Only variables matching the prefix (default: `PACKEM_`) are loaded for security
|
|
533
|
+
- Variables are replaced at compile-time in your code
|
|
534
|
+
|
|
535
|
+
**Example .env file:**
|
|
536
|
+
|
|
537
|
+
```env
|
|
538
|
+
PACKEM_API_URL=https://api.example.com
|
|
539
|
+
PACKEM_VERSION=1.0.0
|
|
540
|
+
PACKEM_DEBUG=true
|
|
541
|
+
```
|
|
542
|
+
|
|
502
543
|
## Programmatic Usage
|
|
503
544
|
|
|
504
545
|
You can use Packem programmatically in your Node.js applications without the CLI:
|
|
@@ -557,8 +598,8 @@ import { defineConfig } from "@visulima/packem/config";
|
|
|
557
598
|
|
|
558
599
|
export default defineConfig({
|
|
559
600
|
// ...
|
|
560
|
-
|
|
561
|
-
|
|
601
|
+
validation: {
|
|
602
|
+
bundleLimit: {
|
|
562
603
|
limit: 1024 * 1024, // 1MB
|
|
563
604
|
// or / and limits per file
|
|
564
605
|
limits: {
|
|
@@ -575,6 +616,34 @@ export default defineConfig({
|
|
|
575
616
|
|
|
576
617
|
## Experimental Features
|
|
577
618
|
|
|
619
|
+
### Rolldown backend (experimental)
|
|
620
|
+
|
|
621
|
+
By default `packem` bundles with [Rollup](https://rollupjs.org). You can opt into the experimental [Rolldown](https://rolldown.rs) backend — a Rust-based, oxc-powered bundler — with the `bundler` option:
|
|
622
|
+
|
|
623
|
+
```ts
|
|
624
|
+
import { defineConfig } from "@visulima/packem/config";
|
|
625
|
+
|
|
626
|
+
export default defineConfig({
|
|
627
|
+
// ...
|
|
628
|
+
bundler: "rolldown", // "rollup" (default) | "rolldown"
|
|
629
|
+
// ...
|
|
630
|
+
});
|
|
631
|
+
```
|
|
632
|
+
|
|
633
|
+
Or from the CLI, without touching the config file:
|
|
634
|
+
|
|
635
|
+
```sh
|
|
636
|
+
packem build --bundler rolldown
|
|
637
|
+
```
|
|
638
|
+
|
|
639
|
+
Notes and current limitations:
|
|
640
|
+
|
|
641
|
+
- **Experimental.** Rolldown is opt-in and not yet at full feature parity with the Rollup backend. Rollup remains the default and the fully-supported path; the Rolldown backend is not deprecating it.
|
|
642
|
+
- **No `transformer` option.** When `bundler` is `"rolldown"`, omit the `transformer` option — Rolldown ships its own oxc-based transform and always uses it. The `esbuild`/`swc`/`sucrase`/`oxc` transformer adapters only apply under the default `"rollup"` bundler.
|
|
643
|
+
- **Declaration files route through Rollup.** Even with `bundler: "rolldown"`, `.d.ts` generation (and DTS watching) still runs through Rollup. Rollup is pulled in automatically when Rolldown is combined with `declaration: true`.
|
|
644
|
+
|
|
645
|
+
For the detailed support matrix and the criteria for graduating Rolldown out of experimental status, see [`docs/rolldown-status.md`](https://github.com/visulima/packem/blob/main/docs/rolldown-status.md).
|
|
646
|
+
|
|
578
647
|
### OXC Resolver
|
|
579
648
|
|
|
580
649
|
`packem` supports the [oxc-resolver](https://github.com/oxc-project/oxc-resolver) resolver to resolve modules in your project.
|
|
@@ -636,26 +705,7 @@ export default defineConfig({
|
|
|
636
705
|
|
|
637
706
|
### Isolated declaration types (in TypeScript 5.5)
|
|
638
707
|
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
You need to choose of the supported transformer to use isolated declaration types.
|
|
642
|
-
|
|
643
|
-
- [oxc](https://github.com/oxc-project/oxc)
|
|
644
|
-
- [@swc/core](https://github.com/swc-project/swc)
|
|
645
|
-
- [typescript](https://github.com/microsoft/TypeScript)
|
|
646
|
-
|
|
647
|
-
Default is `typescript`.
|
|
648
|
-
|
|
649
|
-
```ts
|
|
650
|
-
import { defineConfig } from "@visulima/packem/config";
|
|
651
|
-
import isolatedDeclarationTransformer from "@visulima/packem/dts/isolated/transformer/typescript";
|
|
652
|
-
import transformer from "@visulima/packem/transformer/esbuild";
|
|
653
|
-
|
|
654
|
-
export default defineConfig({
|
|
655
|
-
isolatedDeclarationTransformer,
|
|
656
|
-
transformer,
|
|
657
|
-
});
|
|
658
|
-
```
|
|
708
|
+
Declaration generation runs on top of [`@visulima/rollup-plugin-dts`](../rollup-plugin-dts). Enable TypeScript's isolated declarations feature in your `tsconfig.json` (`"isolatedDeclarations": true`) and packem will use oxc's `isolatedDeclarationSync` to emit `.d.ts` files without running full type inference — no extra config required.
|
|
659
709
|
|
|
660
710
|
<!-- Modified copy of https://github.com/Anidetrix/rollup-plugin-styles/blob/main/README.md -->
|
|
661
711
|
|
|
@@ -895,7 +945,15 @@ Will look for `_custom` first (_with the appropriate extension(s)_), and then fo
|
|
|
895
945
|
styles({
|
|
896
946
|
mode: "inject", // Unnecessary, set by default
|
|
897
947
|
// ...or with custom options for injector
|
|
898
|
-
mode: [
|
|
948
|
+
mode: [
|
|
949
|
+
"inject",
|
|
950
|
+
{
|
|
951
|
+
attributes: { id: "global" },
|
|
952
|
+
container: "body",
|
|
953
|
+
prepend: true,
|
|
954
|
+
singleTag: true,
|
|
955
|
+
},
|
|
956
|
+
],
|
|
899
957
|
// ...or with custom injector
|
|
900
958
|
mode: ["inject", (varname, id) => `console.log(${varname},${JSON.stringify(id)})`],
|
|
901
959
|
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var m=Object.defineProperty;var u=(r,e)=>m(r,"name",{value:e,configurable:!0});import{transformAsync as g}from"@babel/core";var d=Object.defineProperty,l=u((r,e)=>d(r,"name",{value:e,configurable:!0}),"o");const f=/\.tsx?$/,y=/['"]use memo['"]/,_="babel-options",w="__packem_babel_missing_options__",b=l(r=>r.find(e=>e==="babel-plugin-react-compiler"||Array.isArray(e)&&e[0]==="babel-plugin-react-compiler"),"getReactCompilerPlugin"),A=l((r,e)=>{if(r.length===0)return;const s=b(r);if(!(!s||!Array.isArray(s))&&s[1]?.compilationMode==="annotation"&&!y.test(e)){const o=r.indexOf(s);o!==-1&&r.splice(o,1)}},"filterReactCompilerByAnnotation"),v=l(async(r,e,{filename:s,generatorOpts:o,sourceFileName:h,...t})=>{let i=[];t.plugins&&Array.isArray(t.plugins)&&(i=[...t.plugins]),i.length>0&&A(i,r);const a=[];(e.endsWith(".jsx")||e.endsWith(".tsx"))&&a.push("jsx"),f.test(e)&&a.push("typescript");const n=t.parserOpts?.plugins;n&&Array.isArray(n)&&a.unshift(...n);const c=[...new Set(a)],p=await g(r,{...t,filename:e,generatorOpts:{...o,decoratorsBeforeExport:!0,importAttributesKeyword:"with"},parserOpts:{...t.parserOpts,allowAwaitOutsideFunction:!0,plugins:c.length>0?c:[],sourceType:"module"},plugins:i.length>0?i:[],sourceFileName:e});if(p?.code)return{code:p.code,map:p.map??void 0}},"transformCode");export{w as N,_ as O,v as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var s=Object.defineProperty;var n=(r,o)=>s(r,"name",{value:o,configurable:!0});import i from"workerpool";import{N as m,t as c}from"../../packem_shared/transform-code-KNtowoK1.js";var p=Object.defineProperty,v=n((r,o)=>p(r,"name",{value:o,configurable:!0}),"t");const f=new Map,d=v(async(r,o,t,e)=>{e!==void 0&&f.set(t,e);const a=f.get(t);if(a===void 0)throw new Error(m);return c(r,o,a)},"transform");i.worker({transform:d});
|
|
@@ -1,27 +1,15 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { I as InternalBuildOptions } from
|
|
3
|
-
import '@
|
|
4
|
-
import '@
|
|
5
|
-
import '@
|
|
6
|
-
import '@
|
|
7
|
-
import '@
|
|
8
|
-
import '@
|
|
9
|
-
import '@
|
|
10
|
-
import 'rollup';
|
|
11
|
-
import 'rollup-plugin-dts';
|
|
12
|
-
import 'rollup-plugin-polyfill-node';
|
|
13
|
-
import 'rollup-plugin-pure';
|
|
14
|
-
import 'rollup-plugin-visualizer';
|
|
15
|
-
import 'esbuild';
|
|
16
|
-
import '@visulima/package';
|
|
17
|
-
import '@visulima/colorize';
|
|
18
|
-
import 'oxc-resolver';
|
|
19
|
-
import 'oxc-transform';
|
|
20
|
-
import 'sucrase';
|
|
21
|
-
import '@visulima/rollup-css-plugin';
|
|
1
|
+
import { BuildContext } from '@visulima/packem-share/types';
|
|
2
|
+
import { I as InternalBuildOptions } from "../../packem_shared/types.d-BkLP91NJ.js";
|
|
3
|
+
import '@arethetypeswrong/core';
|
|
4
|
+
import '@visulima/packem-plugins';
|
|
5
|
+
import '@visulima/packem-plugins/oxc';
|
|
6
|
+
import '@visulima/packem-plugins/plugin/externals';
|
|
7
|
+
import '@visulima/packem-plugins/plugin/native-modules';
|
|
8
|
+
import '@visulima/packem-rollup';
|
|
9
|
+
import '@visulima/packem-share/utils';
|
|
10
|
+
import '@visulima/rollup-plugin-css';
|
|
22
11
|
import 'jiti';
|
|
12
|
+
import 'rollup';
|
|
23
13
|
import 'typedoc';
|
|
24
|
-
|
|
25
14
|
declare const builder: (context: BuildContext<InternalBuildOptions>, cachePath: string | undefined, _: never, logged: boolean) => Promise<void>;
|
|
26
|
-
|
|
27
15
|
export { builder as default };
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
|
|
2
|
-
${
|
|
3
|
-
`),
|
|
1
|
+
import{P as h,T as w,f as k,q as $}from"../../packem_shared/create-or-update-key-storage-DHOKZmnD.js";import{w as m}from"../../packem_shared/utils-Bsoe7qJG.js";import{readdirSync as E}from"node:fs";import{replaceContentWithinMarker as j}from"@visulima/packem-share";import{Application as A}from"typedoc";const P=(e,o,t,r,n)=>{const s=E(e,{withFileTypes:!0}).filter(a=>a.isFile());let i="";for(const a of s)a.name==="README.md"&&o>1||(i+=h(m(e,a.name)).replaceAll(`<!-- ${t}`,`<!-- _REPLACE_${t}`).replaceAll("<!-- ${marker}",`<!-- _REPLACE_\\${t}`));if(i==="")return;const c=h(r),p=j(c,t,`
|
|
2
|
+
${i}`);if(!p){n.error({message:`Could not find the typedoc marker: <!-- ${t} --><!-- /${t} --> in ${r}`,prefix:"typedoc"});return}c!==p&&w(r,p.replaceAll(`<!-- _REPLACE_${t}`,`<!-- ${t}`).replaceAll(`<!-- _REPLACE_\\${t}`,"<!-- ${marker}"),{overwrite:!0})},v=(e,o,t,r)=>{if(e==="inline"&&t===void 0)throw new Error("The `readmePath` option is required when using the `inline` format.");if(e!=="inline"&&typeof t=="string"&&r.warn({message:"The `readmePath` option is only used when the `inline` format is used.",prefix:"typedoc"}),e==="json"&&!o?.endsWith(".json"))throw new Error(o===void 0?"The `jsonFileName` option is required when using the `json` format.":"The `jsonFileName` option must end with `.json`.");e!=="json"&&typeof o=="string"&&r.warn({message:"The `jsonFileName` option is only used when the `json` format is used.",prefix:"typedoc"})},C=async(e,o,t,r)=>{if(o.length===0)return;const{format:n,jsonFileName:s,marker:i,output:c,plugin:p,readmePath:a,...f}=e;v(n,s,a,r);const y=o.map(g=>g.input),u=p??[];u.push("typedoc-plugin-rename-defaults"),(n==="inline"||n==="markdown")&&u.push("typedoc-plugin-markdown");const l=await A.bootstrapWithPlugins({...f,compilerOptions:{allowJs:!0,declaration:!1,declarationMap:!1,esModuleInterop:!0,module:99,moduleResolution:100,noEmit:!0,noImplicitAny:!1,skipLibCheck:!0,sourceMap:!1,target:99,...f.compilerOptions},entryPoints:y,hideGenerator:!0,out:t,plugin:u,...n==="inline"?{hideBreadcrumbs:!0,hidePageHeader:!0,navigation:!1,outputFileStrategy:"modules",useCodeBlocks:!0}:{}},[]),d=await l.convert();if(d){if(n==="json")await l.generateJson(d,s);else if(n==="html")await l.generateDocs(d,t);else if(await l.generateOutputs(d),n==="inline"){if(i===void 0)throw new Error("The `marker` option is required when using the `inline` format.");P(t,o.length,i,a,r)}}},T=e=>e.logger,L=async(e,o,t,r)=>{if(e.options.typedoc&&e.options.typedoc.format!==void 0){const n=T(e);let s="unknown";e.pkg.dependencies?.typedoc?s=e.pkg.dependencies.typedoc:e.pkg.devDependencies?.typedoc&&(s=e.pkg.devDependencies.typedoc),o&&k("typedoc",o,n),r&&n.raw(`
|
|
3
|
+
`),n.info({message:`Using ${$("typedoc")} ${s} to generate reference documentation`,prefix:"typedoc"}),await e.hooks.callHook("typedoc:before",e);let i=e.options.rootDir;e.options.typedoc.output?i=e.options.typedoc.output:e.options.typedoc.format==="inline"&&o?i=m(o,"typedoc"):e.options.typedoc.format!=="json"&&(i=m(i,"api-docs")),await C(e.options.typedoc,e.options.entries,i,n),await e.hooks.callHook("typedoc:done",e)}};export{L as default};
|
package/dist/cli/index.js
CHANGED
|
@@ -1,55 +1,83 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
|
|
2
|
+
import{createCerebro as Q}from"@visulima/cerebro";import Z from"@visulima/cerebro/logger/pail";import{e as A,S as q,m as ee,f as te,g as se,i as ae,B as ne,T as ie,j as R,v as re,l as oe,d as ce}from"../packem_shared/index-UxllEEEe.js";import k,{cwd as O,exit as le}from"node:process";import{installPackage as h}from"@antfu/install-pkg";import{spinner as D,confirm as f,cancel as B,select as g,multiselect as G,intro as K,log as E,outro as U,isCancel as W}from"@clack/prompts";import{a as de,b as ue,q as pe,s as N,T as me,S as fe}from"../packem_shared/create-or-update-key-storage-DHOKZmnD.js";import{P as L,w as b}from"../packem_shared/utils-Bsoe7qJG.js";import ge from"magic-string";import{exec as ye}from"tinyexec";import{PRODUCTION_ENV as F,DEVELOPMENT_ENV as we}from"@visulima/packem-share/constants";import{createJiti as be}from"jiti";import{writeFile as z,readFile as he}from"node:fs/promises";import{existsSync as V}from"node:fs";import{parseEnv as J}from"node:util";import{createInterface as ve}from"node:readline/promises";import __cjs_mod__ from "node:module"; // -- packem CommonJS require shim --
|
|
3
3
|
const require = __cjs_mod__.createRequire(import.meta.url);
|
|
4
|
-
const
|
|
5
|
-
|
|
6
|
-
|
|
4
|
+
const _={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"]},ke=/defineConfig\s*\(\s*\{/,$e=/preset:\s*['"][^'"]+['"]/,Se=["typedoc","typedoc-plugin-markdown","typedoc-plugin-rename-defaults"],Ce=["@babel/core","@babel/preset-react"],je=["react","react-dom"],xe=["@babel/core","babel-preset-solid"],Pe=["solid-js"],Ee=["@babel/core","@babel/preset-react","babel-plugin-transform-hook-names"],De=["preact"],Le=["unplugin-vue"],Ie=["vue"],Me=["rollup-plugin-svelte"],Ne=["svelte"],$=(t,e,a)=>t.includes(`preset: '${e}'`)||t.includes(`preset: "${e}"`)||t.includes(`preset: '${e}',`)||t.includes(`preset: "${e}",`)||t.includes(a)||t.includes(`@visulima/packem/config/preset/${e}`),S=(t,e)=>{const{logger:a,magic:s,packemConfig:n}=t,i=ke.exec(n);if(i?.index!==void 0){const r=i.index+i[0].length;if(n.includes("preset:")){const o=$e.exec(n);if(o)s.replace(o[0],`preset: '${e}'`);else throw a.warn(`A preset already exists in the config. Please manually set it to '${e}'.`),new Error("Preset exists but is not a string")}else s.appendLeft(r,`
|
|
5
|
+
preset: '${e}',`)}else if(n.includes("transformer:"))s.replace("transformer:",`preset: '${e}',
|
|
6
|
+
transformer:`);else{const r=n.indexOf("{");r!==-1&&s.appendLeft(r+1,`
|
|
7
|
+
preset: '${e}',`)}},Oe=async t=>{try{return((await ye("git",["status","--porcelain"],{nodeOptions:{cwd:t,stdio:["pipe","pipe","pipe"]}})).stdout?.trim().length??0)>0}catch{return!1}},H=async t=>{const e=b(t,"package.json"),a=await q(e,{resolveCatalogs:!0});return!!(a.devDependencies?.typescript??a.dependencies?.typescript)},Be=async t=>{const e=await H(t),a=[...je],s=[...Ce];return e?s.push("@types/react","@types/react-dom"):await f({initialValue:!1,message:"Do you want to use TypeScript?"})&&s.push("typescript","@types/react","@types/react-dom"),{devPackages:s,packages:a}},C=async(t,e,a)=>{const{rootDirectory:s,spinner:n}=t;n.start("Installing packages"),await h(a,{cwd:s,dev:!1,silent:!0}),await h(e,{cwd:s,dev:!0,silent:!0}),n.stop("Installed packages")},Ve=async t=>{const{logger:e,magic:a,packemConfig:s,packemConfigFormat:n,rootDirectory:i,spinner:r,transformerReplaceKey:o,transformerSearchKey:c}=t;if(s.includes("typedoc: typedocBuilder")||s.includes("@visulima/packem/builder/typedoc")){e.warn("Typedoc has already been added to the packem config.");return}n==="cjs"?a.prepend(`const typedocBuilder = require("@visulima/packem/builder/typedoc");
|
|
8
|
+
`):a.prepend(`import typedocBuilder from "@visulima/packem/builder/typedoc";
|
|
9
|
+
`),s.includes("builder: {")?a.replace("builder: {",`builder: {
|
|
7
10
|
typedoc: typedocBuilder,
|
|
8
|
-
`):
|
|
11
|
+
`):a.replace(c,`${o}
|
|
9
12
|
builder: {
|
|
10
13
|
typedoc: typedocBuilder,
|
|
11
|
-
},`),e.info("Adding typedoc dependencies..."),
|
|
12
|
-
Typedoc added!`)}
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
14
|
+
},`),e.info("Adding typedoc dependencies..."),r.start("Installing packages"),await h(Se,{cwd:i,dev:!0,silent:!0}),r.stop("Installed packages"),e.success(`
|
|
15
|
+
Typedoc added!`)},Re=async t=>{const{logger:e,packemConfig:a}=t;if($(a,"react","createReactPreset")){e.warn("React preset has already been added to the packem config.");return}S(t,"react");const{devPackages:s,packages:n}=await Be(t.rootDirectory);e.info("Adding React dependencies..."),await C(t,s,n),e.success(`
|
|
16
|
+
React preset added!`)},Te=async t=>{const{logger:e,packemConfig:a}=t;if($(a,"solid","createSolidPreset")){e.warn("Solid preset has already been added to the packem config.");return}S(t,"solid"),e.info("Adding Solid dependencies..."),await C(t,xe,Pe),e.success(`
|
|
17
|
+
Solid preset added!`)},Ae=async t=>{const e=await H(t),a=[...De],s=[...Ee];return e?s.push("@types/preact"):await f({initialValue:!1,message:"Do you want to use TypeScript?"})&&s.push("typescript","@types/preact"),{devPackages:s,packages:a}},qe=async t=>{const{logger:e,packemConfig:a}=t;if($(a,"preact","createPreactPreset")){e.warn("Preact preset has already been added to the packem config.");return}S(t,"preact");const{devPackages:s,packages:n}=await Ae(t.rootDirectory);e.info("Adding Preact dependencies..."),await C(t,s,n),e.success(`
|
|
18
|
+
Preact preset added!`)},Ge=async t=>{const{logger:e,packemConfig:a}=t;if($(a,"vue","createVuePreset")){e.warn("Vue preset has already been added to the packem config.");return}S(t,"vue"),e.info("Adding Vue dependencies..."),await C(t,Le,Ie),e.success(`
|
|
19
|
+
Vue preset added!`)},Ke=async t=>{const{logger:e,packemConfig:a}=t;if($(a,"svelte","createSveltePreset")){e.warn("Svelte preset has already been added to the packem config.");return}S(t,"svelte"),e.info("Adding Svelte dependencies..."),await C(t,Me,Ne),e.success(`
|
|
20
|
+
Svelte preset added!`)},Ue=async()=>{const t=[],e=await g({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(t.push(e),e!=="tailwindcss"){let a=await G({message:"Pick extra loaders",options:[{label:"Sass",value:"sass"},{label:"Stylus",value:"stylus"},{label:"Less",value:"less"}],required:!1});if(a.includes("sass")){const s=await g({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"}]});s!=="sass"&&(a=a.filter(n=>n!=="sass"),a.push(s))}t.push(...a)}return{cssLoaders:t,mainCssLoader:e}},We=async(t,e,a,s)=>{if(!await f({initialValue:!1,message:"Do you want to minify your css?"}))return;const n=await g({message:"Pick a css minifier",options:[{label:"CSSNano",value:"cssnano"},{label:"Lightning CSS",value:"lightningcss"}]});return a.includes("lightningcss")||s.push(n),e==="cjs"?t.prepend(`const ${n}Minifier = require("@visulima/packem/css/minifier/${n.toLowerCase()}");
|
|
21
|
+
`):t.prepend(`import ${n}Minifier from "@visulima/packem/css/minifier/${n.toLowerCase()}";
|
|
22
|
+
`),n},Fe=async t=>{const{logger:e,magic:a,packemConfig:s,packemConfigFormat:n,transformerReplaceKey:i,transformerSearchKey:r}=t;if(s.includes("css: {")||s.includes("@visulima/packem/css")){e.warn("Css loaders have already been added to the packem config.");return}const{cssLoaders:o,mainCssLoader:c}=await Ue(),l=[];for(const p of o)l.push(..._[p]);c!=="tailwindcss"&&o.push("sourceMap");for(const p of o){const d=p==="sass-embedded"||p==="node-sass"?"sass":p;n==="cjs"?a.prepend(`const ${d}Loader = require("@visulima/packem/css/loader/${d.toLowerCase()}");
|
|
23
|
+
`):a.prepend(`import ${d}Loader from "@visulima/packem/css/loader/${d.toLowerCase()}";
|
|
24
|
+
`)}const u=await We(a,n,o,l),m=o.map(p=>p==="sass-embedded"||p==="node-sass"?"sass":`${p}Loader`).join(", ");s.includes("rollup: {")?a.replace("rollup: {",`rollup: {
|
|
25
|
+
css: {${u?`
|
|
26
|
+
minifier: ${u}Minifier,`:""}
|
|
27
|
+
loaders: [${m}],
|
|
20
28
|
},
|
|
21
|
-
`):
|
|
29
|
+
`):a.replace(r,`${i}
|
|
22
30
|
rollup: {
|
|
23
|
-
css: {${
|
|
24
|
-
minifier: ${
|
|
25
|
-
loaders: [${
|
|
31
|
+
css: {${u?`
|
|
32
|
+
minifier: ${u}Minifier,`:""}
|
|
33
|
+
loaders: [${m}],
|
|
26
34
|
},
|
|
27
|
-
},`),
|
|
28
|
-
CSS loaders added!`)}await ae(d,o.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 Ie=Object.defineProperty,Me=k((s,t)=>Ie(s,"name",{value:t,configurable:!0}),"e$1");const Te=Me(async(s,t,e,r,n)=>{const i=await _(t,n);let d=await s.import(i,{default:!0,try:!0})||{};return typeof d=="function"&&(d=await d(e,r)),{config:d,path:i}},"loadPackemConfig");var Be=Object.defineProperty,T=k((s,t)=>Be(s,"name",{value:t,configurable:!0}),"E$1");const Le=T((s,t)=>s.key==="exports"&&s.subKey===I?I:s.key==="exports"&&s.subKey===V?V:t,"getEnvironment"),P=T((s,t,e,r,n,i,d)=>{const f=Le(n,i.environment);let y=i.options.runtime;for(const p of ue)if(n.file.includes(`.${p}.`)||n.subKey===p){y=p;break}let o=s.find(p=>p.input===t&&p.environment===f&&p.runtime===y);o===void 0?o=s[s.push({environment:f,exportKey:new Set([n.exportKey].filter(Boolean)),input:t,runtime:y})-1]:o.exportKey&&n.exportKey&&o.exportKey.add(n.exportKey),d&&(o.isGlob=!0),e&&(o.outDir=r),n.isExecutable?(o.executable=!0,o.declaration=!1,n.type==="cjs"?o.cjs=!0:n.type==="esm"&&(o.esm=!0)):(/\.d\.[mc]?ts$/.test(n.file)&&i.options.declaration!==!1&&(o.declaration=i.options.declaration),n.type==="cjs"?o.cjs=!0:n.type==="esm"&&(o.esm=!0));const u=n.file.replace(W(n.file),"").replace(new RegExp(`^./${i.options.outDir.replace(/^\.\//,"")}/`),"");q.has(n.subKey)&&!t.includes(u)&&(o.fileAlias=u)},"createOrUpdateEntry");let U=!1;const z=T(s=>{if(s.pkg?.dependencies?.typescript===void 0&&s.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"),Oe=T((s,t,e)=>{const r=(e.options.outputExtensionMap?.cjs??"cjs").replaceAll(".",String.raw`\.`),n=(e.options.outputExtensionMap?.esm??"mjs").replaceAll(".",String.raw`\.`),i=[];t.sort((o,u)=>o.split("/").length-u.split("/").length);const d=s.type==="module"?"esm":"cjs";d==="esm"&&(e.options.emitESM=!0),d==="cjs"&&(e.options.emitCJS=!0);const f=we(s.exports,d,e.options.declaration,[],e.options.ignoreExportKeys).filter(o=>!o.ignored);if(s.bin){const o=(typeof s.bin=="string"?[s.bin]:Object.values(s.bin)).filter(Boolean);for(const u of o){const p=J(u);if(p&&p!==d)throw new Error(`Exported file "${u}" has an extension that does not match the package.json type "${s.type??"commonjs"}".`);f.push({file:u,isExecutable:!0,key:"bin",type:p??d})}}s.main&&f.push({file:s.main,key:"main",type:J(s.main)??d}),s.module&&f.push({file:s.module,key:"module",type:"esm"}),(s.types||s.typings)&&(z(e),e.options.declaration===void 0&&(e.options.declaration="compatible"),f.push({file:s.types??s.typings,key:"types"}));const y=[];for(const o of f){const u=W(o.file);if(u!==""&&!me.includes(u))continue;e.options.declaration===void 0&&(o.key==="types"||o.subKey==="types")&&(e.options.declaration=o.file.includes(".d.ts")?"compatible":!0),e.options.emitCJS===void 0&&o.type==="cjs"&&(e.options.emitCJS=!0),e.options.emitESM===void 0&&o.type==="esm"&&(e.options.emitESM=!0);const p=o.file.replace(new RegExp(String.raw`(?:\*[^/\\]|\.d\.[mc]?ts|\.\w+|${[`\\.${r}`,`\\.${n}`].join("|")})$`),""),l=p.endsWith("/");if(l&&["./","/"].includes(p))continue;const b=p.replace(new RegExp(`(./)?${e.options.outDir}`),e.options.sourceDir).replace("./",""),v="(?<=/|$)",c=l?"":String.raw`(\.d\.[cm]?ts|(\.[cm]?[tj]sx?)|${[`\\.${r}`,`\\.${n}`].join("|")})$`;if(o.file.includes("/*")&&o.key==="exports"){U||(e.logger.debug("Private subfolders are not supported, if you need this feature please open an issue on GitHub."),U=!0);const h=[],j=new RegExp(v+b.replace("*","(.*)")+c),L=b.replace(/^(.+?)\.[^.]*$/,"$1"),H=new RegExp(v+L.replace("*","(.*)")+c);for(const C of t)(j.test(C)||q.has(o.subKey)&&H.test(C))&&h.push(C);if(h.length===0){i.push(`Could not find entrypoint for \`${o.file}\``);continue}for(const C of h)P(y,C,l,p,o,e,!0);continue}const a=new RegExp(v+b+c);let g=t.find(h=>a.test(h));if(q.has(o.subKey)&&g===void 0){const h=b.replace(/^(.+?)\.[^.]*$/,"$1"),j=new RegExp(v+h+c);g=t.find(L=>j.test(L))}if(g===void 0){S(M(e.options.rootDir,o.file))||i.push(`Could not find entrypoint for \`${o.file}\``);continue}S(g)&&/\.[cm]?tsx?$/.test(g)&&z(e);const m=pe(g.replace(fe,""));S(`${m}.cts`)&&S(`${m}.mts`)?(P(y,`${m}.cts`,l,p,{...o,type:"cjs"},e,!1),P(y,`${m}.mts`,l,p,{...o,type:"esm"},e,!1)):P(y,g,l,p,o,e,!1)}return e.options.emitESM&&!e.options.emitCJS&&e.options.declaration===void 0&&(e.options.declaration="node16"),{entries:y,warnings:i}},"inferEntries");var Ne=Object.defineProperty,Ke=k((s,t)=>Ne(s,"name",{value:t,configurable:!0}),"o");const Ve=Ke((s,t)=>{const{publishConfig:e}=s;return e&&(e.bin&&(typeof e.bin=="object"||typeof e.bin=="string")&&(s.bin=e.bin),e.type&&typeof e.type=="string"&&e.type!==""&&(s.type=e.type),e.main&&typeof e.main=="string"&&e.main!==""&&(s.main=e.main),e.module&&typeof e.module=="string"&&e.module!==""&&(s.module=e.module),t===void 0&&e.types&&typeof e.types=="string"&&e.types!==""?s.types=e.types:t===void 0&&e.typings&&typeof e.typings=="string"&&e.typings!==""&&(s.typings=e.typings),e.exports&&typeof e.exports=="object"&&(s.exports=e.exports)),s},"overwriteWithPublishConfig");var qe=Object.defineProperty,Ae=k((s,t)=>qe(s,"name",{value:t,configurable:!0}),"t$1");const Ge={hooks:{"build:prepare":Ae(function(s){if(s.options.entries.length>0)return;const t=x(s.options.rootDir,s.options.sourceDir);if(!S(t))throw new Error("No 'src' directory found. Please provide entries manually.");const e=re(t,{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 r={...s.pkg};r.publishConfig&&(s.logger.info(`Using publishConfig found in package.json, to override the default key-value pairs of "${Object.keys(r.publishConfig).join(", ")}".`),s.logger.debug(r.publishConfig),r=Ve(r,s.options.declaration));const n=Oe(r,e,s);for(const i of n.warnings)he(s,i);if(s.options.entries.push(...n.entries),s.options.entries.length===0)throw new Error("No entries detected. Please provide entries manually.");s.logger.info("Automatically detected entries:",be(s.options.entries.map(i=>i.fileAlias?`${O(i.fileAlias)} => ${O(i.input.replace(`${s.options.rootDir}/`,"").replace(/\/$/,"/*"))}`:O(i.input.replace(`${s.options.rootDir}/`,"").replace(/\/$/,"/*"))).join(", ")),ve([s.options.emitESM&&"esm",s.options.emitCJS&&"cjs",s.options.declaration&&"dts"].filter(Boolean).map(i=>`[${i}]`).join(" ")))},"build:prepare")}};var Je=Object.defineProperty,Re=k((s,t)=>Je(s,"name",{value:t,configurable:!0}),"t");const Ue=Re(async(s,t)=>{if(s==="auto")s=Ge;else{if(s==="none")return{};typeof s=="string"&&(s=await t.import(s)||{})}return typeof s=="function"&&(s=s()),s},"loadPreset");var ze=Object.defineProperty,E=k((s,t)=>ze(s,"name",{value:t,configurable:!0}),"r");const Fe=E(s=>{s.addCommand({description:"Demonstrate options required",execute:E(async({logger:t,options:e})=>{let r="build";e.watch?r="watch":e.jit&&(r="jit");const n={};let i;if(e.env)for(const l of e.env)l.key==="NODE_ENV"?i=l.value:n[`process.env.${l.key}`]=JSON.stringify(l.value);i===void 0&&(e.production?i=I:e.development&&(i=V));const d=[];if(e.external)for(const l of e.external)d.push(l.split(","));const f=M(A(),e.dir??"."),y=ge(f,{debug:e.debug}),{config:o,path:u}=await Te(y,f,i,r,e.config??void 0);t.debug("Using packem config found at",u);const p=await Ue(o.preset??"auto",y);e.minify&&e.sourcemap===void 0&&(e.sourcemap=!0);try{await ke(f,r,i,t,e.debug,ye(o,p,{analyze:e.analyze,cjsInterop:e.cjsInterop,clean:e.clean,dtsOnly:e.dtsOnly,externals:d,killSignal:e.killSignal,minify:e.minify===void 0?i===I:e.minify,onSuccess:e.onSuccess,rollup:{esbuild:{target:e.target},license:{path:e.license},metafile:e.metafile,replace:{values:n},resolveExternals:e.noExternal?{builtins:!1,deps:!1,devDeps:!1,optDeps:!1,peerDeps:!1}:{}},runtime:e.runtime,sourcemap:e.metafile||e.analyze||e.sourcemap,validation:e.validation===!1?!1:{},...e.typedoc?{typedoc:{format:"html"}}:{}}),e.tsconfig??void 0)}catch(l){t.error(l),ee(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:E(t=>{const[e,r]=t.split("=");return{key:e,value:r}},"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:E(t=>{if(t==="SIGTERM"||t==="SIGKILL")return t;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:E(t=>{if(t==="node"||t==="browser")return t;throw new Error("Invalid runtime. Use 'node' or 'browser'.")},"type")}]})},"createBuildCommand");var We=Object.defineProperty,D=k((s,t)=>We(s,"name",{value:t,configurable:!0}),"f");const _e=D(s=>{s.addCommand({description:"Initialize packem configuration",execute:D(async({logger:t,options:e})=>{if(se("Welcome to packem setup"),S(x(e.dir,"packem.config.mjs"))){t.info("Packem project already initialized, you can use `packem build` to build your project");return}const r=M(A(),e.dir??"."),n=x(r,"package.json");if(!S(n))throw new Error("No package.json found in the directory");const i=$e(n),d=[];i.dependencies&&d.push(...Object.keys(i.dependencies)),i.devDependencies&&d.push(...Object.keys(i.devDependencies));const f=!!(i.devDependencies?.typescript??i.dependencies?.typescript),y=[];if(e.typescript===void 0&&!f?(e.typescript=await w({message:"Do you want to install TypeScript?"}),e.typescript&&y.push("typescript@latest")):G.message(`TypeScript version ${i.devDependencies?.typescript??i.dependencies?.typescript} is already installed`),!S(x(r,"tsconfig.json"))){const c=await w({message:"Do you want to use generate a tsconfig.json?"}),a=await w({message:"Do you want to run your code in the DOM?"});if(c){const g=K();g.start("Generating tsconfig.json"),le(x(r,"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:a?["es2022","dom","dom.iterable"]:["es2022"]}}),g.stop("")}}if(e.runtime===void 0&&(e.runtime=await $({message:"Pick a build runtime",options:[{label:"Node",value:"node"},{label:"Browser",value:"browser"}]})),d.includes("esbuild")?e.transformer="esbuild":d.includes("@swc/core")?e.transformer="swc":d.includes("sucrase")&&(e.transformer="sucrase"),e.transformer===void 0?(e.transformer=await $({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"&&!d.includes(e.transformer)&&await w({message:`Do you want to install ${e.transformer}?`})&&y.push(e.transformer==="swc"?"@swc/core":e.transformer)):G.message(`Transformer ${e.transformer} is already installed.`),e.isolatedDeclarationTransformer===void 0&&(e.isolatedDeclarationTransformer=await w({message:"Do you want to use an isolated declaration types?",initialValue:!1})),e.isolatedDeclarationTransformer===void 0&&(e.isolatedDeclarationTransformer=await $({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 c;switch(e.isolatedDeclarationTransformer){case"oxc":{c="oxc-transform";break}case"swc":{c="@swc/core";break}case"typescript":{c="typescript";break}default:te("Invalid isolated declaration transformer")}c!==void 0&&!d.includes(c)&&await w({message:`Do you want to install ${c}?`})&&y.push(c)}e.css===void 0&&(e.css=await w({message:"Do you want to use css in your project?",initialValue:!1}));const o=[];if(e.css){const c=await $({message:"Pick a css loader",options:[{label:"PostCSS",value:"postcss"},{hint:"experimental",label:"Lightning CSS",value:"lightningcss"}]});o.push(c);let a=await F({message:"Pick your loaders",options:[{label:"Sass",value:"sass"},{label:"Stylus",value:"stylus"},{label:"Less",value:"less"}],required:!1});if(a.includes("sass")){const g=await $({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"}]});g!=="sass"&&(a=a.filter(m=>m!=="sass"),a.push(g))}if(o.push(...a),await w({message:`Do you want to install "${o.join('", "')}"?`}))for(const g of o)y.push(...X[g]);o.push("sourceMap")}e.cssMinifier===void 0&&(e.cssMinifier=await w({message:"Do you want to minify your css?",initialValue:!1}));let u;e.cssMinifier&&(u=await $({message:"Pick a css minifier",options:[{label:"CSSNano",value:"cssnano"},{label:"Lightning CSS",value:"lightningcss"}]}),o.includes("lightningcss")||await w({message:`Do you want to install "${u}"?`})&&y.push(u));let p="",l="";if(e.isolatedDeclarationTransformer&&(l+=`,
|
|
29
|
-
|
|
35
|
+
},`),t.spinner.start("Installing packages"),await h(l,{cwd:t.rootDirectory,dev:!0,silent:!0}),t.spinner.stop("Installed packages"),e.success(`
|
|
36
|
+
CSS loaders added!`)},ze=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:async({argument:e,logger:a,options:s})=>{const n=a,i=D(),r=L(O(),typeof s.dir=="string"?s.dir:".");let o;try{o=await A(r,s.config)}catch{n.error("Could not find a packem config file, please run `packem init` first.");return}if(await Oe(r)&&!await f({initialValue:!1,message:"Git repository has uncommitted changes. Do you want to proceed?"})){B("Operation cancelled.");return}const c=await de(o,{buffer:!1}),l=c.includes("import")?"esm":"cjs",u=new ge(c),m=" transformer,",p=c.includes(" transformer,")?" transformer,":" transformer",d={logger:n,magic:u,packemConfig:c,packemConfigFormat:l,rootDirectory:r,spinner:i,transformerReplaceKey:m,transformerSearchKey:p};e.includes("typedoc")&&await Ve(d),e.includes("react")&&await Re(d),e.includes("solid")&&await Te(d),e.includes("preact")&&await qe(d),e.includes("vue")&&await Ge(d),e.includes("svelte")&&await Ke(d),e.includes("css")&&await Fe(d),await ue(o,u.toString(),{overwrite:!0})},name:"add",options:[{defaultValue:".",description:"The directory to build",name:"dir",type:String},{description:"Use a custom config file",name:"config",type:String}]})},Je=(t,e)=>{if(t==="rolldown")return`// Generated by \`packem\` first-run setup. See https://packem.dev for full options.
|
|
37
|
+
import { defineConfig } from "@visulima/packem/config";
|
|
38
|
+
|
|
39
|
+
export default defineConfig({
|
|
40
|
+
bundler: "${t}",
|
|
41
|
+
declaration: true,
|
|
42
|
+
});
|
|
43
|
+
`;if(!e)throw new Error("A transformer must be selected for the rollup bundler.");return`// Generated by \`packem\` first-run setup. See https://packem.dev for full options.
|
|
44
|
+
import { defineConfig } from "@visulima/packem/config";
|
|
45
|
+
import transformer from "@visulima/packem/transformer/${e}";
|
|
46
|
+
|
|
47
|
+
export default defineConfig({
|
|
48
|
+
bundler: "${t}",
|
|
49
|
+
declaration: true,
|
|
50
|
+
transformer,
|
|
51
|
+
});
|
|
52
|
+
`},_e=async()=>{const t=await g({initialValue:"rollup",message:"Which bundler do you want to use?",options:[{hint:"stable, full feature set, supports DTS",label:"rollup",value:"rollup"},{hint:"experimental, fast",label:"rolldown",value:"rolldown"}]});if(W(t))throw B("Setup cancelled."),new Error("Packem setup was cancelled.");return t},He=async()=>{const t=await g({initialValue:"esbuild",message:"Which transformer do you want to use?",options:[{hint:"fast, widely used",label:"esbuild",value:"esbuild"},{hint:"fastest, Rust-based",label:"oxc",value:"oxc"},{hint:"TypeScript-aware, Rust-based",label:"swc",value:"swc"},{hint:"minimal, JS-based",label:"sucrase",value:"sucrase"}]});if(W(t))throw B("Setup cancelled."),new Error("Packem setup was cancelled.");return t},Xe=async(t,e)=>{if(t.length===0)return;const a=D();a.start(`Installing ${t.join(", ")}`);try{await h(t,{cwd:e,dev:!0,silent:!0}),a.stop(`Installed ${t.join(", ")}`)}catch(s){throw a.stop(`Failed to install ${t.join(", ")}`),s}},Ye=async t=>{if(await ee(t))return;if(!(process.stdout.isTTY&&!process.env.CI)){const i=await te(["rollup","esbuild"],t);throw new Error(`No packem.config found. Run packem in an interactive terminal to generate one, or install the defaults manually:
|
|
53
|
+
${i}
|
|
54
|
+
and create a packem.config.ts.`)}K(pe("Packem first-run setup")),E.info("No packem.config found — let's create one.");const e=await _e(),a=e==="rolldown"?void 0:await He(),s=[e];a&&s.push(se[a]),await Xe(s,t);const n=b(t,"packem.config.ts");await z(n,Je(e,a),"utf8"),E.success(`Created ${n}`),U("Setup complete — continuing with build.")},Qe=/^([^#:=]+)=(.*)$/,T=(t,e="PACKEM_")=>{const a={};for(const s of t.split(`
|
|
55
|
+
`)){const n=s.trim();if(!n||n.startsWith("#"))continue;const i=Qe.exec(n);if(i?.[1]){const r=i[1].trim();let o=i[2].trim();(o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'"))&&(o=o.slice(1,-1)),(!e||r.startsWith(e))&&(a[`process.env.${r}`]=JSON.stringify(o))}}return a},Ze=(t,e,a,s)=>{const n=J(t),i=Object.keys(n).length,r={};for(const[c,l]of Object.entries(n))(!e||c.startsWith(e))&&(r[`process.env.${c}`]=JSON.stringify(l));const o=Object.keys(r).length;return i>0&&o===0&&e?s?.warn(`Loaded 0 of ${String(i)} variables from "${a}"; none matched the "${e}" prefix.`):s?.info(`Loaded ${String(o)} of ${String(i)} variables from "${a}"${e?` (prefix "${e}")`:""}.`),r},et=async(t,e,a="PACKEM_",s)=>{const n=L(e,t);if(!V(n))return s?.warn(`Env file not found at "${n}"; no environment variables were loaded.`),{};const{readFile:i}=await import("node:fs/promises"),r=await i(n,"utf8");if(typeof J!="function")return T(r,a);try{return Ze(r,a,t,s)}catch{return T(r,a)}},tt=async(t,e,a,s,n)=>{const i=await A(e,n),r=await t.import(i,{default:!0})??{};return{config:typeof r=="function"?await r(a,s):r,path:i}},st=async(t,e)=>{switch(t){case"none":return{};case"preact":{const{createPreactPreset:a}=await import("../config/preset/preact.js");t=a();break}case"react":{const{createReactPreset:a}=await import("../config/preset/react.js");t=a();break}case"solid":{const{createSolidPreset:a}=await import("../config/preset/solid.js");t=a();break}case"svelte":{const{createSveltePreset:a}=await import("../config/preset/svelte.js");t=a();break}case"vue":{const{createVuePreset:a}=await import("../config/preset/vue.js");t=a();break}default:typeof t=="string"&&(t=await e.import(t,{default:!0})||{})}return typeof t=="function"&&(t=t()),t},at=t=>t.watch?"watch":t.jit?"jit":"build",nt=t=>{let e;const a={};if(t.env)for(const s of t.env)s.key==="NODE_ENV"?e=s.value:a[`process.env.${s.key}`]=JSON.stringify(s.value);return{cliEnvVariables:a,nodeEnvironment:e}},it=(t,e)=>{if(e!==void 0)return e;if(t.production)return F;if(t.development)return we},rt=t=>{const e=[];if(t.external)for(const a of t.external)e.push(a.split(","));return e},ot=t=>{t.addCommand({description:"Build the package using the resolved packem configuration",execute:async({logger:e,options:a})=>{const s=a,n=at(s),{cliEnvVariables:i,nodeEnvironment:r}=nt(s),o=it(s,r),c=rt(s),l=L(O(),s.dir??".");await Ye(l);const u=be(l,{debug:s.debug}),{config:m,path:p}=await tt(u,l,o,n,s.config??void 0);e.debug("Using packem config found at",p);const d=s.envFile??m.envFile,x=s.envPrefix??m.envPrefix??"PACKEM_",w={};if(d){const y=await et(d,l,x,{info:v=>{e.info(v)},warn:v=>{e.warn(v)}});Object.assign(w,y)}Object.assign(w,i);const I=await st(m.preset??"none",u);s.minify&&s.sourcemap===void 0&&(s.sourcemap=!0);try{const y=ae()(m,ne,I,{analyze:s.analyze,bundler:s.bundler,cjsInterop:s.cjsInterop,clean:s.clean,dtsOnly:s.dtsOnly,externals:c,killSignal:s.killSignal,minify:s.minify??o===F,onSuccess:s.onSuccess,rollup:{esbuild:{target:s.target},license:{path:s.license},metafile:s.metafile,...Object.keys(w).length>0||Object.keys(i).length>0?{replace:{values:w}}:{},resolveExternals:s.noExternal?{builtins:!1,deps:!1,devDeps:!1,optDeps:!1,peerDeps:!1}:{}},runtime:s.runtime,sourcemap:s.metafile||s.analyze||s.sourcemap,unbundle:s.unbundle,validation:s.validation===!1?!1:{},...s.exe?{exe:!0}:{},...s.typedoc?{typedoc:{format:"html"}}:{}});s.validation===!1&&!m.validation&&(y.validation=!1),s.cache===!1&&(y.fileCache=!1),await ie(l,n,o,e,s.debug??!1,y,s.tsconfig??void 0)}catch(y){e.error(y),le(1)}},name:"build",options:[{description:"Specify the bundler to use (rollup or rolldown)",name:"bundler",type:e=>{if(e==="rollup"||e==="rolldown")return e;throw new Error("Invalid bundler. Use 'rollup' or 'rolldown'.")}},{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:e=>{const a=e.indexOf("=");return a===-1?{key:e,value:""}:{key:e.slice(0,a),value:e.slice(a+1)}}},{description:"Path to the .env file to load environment variables from",name:"env-file",type:String},{description:"Prefix for environment variables to load from .env file (default: PACKEM_)",name:"env-prefix",type:String},{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:e=>{if(e==="SIGTERM"||e==="SIGKILL")return e;throw new Error("Invalid kill signal. Use 'SIGTERM' or 'SIGKILL'.")}},{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 (node, browser).",name:"runtime",type:e=>{if(e==="node"||e==="browser")return e;throw new Error("Invalid runtime. Use 'node' or 'browser'.")}},{description:"Enable unbundle mode to preserve source file structure instead of bundling into a single file",name:"unbundle",type:Boolean},{description:"Bundle the output into a standalone executable via Node.js SEA (requires Node.js >= 25.7.0, single entry)",name:"exe",type:Boolean}]})},X=t=>t==="sass-embedded"||t==="node-sass"?"sass":t,ct=(t,e)=>{fe(b(t,"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:e?["es2022","dom","dom.iterable"]:["es2022"]}})},lt=(t,e,a,s,n)=>{let i="";if(t)for(const r of e){const o=X(r);i+=n?`import ${o}Loader from "@visulima/packem/css/loader/${o.toLowerCase()}";
|
|
56
|
+
`:`const ${o}Loader = require("@visulima/packem/css/loader/${o.toLowerCase()}");
|
|
57
|
+
`}return s&&a&&(i+=n?`import ${a}Minifier from "@visulima/packem/css/minifier/${a.toLowerCase()}";
|
|
58
|
+
`:`const ${a}Minifier = require("@visulima/packem/css/minifier/${a.toLowerCase()}");
|
|
59
|
+
`),i},dt=(t,e,a,s)=>{if(!t&&!a)return"";let n=`,
|
|
30
60
|
rollup: {
|
|
31
|
-
css: {
|
|
32
|
-
loaders: [${
|
|
33
|
-
minifier: ${
|
|
61
|
+
css: {`;if(t){const i=s.map(r=>`${X(r)}Loader`).join(", ");n+=`
|
|
62
|
+
loaders: [${i}],`}return a&&e&&(n+=`
|
|
63
|
+
minifier: ${e}Minifier,`),n+=`
|
|
34
64
|
}
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
`),p=`import { defineConfig } from "@visulima/packem/config";
|
|
39
|
-
import transformer from "@visulima/packem/transformer/${e.transformer}";
|
|
40
|
-
${c}
|
|
65
|
+
}`,n},ut=(t,e,a,s,n)=>t?`import { defineConfig } from "@visulima/packem/config";
|
|
66
|
+
import transformer from "@visulima/packem/transformer/${e}";
|
|
67
|
+
${s}
|
|
41
68
|
export default defineConfig({
|
|
42
|
-
runtime: "${
|
|
43
|
-
transformer${
|
|
69
|
+
runtime: "${a}",
|
|
70
|
+
transformer${n}
|
|
44
71
|
});
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
`),p=`const { defineConfig } = require("@visulima/packem/config");
|
|
49
|
-
const transformer = require("@visulima/packem/transformer/${e.transformer}");
|
|
50
|
-
${c}
|
|
72
|
+
`:`const { defineConfig } = require("@visulima/packem/config");
|
|
73
|
+
const transformer = require("@visulima/packem/transformer/${e}");
|
|
74
|
+
${s}
|
|
51
75
|
module.exports = defineConfig({
|
|
52
|
-
runtime: ${
|
|
53
|
-
transformer${
|
|
76
|
+
runtime: ${a},
|
|
77
|
+
transformer${n}
|
|
54
78
|
});
|
|
55
|
-
`}const
|
|
79
|
+
`,pt=t=>{const e=[];return t.dependencies&&e.push(...Object.keys(t.dependencies)),t.devDependencies&&e.push(...Object.keys(t.devDependencies)),e},mt=async(t,e,a,s)=>{if(t===void 0&&!e){const i=await f({message:"Do you want to install TypeScript?"});return i&&s.push("typescript@latest"),i}const n=a.devDependencies?.typescript??a.dependencies?.typescript??"unknown";return E.message(`TypeScript version ${n} is already installed`),t},ft=async(t,e,a)=>{let s=t;return e.includes("esbuild")?s="esbuild":e.includes("@swc/core")?s="swc":e.includes("sucrase")&&(s="sucrase"),s!==void 0?(E.message(`Transformer ${s} is already installed.`),s):(s=await g({message:"Pick a transformer",options:[{label:"esbuild",value:"esbuild"},{label:"swc",value:"swc"},{label:"Sucrase",value:"sucrase"},{label:"OXC",value:"oxc"}]}),s&&s!=="oxc"&&!e.includes(s)&&await f({message:`Do you want to install ${s}?`})&&a.push(s==="swc"?"@swc/core":s),s)},gt=async t=>{if(N(b(t,"tsconfig.json")))return;const e=await f({message:"Do you want to use generate a tsconfig.json?"}),a=await f({message:"Do you want to run your code in the DOM?"});if(e){const s=D();s.start("Generating tsconfig.json"),ct(t,!!a),s.stop("")}},yt=async t=>{if(!t.includes("sass"))return t;const e=await g({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"}]});return e==="sass"?t:[...t.filter(a=>a!=="sass"),e]},wt=async t=>{const e=[],a=await g({message:"Pick a css loader",options:[{label:"PostCSS",value:"postcss"},{hint:"experimental",label:"Lightning CSS",value:"lightningcss"}]});e.push(a);const s=await G({message:"Pick your loaders",options:[{label:"Sass",value:"sass"},{label:"Stylus",value:"stylus"},{label:"Less",value:"less"}],required:!1}),n=await yt(s);if(e.push(...n),await f({message:`Do you want to install "${e.join('", "')}"?`}))for(const i of e)t.push(..._[i]);return e.push("sourceMap"),e},bt=async(t,e)=>{const a=await g({message:"Pick a css minifier",options:[{label:"CSSNano",value:"cssnano"},{label:"Lightning CSS",value:"lightningcss"}]});return t.includes("lightningcss")||await f({message:`Do you want to install "${a}"?`})&&e.push(a),a},ht=t=>{t.addCommand({description:"Initialize packem configuration",execute:async({logger:e,options:a})=>{const s=a,n=e;if(K("Welcome to packem setup"),N(b(s.dir??".","packem.config.ts"))){n.info("Packem project already initialized, you can use `packem build` to build your project");return}const i=L(O(),s.dir??"."),r=b(i,"package.json");if(!N(r))throw new Error("No package.json found in the directory");const o=await q(r,{resolveCatalogs:!0}),c=pt(o),l=!!(o.devDependencies?.typescript??o.dependencies?.typescript),u=[];s.typescript=await mt(s.typescript,l,o,u),await gt(i),s.runtime??=await g({message:"Pick a build runtime",options:[{label:"Node",value:"node"},{label:"Browser",value:"browser"}]}),s.transformer=await ft(s.transformer,c,u),s.css??=await f({initialValue:!1,message:"Do you want to use css in your project?"});const m=s.css?await wt(u):[];s.cssMinifier??=await f({initialValue:!1,message:"Do you want to minify your css?"});const p=s.cssMinifier?await bt(m,u):void 0,d=s.css??!1,x=s.cssMinifier??!1,w=l||o.type==="module",I=dt(d,p,x,m),y=lt(d,m,p,x,w),v=ut(w,s.transformer??"",s.runtime??"",y,I),P=D(),M=l?"ts":"js";u.length>0&&(P.start("Installing packages"),await h(u,{cwd:i,dev:!0,silent:!0}),P.stop("Installed packages")),P.start(`Creating packem.config.${M}`),me(b(i,`packem.config.${M}`),v),P.stop(`Created packem.config.${M}`),U("Now you can run `packem build` to build your project")},name:"init",options:[{defaultValue:".",description:"The directory to initialize",name:"dir",type:String},{description:"Choose a transformer",name:"transformer",type:e=>{if(typeof e=="string"&&["esbuild","sucrase","swc"].includes(e))return e;throw new Error("Invalid transformer, please choose one of 'swc', 'sucrase' or 'esbuild'")}},{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:e=>{if(e==="node"||e==="browser")return e;throw new Error("Invalid runtime. Use 'node' or 'browser'.")}}]})},Y={bunchee:"@visulima/packem",tsup:"@visulima/packem","tsup-node":"@visulima/packem",unbuild:"@visulima/packem"},vt={dependencies:`^${R.version}`,devDependencies:`^${R.version}`,peerDependencies:"*"},kt=(t,e,a,s)=>{const n={};for(const i of Object.keys(t))i===e?n[a]=s??t[e]:n[i]=t[i];return n},$t=/\bunbuild\b/g,St=/\bbunchee\b/g,Ct=/\btsup(?:-node)?/g,jt=/\bbuild\b/g,xt=[{from:"tsup",rewrite:t=>t.replaceAll(Ct,"packem build").replaceAll(jt,"build")},{from:"unbuild",rewrite:t=>t.replaceAll($t,"packem build")},{from:"bunchee",rewrite:t=>t.replaceAll(St,"packem build")}],Pt=(t,e,a)=>{let s=e,n=!1;for(const i of Object.keys(Y))s.includes(i)&&(a.info(`Migrating \`${t}\` script from ${i} to packem`),n=!0,s=s.replaceAll(new RegExp(String.raw`\b${i}\b`,"g"),"packem").replaceAll(new RegExp(String.raw`\b${i}-node\b`,"g"),"packem"));for(const{from:i,rewrite:r}of xt)s.includes(i)&&(a.info(`Migrating \`${t}\` script from ${i} to packem`),n=!0,s=r(s));return n?s:void 0},Et=(t,e)=>{const a={...t};let s=!1;for(const n of Object.keys(a)){const i=Pt(n,a[n],e);i!==void 0&&(a[n]=i,s=!0)}return{found:s,scripts:a}},Dt=(t,e)=>{const a={...t};let s=!1;for(const[n,i]of Object.entries(vt)){let r=a[n];for(const[o,c]of Object.entries(Y))r?.[o]&&(e.info(`Migrating \`${n}\` from ${o} to ${c}.`),s=!0,r=kt(r,o,c,i),a[n]=r)}return{found:s,pkg:a}},Lt=(t,e)=>{const a=["tsup","unbuild","bunchee"];for(const s of a)t[s]&&e.info(`Found \`${s}\` config field in package.json. Consider moving to packem.config.ts`)},It=async(t,e)=>{if(!V("package.json"))return e.error("No package.json found"),!1;const a=await he("package.json","utf8"),s=JSON.parse(a),{found:n,pkg:i}=Dt(s,e);let r=n;if(i.scripts){const{found:c,scripts:l}=Et(i.scripts,e);c&&(i.scripts=l,r=!0)}if(Lt(i,e),!r)return e.warn("No migratable bundler dependencies found in package.json"),!1;const o=`${JSON.stringify(i,void 0,a.includes(" ")?" ":2)}
|
|
80
|
+
`;return t?(e.info("[dry-run] package.json changes:"),e.info("Old content:"),console.info(a),e.info("New content:"),console.info(o)):(await z("package.json",o),e.success("Migrated `package.json`")),!0},Mt=["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"],Nt=t=>{let e=!1;for(const a of Mt)V(a)&&(t.info(`Found config file \`${a}\`. Consider creating packem.config.ts instead.`),t.warn("Manual migration required for config files. See https://www.visulima.com/docs/package/packem"),e=!0);return e||t.warn("No bundler config files found"),e},Ot=async({cwd:t,dryRun:e,logger:a})=>{if(e)a.info("Dry run enabled. No changes will be made.");else{const n=ve({input:k.stdin,output:k.stdout});a.warn(`
|
|
81
|
+
|
|
82
|
+
Before proceeding, review the migration guide at https://www.visulima.com/docs/package/packem, as this process will modify your files.
|
|
83
|
+
Uncommitted changes will be lost. Use the --dry-run flag to preview changes without applying them.`);const i=await n.question("Continue? (Y/n) ");if(n.close(),!(i.toLowerCase()==="y"||i==="")){a.error("Migration cancelled."),k.exitCode=1;return}}t&&k.chdir(t);let s=!1;await It(e,a)&&(s=!0),Nt(a)&&(s=!0),s?a.success("Migration completed. Remember to run install command with your package manager."):(a.error("No migration performed."),k.exitCode=1)},Bt=t=>{t.addCommand({description:"Migrate from other bundlers (tsup, unbuild, bunchee, etc.) to packem",execute:async({logger:e,options:a})=>{const s=a;await Ot({cwd:s.cwd,dryRun:s.dryRun,logger:e})},name:"migrate",options:[{defaultValue:".",description:"The directory to migrate",name:"cwd",type:String},{description:"Preview changes without applying them",name:"dry-run",type:Boolean}]})};try{require("node:module").enableCompileCache?.()}catch{}const j=Q("packem",{logger:Z({reporters:[new ce({error:{hideErrorCauseCodeView:!0,hideErrorCodeView:!0,hideErrorErrorsCodeView:!0}})],scope:"packem"}),packageName:oe,packageVersion:re});ht(j);ot(j);ze(j);Bt(j);j.run({shouldExitProcess:!1});
|