cnvr 2.8.6 → 2.8.8
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/LICENSE +1 -1
- package/README.md +341 -6
- package/dist/index.js +6 -6
- package/dist/index.js.map +4 -4
- package/dist/stages/ESBuild.d.ts.map +1 -1
- package/dist/utils/index.d.ts +1 -0
- package/dist/utils/index.d.ts.map +1 -1
- package/dist/utils/rawImportPlugin.d.ts +3 -0
- package/dist/utils/rawImportPlugin.d.ts.map +1 -0
- package/package.json +47 -31
package/LICENSE
CHANGED
package/README.md
CHANGED
|
@@ -1,13 +1,348 @@
|
|
|
1
|
-
#
|
|
1
|
+
# cnvr
|
|
2
|
+
|
|
3
|
+
**Build and dev in one config file.**
|
|
4
|
+
|
|
5
|
+
Chain stages, run once to build, or watch and rebuild.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
node .conveyer.js
|
|
9
|
+
```
|
|
2
10
|
|
|
3
11
|
## Installation
|
|
4
12
|
|
|
5
|
-
```
|
|
6
|
-
|
|
13
|
+
```bash
|
|
14
|
+
npm install cnvr --save-dev
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
For `.conveyer.ts` you need `tsx` as a peer dependency:
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
npm install tsx --save-dev
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Quick Start
|
|
24
|
+
|
|
25
|
+
Create `.conveyer.js` in your project root:
|
|
26
|
+
|
|
27
|
+
```javascript
|
|
28
|
+
import { resolve } from "node:path";
|
|
29
|
+
import { Conveyer, ESBuild } from "cnvr";
|
|
30
|
+
|
|
31
|
+
new Conveyer([
|
|
32
|
+
new ESBuild({
|
|
33
|
+
entryPoints: [ "src/index.ts" ],
|
|
34
|
+
outfile: resolve("dist", "index.js"),
|
|
35
|
+
external: true,
|
|
36
|
+
platform: "neutral",
|
|
37
|
+
format: "esm",
|
|
38
|
+
sourcemap: true,
|
|
39
|
+
target: "es2020"
|
|
40
|
+
})
|
|
41
|
+
], { initialCleanup: "dist" });
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Add to `package.json`:
|
|
45
|
+
|
|
46
|
+
```json
|
|
47
|
+
{
|
|
48
|
+
"scripts": {
|
|
49
|
+
"build": "node .conveyer.js",
|
|
50
|
+
"dev": "node .conveyer.js --dev"
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Run `npm run build` for a one-shot build, or `npm run dev` for watch mode.
|
|
56
|
+
|
|
57
|
+
## Entry Points
|
|
58
|
+
|
|
59
|
+
cnvr looks for a conveyer file in the current directory or the path you pass:
|
|
60
|
+
|
|
61
|
+
| Pattern | Example |
|
|
62
|
+
|---------|---------|
|
|
63
|
+
| `.conveyer.js` | Root file |
|
|
64
|
+
| `.conveyer.ts` | TypeScript (requires tsx) |
|
|
65
|
+
| `.conveyer.mjs` / `.conveyer.cjs` | ESM / CJS |
|
|
66
|
+
| `.conveyer/index.{js,ts,mjs,cjs}` | Alternative layout |
|
|
67
|
+
|
|
68
|
+
**CLI:**
|
|
69
|
+
|
|
70
|
+
- `cnvr` — runs `.conveyer.js` (or path you pass)
|
|
71
|
+
- `cnvr-ts` — runs `.conveyer.ts` via tsx
|
|
72
|
+
|
|
73
|
+
**Direct run:**
|
|
74
|
+
|
|
75
|
+
```bash
|
|
76
|
+
node .conveyer.js
|
|
77
|
+
npx cnvr
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## Environment Variables
|
|
81
|
+
|
|
82
|
+
| Variable | Description |
|
|
83
|
+
|----------|-------------|
|
|
84
|
+
| `NODE_ENV` | `development` or `production` |
|
|
85
|
+
| `WATCH` | Enable watch mode |
|
|
86
|
+
| `BUILD` | Production build mode |
|
|
87
|
+
| `DEV` | Dev mode (watch + dev options) |
|
|
88
|
+
| `BUNDLE` | Create zip bundle |
|
|
89
|
+
| `FORCE` | Rebuild all, including dependencies |
|
|
90
|
+
| `VERSION` | From package.json |
|
|
91
|
+
| `GIT_COMMIT_ID` | Current git commit |
|
|
92
|
+
| `SOURCEMAPS` | Enable sourcemaps in production |
|
|
93
|
+
|
|
94
|
+
**CLI flags:** `-p` / `--production`, `-d` / `--development`, `-e` / `--env <name>`, `-f` / `--force`.
|
|
95
|
+
|
|
96
|
+
## Public API
|
|
97
|
+
|
|
98
|
+
### Conveyer
|
|
99
|
+
|
|
100
|
+
```javascript
|
|
101
|
+
new Conveyer(stages, options?)
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
- `stages` — Array of stages (supports nesting up to 3 levels)
|
|
105
|
+
- `options.initialCleanup` — Path(s) to clean before first run
|
|
106
|
+
- `options.context` — Extra data in shared context
|
|
107
|
+
|
|
108
|
+
### Stage (base class)
|
|
109
|
+
|
|
110
|
+
All stages extend `Stage`. Base options:
|
|
111
|
+
|
|
112
|
+
```javascript
|
|
113
|
+
new Stage({ watch, initialCleanup, cwd, symbol, title, id, ... })
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
| Option | Type | Description |
|
|
117
|
+
|--------|------|-------------|
|
|
118
|
+
| `watch` | `string` \| `string[]` \| `{ paths, events, ... }` | Paths to watch (chokidar) |
|
|
119
|
+
| `initialCleanup` | `string` \| `string[]` | Dir(s) to clean before `run` |
|
|
120
|
+
| `cwd` | `string` | Working directory (default: `process.cwd()`) |
|
|
121
|
+
| `symbol` | `string` | Log icon |
|
|
122
|
+
| `title` | `string` | Stage name in logs |
|
|
123
|
+
| `id` | `string` | Unique ID (default: derived from title) |
|
|
124
|
+
|
|
125
|
+
**Hooks:** `onInit`, `onBefore`, `onAfter` — all optional, async.
|
|
126
|
+
|
|
127
|
+
**Override:** `do(isInitial, ...args)` — main logic.
|
|
128
|
+
|
|
129
|
+
### ESBuild
|
|
130
|
+
|
|
131
|
+
Bundles with esbuild. Supports JSX, jscc, raw imports.
|
|
132
|
+
|
|
133
|
+
```javascript
|
|
134
|
+
new ESBuild({
|
|
135
|
+
entryPoints: [ "src/index.ts" ],
|
|
136
|
+
outfile: resolve("dist", "index.js"),
|
|
137
|
+
external: true, // or array of package names, or [ true ] for auto
|
|
138
|
+
local: [ "my-pkg" ], // local packages to bundle
|
|
139
|
+
alias: { "@": "src" },
|
|
140
|
+
define: { "process.env.NODE_ENV": JSON.stringify(NODE_ENV) },
|
|
141
|
+
jsx: "automatic",
|
|
142
|
+
jsccValues: { _DEV: true },
|
|
143
|
+
plugins: [ myPlugin ],
|
|
144
|
+
platform: "neutral",
|
|
145
|
+
format: "esm",
|
|
146
|
+
target: "es2020",
|
|
147
|
+
loader: { ".svg": "file" },
|
|
148
|
+
mainFields: [ "module", "main" ],
|
|
149
|
+
watch: { paths: [ "public" ], events: [ "change" ] }
|
|
150
|
+
})
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
After build: `context.packages`, `context.dependencies` (from metafile).
|
|
154
|
+
|
|
155
|
+
### Copier
|
|
156
|
+
|
|
157
|
+
Copies files or directories. Watches and syncs on change.
|
|
158
|
+
|
|
159
|
+
```javascript
|
|
160
|
+
new Copier({
|
|
161
|
+
targets: [
|
|
162
|
+
[ "public", "dist/public" ],
|
|
163
|
+
[ "assets", "dist/assets" ]
|
|
164
|
+
]
|
|
165
|
+
})
|
|
7
166
|
```
|
|
8
167
|
|
|
9
|
-
|
|
168
|
+
- `targets` — `[[src, dest], ...]` or `[src, dest]` for a single pair
|
|
169
|
+
- Other stages can push to `context.targets` (Map) before Copier runs
|
|
170
|
+
- Watch: add/change → copy, addDir → mkdir, unlink/unlinkDir → rm
|
|
10
171
|
|
|
11
|
-
|
|
12
|
-
|
|
172
|
+
### Bundler
|
|
173
|
+
|
|
174
|
+
Creates a zip archive from targets.
|
|
175
|
+
|
|
176
|
+
```javascript
|
|
177
|
+
new Bundler({
|
|
178
|
+
target: "dist",
|
|
179
|
+
targets: [ [ "dist", ".", false, false ] ],
|
|
180
|
+
destDir: "release",
|
|
181
|
+
name: "my-app-1.0.0",
|
|
182
|
+
getName: (ctx) => `${ctx.packageJSON.name}-${ctx.packageJSON.version}`,
|
|
183
|
+
compressionLevel: "high",
|
|
184
|
+
onDone: (path) => console.log("Bundle:", path)
|
|
185
|
+
})
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
- `target` / `targets` — `src` or `[src, relativeDest?, shouldCompress?, shouldRemove?]`
|
|
189
|
+
- Uses `context.targets` (array) from other stages
|
|
190
|
+
- `compressionLevel`: `"high"` \| `"medium"` \| `"low"`
|
|
191
|
+
|
|
192
|
+
### NodeProcess
|
|
193
|
+
|
|
194
|
+
Runs Node.js with dev-friendly flags.
|
|
195
|
+
|
|
196
|
+
```javascript
|
|
197
|
+
new NodeProcess({
|
|
198
|
+
entry: "dist/index.js",
|
|
199
|
+
inspect: true,
|
|
200
|
+
enableSourceMaps: true,
|
|
201
|
+
traceWarnings: true,
|
|
202
|
+
traceUncaught: true,
|
|
203
|
+
args: [ "--experimental-vm-modules" ],
|
|
204
|
+
watch: { paths: [ "dist" ] }
|
|
205
|
+
})
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
### BunProcess
|
|
209
|
+
|
|
210
|
+
Runs Bun.
|
|
211
|
+
|
|
212
|
+
```javascript
|
|
213
|
+
new BunProcess({
|
|
214
|
+
entry: "src/index.ts",
|
|
215
|
+
inspect: false,
|
|
216
|
+
hot: true,
|
|
217
|
+
smol: false,
|
|
218
|
+
args: [],
|
|
219
|
+
watch: { paths: [ "src" ] }
|
|
220
|
+
})
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
### ChildProcess (base)
|
|
224
|
+
|
|
225
|
+
Base for custom process stages.
|
|
226
|
+
|
|
227
|
+
```javascript
|
|
228
|
+
new ChildProcess({
|
|
229
|
+
command: "my-cli",
|
|
230
|
+
args: [ "--flag" ],
|
|
231
|
+
cwd: process.cwd(),
|
|
232
|
+
env: { CUSTOM: "1" },
|
|
233
|
+
watchdog: true,
|
|
234
|
+
checkIfRunning: false,
|
|
235
|
+
filterStdout: [ "noise" ],
|
|
236
|
+
filterStderr: [ "deprecated" ],
|
|
237
|
+
stopTimeout: 3000,
|
|
238
|
+
killTimeout: 1000,
|
|
239
|
+
isDetached: false
|
|
240
|
+
})
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
### MongodProcess
|
|
244
|
+
|
|
245
|
+
Starts MongoDB. Skips if already running.
|
|
246
|
+
|
|
247
|
+
```javascript
|
|
248
|
+
new MongodProcess({
|
|
249
|
+
config: "/usr/local/etc/mongod.conf",
|
|
250
|
+
args: [],
|
|
251
|
+
watch: { paths: [ "config" ] }
|
|
252
|
+
})
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
### NginxProcess
|
|
256
|
+
|
|
257
|
+
Starts nginx. Uses `nginx -s stop` on exit.
|
|
258
|
+
|
|
259
|
+
```javascript
|
|
260
|
+
new NginxProcess({
|
|
261
|
+
config: "nginx.conf",
|
|
262
|
+
args: [],
|
|
263
|
+
watch: { paths: [ "nginx.conf" ] }
|
|
264
|
+
})
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
### PackageJSONMaker
|
|
268
|
+
|
|
269
|
+
Generates a minimal `package.json` with selected dependencies.
|
|
270
|
+
|
|
271
|
+
```javascript
|
|
272
|
+
new PackageJSONMaker({
|
|
273
|
+
src: ".",
|
|
274
|
+
dest: "dist",
|
|
275
|
+
dependenciesOf: [ "esbuild" ],
|
|
276
|
+
dependencies: [ "chalk", "ora" ],
|
|
277
|
+
symlinkNodeModules: true,
|
|
278
|
+
overrides: { "engines": { "node": ">=18" } }
|
|
279
|
+
})
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
- `dependenciesOf` — Stage IDs to pull dependencies from (e.g. `["esbuild"]`)
|
|
283
|
+
- `dependencies` — Array of names or `() => string[]`
|
|
284
|
+
- `symlinkNodeModules` — Symlink instead of copy (for dev)
|
|
285
|
+
|
|
286
|
+
### Reveal
|
|
287
|
+
|
|
288
|
+
Opens a path in the system file manager (Finder, Explorer, nautilus, etc.).
|
|
289
|
+
|
|
290
|
+
```javascript
|
|
291
|
+
new Reveal({
|
|
292
|
+
target: "dist",
|
|
293
|
+
noTargetPhrase: "Nothing to show"
|
|
294
|
+
})
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
Uses `target` or `context.target` if set.
|
|
298
|
+
|
|
299
|
+
## Utils
|
|
300
|
+
|
|
301
|
+
Exported helpers:
|
|
302
|
+
|
|
303
|
+
| Export | Description |
|
|
304
|
+
|--------|-------------|
|
|
305
|
+
| `env(dirName?, envName?)` | Load `.env` with `${VAR}` interpolation, `.env.local`, `.env.{NODE_ENV}` |
|
|
306
|
+
| `log(message, type?, title?, bold?)` | Console output; `log.progress()`, `log.finish()` |
|
|
307
|
+
| `Packages` | Package.json, workspace, external/local resolution |
|
|
308
|
+
| `getCurrentCommitId(short?)` | Current git commit |
|
|
309
|
+
| `reveal(path)` | Open path in file manager |
|
|
310
|
+
| `rawImportPlugin()` | esbuild plugin for `?raw` imports |
|
|
311
|
+
| `copyRecursive`, `pathExists`, `isRunning` | File utilities |
|
|
312
|
+
|
|
313
|
+
## Workspace & Multi-Entrypoint
|
|
314
|
+
|
|
315
|
+
For monorepos, use `Entrypoints` to orchestrate multiple conveyer files. Dependencies are inferred from `scripts.build` in package.json.
|
|
316
|
+
|
|
317
|
+
```javascript
|
|
318
|
+
import { __Entrypoints as Entrypoints } from "cnvr";
|
|
319
|
+
|
|
320
|
+
new Entrypoints({ entrypointsWatchQueueDelay: 300 }, true);
|
|
321
|
+
```
|
|
322
|
+
|
|
323
|
+
## Custom Stage
|
|
324
|
+
|
|
325
|
+
```javascript
|
|
326
|
+
import { Stage } from "cnvr";
|
|
327
|
+
|
|
328
|
+
class MyStage extends Stage {
|
|
329
|
+
constructor(options) {
|
|
330
|
+
super({
|
|
331
|
+
symbol: "🔧",
|
|
332
|
+
title: "My Stage",
|
|
333
|
+
watch: "src/**",
|
|
334
|
+
...options
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
async do(isInitial, eventMap) {
|
|
339
|
+
// Your logic
|
|
340
|
+
}
|
|
341
|
+
}
|
|
13
342
|
```
|
|
343
|
+
|
|
344
|
+
## Transparency
|
|
345
|
+
|
|
346
|
+
- Runs locally — no external services, no data leaves your machine
|
|
347
|
+
- Peer: `tsx` for TypeScript conveyer files
|
|
348
|
+
- cnvr is maintained by one developer
|
package/dist/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import{existsSync as
|
|
2
|
-
`),foundClosing:!0,nextIndex:a+1};o.push(c)}return{value:s.slice(r).trim(),foundClosing:!1,nextIndex:a}}function
|
|
3
|
-
`).replaceAll(String.raw`\r`,"\r").replaceAll(String.raw`\t`," ").replaceAll(String.raw`\v`,"\v").replaceAll(String.raw`\b`,"\b").replaceAll(String.raw`\f`,"\f").replaceAll(String.raw`\"`,'"').replaceAll(String.raw`\\`,"\\"):a.replaceAll(String.raw`\'`,"'").replaceAll(String.raw`\\`,"\\")}else{let c=
|
|
4
|
-
${s?S.underline.bold(t):S.underline(t)}:`:""),i&&console.log(e==="error"?i.startsWith("Trace:")?S.blue(i):i.startsWith("Debugger")?`\u{1FAB2} ${i}`:S.red(i):i),U=t,H=setTimeout(vt
|
|
1
|
+
import{existsSync as Ae,readdirSync as ns,statSync as os}from"node:fs";import{isAbsolute as as,resolve as se}from"node:path";import{watch as cs}from"chokidar";import{sleep as Fe}from"@nesvet/n";import{copyFile as et,mkdir as tt,readdir as st,stat as it}from"node:fs/promises";import{join as de}from"node:path";async function P(i,e){(await it(i)).isDirectory()?(await tt(e,{recursive:!0}),await Promise.all((await st(i)).map(t=>P(de(i,t),de(e,t))))):await et(i,e)}import{readFileSync as rt,realpathSync as nt,statSync as ot}from"node:fs";import{basename as at,dirname as ct,isAbsolute as lt,resolve as fe}from"node:path";process._conveyerEnv={};var ht=process._conveyerEnv,me=new Set,ge=10;function pt(i){let e=!1,t="",s=!1;for(let r=0;r<i.length;r++){let n=i[r];if(s){s=!1;continue}if(n==="\\"){s=!0;continue}if(!e&&(n==='"'||n==="'"))e=!0,t=n;else if(e&&n===t)e=!1,t="";else if(!e&&n==="#")return r}return-1}function ut(i,e,t){let s=i[e],r=s.indexOf("=")+1,n=s.slice(r).trim().slice(3);if(n.endsWith(t))return{value:n.slice(0,-t.length),foundClosing:!0,nextIndex:e+1};let o=[n],a=e;for(;++a<i.length;){let c=i[a];if(c.trim().endsWith(t))return o.push(c.trim().slice(0,-t.length)),{value:o.join(`
|
|
2
|
+
`),foundClosing:!0,nextIndex:a+1};o.push(c)}return{value:s.slice(r).trim(),foundClosing:!1,nextIndex:a}}function dt(i){let e={...i},t=0,s=/\${([^}]+)}|\$([A-Z_a-z]\w*)/;for(;t<ge;){t++;let r=JSON.stringify(e),n={};for(let[a,c]of Object.entries(e)){if(!c.includes("$")){n[a]=c;continue}let h=c.replaceAll(/\${([^}]+)}|\$([A-Z_a-z]\w*)/g,(v,z,g)=>{let y=z||g,x=y,E,O=y.indexOf(":-");O!==-1&&(E=y.slice(O+2),x=y.slice(0,O));let W=e[x]??process.env[x];if(W!==void 0)return W;if(E!==void 0)return E;throw new Error(`Undefined variable '${x}' in value for key '${a}'`)});n[a]=h}e=n;let o=JSON.stringify(e);if(r===o){if(s.test(o))throw new Error("Interpolation cycle detected");return e}}throw new Error(`Interpolation cycle detected or max passes (${ge}) exceeded.`)}function ft(i){let e={},t=i.split(/\r?\n/),s=0;for(;s<t.length;){let r=t[s].trim();if(!r||r.startsWith("#")){s++;continue}r.startsWith("export ")&&(r=r.slice(7).trim());let n=r.indexOf("=");if(n===-1)throw new Error(`Invalid line without '=' at line ${s+1}`);let o=r.slice(0,n).trim();if(!o||!/^[A-Z_a-z]\w*$/.test(o))throw new Error(`Invalid key '${o}' at line ${s+1}`);let a=r.slice(n+1).trim();if(a.startsWith('"""')||a.startsWith("'''")){let c=a.slice(0,3),h=ut(t,s,c);if(h.foundClosing)({value:a}=h);else throw new Error(`Unclosed triple quotes for key '${o}' starting at line ${s+1}`);s=h.nextIndex}else{if(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'")){let[c]=a;a=a.slice(1,-1),a=c==='"'?a.replaceAll(String.raw`\n`,`
|
|
3
|
+
`).replaceAll(String.raw`\r`,"\r").replaceAll(String.raw`\t`," ").replaceAll(String.raw`\v`,"\v").replaceAll(String.raw`\b`,"\b").replaceAll(String.raw`\f`,"\f").replaceAll(String.raw`\"`,'"').replaceAll(String.raw`\\`,"\\"):a.replaceAll(String.raw`\'`,"'").replaceAll(String.raw`\\`,"\\")}else{let c=pt(a);c!==-1&&(a=a.slice(0,c).trim()),a=a.replaceAll(String.raw`\#`,"#")}s++}e[o]=a}return dt(e)}function we(i){let e=i.find(t=>ot(t,{throwIfNoEntry:!1})?.isFile());if(e&&(e=nt(e),!me.has(e))){me.add(e);try{let t=rt(e,"utf8");t.codePointAt(0)===65279&&(t=t.slice(1));let s=ft(t),r=ht[at(e)]={dir:ct(e),vars:Object.keys(s)};for(let[n,o]of Object.entries(s))process.env[n]=o,r.vars.push(n)}catch(t){throw new Error(`Failed to parse environment variables in ${e}`,{cause:t})}}}function A(i,e=""){let t=i?lt(i)?[i]:(/\.env(?:\W|$)|(?:\W|^)env\./.test(i)?[i,...i.startsWith(".")?[]:[`.${i}`]]:[`${i}.env`,...i.startsWith(".")?[]:[`.${i}.env`],`.env.${i}`]).map(s=>fe(e,s)):[fe(e,".env")];we(t),we(t.map(s=>`${s}.local`))}function F(i=p.getClosestPackageDir(process.argv[1]),e){let{argv:t}=process;A("",i);let s=process.env.NODE_ENV,r=t.includes("--development")||t.includes("-d"),n=t.includes("--production")||t.includes("-p"),o=process.env.npm_lifecycle_event==="build"||t.includes("--build"),a=s;(!a||r||n)&&(r?a="development":n||o?a="production":a="development"),a&&A(a,i);for(let c=2;c<t.length;c++)(t[c]==="-e"||t[c]==="--env")&&t[c+1]&&A(t[++c],i);e&&A(e,i),process.env.NODE_ENV=a}import{readFile as ve}from"node:fs/promises";async function ye(i=!1){let e;try{let t=(await ve(".git/HEAD","utf8")).trim();e=t.startsWith("ref: ")?(await ve(`.git/${t.slice(5)}`,"utf8")).trim():t}catch{}return e&&i?e.slice(0,8):e}import mt from"node:child_process";function M(i){let e={darwin:"ps -ax",linux:"ps -A",win32:"tasklist"}[process.platform];return e?new Promise((t,s)=>{mt.exec(e,(r,n)=>{r?s(r):t(n.toLowerCase().includes(i.toLowerCase()))})}):!1}import gt from"node:readline/promises";import S from"chalk";import wt from"ora";var vt=600*1e3,U="",H=null,yt=()=>U=null,xt=new gt.Readline(process.stdout);async function l(i,e="info",t="",s=!1){clearTimeout(H),await xt.clearLine(0).cursorTo(0).commit(),U!==t&&console.log(t?`
|
|
4
|
+
${s?S.underline.bold(t):S.underline(t)}:`:""),i&&console.log(e==="error"?i.startsWith("Trace:")?S.blue(i):i.startsWith("Debugger")?`\u{1FAB2} ${i}`:S.red(i):i),U=t,H=setTimeout(yt,vt),H.unref()}var xe=Symbol("props"),f;l.progress=async function({title:i="",symbol:e,spinner:t},s,r){f&&this.finish(null,!0),await this(null,null,s,r);let{spinner:n,color:o=u.colors.random(),indent:a=0,outdent:c=0}=u.get(t),h=i&&c?(c>0?" ":"\b").repeat(Math.abs(c)):"";f=wt({spinner:n,color:o,indent:a,text:`${h}${i}`,stream:process.stdout}).start();let v=0;f[xe]={symbol:e,title:i,startAt:Date.now(),interval:setInterval(()=>f.text=`${h}${i} ${S.dim(++v)}`,1e3)}};l.finish=function(i,e){if(f){let{symbol:t,title:s,startAt:r,interval:n}={...f[xe],...i};if(clearInterval(n),e)f.stop();else{f.indent=0;let o=(Date.now()-r)/1e3;f.stopAndPersist({symbol:t,text:`${s}${o?`${s?" ":""}${S.dim(o)}`:""}`})}f=null}};import{existsSync as bt}from"node:fs";import{delimiter as be,dirname as kt,join as ke}from"node:path";import{unique as Pt}from"@nesvet/n";function _(){let i=[],e=process.cwd();for(let t=e;;){bt(ke(t,"package.json"))&&i.push(ke(t,"node_modules"));let s=kt(t);if(t===s)break;t=s}process.env.NODE_PATH=Pt([...process.env.NODE_PATH?.split(be)??[],...i.sort()]).join(be)}var u=[{spinner:"dots",indent:1},{spinner:"dots2",indent:1},{spinner:"dots3",indent:1},{spinner:"dots4",indent:1},{spinner:"dots5",indent:1},{spinner:"dots6",indent:1},{spinner:"dots7",indent:1},{spinner:"dots8",indent:1},{spinner:"dots9",indent:1},{spinner:"dots10",indent:1},{spinner:"dots12"},{spinner:"dots8Bit",indent:1},{spinner:"line",indent:1},{spinner:"pipe",indent:1},{spinner:"star",indent:1},{spinner:"star2",indent:1},{spinner:"growVertical",indent:1},{spinner:"balloon",indent:1},{spinner:"noise",indent:1},{spinner:"boxBounce",indent:1},{spinner:"boxBounce2",indent:1},{spinner:"triangle",indent:1},{spinner:"squareCorners",indent:1},{spinner:"circleQuarters",indent:1},{spinner:"circleHalves",indent:1},{spinner:"toggle13",indent:1},{spinner:"arrow",indent:1},{spinner:"arrow2"},{spinner:"smiley",outdent:-1},{spinner:"monkey",outdent:-1},{spinner:"hearts"},{spinner:"clock",outdent:-1},{spinner:"earth",outdent:-1},{spinner:"moon",outdent:-1},{spinner:"runner",outdent:-1},{spinner:"weather"},{spinner:"christmas"},{spinner:"layer",indent:1},{spinner:"fingerDance",outdent:-1},{spinner:"mindblown",outdent:-1},{spinner:"speaker",outdent:-1},{spinner:"orangePulse",outdent:-1},{spinner:"bluePulse",outdent:-1},{spinner:"orangeBluePulse",outdent:-1},{spinner:"timeTravel",outdent:-1}],St=["dots","dots2","dots3","dots4","dots5","dots6","dots7","dots8","dots9","dots10","dots12","dots8Bit"],$t=["line","pipe","star","star2","growVertical","balloon","noise","boxBounce","boxBounce2","triangle","squareCorners","circleQuarters","circleHalves","toggle13","arrow","layer"],Et=["arrow2","smiley","monkey","hearts","clock","earth","moon","runner","weather","christmas","fingerDance","mindblown","speaker","orangePulse","bluePulse","orangeBluePulse","timeTravel"];for(let i of u)u[i.spinner]=i;function N(){return this[this.length*Math.random()|0]}u.random=N;u.get=function(i){return!i||i==="dots"?u[N.call(St)]:i==="simple"?u[N.call($t)]:i==="emoji"||i==="emojis"?u[N.call(Et)]:i==="random"?u.random():u[i]??u[0]};u.colors=["red","green","yellow","blue","magenta","cyan"];u.colors.random=N;import{readFile as Ot}from"node:fs/promises";import{watch as Nt}from"chokidar";var $={},Se=new Set;async function $e(){Object.assign($,JSON.parse(await Ot("package.json","utf8")));for(let i of Se)i($)}await $e();var Pe;function Ee(i){return Pe??=Nt("package.json",{ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:500,pollInterval:50}}).on("change",$e),i&&Se.add(i),Pe}import{spawn as It}from"node:child_process";import{existsSync as Y,readFileSync as Rt,statSync as Oe}from"node:fs";import{readFile as Dt}from"node:fs/promises";import{dirname as I,isAbsolute as Tt,join as K,resolve as R,sep as Ct}from"node:path";import w from"chalk";import Ne from"micromatch";import Z from"resolve-package-path";import{gt as Wt,satisfies as jt,validRange as At}from"semver";import{getPath as Ft,noop as Mt,setPath as _t}from"@nesvet/n";var Jt=/\/node_modules\//,Ie=/(?:@[\da-z~-][\d._a-z~-]*\/)?[\da-z~-][\d._a-z~-]*/,Lt=new RegExp(`^${Ie.source}$`),qt=new RegExp(`^(${Ie.source})/.+$`),J=new Map,X=class i{constructor({name:e,version:t,path:s,props:r,isSource:n,isLocal:o,...a}){if(Object.assign(this,{name:e,version:t,path:s,...n?{isSource:n}:o?{isLocal:o}:{isExternal:!0}}),r)for(let c of r){let h=Ft(a,c);h&&_t(this,c,h)}p.all.set(e,this)}async rebuild(){for(let e of["prebuild","build","postbuild"])this.scripts[e]&&await new Promise((t,s)=>{let[r,...n]=this.scripts[e].split(/\s+/);It(r,n,{cwd:this.path}).on("exit",t).on("error",s)})}bumpVersion(){return i.bumpVersion(this)}static bumpVersion=Mt};function Re(i,e,t){t&&(e.sourcePath=i);let{map:s,localMatcher:r,externalMatcher:n,dev:o,optional:a,peer:c,props:h,unresolvedDependencies:v,versionMismatches:z}=e,{name:g,dependencies:y,devDependencies:x,optionalDependencies:E,peerDependencies:O,...W}=p.getParsedPackageJSON(K(i,"package.json"));if(!s.has(g)){let pe=r?.(g)||!Jt.test(i)&&!n?.(g),Xe=new X({name:g,...W,path:i,props:h,isSource:t,isLocal:pe});if(s.set(g,Xe),t||pe){let ue={...y,...o&&x,...a&&E,...c&&O};for(let j of Object.keys(ue)){let G=[i,e.sourcePath,process.env.CONVEYER_PROJECT_ROOT,process.env.CONVEYER_WORKSPACE_ROOT].reduce((b,k)=>b||k&&Z(j,k),null);if(G){let b=ue[j],k=p.getParsedPackageJSON(G).version;if(b&&k)try{At(b)&&!jt(k,b)&&z.push({consumer:g,dependency:j,declared:b,actual:k})}catch{}Re(I(G),e)}else v.set(j,g)}}}}function Vt(i,e){return i.name>e.name?1:e.name>i.name?-1:0}var L=class i extends Map{#e=null;get local(){return this.#e??=new i([...this.entries()].filter(([,e])=>e.isLocal))}#t=null;get external(){return this.#t??=new i([...this.entries()].filter(([,e])=>e.isExternal))}#s=null;get sources(){return this.#s??=new i([...this.entries()].filter(([,e])=>e.isSource))}pick(e){let t=new i;for(let s of e){let r=this.get(s);r&&t.set(r.name,r)}return t}metaPick(e){return this.pick(Object.values(e.outputs).flatMap(({imports:t})=>t.filter(({path:s,kind:r,external:n})=>n&&r==="import-statement"&&!s.startsWith("node:")).map(({path:s})=>s.replace(qt,"$1"))))}#i=null;get#r(){return this.#i??=[...this.values()].filter(e=>!e.isSource)}asNames(){return this.#r.map(e=>e.name).sort()}asPaths(){return this.#r.map(e=>e.path)}asDependencies(){return this.#r.sort(Vt).reduce((e,t)=>((!e[t.name]||Wt(t.version,e[t.name]))&&(e[t.name]=t.version),e),{})}verifyExternal(e,t){let s=[],r=Object.keys(e.inputs).map(n=>R(t,n));for(let n of this.values())r.some(o=>o.startsWith(`${n.path}${Ct}`))&&s.push(n.name);if(s.length)throw new Error(`The following packages were declared as ${w.italic("external")} but were bundled anyway:
|
|
5
5
|
${s.map(n=>` ${w.bold(n)}`).join(`
|
|
6
|
-
`)}`)}clear(){super.clear(),this.#e=null,this.#t=null,this.#s=null,this.#i=null}static unite(...e){return new i(e.flatMap(t=>[...t]))}},p=class i extends
|
|
6
|
+
`)}`)}clear(){super.clear(),this.#e=null,this.#t=null,this.#s=null,this.#i=null}static unite(...e){return new i(e.flatMap(t=>[...t]))}},p=class i extends L{constructor({sources:e=[process.cwd()],local:t,external:s,...r}={}){super();let n={map:this,localMatcher:t&&Ne.matcher(t,{dot:!0}),externalMatcher:s&&Ne.matcher(s,{dot:!0}),unresolvedDependencies:new Map,versionMismatches:[],...r};for(let o of e)Re(o,n,!0);if(n.unresolvedDependencies.size)throw new Error(`Could not resolve the following dependencies:
|
|
7
7
|
${[...n.unresolvedDependencies].map(([o,a])=>` ${w.bold(o)} ${w.italic(`(required by ${a})`)}`).join(`
|
|
8
|
-
`)}`);for(let{consumer:o,dependency:a,declared:c,actual:h}of n.versionMismatches)console.warn(`\u26A0\uFE0F Version Mismatch: ${w.bold(o)} wants ${w.bold(a)}@${w.underline(c)}, but resolved to ${w.underline(h)}`)}static of(e,t){return new i({sources:e,...t})}static nameRegExp=Jt;static metaFileNames(e,t){let s=t?r=>R(t,r):r=>R(r);return Object.values(e.outputs).filter(r=>r.entryPoint).flatMap(r=>Object.keys(r.inputs).map(s))}static getClosestPackageDir(e){for(Dt(e)||(e=R(e)),Oe(e).isFile()&&(e=I(e));!Y(K(e,"package.json"));){let t=I(e);if(e===t){e=null;break}else e=t}return e}static findWorkspaceRoot(e){let t=R(e);for(Y(t)&&Oe(t).isFile()&&(t=I(t));t;){let s=K(t,"package.json");if(Y(s)&&this.getParsedPackageJSON(s)?.workspaces)return t;let r=I(t);if(t===r)break;t=r}return null}static resolvePath(e,t="."){return Z(e,t)}static async resolveAndRead(e,t="."){return JSON.parse(await Rt(Z(e,t),"utf8"))}static getParsedPackageJSON(e){if(J.has(e))return J.get(e);let{name:t,version:s,dependencies:r,devDependencies:n,optionalDependencies:o,peerDependencies:a,scripts:c,workspaces:h}=JSON.parse(It(e,"utf8")),v={name:t,version:s,dependencies:r,devDependencies:n,optionalDependencies:o,peerDependencies:a,...h&&{workspaces:h},...c&&(c.prebuild||c.build||c.postbuild)&&{scripts:{...c.prebuild&&{prebuild:c.prebuild},...c.build&&{build:c.build},...c.postbuild&&{postbuild:c.postbuild}}}};return J.set(e,v),v}static all=new q;static clearCache(){J.clear(),this.all.clear()}};import{access as Vt}from"node:fs/promises";async function De(i){try{return await Vt(i),!0}catch{return!1}}import{createRequire as Bt}from"node:module";var Fi=Bt(import.meta.url);import{spawn as ee}from"node:child_process";import{once as Qt}from"node:events";import{existsSync as zt,statSync as Gt}from"node:fs";import{dirname as Ht,resolve as Ut}from"node:path";import{noop as Yt}from"@nesvet/n";async function Te(i){if(i=Ut(i),!zt(i))return console.error("Path does not exist:",i);try{await new Promise((e,t)=>{switch(process.platform){case"win32":ee("explorer",["/select,",i]).on("error",t).on("exit",e);break;case"darwin":ee("open",["-R",i]).on("error",t).on("exit",e);break;case"linux":(async()=>{let s=Gt(i).isDirectory()?i:Ht(i);for(let[r,...n]of[["nautilus","--select",i],["dolphin","--select",i],["nemo",s],["thunar",s],["xdg-open",s]])try{return await Qt(ee(r,n).on("error",Yt),"exit"),e()}catch{}t()})();break;default:t()}})}catch{console.log(i)}}F(process.cwd());(process.argv.includes("--force")||process.argv.includes("-f"))&&(process.env.FORCE="true");import Kt from"node:child_process";import Ce from"node:fs";import We from"node:path";import D from"chalk";import{RequestListener as Zt,RequestSender as Xt}from"process-request";import{debounce as es}from"@nesvet/n";var ts=["The `punycode` module is deprecated"],L=class i{constructor(e,t,s=!1){V.push(e),this.conveyerFileName=e,this.entrypoints=t,this.isTarget=s,this.conveyerName=We.basename(this.conveyerFileName).replace(/\.conveyer\.(?:[cm]?j|t)s$/,"").replace(/^\./,"");let{sources:r,local:n}=new p({sources:[p.getClosestPackageDir(this.conveyerFileName)],dev:!0,optional:!0,props:["scripts.prebuild","scripts.build","scripts.postbuild"]});[this.package]=[...r.values()],this.dependencies=n;for(let o of this.dependencies.values())if(o.scripts?.build){let a=/\S*\.conveyer(?:\.(?:[cm]?j|t)s)?/.exec(o.scripts.build)?.[0];if(a){if(a=We.resolve(o.path,a),/\.(?:[cm]?j|t)s$/.test(a))Ce.existsSync(a)||(a=void 0);else{let c;for(let h of T){if(c=`${a}.${h}`,Ce.existsSync(c))break;c=void 0}a=c}a&&!V.includes(a)&&new i(a,this.entrypoints)}else new te(o,this.entrypoints)}this.title=`${this.package.name}${this.conveyerName?`/${this.conveyerName}`:""}`,this.entrypoints.set(this.conveyerFileName,this)}#e;init(){if(!this.conveyerProcess)return new Promise(e=>{this.#e=e,this.conveyerProcess=Kt.fork(this.conveyerFileName,this.entrypoints.otherArgs,{cwd:this.package.path,env:{...process.env,IS_ENTRYPOINT:!0,...this.isTarget&&{IS_ENTRYPOINT_TARGET:!0}},stdio:"pipe"}),this.conveyerProcess.stdout.on("data",this.#t),this.conveyerProcess.stderr.on("data",this.#s),this.conveyerProcess.on("error",this.#i),this.conveyerProcess.on("exit",this.#r),this.requestSender=new Xt(this.conveyerProcess),new Zt(this.conveyerProcess,this.#n)})}async reinit(){await new Promise(e=>{this.resolveExited=e,this.conveyerProcess?.kill("SIGINT")}),await this.init()}#t=e=>l(e.toString().trim(),"info",this.title);#s=async e=>{let t=e.toString().trim();for(let s of ts)if(t.includes(s))return;await l(t,"error",this.title)};#i=e=>l(`\u2757\uFE0F ${D.bold(this.title)}: ${e}`,"error");#r=()=>{delete this.conveyerProcess,this.resolveExited?.(),l(`\u{1F6AA} ${D.bold(this.title)} conveyer exited`)};#n={init:(e={},t)=>(this.options=e,this.initAt=Date.now(),l.progress({symbol:"\u{1F300}",title:`${this.package.version} ${D.dim(t)}`},this.title,this.isTarget)),inited:()=>{l.finish(),this.#e?.()},beginStage:e=>l.progress(e,this.title),doneStage:e=>l.finish(e),logFinish:e=>l.finish(e),enqueueWatch:es(()=>this.entrypoints.enqueueWatch(this),100)};async run(){try{return await this.requestSender.send("run"),await l(`\u2714\uFE0F ${D.underline("Passed")} ${D.bold.dim((Date.now()-this.initAt)/1e3)}`,"info",this.title)}catch{return l.finish()}}watch(){return this.requestSender.send("watch")}runWatchQueue(){return this.requestSender.send("runWatchQueue")}},te=class{constructor(e,t){this.package=e,this.entrypoints=t,this.entrypoints.buildableDependencies.set(this.package.path,this)}async run(){await l.progress({symbol:"\u{1F3D7}\uFE0F "},this.package.name);try{await this.package.rebuild(),l.finish()}catch(e){l.finish(),await l(e.stack,"error")}}watch(){}};var{FORCE:Fe}=process.env,T=["js","cjs","mjs","ts"],os=new RegExp(String.raw`^\.conveyer\.(${T.join("|")})$`),as=[["-e","--env"]].flat(),V=[],ie=class i extends Map{constructor({entrypointsWatchQueueDelay:e}={},t){super(),e&&(this.#t=e);let s=[];for(let o=2,{length:a}=process.argv;o<a;o++){let c=process.argv[o];c.startsWith("-")?(this.otherArgs.push(c),as.includes(c)&&this.otherArgs.push(process.argv[++o])):s.push(c)}let r=i.getConveyerFiles(s);if(!r)return l("\u274C No valid conveyer entrypoints","error");let n=p.getClosestPackageDir(r[0]);if(n){process.env.CONVEYER_PROJECT_ROOT=n;let o=n&&p.findWorkspaceRoot(n);o&&(process.env.CONVEYER_WORKSPACE_ROOT=o)}for(let o of r)V.includes(o)||new L(o,this,!0);process.on("SIGINT",()=>process.exit(0)),t&&this.run()}otherArgs=[];buildableDependencies=new Map;#e=new Set;#t=300;#s=!1;async run(){for(let e of this.values())await e.init();for(let e of Fe?[...this.buildableDependencies.values(),...this.values()]:this.values())(e.isTarget||Fe)&&await e.run();await Ae(1e3),await l("\u{1F440} Watching packages");for(let e of[...this.buildableDependencies.values(),...this.values()])await e.watch(),await l(` \u23A3 ${e.package.name}`);ns([...this.keys()],{ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:500,pollInterval:50}}).on("change",async e=>{let t=this.get(e);await t.reinit(),await t.run(),await t.watch()})}enqueueWatch(e){this.#e.add(e),this.#s||this.runEntrypointsWatchQueue()}async runEntrypointsWatchQueue(){for(this.#s=!0;this.#e.size;)for(let e of this.values())this.#e.has(e)&&(await e.runWatchQueue(),this.#e.delete(e),await Ae(this.#t));this.#s=!1}static{_();let e=process.cwd();this.getConveyerFiles=t=>{t.length||t.push(e);let s=[];for(let r of t){let n=rs(r)?r:se(e,r),o=is(n,{throwIfNoEntry:!1});if(o?.isFile()){s.push(n);continue}if(o?.isDirectory()){let a=!1;for(let c of ss(n))if(os.test(c)){s.push(se(n,c)),a=!0;break}if(!a)for(let c of T){let h=se(n,".conveyer",`index.${c}`);if(je(h)){s.push(h);break}}continue}for(let a of T){let c=`${n}.conveyer.${a}`;if(je(c)){s.push(c);break}}}return s.length?s:null}}};import{randomBytes as fs}from"node:crypto";import{mkdir as ms,rm as re}from"node:fs/promises";import{basename as gs,join as ne}from"node:path";import{Worker as ws}from"node:worker_threads";import{COMPRESSION_LEVEL as vs,zip as ys}from"zip-a-folder";import{mkdir as cs,rm as ls,stat as hs}from"node:fs/promises";import{isAbsolute as ps,resolve as us}from"node:path";import{watch as ds}from"chokidar";var d=class{constructor({watch:e,initialCleanup:t,cwd:s=process.cwd(),...r}){if(e){let{paths:n,events:o,...a}={};typeof e=="string"?n=[e]:Array.isArray(e)?n=e:typeof e=="object"&&({paths:n,events:o,...a}=e),this.watchPaths=n?.filter(Boolean).map(c=>ps(c)?c:us(s,c)),this.watchOptions=a,this.watchEvents=o&&(Array.isArray(o)?o:[o])}Object.assign(this,{symbol:"\u{1F535}",initialCleanup:t?(Array.isArray(t)?t:[t]).filter(Boolean):!1,cwd:s,...r})}#e=new Map;handleInited(){return this.onInit?.()}async run(e,...t){try{if(e&&this.initialCleanup)for(let s of this.initialCleanup)try{(await hs(s)).isDirectory()&&(await ls(s,{recursive:!0,force:!0}),await cs(s,{recursive:!0}))}catch{}return await this.conveyer.beginStage({spinner:this.spinner,symbol:this.symbol,title:this.title}),await this.onBefore?.(e,...t),await this.do(e,...t),await this.onAfter?.(e,...t),await this.conveyer.doneStage(),!0}catch(s){return console.error(`\u2757\uFE0F${this.symbol} ${this.title} ${s.stack}`),!1}}#t=(e,t)=>(this.#e.set(t,e),this.conveyer.enqueueWatch(this));async watch(){if(this.watcher&&(await this.watcher.close(),delete this.watcher),this.watchEvents&&this.watchPaths){this.watcher=ds(this.watchPaths,{ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:500,pollInterval:50},followSymlinks:!1,...this.watchOptions});for(let e of this.watchEvents)this.watcher.on(e,e==="all"?this.#t:(...t)=>this.#t(e,...t));this.watcher.on("error",e=>console.error(`\u2757\uFE0F${this.symbol} ${this.title} watcher ${e.stack}`))}return this.watcher}async runWatchQueue(){for(;this.#e.size;){let e=[...this.#e];this.#e.clear(),await this.run(!1,e)}}};function xs(){return`${this.conveyer.context.packageJSON.name}-${this.conveyer.context.packageJSON.version}`}var Me=class i extends d{constructor(e={}){super({symbol:"\u{1F4E6}",title:"Bundler",getName:xs,compressionLevel:"high",...e})}handleInited(){return this.context.targets=[],super.handleInited()}async do(){let e=[this.target,...this.targets??[],...this.context?.targets??[]].filter(Boolean);if(!e.length)return;let t=ne(this.destDir,`bundle-${Date.now().toString(36)}${fs(12).toString("hex")}`);await ms(t,{recursive:!0});let s=ne(this.destDir,`${this.name||this.getName(this)}.zip`);await re(s,{force:!0}),await Promise.all(e.map(async r=>{let[n,o,a,c]=Array.isArray(r)?r:[r],h=ne(t,o??gs(n));await(a?i.#e({src:n,dest:`${h}.zip`}):P(n,h)),c&&await re(n,{recursive:!0,force:!0})})),await ys(t,s,{compression:vs[this.compressionLevel]}),await re(t,{recursive:!0,force:!0}),this.onDone?.(s)}static#e({src:e,dest:t}){return new Promise((s,r)=>{new ws(new URL("./zip-worker.js",import.meta.url),{workerData:{src:e,dest:t}}).once("message",s).once("error",r).once("exit",n=>n?r(new Error(`Worker stopped with code ${n}`)):s())})}};import{execSync as bs,spawn as ks}from"node:child_process";import{parse as _e}from"node:path";import{noop as Ps}from"@nesvet/n";var m=class extends d{constructor({command:e,watch:t,filterStdout:s,filterStderr:r,...n}){super({symbol:"\u2699\uFE0F ",title:`${e} process`,command:e,cwd:Object.values(process._conveyerEnv)[0]?.dir,watchdog:!0,checkIfRunning:!1,args:[],stdio:["ignore",s?"pipe":"inherit",r?"pipe":"inherit","ipc"],filterStdout:s,filterStderr:r,isDetached:!1,stopTimeout:3e3,killTimeout:1e3,...n,watch:{paths:[],events:["change"],...t}})}#e=null;#t=!1;#s=!1;async start(){this.checkIfRunning&&await M(this.command)?(this.stop=Ps,console.warn(`\u26A0\uFE0F${this.symbol} ${this.title} is already running`)):(this.#e=ks(this.command,this.args,{detached:this.isDetached,stdio:this.stdio,env:{...process.env,...this.env},cwd:this.cwd}),this.#e.on("exit",this.watchdog?this.#o:this.#a),this.stdio.includes("ipc")&&this.#e.on("message",this.#r),this.filterStdout&&this.#e.stdout.on("data",e=>{let t=e.toString();this.filterStdout.some(s=>t.includes(s))||process.stderr.write(t)}),this.filterStderr&&this.#e.stderr.on("data",e=>{let t=e.toString();this.filterStderr.some(s=>t.includes(s))||process.stderr.write(t)}))}stop(e){if(!this.#e)return;let t=this.#e;t.off("exit",this.#o);let s=typeof e=="string"&&e.startsWith("SIG")?e:"SIGTERM";return new Promise(r=>{if(t.exitCode!==null||t.signalCode!==null)this.#e=null,r();else{let n,o=()=>{clearTimeout(n),this.#e=null,r()};t.once("exit",o),t.once("error",o),this.#i(t,s),n=setTimeout(()=>{this.#i(t,"SIGKILL"),setTimeout(o,this.killTimeout)},this.stopTimeout)}})}#i(e,t){try{if(process.platform==="win32")t==="SIGKILL"?bs(`taskkill /pid ${e.pid} /T /F`,{stdio:"ignore"}):e.kill(t);else if(this.isDetached)try{process.kill(-e.pid,t)}catch{}else e.kill(t)}catch{}}async do(){this.#e&&(this.#t=!0,await this.stop(),this.#t=!1),await this.start()}#r=e=>{try{let[t,...s]=e;this.#n[t].apply(this,s)}catch{}};#n={restart(e){if(e){for(let t of e){let s=new RegExp(`^${t.replace(/=.*$/,"")}(=|$)`),r=this.args.findIndex(n=>s.test(n));~r?this.args[r]=t:this.args.unshift(t)}e.length&&_e(e.at(-1)).root&&(this.args.length&&_e(this.args.at(-1)).root?this.args[this.args.length-1]=e.at(-1):this.args.push(e.at(-1)))}this.do()}};#a=()=>{this.#t||(this.#e=null,console.info(`\u{1F6AA}${this.symbol} ${this.title} exited`))};#o=()=>!this.#s&&!this.#t&&this.start()};var Je=class extends m{constructor({entry:e=".",inspect:t=!1,hot:s=!1,smol:r=!1,args:n=[],watch:o,...a}){super({symbol:"\u{1F35E}",title:"Bun",command:"bun",entry:e,args:["run",t&&`--inspect${typeof t=="string"?`=${t}`:""}`,s&&"--hot",r&&"--smol",e,...n].filter(Boolean),watchdog:!1,watch:{events:["change"],...o},...a})}};import{existsSync as Ss,readFileSync as $s}from"node:fs";import{readdir as Es,rm as Os}from"node:fs/promises";import oe from"node:path";import B from"chalk";import{RequestListener as Ns,RequestSender as Is}from"process-request";if(process.env.IS_ENTRYPOINT){if(process.env.WATCH="true",!process.env.IS_ENTRYPOINT_TARGET){process.env.npm_lifecycle_event="build";let i=process.argv.indexOf("--dev");if(~i&&process.argv.splice(i,1),delete process.env.DEV,!process.env.FORCE){let e=process.argv.indexOf("--build");~e&&process.argv.splice(e,1);let t=process.argv.indexOf("--bundle");~t&&process.argv.splice(t,1),delete process.env.BUILD,delete process.env.BUNDLE}}}else _();F();(process.env.npm_lifecycle_event==="dev"||process.argv.includes("--dev"))&&(process.env.DEV="true",process.env.WATCH="true");(process.env.npm_lifecycle_event==="build"||process.argv.includes("--build"))&&(process.env.BUILD="true");var ae=process.argv.find(i=>i.startsWith("--bundle"));ae&&(process.env.BUNDLE=ae.includes("=")?ae.split("=")[1]:"true");process.env.VERSION=$.version;process.env.GIT_COMMIT_ID=await ye();var{NODE_ENV:qe,WATCH:Rs,IS_ENTRYPOINT:Ds}=process.env,Ts=3,Le=class{constructor(e,t={}){let{initialCleanup:s,...r}=t;this.name=oe.basename(process.argv[1]).replace(/.conveyer(.(?:[cm]?j|t)s)?$/,"").replace(/^\./,""),this.options={context:this.context,initialCleanup:s?(Array.isArray(s)?s:[s]).filter(Boolean):!1,...r},this.isEntrypoint=!!Ds,Rs&&this.watchers.push(Ee(this.#e));let n=1;for(let o of e.flat(Ts))if(o){for(o.title||(o.title=o.constructor.name),o.id||(o.id=o.title.toLowerCase().replaceAll(/\W/g,""));this.stages.has(o.id);)o.id+=n;this.stages.set(o.id,o),o.conveyer=this,o.context=o.conveyer.context[o.id]={stage:o.constructor.name},n++}process.on("exit",o=>this.exit(o)),process.on("SIGINT",()=>this.exit("SIGINT")),process.on("SIGTERM",()=>this.exit("SIGTERM")),this.isEntrypoint&&(this.requestSender=new Is(process),new Ns(process,o=>this[o]())),this.init()}stages=new Map;context={conveyerVersion:JSON.parse($s(oe.join(p.getClosestPackageDir(import.meta.filename),"package.json"))).version,packageJSON:$};watchers=[];#e=({name:e,version:t})=>{this.title=`${e}${this.name?`/${this.name}`:""}`,this.version=t};async init(){this.#e($),this.isEntrypoint?this.requestSender.send("init",this.options,qe):(this.initAt=Date.now(),await l.progress({symbol:"\u{1F300}",title:`${B.bold(this.title)} ${this.version} ${B.dim(qe)}`}));for(let e of this.stages.values())await e.handleInited();return this.isEntrypoint?(this.requestSender.send("inited"),null):(l.finish(),this.run())}logFinish(e){return this.isEntrypoint?this.requestSender.send("logFinish",e):l.finish(e)}beginStage(e){return this.isEntrypoint?this.requestSender.send("beginStage",e):l.progress(e)}doneStage(e){return this.isEntrypoint?this.requestSender.send("doneStage",e):l.finish(e)}async run(){if(this.options.initialCleanup)for(let e of this.options.initialCleanup)Ss(e)&&await Promise.all((await Es(e)).map(t=>Os(oe.resolve(e,t),{recursive:!0,force:!0})));for(let e of this.stages.values())if(!await e.run(!0))throw this.isEntrypoint||l.finish(),await this.exit(),new Error(`Stage ${e.symbol} ${e.title} broke conveyer`);return this.isEntrypoint?null:l(`\u2714\uFE0F ${B.underline("Passed")} ${B.bold.dim((Date.now()-this.initAt)/1e3)}`)}async watch(){for(let e of this.stages.values())await e.watch(!0)}watchQueue=new Set;enqueueWatch(e){return this.watchQueue.add(e),this.requestSender.send("enqueueWatch")}async runWatchQueue(){for(;this.watchQueue.size;)for(let e of this.stages.values())this.watchQueue.has(e)&&(this.watchQueue.delete(e),await e.watchQueuePromise,e.watchQueuePromise=await e.runWatchQueue(),delete e.watchQueuePromise)}async exit(e){for(let t of this.stages.values())t.watchdog&&(t.isStopped=!0),await t.stop?.(e);process.exit()}};import{mkdir as Cs,rm as Ws,stat as js}from"node:fs/promises";import ce from"node:path";function As(i,e){return i[0]>e[0]?-1:i[0]<e[0]?1:0}var Ve=class extends d{constructor({targets:e,watch:t,...s}){typeof e[0]=="string"&&(e=[e]),super({symbol:"\u{1F6D2}",title:"Copier",targets:e,watch:{ignoreInitial:!0,events:["all"],...t},...s})}handleInited(){return this.context.targets=new Map,super.handleInited()}async copy(e,t){if(e){this.targets=new Map([...this.targets,...[...this.context.targets].map(s=>s.reverse())].filter(Boolean).map(([s,r])=>[ce.resolve(s),ce.resolve(r)]).sort(As)),this.watchPaths=[];for(let[s,r]of this.targets)if(await De(s))this.watchPaths.push(s),(await js(s)).isDirectory()&&this.watchPaths.push(`${s}/**`),await P(s,r);else throw new Error(`Path ${s} not exists`)}else if(t)for(let[s,r]of t){let n,o;for([n,o]of this.targets){if(n===s)break;if(s.indexOf(n)===0){o=ce.join(o,s.replace(n,""));break}}r==="add"||r==="change"?await P(s,o):r==="addDir"?await Cs(o,{recursive:!0}):(r==="unlink"||r==="unlinkDir"&&s!==n)&&await Ws(o,{recursive:!0,force:!0})}}do=this.copy};import Q from"node:path";import*as ze from"esbuild";import{jscc as Fs}from"esbuild-plugin-jscc";import{unique as Ms}from"@nesvet/n";var{NODE_ENV:Be,WATCH:le,SOURCEMAPS:_s}=process.env,Qe=class extends d{constructor({jsx:e,jsxDev:t,alias:s,watch:r,local:n,...o}={}){super({symbol:"\u{1F528}",title:"esbuild",mainFields:["module","main"],loader:{".node":"file",".css":"text"},...Be==="production"&&{legalComments:"none",minify:!0,treeShaking:!0},...(le||_s)&&{sourcemap:"linked"},color:!0,...n&&{local:Array.isArray(n)?n:[n]},...o,jsx:e===!0?"automatic":e,jsxDev:t||e&&Be==="development",...s&&{alias:Object.fromEntries(Object.entries(s).map(([a,c])=>[a,Q.resolve(c)]))},watch:{paths:[],events:["change"],...r}})}async handleInited(){let e=Array.isArray(this.external)?this.external.filter(t=>typeof t=="string"):[];this.context.packages=new p({external:e,local:this.local}),this.external&&(this.external===!0||this.external.includes(!0))&&e.push(...this.context.packages.external.asNames()),this.define&&Object.values(this.define).some(t=>typeof t=="function")&&(this.define=Object.fromEntries(Object.entries(this.define).map(([t,s])=>[t,typeof s=="function"?s.call(this):s]))),this.buildContext=await ze.context({absWorkingDir:this.cwd,bundle:!0,entryPoints:this.entryPoints,loader:this.loader,jsx:this.jsx,jsxDev:this.jsxDev,external:e,mainFields:this.mainFields,nodePaths:[...process.env.NODE_PATH?.split(Q.delimiter)??[],...this.nodePaths??[]],outfile:this.outfile,alias:this.alias,define:this.define,plugins:[this.jsccValues&&Fs({values:this.jsccValues,ignore:this.jsccIgnore,sourceMap:!!this.sourcemap}),...this.plugins??[]].filter(Boolean),platform:this.platform,format:this.format,target:this.target,legalComments:this.legalComments,minify:this.minify,treeShaking:this.treeShaking,sourcemap:this.sourcemap,color:this.color,metafile:!0}),this.watchPaths=Ms(this.entryPoints.map(t=>Q.join(Q.dirname(t),"**")))}async#e(e){return e=e.filter(t=>!/\/node_modules\//.test(t)),this.watchPaths.join(",")!==e.join(",")?(this.watchPaths=e,this.watcher&&await this.watch(),!0):!1}async build(e){let{metafile:t}=await this.buildContext.rebuild();(this.local||this.external===!0||this.external?.includes(!0))&&this.context.packages.external.verifyExternal(t,this.cwd);let s;le&&(s=await this.#e(p.metaFileNames(t))),(e||s)&&(this.context.dependencies=this.context.packages.metaPick(t)),le||await this.buildContext.dispose()}do=this.build};var Js="/usr/local/etc/mongod.conf",Ge=class extends m{constructor(e={}){let{config:t,args:s=[],watch:r,...n}=e;super({symbol:"\u{1F33F}",title:"MongoDB",command:"mongod",args:["--config",t??Js,...s],checkIfRunning:!0,watch:t?{events:["change"],...r,paths:[t,...r?.paths??[]]}:!1,watchdog:!1,...n})}};import qs from"node:child_process";var Ls=250,He=class extends m{constructor(e={}){let{config:t,args:s=[],watch:r,...n}=e;super({symbol:"\u{1F578} ",title:"nginx",command:"nginx",args:[...t?["-c",t]:[],...s],checkIfRunning:!0,watch:t&&{events:["change"],...r,paths:[t,...r?.paths??[]]},watchdog:!1,isDetached:!0,...n})}async stop(){qs.exec("nginx -s stop"),await new Promise(e=>{let t=setInterval(async()=>await M("nginx")||e(clearInterval(t)),Ls);t.unref()}),this.isExited=!0}};var Ue=class extends m{constructor({entry:e=".",inspect:t=!0,enableSourceMaps:s=!0,traceWarnings:r=!0,traceUncaught:n=!0,args:o=[],watch:a,...c}){super({symbol:"\u{1F9E9}",title:"Node.js",command:"node",entry:e,args:[t&&`--inspect${typeof t=="string"?`=${t}`:""}`,s&&"--enable-source-maps",r&&"--trace-warnings",n&&"--trace-uncaught",e,...o].filter(Boolean),watchdog:!1,watch:{events:["change"],...a},...c})}};import{mkdir as he,readFile as Vs,rm as Bs,symlink as Qs,writeFile as zs}from"node:fs/promises";import{dirname as Gs,resolve as C}from"node:path";import{isEmpty as Hs,pick as Us}from"@nesvet/n";var{DEV:Ys,PWD:Ks}=process.env,Ye=class extends d{constructor(e={}){super({symbol:"\u{1F4C3}",title:"package.json",src:Ks,symlinkNodeModules:!!Ys,watch:{events:["change"],...e.watch},...e}),this.src=this.src.replace(/package\.json$/,""),this.dest=this.dest.replace(/package\.json$/,"")}async make(){await he(C(this.dest),{recursive:!0});let e=JSON.parse(await Vs(C(this.src,"package.json"),"utf8")),t={};if(this.dependenciesOf)for(let s of this.dependenciesOf){let r=this.conveyer.context[s];if(r)for(let{name:n,version:o}of r.dependencies.values())t[n]=o;else console.warn(`[PackageJSONMaker] Unknown stage "${s}"`)}if(this.dependencies){new p;for(let s of typeof this.dependencies=="function"?this.dependencies():this.dependencies)try{t[s]=p.all.get(s).version}catch{console.warn(`[PackageJSONMaker] Unknown dependency "${s}"`)}}if(t=Object.fromEntries(Object.entries(t).sort(([s],[r])=>s<r?-1:s>r?1:0)),this.symlinkNodeModules){let s=C(this.dest,"node_modules");try{await Bs(s,{recursive:!0,force:!0})}catch{}await he(s,{recursive:!0});for(let r of Object.keys(t)){let n=p.all.get(r).path,o=C(s,r);try{await he(Gs(o),{recursive:!0}),await Qs(n,o,"junction")}catch(a){console.warn(`[PackageJSONMaker] Could not symlink dependency "${r}": ${a.message}`)}}}await zs(C(this.dest,"package.json"),JSON.stringify({...Us(e,["name","version","description","productName","type","main","module","author","license","private"]),...!Hs(t)&&{dependencies:t},...this.overrides},null," "))}do=this.make};import{randomItem as Zs}from"@nesvet/n";var Xs=["Moment of truth\u2014let\u2019s see what came out","Time to admire our creation","Let\u2019s see what just happened","Well, let\u2019s take a peek, shall we?","Time to inspect the masterpiece","Drumroll, please\u2026","Voil\xE0. Let\u2019s have a look","Behold!","Magic\u2019s done. Let\u2019s see if it worked","Crossing fingers\u2026 Opening the results","No smoke? No fire? Let\u2019s find out","Let\u2019s unveil the result","Here goes nothing!"],Ke=class extends d{constructor(e={}){super({id:"reveal",symbol:"\u{1F4C1}",title:Zs(Xs),noTargetPhrase:"Nothing",...e})}do(){let e=this.target??this.context.target;e?Te(e):l(` ${this.noTargetPhrase}`)}};export{Je as BunProcess,Me as Bundler,m as ChildProcess,Le as Conveyer,Ve as Copier,Qe as ESBuild,Ge as MongodProcess,He as NginxProcess,Ue as NodeProcess,Ye as PackageJSONMaker,q as PackageMap,p as Packages,Ke as Reveal,d as Stage,ie as __Entrypoints,P as copyRecursive,F as env,ye as getCurrentCommitId,M as isRunning,l as log,u as options,$ as packageJSON,Se as packageJSONListeners,De as pathExists,Fi as require,Te as reveal,_ as setNodePath,Ee as watchPackageJSON};
|
|
8
|
+
`)}`);for(let{consumer:o,dependency:a,declared:c,actual:h}of n.versionMismatches)console.warn(`\u26A0\uFE0F Version Mismatch: ${w.bold(o)} wants ${w.bold(a)}@${w.underline(c)}, but resolved to ${w.underline(h)}`)}static of(e,t){return new i({sources:e,...t})}static nameRegExp=Lt;static metaFileNames(e,t){let s=t?r=>R(t,r):r=>R(r);return Object.values(e.outputs).filter(r=>r.entryPoint).flatMap(r=>Object.keys(r.inputs).map(s))}static getClosestPackageDir(e){for(Tt(e)||(e=R(e)),Oe(e).isFile()&&(e=I(e));!Y(K(e,"package.json"));){let t=I(e);if(e===t){e=null;break}else e=t}return e}static findWorkspaceRoot(e){let t=R(e);for(Y(t)&&Oe(t).isFile()&&(t=I(t));t;){let s=K(t,"package.json");if(Y(s)&&this.getParsedPackageJSON(s)?.workspaces)return t;let r=I(t);if(t===r)break;t=r}return null}static resolvePath(e,t="."){return Z(e,t)}static async resolveAndRead(e,t="."){return JSON.parse(await Dt(Z(e,t),"utf8"))}static getParsedPackageJSON(e){if(J.has(e))return J.get(e);let{name:t,version:s,dependencies:r,devDependencies:n,optionalDependencies:o,peerDependencies:a,scripts:c,workspaces:h}=JSON.parse(Rt(e,"utf8")),v={name:t,version:s,dependencies:r,devDependencies:n,optionalDependencies:o,peerDependencies:a,...h&&{workspaces:h},...c&&(c.prebuild||c.build||c.postbuild)&&{scripts:{...c.prebuild&&{prebuild:c.prebuild},...c.build&&{build:c.build},...c.postbuild&&{postbuild:c.postbuild}}}};return J.set(e,v),v}static all=new L;static clearCache(){J.clear(),this.all.clear()}};import{access as Bt}from"node:fs/promises";async function De(i){try{return await Bt(i),!0}catch{return!1}}import{readFile as Qt}from"node:fs/promises";import{resolve as zt}from"node:path";var Te=()=>({name:"raw-import",setup(i){i.onResolve({filter:/\?raw$/},e=>({path:zt(e.resolveDir,e.path.slice(0,-4)),namespace:"raw-import"})),i.onLoad({filter:/.*/,namespace:"raw-import"},async e=>({contents:await Qt(e.path,"utf8"),loader:"text",watchFiles:[e.path]}))}});import{createRequire as Gt}from"node:module";var Vi=Gt(import.meta.url);import{spawn as ee}from"node:child_process";import{once as Ht}from"node:events";import{existsSync as Ut,statSync as Yt}from"node:fs";import{dirname as Kt,resolve as Zt}from"node:path";import{noop as Xt}from"@nesvet/n";async function Ce(i){if(i=Zt(i),!Ut(i))return console.error("Path does not exist:",i);try{await new Promise((e,t)=>{switch(process.platform){case"win32":ee("explorer",["/select,",i]).on("error",t).on("exit",e);break;case"darwin":ee("open",["-R",i]).on("error",t).on("exit",e);break;case"linux":(async()=>{let s=Yt(i).isDirectory()?i:Kt(i);for(let[r,...n]of[["nautilus","--select",i],["dolphin","--select",i],["nemo",s],["thunar",s],["xdg-open",s]])try{return await Ht(ee(r,n).on("error",Xt),"exit"),e()}catch{}t()})();break;default:t()}})}catch{console.log(i)}}F(process.cwd());(process.argv.includes("--force")||process.argv.includes("-f"))&&(process.env.FORCE="true");import es from"node:child_process";import We from"node:fs";import je from"node:path";import D from"chalk";import{RequestListener as ts,RequestSender as ss}from"process-request";import{debounce as is}from"@nesvet/n";var rs=["The `punycode` module is deprecated"],q=class i{constructor(e,t,s=!1){V.push(e),this.conveyerFileName=e,this.entrypoints=t,this.isTarget=s,this.conveyerName=je.basename(this.conveyerFileName).replace(/\.conveyer\.(?:[cm]?j|t)s$/,"").replace(/^\./,"");let{sources:r,local:n}=new p({sources:[p.getClosestPackageDir(this.conveyerFileName)],dev:!0,optional:!0,props:["scripts.prebuild","scripts.build","scripts.postbuild"]});[this.package]=[...r.values()],this.dependencies=n;for(let o of this.dependencies.values())if(o.scripts?.build){let a=/\S*\.conveyer(?:\.(?:[cm]?j|t)s)?/.exec(o.scripts.build)?.[0];if(a){if(a=je.resolve(o.path,a),/\.(?:[cm]?j|t)s$/.test(a))We.existsSync(a)||(a=void 0);else{let c;for(let h of T){if(c=`${a}.${h}`,We.existsSync(c))break;c=void 0}a=c}a&&!V.includes(a)&&new i(a,this.entrypoints)}else new te(o,this.entrypoints)}this.title=`${this.package.name}${this.conveyerName?`/${this.conveyerName}`:""}`,this.entrypoints.set(this.conveyerFileName,this)}#e;init(){if(!this.conveyerProcess)return new Promise(e=>{this.#e=e,this.conveyerProcess=es.fork(this.conveyerFileName,this.entrypoints.otherArgs,{cwd:this.package.path,env:{...process.env,IS_ENTRYPOINT:!0,...this.isTarget&&{IS_ENTRYPOINT_TARGET:!0}},stdio:"pipe"}),this.conveyerProcess.stdout.on("data",this.#t),this.conveyerProcess.stderr.on("data",this.#s),this.conveyerProcess.on("error",this.#i),this.conveyerProcess.on("exit",this.#r),this.requestSender=new ss(this.conveyerProcess),new ts(this.conveyerProcess,this.#n)})}async reinit(){await new Promise(e=>{this.resolveExited=e,this.conveyerProcess?.kill("SIGINT")}),await this.init()}#t=e=>l(e.toString().trim(),"info",this.title);#s=async e=>{let t=e.toString().trim();for(let s of rs)if(t.includes(s))return;await l(t,"error",this.title)};#i=e=>l(`\u2757\uFE0F ${D.bold(this.title)}: ${e}`,"error");#r=()=>{delete this.conveyerProcess,this.resolveExited?.(),l(`\u{1F6AA} ${D.bold(this.title)} conveyer exited`)};#n={init:(e={},t)=>(this.options=e,this.initAt=Date.now(),l.progress({symbol:"\u{1F300}",title:`${this.package.version} ${D.dim(t)}`},this.title,this.isTarget)),inited:()=>{l.finish(),this.#e?.()},beginStage:e=>l.progress(e,this.title),doneStage:e=>l.finish(e),logFinish:e=>l.finish(e),enqueueWatch:is(()=>this.entrypoints.enqueueWatch(this),100)};async run(){try{return await this.requestSender.send("run"),await l(`\u2714\uFE0F ${D.underline("Passed")} ${D.bold.dim((Date.now()-this.initAt)/1e3)}`,"info",this.title)}catch{return l.finish()}}watch(){return this.requestSender.send("watch")}runWatchQueue(){return this.requestSender.send("runWatchQueue")}},te=class{constructor(e,t){this.package=e,this.entrypoints=t,this.entrypoints.buildableDependencies.set(this.package.path,this)}async run(){await l.progress({symbol:"\u{1F3D7}\uFE0F "},this.package.name);try{await this.package.rebuild(),l.finish()}catch(e){l.finish(),await l(e.stack,"error")}}watch(){}};var{FORCE:Me}=process.env,T=["js","cjs","mjs","ts"],ls=new RegExp(String.raw`^\.conveyer\.(${T.join("|")})$`),hs=[["-e","--env"]].flat(),V=[],ie=class i extends Map{constructor({entrypointsWatchQueueDelay:e}={},t){super(),e&&(this.#t=e);let s=[];for(let o=2,{length:a}=process.argv;o<a;o++){let c=process.argv[o];c.startsWith("-")?(this.otherArgs.push(c),hs.includes(c)&&this.otherArgs.push(process.argv[++o])):s.push(c)}let r=i.getConveyerFiles(s);if(!r)return l("\u274C No valid conveyer entrypoints","error");let n=p.getClosestPackageDir(r[0]);if(n){process.env.CONVEYER_PROJECT_ROOT=n;let o=n&&p.findWorkspaceRoot(n);o&&(process.env.CONVEYER_WORKSPACE_ROOT=o)}for(let o of r)V.includes(o)||new q(o,this,!0);process.on("SIGINT",()=>process.exit(0)),t&&this.run()}otherArgs=[];buildableDependencies=new Map;#e=new Set;#t=300;#s=!1;async run(){for(let e of this.values())await e.init();for(let e of Me?[...this.buildableDependencies.values(),...this.values()]:this.values())(e.isTarget||Me)&&await e.run();await Fe(1e3),await l("\u{1F440} Watching packages");for(let e of[...this.buildableDependencies.values(),...this.values()])await e.watch(),await l(` \u23A3 ${e.package.name}`);cs([...this.keys()],{ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:500,pollInterval:50}}).on("change",async e=>{let t=this.get(e);await t.reinit(),await t.run(),await t.watch()})}enqueueWatch(e){this.#e.add(e),this.#s||this.runEntrypointsWatchQueue()}async runEntrypointsWatchQueue(){for(this.#s=!0;this.#e.size;)for(let e of this.values())this.#e.has(e)&&(await e.runWatchQueue(),this.#e.delete(e),await Fe(this.#t));this.#s=!1}static{_();let e=process.cwd();this.getConveyerFiles=t=>{t.length||t.push(e);let s=[];for(let r of t){let n=as(r)?r:se(e,r),o=os(n,{throwIfNoEntry:!1});if(o?.isFile()){s.push(n);continue}if(o?.isDirectory()){let a=!1;for(let c of ns(n))if(ls.test(c)){s.push(se(n,c)),a=!0;break}if(!a)for(let c of T){let h=se(n,".conveyer",`index.${c}`);if(Ae(h)){s.push(h);break}}continue}for(let a of T){let c=`${n}.conveyer.${a}`;if(Ae(c)){s.push(c);break}}}return s.length?s:null}}};import{randomBytes as ws}from"node:crypto";import{mkdir as vs,rm as re}from"node:fs/promises";import{basename as ys,join as ne}from"node:path";import{Worker as xs}from"node:worker_threads";import{COMPRESSION_LEVEL as bs,zip as ks}from"zip-a-folder";import{mkdir as ps,rm as us,stat as ds}from"node:fs/promises";import{isAbsolute as fs,resolve as ms}from"node:path";import{watch as gs}from"chokidar";var d=class{constructor({watch:e,initialCleanup:t,cwd:s=process.cwd(),...r}){if(e){let{paths:n,events:o,...a}={};typeof e=="string"?n=[e]:Array.isArray(e)?n=e:typeof e=="object"&&({paths:n,events:o,...a}=e),this.watchPaths=n?.filter(Boolean).map(c=>fs(c)?c:ms(s,c)),this.watchOptions=a,this.watchEvents=o&&(Array.isArray(o)?o:[o])}Object.assign(this,{symbol:"\u{1F535}",initialCleanup:t?(Array.isArray(t)?t:[t]).filter(Boolean):!1,cwd:s,...r})}#e=new Map;handleInited(){return this.onInit?.()}async run(e,...t){try{if(e&&this.initialCleanup)for(let s of this.initialCleanup)try{(await ds(s)).isDirectory()&&(await us(s,{recursive:!0,force:!0}),await ps(s,{recursive:!0}))}catch{}return await this.conveyer.beginStage({spinner:this.spinner,symbol:this.symbol,title:this.title}),await this.onBefore?.(e,...t),await this.do(e,...t),await this.onAfter?.(e,...t),await this.conveyer.doneStage(),!0}catch(s){return console.error(`\u2757\uFE0F${this.symbol} ${this.title} ${s.stack}`),!1}}#t=(e,t)=>(this.#e.set(t,e),this.conveyer.enqueueWatch(this));async watch(){if(this.watcher&&(await this.watcher.close(),delete this.watcher),this.watchEvents&&this.watchPaths){this.watcher=gs(this.watchPaths,{ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:500,pollInterval:50},followSymlinks:!1,...this.watchOptions});for(let e of this.watchEvents)this.watcher.on(e,e==="all"?this.#t:(...t)=>this.#t(e,...t));this.watcher.on("error",e=>console.error(`\u2757\uFE0F${this.symbol} ${this.title} watcher ${e.stack}`))}return this.watcher}async runWatchQueue(){for(;this.#e.size;){let e=[...this.#e];this.#e.clear(),await this.run(!1,e)}}};function Ps(){return`${this.conveyer.context.packageJSON.name}-${this.conveyer.context.packageJSON.version}`}var _e=class i extends d{constructor(e={}){super({symbol:"\u{1F4E6}",title:"Bundler",getName:Ps,compressionLevel:"high",...e})}handleInited(){return this.context.targets=[],super.handleInited()}async do(){let e=[this.target,...this.targets??[],...this.context?.targets??[]].filter(Boolean);if(!e.length)return;let t=ne(this.destDir,`bundle-${Date.now().toString(36)}${ws(12).toString("hex")}`);await vs(t,{recursive:!0});let s=ne(this.destDir,`${this.name||this.getName(this)}.zip`);await re(s,{force:!0}),await Promise.all(e.map(async r=>{let[n,o,a,c]=Array.isArray(r)?r:[r],h=ne(t,o??ys(n));await(a?i.#e({src:n,dest:`${h}.zip`}):P(n,h)),c&&await re(n,{recursive:!0,force:!0})})),await ks(t,s,{compression:bs[this.compressionLevel]}),await re(t,{recursive:!0,force:!0}),this.onDone?.(s)}static#e({src:e,dest:t}){return new Promise((s,r)=>{new xs(new URL("./zip-worker.js",import.meta.url),{workerData:{src:e,dest:t}}).once("message",s).once("error",r).once("exit",n=>n?r(new Error(`Worker stopped with code ${n}`)):s())})}};import{execSync as Ss,spawn as $s}from"node:child_process";import{parse as Je}from"node:path";import{noop as Es}from"@nesvet/n";var m=class extends d{constructor({command:e,watch:t,filterStdout:s,filterStderr:r,...n}){super({symbol:"\u2699\uFE0F ",title:`${e} process`,command:e,cwd:Object.values(process._conveyerEnv)[0]?.dir,watchdog:!0,checkIfRunning:!1,args:[],stdio:["ignore",s?"pipe":"inherit",r?"pipe":"inherit","ipc"],filterStdout:s,filterStderr:r,isDetached:!1,stopTimeout:3e3,killTimeout:1e3,...n,watch:{paths:[],events:["change"],...t}})}#e=null;#t=!1;#s=!1;async start(){this.checkIfRunning&&await M(this.command)?(this.stop=Es,console.warn(`\u26A0\uFE0F${this.symbol} ${this.title} is already running`)):(this.#e=$s(this.command,this.args,{detached:this.isDetached,stdio:this.stdio,env:{...process.env,...this.env},cwd:this.cwd}),this.#e.on("exit",this.watchdog?this.#o:this.#a),this.stdio.includes("ipc")&&this.#e.on("message",this.#r),this.filterStdout&&this.#e.stdout.on("data",e=>{let t=e.toString();this.filterStdout.some(s=>t.includes(s))||process.stderr.write(t)}),this.filterStderr&&this.#e.stderr.on("data",e=>{let t=e.toString();this.filterStderr.some(s=>t.includes(s))||process.stderr.write(t)}))}stop(e){if(!this.#e)return;let t=this.#e;t.off("exit",this.#o);let s=typeof e=="string"&&e.startsWith("SIG")?e:"SIGTERM";return new Promise(r=>{if(t.exitCode!==null||t.signalCode!==null)this.#e=null,r();else{let n,o=()=>{clearTimeout(n),this.#e=null,r()};t.once("exit",o),t.once("error",o),this.#i(t,s),n=setTimeout(()=>{this.#i(t,"SIGKILL"),setTimeout(o,this.killTimeout)},this.stopTimeout)}})}#i(e,t){try{if(process.platform==="win32")t==="SIGKILL"?Ss(`taskkill /pid ${e.pid} /T /F`,{stdio:"ignore"}):e.kill(t);else if(this.isDetached)try{process.kill(-e.pid,t)}catch{}else e.kill(t)}catch{}}async do(){this.#e&&(this.#t=!0,await this.stop(),this.#t=!1),await this.start()}#r=e=>{try{let[t,...s]=e;this.#n[t].apply(this,s)}catch{}};#n={restart(e){if(e){for(let t of e){let s=new RegExp(`^${t.replace(/=.*$/,"")}(=|$)`),r=this.args.findIndex(n=>s.test(n));~r?this.args[r]=t:this.args.unshift(t)}e.length&&Je(e.at(-1)).root&&(this.args.length&&Je(this.args.at(-1)).root?this.args[this.args.length-1]=e.at(-1):this.args.push(e.at(-1)))}this.do()}};#a=()=>{this.#t||(this.#e=null,console.info(`\u{1F6AA}${this.symbol} ${this.title} exited`))};#o=()=>!this.#s&&!this.#t&&this.start()};var Le=class extends m{constructor({entry:e=".",inspect:t=!1,hot:s=!1,smol:r=!1,args:n=[],watch:o,...a}){super({symbol:"\u{1F35E}",title:"Bun",command:"bun",entry:e,args:["run",t&&`--inspect${typeof t=="string"?`=${t}`:""}`,s&&"--hot",r&&"--smol",e,...n].filter(Boolean),watchdog:!1,watch:{events:["change"],...o},...a})}};import{existsSync as Os,readFileSync as Ns}from"node:fs";import{readdir as Is,rm as Rs}from"node:fs/promises";import oe from"node:path";import B from"chalk";import{RequestListener as Ds,RequestSender as Ts}from"process-request";if(process.env.IS_ENTRYPOINT){if(process.env.WATCH="true",!process.env.IS_ENTRYPOINT_TARGET){process.env.npm_lifecycle_event="build";let i=process.argv.indexOf("--dev");if(~i&&process.argv.splice(i,1),delete process.env.DEV,!process.env.FORCE){let e=process.argv.indexOf("--build");~e&&process.argv.splice(e,1);let t=process.argv.indexOf("--bundle");~t&&process.argv.splice(t,1),delete process.env.BUILD,delete process.env.BUNDLE}}}else _();F();(process.env.npm_lifecycle_event==="dev"||process.argv.includes("--dev"))&&(process.env.DEV="true",process.env.WATCH="true");(process.env.npm_lifecycle_event==="build"||process.argv.includes("--build"))&&(process.env.BUILD="true");var ae=process.argv.find(i=>i.startsWith("--bundle"));ae&&(process.env.BUNDLE=ae.includes("=")?ae.split("=")[1]:"true");process.env.VERSION=$.version;process.env.GIT_COMMIT_ID=await ye();var{NODE_ENV:qe,WATCH:Cs,IS_ENTRYPOINT:Ws}=process.env,js=3,Ve=class{constructor(e,t={}){let{initialCleanup:s,...r}=t;this.name=oe.basename(process.argv[1]).replace(/.conveyer(.(?:[cm]?j|t)s)?$/,"").replace(/^\./,""),this.options={context:this.context,initialCleanup:s?(Array.isArray(s)?s:[s]).filter(Boolean):!1,...r},this.isEntrypoint=!!Ws,Cs&&this.watchers.push(Ee(this.#e));let n=1;for(let o of e.flat(js))if(o){for(o.title||(o.title=o.constructor.name),o.id||(o.id=o.title.toLowerCase().replaceAll(/\W/g,""));this.stages.has(o.id);)o.id+=n;this.stages.set(o.id,o),o.conveyer=this,o.context=o.conveyer.context[o.id]={stage:o.constructor.name},n++}process.on("exit",o=>this.exit(o)),process.on("SIGINT",()=>this.exit("SIGINT")),process.on("SIGTERM",()=>this.exit("SIGTERM")),this.isEntrypoint&&(this.requestSender=new Ts(process),new Ds(process,o=>this[o]())),this.init()}stages=new Map;context={conveyerVersion:JSON.parse(Ns(oe.join(p.getClosestPackageDir(import.meta.filename),"package.json"))).version,packageJSON:$};watchers=[];#e=({name:e,version:t})=>{this.title=`${e}${this.name?`/${this.name}`:""}`,this.version=t};async init(){this.#e($),this.isEntrypoint?this.requestSender.send("init",this.options,qe):(this.initAt=Date.now(),await l.progress({symbol:"\u{1F300}",title:`${B.bold(this.title)} ${this.version} ${B.dim(qe)}`}));for(let e of this.stages.values())await e.handleInited();return this.isEntrypoint?(this.requestSender.send("inited"),null):(l.finish(),this.run())}logFinish(e){return this.isEntrypoint?this.requestSender.send("logFinish",e):l.finish(e)}beginStage(e){return this.isEntrypoint?this.requestSender.send("beginStage",e):l.progress(e)}doneStage(e){return this.isEntrypoint?this.requestSender.send("doneStage",e):l.finish(e)}async run(){if(this.options.initialCleanup)for(let e of this.options.initialCleanup)Os(e)&&await Promise.all((await Is(e)).map(t=>Rs(oe.resolve(e,t),{recursive:!0,force:!0})));for(let e of this.stages.values())if(!await e.run(!0))throw this.isEntrypoint||l.finish(),await this.exit(),new Error(`Stage ${e.symbol} ${e.title} broke conveyer`);return this.isEntrypoint?null:l(`\u2714\uFE0F ${B.underline("Passed")} ${B.bold.dim((Date.now()-this.initAt)/1e3)}`)}async watch(){for(let e of this.stages.values())await e.watch(!0)}watchQueue=new Set;enqueueWatch(e){return this.watchQueue.add(e),this.requestSender.send("enqueueWatch")}async runWatchQueue(){for(;this.watchQueue.size;)for(let e of this.stages.values())this.watchQueue.has(e)&&(this.watchQueue.delete(e),await e.watchQueuePromise,e.watchQueuePromise=await e.runWatchQueue(),delete e.watchQueuePromise)}async exit(e){for(let t of this.stages.values())t.watchdog&&(t.isStopped=!0),await t.stop?.(e);process.exit()}};import{mkdir as As,rm as Fs,stat as Ms}from"node:fs/promises";import ce from"node:path";function _s(i,e){return i[0]>e[0]?-1:i[0]<e[0]?1:0}var Be=class extends d{constructor({targets:e,watch:t,...s}){typeof e[0]=="string"&&(e=[e]),super({symbol:"\u{1F6D2}",title:"Copier",targets:e,watch:{ignoreInitial:!0,events:["all"],...t},...s})}handleInited(){return this.context.targets=new Map,super.handleInited()}async copy(e,t){if(e){this.targets=new Map([...this.targets,...[...this.context.targets].map(s=>s.reverse())].filter(Boolean).map(([s,r])=>[ce.resolve(s),ce.resolve(r)]).sort(_s)),this.watchPaths=[];for(let[s,r]of this.targets)if(await De(s))this.watchPaths.push(s),(await Ms(s)).isDirectory()&&this.watchPaths.push(`${s}/**`),await P(s,r);else throw new Error(`Path ${s} not exists`)}else if(t)for(let[s,r]of t){let n,o;for([n,o]of this.targets){if(n===s)break;if(s.indexOf(n)===0){o=ce.join(o,s.replace(n,""));break}}r==="add"||r==="change"?await P(s,o):r==="addDir"?await As(o,{recursive:!0}):(r==="unlink"||r==="unlinkDir"&&s!==n)&&await Fs(o,{recursive:!0,force:!0})}}do=this.copy};import Q from"node:path";import*as Ge from"esbuild";import{jscc as Js}from"esbuild-plugin-jscc";import{unique as Ls}from"@nesvet/n";var{NODE_ENV:Qe,WATCH:le,SOURCEMAPS:qs}=process.env,ze=class extends d{constructor({jsx:e,jsxDev:t,alias:s,watch:r,local:n,...o}={}){super({symbol:"\u{1F528}",title:"esbuild",mainFields:["module","main"],loader:{".node":"file"},...Qe==="production"&&{legalComments:"none",minify:!0,treeShaking:!0},...(le||qs)&&{sourcemap:"linked"},color:!0,...n&&{local:Array.isArray(n)?n:[n]},...o,jsx:e===!0?"automatic":e,jsxDev:t||e&&Qe==="development",...s&&{alias:Object.fromEntries(Object.entries(s).map(([a,c])=>[a,Q.resolve(c)]))},watch:{paths:[],events:["change"],...r}})}async handleInited(){let e=Array.isArray(this.external)?this.external.filter(t=>typeof t=="string"):[];this.context.packages=new p({external:e,local:this.local}),this.external&&(this.external===!0||this.external.includes(!0))&&e.push(...this.context.packages.external.asNames()),this.define&&Object.values(this.define).some(t=>typeof t=="function")&&(this.define=Object.fromEntries(Object.entries(this.define).map(([t,s])=>[t,typeof s=="function"?s.call(this):s]))),this.buildContext=await Ge.context({absWorkingDir:this.cwd,bundle:!0,entryPoints:this.entryPoints,loader:this.loader,jsx:this.jsx,jsxDev:this.jsxDev,external:e,mainFields:this.mainFields,nodePaths:[...process.env.NODE_PATH?.split(Q.delimiter)??[],...this.nodePaths??[]],outfile:this.outfile,alias:this.alias,define:this.define,plugins:[Te(),this.jsccValues&&Js({values:this.jsccValues,ignore:this.jsccIgnore,sourceMap:!!this.sourcemap}),...this.plugins??[]].filter(Boolean),platform:this.platform,format:this.format,target:this.target,legalComments:this.legalComments,minify:this.minify,treeShaking:this.treeShaking,sourcemap:this.sourcemap,color:this.color,metafile:!0}),this.watchPaths=Ls(this.entryPoints.map(t=>Q.join(Q.dirname(t),"**")))}async#e(e){return e=e.filter(t=>!/\/node_modules\//.test(t)),this.watchPaths.join(",")!==e.join(",")?(this.watchPaths=e,this.watcher&&await this.watch(),!0):!1}async build(e){let{metafile:t}=await this.buildContext.rebuild();(this.local||this.external===!0||this.external?.includes(!0))&&this.context.packages.external.verifyExternal(t,this.cwd);let s;le&&(s=await this.#e(p.metaFileNames(t))),(e||s)&&(this.context.dependencies=this.context.packages.metaPick(t)),le||await this.buildContext.dispose()}do=this.build};var Vs="/usr/local/etc/mongod.conf",He=class extends m{constructor(e={}){let{config:t,args:s=[],watch:r,...n}=e;super({symbol:"\u{1F33F}",title:"MongoDB",command:"mongod",args:["--config",t??Vs,...s],checkIfRunning:!0,watch:t?{events:["change"],...r,paths:[t,...r?.paths??[]]}:!1,watchdog:!1,...n})}};import Bs from"node:child_process";var Qs=250,Ue=class extends m{constructor(e={}){let{config:t,args:s=[],watch:r,...n}=e;super({symbol:"\u{1F578} ",title:"nginx",command:"nginx",args:[...t?["-c",t]:[],...s],checkIfRunning:!0,watch:t&&{events:["change"],...r,paths:[t,...r?.paths??[]]},watchdog:!1,isDetached:!0,...n})}async stop(){Bs.exec("nginx -s stop"),await new Promise(e=>{let t=setInterval(async()=>await M("nginx")||e(clearInterval(t)),Qs);t.unref()}),this.isExited=!0}};var Ye=class extends m{constructor({entry:e=".",inspect:t=!0,enableSourceMaps:s=!0,traceWarnings:r=!0,traceUncaught:n=!0,args:o=[],watch:a,...c}){super({symbol:"\u{1F9E9}",title:"Node.js",command:"node",entry:e,args:[t&&`--inspect${typeof t=="string"?`=${t}`:""}`,s&&"--enable-source-maps",r&&"--trace-warnings",n&&"--trace-uncaught",e,...o].filter(Boolean),watchdog:!1,watch:{events:["change"],...a},...c})}};import{mkdir as he,readFile as zs,rm as Gs,symlink as Hs,writeFile as Us}from"node:fs/promises";import{dirname as Ys,resolve as C}from"node:path";import{isEmpty as Ks,pick as Zs}from"@nesvet/n";var{DEV:Xs,PWD:ei}=process.env,Ke=class extends d{constructor(e={}){super({symbol:"\u{1F4C3}",title:"package.json",src:ei,symlinkNodeModules:!!Xs,watch:{events:["change"],...e.watch},...e}),this.src=this.src.replace(/package\.json$/,""),this.dest=this.dest.replace(/package\.json$/,"")}async make(){await he(C(this.dest),{recursive:!0});let e=JSON.parse(await zs(C(this.src,"package.json"),"utf8")),t={};if(this.dependenciesOf)for(let s of this.dependenciesOf){let r=this.conveyer.context[s];if(r)for(let{name:n,version:o}of r.dependencies.values())t[n]=o;else console.warn(`[PackageJSONMaker] Unknown stage "${s}"`)}if(this.dependencies){new p;for(let s of typeof this.dependencies=="function"?this.dependencies():this.dependencies)try{t[s]=p.all.get(s).version}catch{console.warn(`[PackageJSONMaker] Unknown dependency "${s}"`)}}if(t=Object.fromEntries(Object.entries(t).sort(([s],[r])=>s<r?-1:s>r?1:0)),this.symlinkNodeModules){let s=C(this.dest,"node_modules");try{await Gs(s,{recursive:!0,force:!0})}catch{}await he(s,{recursive:!0});for(let r of Object.keys(t)){let n=p.all.get(r).path,o=C(s,r);try{await he(Ys(o),{recursive:!0}),await Hs(n,o,"junction")}catch(a){console.warn(`[PackageJSONMaker] Could not symlink dependency "${r}": ${a.message}`)}}}await Us(C(this.dest,"package.json"),JSON.stringify({...Zs(e,["name","version","description","productName","type","main","module","author","license","private"]),...!Ks(t)&&{dependencies:t},...this.overrides},null," "))}do=this.make};import{randomItem as ti}from"@nesvet/n";var si=["Moment of truth\u2014let\u2019s see what came out","Time to admire our creation","Let\u2019s see what just happened","Well, let\u2019s take a peek, shall we?","Time to inspect the masterpiece","Drumroll, please\u2026","Voil\xE0. Let\u2019s have a look","Behold!","Magic\u2019s done. Let\u2019s see if it worked","Crossing fingers\u2026 Opening the results","No smoke? No fire? Let\u2019s find out","Let\u2019s unveil the result","Here goes nothing!"],Ze=class extends d{constructor(e={}){super({id:"reveal",symbol:"\u{1F4C1}",title:ti(si),noTargetPhrase:"Nothing",...e})}do(){let e=this.target??this.context.target;e?Ce(e):l(` ${this.noTargetPhrase}`)}};export{Le as BunProcess,_e as Bundler,m as ChildProcess,Ve as Conveyer,Be as Copier,ze as ESBuild,He as MongodProcess,Ue as NginxProcess,Ye as NodeProcess,Ke as PackageJSONMaker,L as PackageMap,p as Packages,Ze as Reveal,d as Stage,ie as __Entrypoints,P as copyRecursive,F as env,ye as getCurrentCommitId,M as isRunning,l as log,u as options,$ as packageJSON,Se as packageJSONListeners,De as pathExists,Te as rawImportPlugin,Vi as require,Ce as reveal,_ as setNodePath,Ee as watchPackageJSON};
|
|
9
9
|
//# sourceMappingURL=index.js.map
|