@sse-ui/builder 1.0.0 → 1.0.2

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/dist/cli.js ADDED
@@ -0,0 +1,2628 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ createPackageBin,
4
+ createPackageExports,
5
+ getOutExtension,
6
+ mapConcurrently,
7
+ validatePkgJson
8
+ } from "./chunk-5S2N5WDQ.js";
9
+
10
+ // src/cli.ts
11
+ import { Command as Command11 } from "commander";
12
+
13
+ // src/core/build.ts
14
+ import { findWorkspacesRoot } from "find-workspaces";
15
+ import { $ } from "execa";
16
+ import { globby } from "globby";
17
+ import * as fs from "fs/promises";
18
+ import * as path from "path";
19
+ import { sep as posixSep } from "path/posix";
20
+ import * as semver from "semver";
21
+ import { Command } from "commander";
22
+
23
+ // src/utils/loadConfig.ts
24
+ import { loadConfig as loadC12Config } from "c12";
25
+ async function loadConfig() {
26
+ try {
27
+ const { config, configFile } = await loadC12Config({
28
+ name: "sse",
29
+ rcFile: false,
30
+ globalRc: false
31
+ });
32
+ if (configFile) {
33
+ console.log(`\u{1F4DD} Loaded config from ${configFile}`);
34
+ }
35
+ return config || {};
36
+ } catch (error) {
37
+ console.error(`\u274C Failed to parse configuration:`);
38
+ console.error(error);
39
+ process.exit(1);
40
+ }
41
+ }
42
+
43
+ // src/core/build.ts
44
+ async function addLicense({
45
+ name,
46
+ version,
47
+ license,
48
+ bundle,
49
+ outputDir,
50
+ isFlat,
51
+ packageType
52
+ }) {
53
+ const outExtension = getOutExtension(bundle, { isFlat, packageType });
54
+ const file = path.join(outputDir, `index${outExtension}`);
55
+ if (!await fs.stat(file).then(
56
+ (stats) => stats.isFile(),
57
+ () => false
58
+ )) {
59
+ return;
60
+ }
61
+ const content = await fs.readFile(file, { encoding: "utf8" });
62
+ await fs.writeFile(
63
+ file,
64
+ `/**
65
+ * ${name} v${version}
66
+ *
67
+ * @license ${license}
68
+ * This source code is licensed under the ${license} license found in the
69
+ * LICENSE file in the root directory of this source tree.
70
+ */
71
+ ${content}`,
72
+ { encoding: "utf8" }
73
+ );
74
+ console.log(`License added to ${file}`);
75
+ }
76
+ async function writePackageJson({
77
+ packageJson,
78
+ bundles,
79
+ outputDir,
80
+ cwd,
81
+ addTypes = false,
82
+ isFlat = false,
83
+ packageType
84
+ }) {
85
+ delete packageJson.scripts;
86
+ delete packageJson.publishConfig?.directory;
87
+ delete packageJson.devDependencies;
88
+ delete packageJson.imports;
89
+ const resolvedPackageType = packageType || packageJson.type || "commonjs";
90
+ packageJson.type = resolvedPackageType;
91
+ const originalExports = packageJson.exports;
92
+ delete packageJson.exports;
93
+ const originalBin = packageJson.bin;
94
+ delete packageJson.bin;
95
+ const {
96
+ exports: packageExports,
97
+ main: main2,
98
+ types
99
+ } = await createPackageExports({
100
+ exports: originalExports,
101
+ bundles,
102
+ outputDir,
103
+ cwd,
104
+ addTypes,
105
+ isFlat,
106
+ packageType: resolvedPackageType
107
+ });
108
+ packageJson.exports = packageExports;
109
+ if (main2) {
110
+ packageJson.main = main2;
111
+ }
112
+ if (types) {
113
+ packageJson.types = types;
114
+ }
115
+ const bin = await createPackageBin({
116
+ bin: originalBin,
117
+ bundles,
118
+ cwd,
119
+ isFlat,
120
+ packageType: resolvedPackageType
121
+ });
122
+ if (bin) {
123
+ packageJson.bin = bin;
124
+ }
125
+ await fs.writeFile(
126
+ path.join(outputDir, "package.json"),
127
+ JSON.stringify(packageJson, null, 2),
128
+ "utf-8"
129
+ );
130
+ }
131
+ var buildCommand = new Command("build").description("Builds the package for publishing.").option("--bundle <bundles...>", "Bundles to output", ["esm", "cjs"]).option(
132
+ "--hasLargeFiles",
133
+ "Set to `true` if you know you are transpiling large files.",
134
+ false
135
+ ).option(
136
+ "--skipBundlePackageJson",
137
+ "Set to `true` if you don't want to generate a package.json file in the bundle output.",
138
+ false
139
+ ).option("--buildTypes", "Do not build types for the package.").option(
140
+ "--skipTsc",
141
+ "Skip running TypeScript compiler (tsc) for building types.",
142
+ false
143
+ ).option("--ignore <globs...>", "Extra globs to be ignored by Babel.", []).option(
144
+ "--skipBabelRuntimeCheck",
145
+ "Skip checking for Babel runtime dependencies in the package.",
146
+ false
147
+ ).option(
148
+ "--skipPackageJson",
149
+ "Skip generating the package.json file in the bundle output.",
150
+ false
151
+ ).option(
152
+ "--skipMainCheck",
153
+ "Skip checking for main field in package.json.",
154
+ false
155
+ ).option(
156
+ "--copy <globs...>",
157
+ "Files/Directories to be copied to the output directory. Can be a glob pattern.",
158
+ []
159
+ ).option("--enableReactCompiler", "Whether to use the React compiler.", false).option(
160
+ "--tsgo",
161
+ 'Uses tsgo cli instead of tsc for type generation. Can also be set via env var "SSE_USE_TSGO"',
162
+ process.env.SSE_USE_TSGO === "1" || process.env.SSE_USE_TSGO === "true"
163
+ ).option(
164
+ "--flat",
165
+ "Builds the package in a flat structure without subdirectories for each module type.",
166
+ process.env.SSE_BUILD_FLAT === "1"
167
+ ).option("--verbose", "Enable verbose logging.", false).action(async (cliOptions) => {
168
+ const fileConfig = await loadConfig();
169
+ const options = {
170
+ bundle: cliOptions.bundle || fileConfig.bundle || ["esm", "cjs"],
171
+ hasLargeFiles: cliOptions.hasLargeFiles ?? fileConfig.hasLargeFiles ?? false,
172
+ skipBundlePackageJson: cliOptions.skipBundlePackageJson ?? fileConfig.skipBundlePackageJson ?? false,
173
+ buildTypes: cliOptions.buildTypes ?? fileConfig.buildTypes ?? true,
174
+ skipTsc: cliOptions.skipTsc ?? fileConfig.skipTsc ?? false,
175
+ ignore: [...fileConfig.ignore || [], ...cliOptions.ignore || []],
176
+ copy: [...fileConfig.copy || [], ...cliOptions.copy || []],
177
+ enableReactCompiler: cliOptions.enableReactCompiler ?? fileConfig.enableReactCompiler ?? false,
178
+ tsgo: cliOptions.tsgo ?? fileConfig.tsgo ?? false,
179
+ flat: cliOptions.flat ?? fileConfig.flat ?? false,
180
+ verbose: cliOptions.verbose ?? fileConfig.verbose ?? false,
181
+ skipBabelRuntimeCheck: false,
182
+ skipPackageJson: false,
183
+ skipMainCheck: false
184
+ };
185
+ const {
186
+ bundle: bundles,
187
+ hasLargeFiles,
188
+ skipBundlePackageJson,
189
+ verbose = false,
190
+ ignore: extraIgnores,
191
+ buildTypes,
192
+ skipTsc,
193
+ skipBabelRuntimeCheck = false,
194
+ skipPackageJson = false,
195
+ enableReactCompiler = false,
196
+ tsgo: useTsgo = false
197
+ } = options;
198
+ const cwd = process.cwd();
199
+ const pkgJsonPath = path.join(cwd, "package.json");
200
+ const packageJson = JSON.parse(
201
+ await fs.readFile(pkgJsonPath, { encoding: "utf8" })
202
+ );
203
+ validatePkgJson(packageJson, {
204
+ skipMainCheck: options.skipMainCheck,
205
+ enableReactCompiler
206
+ });
207
+ const buildDirBase = packageJson.publishConfig?.directory;
208
+ const buildDir = path.join(cwd, buildDirBase);
209
+ const packageType = packageJson.type === "module" ? "module" : "commonjs";
210
+ console.log(`Selected output directory: "${buildDirBase}"`);
211
+ if (options.flat) {
212
+ console.log("Building package in flat structure.");
213
+ }
214
+ await fs.rm(buildDir, { recursive: true, force: true });
215
+ let babelRuntimeVersion = packageJson.dependencies?.["@babel/runtime"];
216
+ if (babelRuntimeVersion === "catalog:") {
217
+ const { stdout: configStdout } = await $`pnpm config list --json`;
218
+ const pnpmWorkspaceConfig = JSON.parse(configStdout);
219
+ babelRuntimeVersion = pnpmWorkspaceConfig.catalog["@babel/runtime"];
220
+ }
221
+ if (!babelRuntimeVersion && !skipBabelRuntimeCheck) {
222
+ throw new Error(
223
+ "package.json needs to have a dependency on `@babel/runtime` when building with `@babel/plugin-transform-runtime`."
224
+ );
225
+ }
226
+ if (!bundles || bundles.length === 0) {
227
+ console.error(
228
+ "No bundles specified. Use --bundle to specify which bundles to build."
229
+ );
230
+ return;
231
+ }
232
+ const { build: babelBuild, cjsCopy } = await import("./babel-VTL3CZAT.js");
233
+ const relativeOutDirs = !options.flat ? {
234
+ cjs: ".",
235
+ esm: "esm"
236
+ } : {
237
+ cjs: ".",
238
+ esm: "."
239
+ };
240
+ const sourceDir = path.join(cwd, "src");
241
+ const reactVersion = semver.minVersion(packageJson.peerDependencies?.react || "")?.version ?? "latest";
242
+ if (enableReactCompiler) {
243
+ const mode = process.env.SSE_REACT_COMPILER_MODE ?? "opt-in";
244
+ console.log(
245
+ `[feature] Building with React compiler enabled. The compiler mode is "${mode}" right now.${mode === "opt-in" ? ' Use explicit "use memo" directives in your components to enable the React compiler for them.' : ""}`
246
+ );
247
+ }
248
+ await Promise.all(
249
+ bundles.map(async (bundle) => {
250
+ const outExtension = getOutExtension(bundle, {
251
+ isFlat: !!options.flat,
252
+ isType: false,
253
+ packageType
254
+ });
255
+ const relativeOutDir = relativeOutDirs[bundle];
256
+ const outputDir = path.join(buildDir, relativeOutDir);
257
+ await fs.mkdir(outputDir, { recursive: true });
258
+ const promises = [];
259
+ promises.push(
260
+ babelBuild({
261
+ cwd,
262
+ sourceDir,
263
+ outDir: outputDir,
264
+ babelRuntimeVersion,
265
+ hasLargeFiles,
266
+ bundle,
267
+ verbose,
268
+ optimizeClsx: packageJson.dependencies?.clsx !== void 0 || packageJson.dependencies?.classnames !== void 0,
269
+ removePropTypes: packageJson.dependencies?.["prop-types"] !== void 0,
270
+ pkgVersion: packageJson.version,
271
+ ignores: extraIgnores,
272
+ outExtension,
273
+ reactCompiler: enableReactCompiler ? {
274
+ reactVersion: reactVersion || "latest"
275
+ } : void 0
276
+ })
277
+ );
278
+ if (buildDir !== outputDir && !skipBundlePackageJson && !options.flat) {
279
+ promises.push(
280
+ fs.writeFile(
281
+ path.join(outputDir, "package.json"),
282
+ JSON.stringify({
283
+ type: bundle === "esm" ? "module" : "commonjs",
284
+ sideEffects: packageJson.sideEffects ?? false
285
+ })
286
+ )
287
+ );
288
+ }
289
+ if (!options.flat) {
290
+ promises.push(cjsCopy({ from: sourceDir, to: outputDir }));
291
+ }
292
+ await Promise.all(promises);
293
+ await addLicense({
294
+ bundle,
295
+ license: packageJson.license,
296
+ name: packageJson.name,
297
+ version: packageJson.version,
298
+ outputDir,
299
+ isFlat: !!options.flat,
300
+ packageType
301
+ });
302
+ })
303
+ );
304
+ if (options.flat) {
305
+ await cjsCopy({ from: sourceDir, to: buildDir });
306
+ }
307
+ if (buildTypes) {
308
+ const tsMod = await import("./typescript-CS6YZCMJ.js");
309
+ const bundleMap = bundles.map((type) => ({
310
+ type,
311
+ dir: relativeOutDirs[type]
312
+ }));
313
+ await tsMod.createTypes({
314
+ bundles: bundleMap,
315
+ srcDir: sourceDir,
316
+ cwd,
317
+ skipTsc,
318
+ isFlat: !!options.flat,
319
+ buildDir,
320
+ useTsgo,
321
+ packageType,
322
+ verbose: options.verbose
323
+ });
324
+ }
325
+ if (skipPackageJson) {
326
+ console.log("Skipping package.json generation in the output directory.");
327
+ return;
328
+ }
329
+ await writePackageJson({
330
+ cwd,
331
+ packageJson,
332
+ bundles: bundles.map((type) => ({
333
+ type,
334
+ dir: relativeOutDirs[type]
335
+ })),
336
+ outputDir: buildDir,
337
+ addTypes: buildTypes,
338
+ isFlat: !!options.flat,
339
+ packageType
340
+ });
341
+ await copyHandler({
342
+ cwd,
343
+ globs: options.copy ?? [],
344
+ buildDir,
345
+ verbose: options.verbose
346
+ });
347
+ });
348
+ async function copyHandler({
349
+ cwd,
350
+ globs = [],
351
+ buildDir,
352
+ verbose = false
353
+ }) {
354
+ const defaultFiles = [];
355
+ const workspaceRoot = await findWorkspacesRoot(cwd);
356
+ const localOrRootFiles = [
357
+ [path.join(cwd, "README.md")],
358
+ [path.join(cwd, "LICENSE")],
359
+ [path.join(cwd, "CHANGELOG.md")]
360
+ ];
361
+ if (workspaceRoot) {
362
+ localOrRootFiles[0].push(path.join(workspaceRoot.location, "README.md"));
363
+ localOrRootFiles[1].push(path.join(workspaceRoot.location, "LICENSE"));
364
+ localOrRootFiles[2].push(path.join(workspaceRoot.location, "CHANGELOG.md"));
365
+ }
366
+ await Promise.all(
367
+ localOrRootFiles.map(async (filesToCopy) => {
368
+ for (const file of filesToCopy) {
369
+ if (
370
+ // eslint-disable-next-line no-await-in-loop
371
+ await fs.stat(file).then(
372
+ () => true,
373
+ () => false
374
+ )
375
+ ) {
376
+ defaultFiles.push(file);
377
+ break;
378
+ }
379
+ }
380
+ })
381
+ );
382
+ if (globs.length) {
383
+ const res = globs.map((globPattern) => {
384
+ const [pattern, baseDir] = globPattern.split(":");
385
+ return { pattern, baseDir };
386
+ });
387
+ const globToResMap = /* @__PURE__ */ new Map();
388
+ const result = await Promise.all(
389
+ res.map(async ({ pattern, baseDir }) => {
390
+ if (!globToResMap.has(pattern)) {
391
+ const promise = globby(pattern, { cwd });
392
+ globToResMap.set(pattern, promise);
393
+ }
394
+ const files = await globToResMap.get(pattern);
395
+ return { files: files ?? [], baseDir };
396
+ })
397
+ );
398
+ globToResMap.clear();
399
+ result.forEach(({ files, baseDir }) => {
400
+ files.forEach((file) => {
401
+ const sourcePath = path.resolve(cwd, file);
402
+ const pathSegments = file.split(posixSep);
403
+ const relativePath = (
404
+ // Use index 2 (when required) since users can also specify paths like `./src/index.js`
405
+ pathSegments.slice(pathSegments[0] === "." ? 2 : 1).join(posixSep) || file
406
+ );
407
+ const targetPath = baseDir ? path.resolve(buildDir, baseDir, relativePath) : path.resolve(buildDir, relativePath);
408
+ defaultFiles.push({ sourcePath, targetPath });
409
+ });
410
+ });
411
+ }
412
+ if (!defaultFiles.length) {
413
+ if (verbose) {
414
+ console.log("\u24FF No files to copy.");
415
+ }
416
+ }
417
+ await mapConcurrently(
418
+ defaultFiles,
419
+ async (file) => {
420
+ if (typeof file === "string") {
421
+ const sourcePath = file;
422
+ const fileName = path.basename(file);
423
+ const targetPath = path.join(buildDir, fileName);
424
+ await recursiveCopy({
425
+ source: sourcePath,
426
+ target: targetPath,
427
+ verbose
428
+ });
429
+ } else {
430
+ await fs.mkdir(path.dirname(file.targetPath), { recursive: true });
431
+ await recursiveCopy({
432
+ source: file.sourcePath,
433
+ target: file.targetPath,
434
+ verbose
435
+ });
436
+ }
437
+ },
438
+ 20
439
+ );
440
+ console.log(`\u{1F4CB} Copied ${defaultFiles.length} files.`);
441
+ }
442
+ async function recursiveCopy({
443
+ source,
444
+ target,
445
+ verbose = true
446
+ }) {
447
+ try {
448
+ await fs.cp(source, target, { recursive: true });
449
+ if (verbose) {
450
+ console.log(`Copied ${source} to ${target}`);
451
+ }
452
+ return true;
453
+ } catch (err) {
454
+ if (err && typeof err === "object" && "code" in err && err.code !== "ENOENT") {
455
+ throw err;
456
+ }
457
+ if (verbose) {
458
+ console.warn(`Source does not exist: ${source}`);
459
+ }
460
+ throw err;
461
+ }
462
+ }
463
+
464
+ // src/core/publish.ts
465
+ import * as fs2 from "fs/promises";
466
+ import * as path2 from "path";
467
+ import { Command as Command2 } from "commander";
468
+ import { $ as $2 } from "execa";
469
+ function getPackageManager() {
470
+ const userAgent = process.env.npm_config_user_agent || "";
471
+ if (userAgent.includes("pnpm")) return "pnpm";
472
+ if (userAgent.includes("yarn")) return "yarn";
473
+ return "npm";
474
+ }
475
+ var publishCommand = new Command2("publish").description(
476
+ "Automatically publishes the built package from the publishConfig.directory"
477
+ ).option("--tag <tag>", "Registers the published package with the given tag").option(
478
+ "--access <access>",
479
+ "Tells the registry whether this package should be published as public or restricted"
480
+ ).option(
481
+ "--dry-run",
482
+ "Does everything publish would do except actually publishing"
483
+ ).option(
484
+ "--pm <manager>",
485
+ "Force a specific package manager (npm, yarn, pnpm)"
486
+ ).action(async (options) => {
487
+ const cwd = process.cwd();
488
+ const pkgJsonPath = path2.join(cwd, "package.json");
489
+ try {
490
+ const packageJsonContent = await fs2.readFile(pkgJsonPath, {
491
+ encoding: "utf8"
492
+ });
493
+ const packageJson = JSON.parse(packageJsonContent);
494
+ const publishDirBase = packageJson.publishConfig?.directory;
495
+ if (!publishDirBase) {
496
+ throw new Error(
497
+ `No publish directory specified in "${packageJson.name}" package.json. Specify it in the "publishConfig.directory" field.`
498
+ );
499
+ }
500
+ const publishDir = path2.join(cwd, publishDirBase);
501
+ const dirExists = await fs2.stat(publishDir).then(
502
+ (stats) => stats.isDirectory(),
503
+ () => false
504
+ );
505
+ if (!dirExists) {
506
+ throw new Error(
507
+ `Publish directory "${publishDir}" does not exist. Please run the build command first.`
508
+ );
509
+ }
510
+ const pm = options.pm || getPackageManager();
511
+ console.log(
512
+ `\u{1F680} Publishing via ${pm.toUpperCase()} from directory: ${publishDirBase}`
513
+ );
514
+ const args = ["publish"];
515
+ if (options.tag) args.push("--tag", options.tag);
516
+ if (options.access) args.push("--access", options.access);
517
+ if (options.dryRun) args.push("--dry-run");
518
+ if (pm === "yarn" && !process.env.npm_config_user_agent?.includes("yarn/3") && !process.env.npm_config_user_agent?.includes("yarn/4")) {
519
+ args.push("--non-interactive");
520
+ }
521
+ await $2({
522
+ stdio: "inherit",
523
+ cwd: publishDir
524
+ })`${pm} ${args}`;
525
+ console.log("\u2705 Successfully published!");
526
+ } catch (error) {
527
+ console.error("\u274C Error executing publish command:");
528
+ if (error instanceof Error) {
529
+ console.error(error.message);
530
+ }
531
+ process.exit(1);
532
+ }
533
+ });
534
+
535
+ // src/core/clean.ts
536
+ import * as fs3 from "fs/promises";
537
+ import * as path3 from "path";
538
+ import { Command as Command3 } from "commander";
539
+ var cleanCommand = new Command3("clean").description(
540
+ "Removes the build directory specified in package.json to start fresh"
541
+ ).action(async () => {
542
+ const cwd = process.cwd();
543
+ const pkgJsonPath = path3.join(cwd, "package.json");
544
+ try {
545
+ const packageJsonContent = await fs3.readFile(pkgJsonPath, {
546
+ encoding: "utf8"
547
+ });
548
+ const packageJson = JSON.parse(packageJsonContent);
549
+ const buildDirBase = packageJson.publishConfig?.directory || "build";
550
+ const buildDir = path3.join(cwd, buildDirBase);
551
+ console.log(`\u{1F9F9} Cleaning build directory: ${buildDirBase}...`);
552
+ await fs3.rm(buildDir, { recursive: true, force: true });
553
+ console.log("\u2728 Cleaned successfully!");
554
+ } catch (error) {
555
+ console.error("\u274C Error executing clean command:");
556
+ if (error instanceof Error) {
557
+ console.error(error.message);
558
+ }
559
+ process.exit(1);
560
+ }
561
+ });
562
+
563
+ // src/core/typecheck.ts
564
+ import { Command as Command4 } from "commander";
565
+ import { $ as $3 } from "execa";
566
+ var typecheckCommand = new Command4("typecheck").description(
567
+ "Runs TypeScript validation across the project without emitting files"
568
+ ).option("--watch", "Run typechecking in watch mode").action(async (options) => {
569
+ console.log("\u{1F50D} Running typecheck...");
570
+ try {
571
+ const args = ["tsc", "--noEmit"];
572
+ if (options.watch) {
573
+ args.push("--watch");
574
+ }
575
+ await $3({ stdio: "inherit" })`${args.join(" ")}`;
576
+ if (!options.watch) {
577
+ console.log("\u2705 Typecheck passed! No errors found.");
578
+ }
579
+ } catch (error) {
580
+ console.error(
581
+ "\u274C Typecheck failed. Please fix the TypeScript errors above."
582
+ );
583
+ process.exit(1);
584
+ }
585
+ });
586
+
587
+ // src/core/pack.ts
588
+ import * as fs4 from "fs/promises";
589
+ import * as path4 from "path";
590
+ import { Command as Command5 } from "commander";
591
+ import { $ as $4 } from "execa";
592
+ var packCommand = new Command5("pack").description(
593
+ "Creates a tarball (.tgz) of the built package to inspect before publishing"
594
+ ).action(async () => {
595
+ const cwd = process.cwd();
596
+ const pkgJsonPath = path4.join(cwd, "package.json");
597
+ try {
598
+ const packageJsonContent = await fs4.readFile(pkgJsonPath, {
599
+ encoding: "utf8"
600
+ });
601
+ const packageJson = JSON.parse(packageJsonContent);
602
+ const publishDirBase = packageJson.publishConfig?.directory;
603
+ if (!publishDirBase) {
604
+ throw new Error(`No publish directory specified in package.json.`);
605
+ }
606
+ const publishDir = path4.join(cwd, publishDirBase);
607
+ console.log(`\u{1F4E6} Packing package from directory: ${publishDirBase}...`);
608
+ await $4({
609
+ stdio: "inherit",
610
+ cwd: publishDir
611
+ })`npm pack`;
612
+ console.log(
613
+ "\u2705 Pack successful! You can inspect the generated .tgz file."
614
+ );
615
+ } catch (error) {
616
+ console.error("\u274C Error executing pack command:");
617
+ if (error instanceof Error) console.error(error.message);
618
+ process.exit(1);
619
+ }
620
+ });
621
+
622
+ // src/core/version.ts
623
+ import { Command as Command6 } from "commander";
624
+ import { $ as $5 } from "execa";
625
+ var versionCommand = new Command6("version").description("Bumps the package version (patch, minor, or major)").argument(
626
+ "<type>",
627
+ "Version update type (patch, minor, major, or specific version like 1.2.3)"
628
+ ).option("--no-git-tag-version", "Do not create a git tag").action(async (type, options) => {
629
+ const validTypes = [
630
+ "patch",
631
+ "minor",
632
+ "major",
633
+ "prepatch",
634
+ "preminor",
635
+ "premajor",
636
+ "prerelease"
637
+ ];
638
+ if (!validTypes.includes(type) && !/^\d+\.\d+\.\d+/.test(type)) {
639
+ console.error(
640
+ `\u274C Invalid version type: ${type}. Use patch, minor, major, or a valid semver.`
641
+ );
642
+ process.exit(1);
643
+ }
644
+ console.log(`\u{1F4C8} Bumping version (${type})...`);
645
+ try {
646
+ const args = ["version", type];
647
+ if (!options.gitTagVersion) {
648
+ args.push("--no-git-tag-version");
649
+ }
650
+ await $5({ stdio: "inherit" })`npm ${args}`;
651
+ console.log("\u2705 Version bumped successfully!");
652
+ } catch (error) {
653
+ console.error("\u274C Failed to bump version.");
654
+ process.exit(1);
655
+ }
656
+ });
657
+
658
+ // src/core/info.ts
659
+ import * as fs5 from "fs/promises";
660
+ import * as path5 from "path";
661
+ import { Command as Command7 } from "commander";
662
+ async function getDirSize(dirPath) {
663
+ let size = 0;
664
+ const files = await fs5.readdir(dirPath, { withFileTypes: true });
665
+ for (const file of files) {
666
+ const fullPath = path5.join(dirPath, file.name);
667
+ if (file.isDirectory()) {
668
+ size += await getDirSize(fullPath);
669
+ } else {
670
+ const stats = await fs5.stat(fullPath);
671
+ size += stats.size;
672
+ }
673
+ }
674
+ return size;
675
+ }
676
+ var infoCommand = new Command7("info").description("Displays size and file statistics of the built package").action(async () => {
677
+ const cwd = process.cwd();
678
+ const pkgJsonPath = path5.join(cwd, "package.json");
679
+ try {
680
+ const packageJsonContent = await fs5.readFile(pkgJsonPath, {
681
+ encoding: "utf8"
682
+ });
683
+ const packageJson = JSON.parse(packageJsonContent);
684
+ const publishDirBase = packageJson.publishConfig?.directory;
685
+ if (!publishDirBase) {
686
+ throw new Error(`No publish directory specified in package.json.`);
687
+ }
688
+ const publishDir = path5.join(cwd, publishDirBase);
689
+ const sizeBytes = await getDirSize(publishDir);
690
+ const sizeKB = (sizeBytes / 1024).toFixed(2);
691
+ const sizeMB = (sizeBytes / (1024 * 1024)).toFixed(2);
692
+ console.log(`
693
+ \u{1F4CA} Package Info: ${packageJson.name}`);
694
+ console.log(`================================`);
695
+ console.log(`Version: ${packageJson.version}`);
696
+ console.log(`Build Folder: ./${publishDirBase}`);
697
+ if (sizeBytes > 1024 * 1024) {
698
+ console.log(
699
+ `Total Size: ${sizeMB} MB \u26A0\uFE0F (Consider keeping packages under 1MB)`
700
+ );
701
+ } else {
702
+ console.log(`Total Size: ${sizeKB} KB \u2705`);
703
+ }
704
+ console.log(`================================
705
+ `);
706
+ } catch (error) {
707
+ console.error(
708
+ "\u274C Error fetching package info. Did you build the project first?"
709
+ );
710
+ process.exit(1);
711
+ }
712
+ });
713
+
714
+ // src/core/link.ts
715
+ import * as fs6 from "fs/promises";
716
+ import * as path6 from "path";
717
+ import { Command as Command8 } from "commander";
718
+ import { $ as $6 } from "execa";
719
+ var linkCommand = new Command8("link").description(
720
+ "Symlinks the built package directory so it can be tested in other local projects"
721
+ ).action(async () => {
722
+ const cwd = process.cwd();
723
+ const pkgJsonPath = path6.join(cwd, "package.json");
724
+ try {
725
+ const packageJsonContent = await fs6.readFile(pkgJsonPath, {
726
+ encoding: "utf8"
727
+ });
728
+ const packageJson = JSON.parse(packageJsonContent);
729
+ const publishDirBase = packageJson.publishConfig?.directory;
730
+ if (!publishDirBase) {
731
+ throw new Error(`No publish directory specified in package.json.`);
732
+ }
733
+ const publishDir = path6.join(cwd, publishDirBase);
734
+ console.log(`\u{1F517} Linking package from: ./${publishDirBase}...`);
735
+ await $6({
736
+ stdio: "inherit",
737
+ cwd: publishDir
738
+ })`npm link`;
739
+ console.log(`
740
+ \u2705 Successfully linked!`);
741
+ console.log(
742
+ `To use this in another project, go to that project and run:`
743
+ );
744
+ console.log(`\u{1F449} npm link ${packageJson.name}`);
745
+ } catch (error) {
746
+ console.error("\u274C Error executing link command:");
747
+ if (error instanceof Error) console.error(error.message);
748
+ process.exit(1);
749
+ }
750
+ });
751
+
752
+ // src/core/check-exports.ts
753
+ import * as fs7 from "fs/promises";
754
+ import * as path7 from "path";
755
+ import { Command as Command9 } from "commander";
756
+ async function fileExists(filePath) {
757
+ return fs7.stat(filePath).then(() => true).catch(() => false);
758
+ }
759
+ function extractPaths(exportsObj) {
760
+ let paths = [];
761
+ if (typeof exportsObj === "string") {
762
+ return [exportsObj];
763
+ }
764
+ if (typeof exportsObj === "object" && exportsObj !== null) {
765
+ for (const key of Object.values(exportsObj)) {
766
+ paths = paths.concat(extractPaths(key));
767
+ }
768
+ }
769
+ return paths;
770
+ }
771
+ var checkExportsCommand = new Command9("check-exports").description(
772
+ "Verifies that all files declared in package.json 'exports' actually exist in the build folder"
773
+ ).action(async () => {
774
+ const cwd = process.cwd();
775
+ const pkgJsonPath = path7.join(cwd, "package.json");
776
+ try {
777
+ const rootPkgContent = await fs7.readFile(pkgJsonPath, {
778
+ encoding: "utf8"
779
+ });
780
+ const publishDirBase = JSON.parse(rootPkgContent).publishConfig?.directory || "build";
781
+ const buildPkgPath = path7.join(cwd, publishDirBase, "package.json");
782
+ if (!await fileExists(buildPkgPath)) {
783
+ throw new Error(
784
+ `Could not find compiled package.json at ./${publishDirBase}/package.json. Did you build first?`
785
+ );
786
+ }
787
+ const buildPkgContent = await fs7.readFile(buildPkgPath, {
788
+ encoding: "utf8"
789
+ });
790
+ const buildPkg = JSON.parse(buildPkgContent);
791
+ if (!buildPkg.exports) {
792
+ console.log("\u26A0\uFE0F No 'exports' field found to check.");
793
+ return;
794
+ }
795
+ console.log(`\u{1F575}\uFE0F Checking exports mapping in ./${publishDirBase}...`);
796
+ const allPaths = extractPaths(buildPkg.exports);
797
+ let hasErrors = false;
798
+ for (const relativePath of allPaths) {
799
+ const absolutePath = path7.join(cwd, publishDirBase, relativePath);
800
+ const exists = await fileExists(absolutePath);
801
+ if (exists) {
802
+ console.log(` \u2705 Found: ${relativePath}`);
803
+ } else {
804
+ console.error(` \u274C Missing: ${relativePath}`);
805
+ hasErrors = true;
806
+ }
807
+ }
808
+ if (hasErrors) {
809
+ console.error(
810
+ "\n\u274C Export check failed! Some files declared in package.json are missing."
811
+ );
812
+ process.exit(1);
813
+ } else {
814
+ console.log("\n\u2728 All exported files are present and accounted for!");
815
+ }
816
+ } catch (error) {
817
+ if (error instanceof Error) console.error(error.message);
818
+ process.exit(1);
819
+ }
820
+ });
821
+
822
+ // src/core/watch.ts
823
+ import * as path8 from "path";
824
+ import { Command as Command10 } from "commander";
825
+
826
+ // node_modules/chokidar/index.js
827
+ import { EventEmitter } from "events";
828
+ import { stat as statcb, Stats } from "fs";
829
+ import { readdir as readdir3, stat as stat7 } from "fs/promises";
830
+ import * as sp2 from "path";
831
+
832
+ // node_modules/readdirp/index.js
833
+ import { lstat, readdir as readdir2, realpath, stat as stat5 } from "fs/promises";
834
+ import { join as pjoin, relative as prelative, resolve as presolve, sep as psep } from "path";
835
+ import { Readable } from "stream";
836
+ var EntryTypes = {
837
+ FILE_TYPE: "files",
838
+ DIR_TYPE: "directories",
839
+ FILE_DIR_TYPE: "files_directories",
840
+ EVERYTHING_TYPE: "all"
841
+ };
842
+ var defaultOptions = {
843
+ root: ".",
844
+ fileFilter: (_entryInfo) => true,
845
+ directoryFilter: (_entryInfo) => true,
846
+ type: EntryTypes.FILE_TYPE,
847
+ lstat: false,
848
+ depth: 2147483648,
849
+ alwaysStat: false,
850
+ highWaterMark: 4096
851
+ };
852
+ Object.freeze(defaultOptions);
853
+ var RECURSIVE_ERROR_CODE = "READDIRP_RECURSIVE_ERROR";
854
+ var NORMAL_FLOW_ERRORS = /* @__PURE__ */ new Set(["ENOENT", "EPERM", "EACCES", "ELOOP", RECURSIVE_ERROR_CODE]);
855
+ var ALL_TYPES = [
856
+ EntryTypes.DIR_TYPE,
857
+ EntryTypes.EVERYTHING_TYPE,
858
+ EntryTypes.FILE_DIR_TYPE,
859
+ EntryTypes.FILE_TYPE
860
+ ];
861
+ var DIR_TYPES = /* @__PURE__ */ new Set([
862
+ EntryTypes.DIR_TYPE,
863
+ EntryTypes.EVERYTHING_TYPE,
864
+ EntryTypes.FILE_DIR_TYPE
865
+ ]);
866
+ var FILE_TYPES = /* @__PURE__ */ new Set([
867
+ EntryTypes.EVERYTHING_TYPE,
868
+ EntryTypes.FILE_DIR_TYPE,
869
+ EntryTypes.FILE_TYPE
870
+ ]);
871
+ var isNormalFlowError = (error) => NORMAL_FLOW_ERRORS.has(error.code);
872
+ var wantBigintFsStats = process.platform === "win32";
873
+ var emptyFn = (_entryInfo) => true;
874
+ var normalizeFilter = (filter) => {
875
+ if (filter === void 0)
876
+ return emptyFn;
877
+ if (typeof filter === "function")
878
+ return filter;
879
+ if (typeof filter === "string") {
880
+ const fl = filter.trim();
881
+ return (entry) => entry.basename === fl;
882
+ }
883
+ if (Array.isArray(filter)) {
884
+ const trItems = filter.map((item) => item.trim());
885
+ return (entry) => trItems.some((f) => entry.basename === f);
886
+ }
887
+ return emptyFn;
888
+ };
889
+ var ReaddirpStream = class extends Readable {
890
+ parents;
891
+ reading;
892
+ parent;
893
+ _stat;
894
+ _maxDepth;
895
+ _wantsDir;
896
+ _wantsFile;
897
+ _wantsEverything;
898
+ _root;
899
+ _isDirent;
900
+ _statsProp;
901
+ _rdOptions;
902
+ _fileFilter;
903
+ _directoryFilter;
904
+ constructor(options = {}) {
905
+ super({
906
+ objectMode: true,
907
+ autoDestroy: true,
908
+ highWaterMark: options.highWaterMark
909
+ });
910
+ const opts = { ...defaultOptions, ...options };
911
+ const { root, type } = opts;
912
+ this._fileFilter = normalizeFilter(opts.fileFilter);
913
+ this._directoryFilter = normalizeFilter(opts.directoryFilter);
914
+ const statMethod = opts.lstat ? lstat : stat5;
915
+ if (wantBigintFsStats) {
916
+ this._stat = (path9) => statMethod(path9, { bigint: true });
917
+ } else {
918
+ this._stat = statMethod;
919
+ }
920
+ this._maxDepth = opts.depth != null && Number.isSafeInteger(opts.depth) ? opts.depth : defaultOptions.depth;
921
+ this._wantsDir = type ? DIR_TYPES.has(type) : false;
922
+ this._wantsFile = type ? FILE_TYPES.has(type) : false;
923
+ this._wantsEverything = type === EntryTypes.EVERYTHING_TYPE;
924
+ this._root = presolve(root);
925
+ this._isDirent = !opts.alwaysStat;
926
+ this._statsProp = this._isDirent ? "dirent" : "stats";
927
+ this._rdOptions = { encoding: "utf8", withFileTypes: this._isDirent };
928
+ this.parents = [this._exploreDir(root, 1)];
929
+ this.reading = false;
930
+ this.parent = void 0;
931
+ }
932
+ async _read(batch) {
933
+ if (this.reading)
934
+ return;
935
+ this.reading = true;
936
+ try {
937
+ while (!this.destroyed && batch > 0) {
938
+ const par = this.parent;
939
+ const fil = par && par.files;
940
+ if (fil && fil.length > 0) {
941
+ const { path: path9, depth } = par;
942
+ const slice = fil.splice(0, batch).map((dirent) => this._formatEntry(dirent, path9));
943
+ const awaited = await Promise.all(slice);
944
+ for (const entry of awaited) {
945
+ if (!entry)
946
+ continue;
947
+ if (this.destroyed)
948
+ return;
949
+ const entryType = await this._getEntryType(entry);
950
+ if (entryType === "directory" && this._directoryFilter(entry)) {
951
+ if (depth <= this._maxDepth) {
952
+ this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
953
+ }
954
+ if (this._wantsDir) {
955
+ this.push(entry);
956
+ batch--;
957
+ }
958
+ } else if ((entryType === "file" || this._includeAsFile(entry)) && this._fileFilter(entry)) {
959
+ if (this._wantsFile) {
960
+ this.push(entry);
961
+ batch--;
962
+ }
963
+ }
964
+ }
965
+ } else {
966
+ const parent = this.parents.pop();
967
+ if (!parent) {
968
+ this.push(null);
969
+ break;
970
+ }
971
+ this.parent = await parent;
972
+ if (this.destroyed)
973
+ return;
974
+ }
975
+ }
976
+ } catch (error) {
977
+ this.destroy(error);
978
+ } finally {
979
+ this.reading = false;
980
+ }
981
+ }
982
+ async _exploreDir(path9, depth) {
983
+ let files;
984
+ try {
985
+ files = await readdir2(path9, this._rdOptions);
986
+ } catch (error) {
987
+ this._onError(error);
988
+ }
989
+ return { files, depth, path: path9 };
990
+ }
991
+ async _formatEntry(dirent, path9) {
992
+ let entry;
993
+ const basename4 = this._isDirent ? dirent.name : dirent;
994
+ try {
995
+ const fullPath = presolve(pjoin(path9, basename4));
996
+ entry = { path: prelative(this._root, fullPath), fullPath, basename: basename4 };
997
+ entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
998
+ } catch (err) {
999
+ this._onError(err);
1000
+ return;
1001
+ }
1002
+ return entry;
1003
+ }
1004
+ _onError(err) {
1005
+ if (isNormalFlowError(err) && !this.destroyed) {
1006
+ this.emit("warn", err);
1007
+ } else {
1008
+ this.destroy(err);
1009
+ }
1010
+ }
1011
+ async _getEntryType(entry) {
1012
+ if (!entry && this._statsProp in entry) {
1013
+ return "";
1014
+ }
1015
+ const stats = entry[this._statsProp];
1016
+ if (stats.isFile())
1017
+ return "file";
1018
+ if (stats.isDirectory())
1019
+ return "directory";
1020
+ if (stats && stats.isSymbolicLink()) {
1021
+ const full = entry.fullPath;
1022
+ try {
1023
+ const entryRealPath = await realpath(full);
1024
+ const entryRealPathStats = await lstat(entryRealPath);
1025
+ if (entryRealPathStats.isFile()) {
1026
+ return "file";
1027
+ }
1028
+ if (entryRealPathStats.isDirectory()) {
1029
+ const len = entryRealPath.length;
1030
+ if (full.startsWith(entryRealPath) && full.substr(len, 1) === psep) {
1031
+ const recursiveError = new Error(`Circular symlink detected: "${full}" points to "${entryRealPath}"`);
1032
+ recursiveError.code = RECURSIVE_ERROR_CODE;
1033
+ return this._onError(recursiveError);
1034
+ }
1035
+ return "directory";
1036
+ }
1037
+ } catch (error) {
1038
+ this._onError(error);
1039
+ return "";
1040
+ }
1041
+ }
1042
+ }
1043
+ _includeAsFile(entry) {
1044
+ const stats = entry && entry[this._statsProp];
1045
+ return stats && this._wantsEverything && !stats.isDirectory();
1046
+ }
1047
+ };
1048
+ function readdirp(root, options = {}) {
1049
+ let type = options.entryType || options.type;
1050
+ if (type === "both")
1051
+ type = EntryTypes.FILE_DIR_TYPE;
1052
+ if (type)
1053
+ options.type = type;
1054
+ if (!root) {
1055
+ throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");
1056
+ } else if (typeof root !== "string") {
1057
+ throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");
1058
+ } else if (type && !ALL_TYPES.includes(type)) {
1059
+ throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(", ")}`);
1060
+ }
1061
+ options.root = root;
1062
+ return new ReaddirpStream(options);
1063
+ }
1064
+
1065
+ // node_modules/chokidar/handler.js
1066
+ import { watch as fs_watch, unwatchFile, watchFile } from "fs";
1067
+ import { realpath as fsrealpath, lstat as lstat2, open, stat as stat6 } from "fs/promises";
1068
+ import { type as osType } from "os";
1069
+ import * as sp from "path";
1070
+ var STR_DATA = "data";
1071
+ var STR_END = "end";
1072
+ var STR_CLOSE = "close";
1073
+ var EMPTY_FN = () => {
1074
+ };
1075
+ var pl = process.platform;
1076
+ var isWindows = pl === "win32";
1077
+ var isMacos = pl === "darwin";
1078
+ var isLinux = pl === "linux";
1079
+ var isFreeBSD = pl === "freebsd";
1080
+ var isIBMi = osType() === "OS400";
1081
+ var EVENTS = {
1082
+ ALL: "all",
1083
+ READY: "ready",
1084
+ ADD: "add",
1085
+ CHANGE: "change",
1086
+ ADD_DIR: "addDir",
1087
+ UNLINK: "unlink",
1088
+ UNLINK_DIR: "unlinkDir",
1089
+ RAW: "raw",
1090
+ ERROR: "error"
1091
+ };
1092
+ var EV = EVENTS;
1093
+ var THROTTLE_MODE_WATCH = "watch";
1094
+ var statMethods = { lstat: lstat2, stat: stat6 };
1095
+ var KEY_LISTENERS = "listeners";
1096
+ var KEY_ERR = "errHandlers";
1097
+ var KEY_RAW = "rawEmitters";
1098
+ var HANDLER_KEYS = [KEY_LISTENERS, KEY_ERR, KEY_RAW];
1099
+ var binaryExtensions = /* @__PURE__ */ new Set([
1100
+ "3dm",
1101
+ "3ds",
1102
+ "3g2",
1103
+ "3gp",
1104
+ "7z",
1105
+ "a",
1106
+ "aac",
1107
+ "adp",
1108
+ "afdesign",
1109
+ "afphoto",
1110
+ "afpub",
1111
+ "ai",
1112
+ "aif",
1113
+ "aiff",
1114
+ "alz",
1115
+ "ape",
1116
+ "apk",
1117
+ "appimage",
1118
+ "ar",
1119
+ "arj",
1120
+ "asf",
1121
+ "au",
1122
+ "avi",
1123
+ "bak",
1124
+ "baml",
1125
+ "bh",
1126
+ "bin",
1127
+ "bk",
1128
+ "bmp",
1129
+ "btif",
1130
+ "bz2",
1131
+ "bzip2",
1132
+ "cab",
1133
+ "caf",
1134
+ "cgm",
1135
+ "class",
1136
+ "cmx",
1137
+ "cpio",
1138
+ "cr2",
1139
+ "cur",
1140
+ "dat",
1141
+ "dcm",
1142
+ "deb",
1143
+ "dex",
1144
+ "djvu",
1145
+ "dll",
1146
+ "dmg",
1147
+ "dng",
1148
+ "doc",
1149
+ "docm",
1150
+ "docx",
1151
+ "dot",
1152
+ "dotm",
1153
+ "dra",
1154
+ "DS_Store",
1155
+ "dsk",
1156
+ "dts",
1157
+ "dtshd",
1158
+ "dvb",
1159
+ "dwg",
1160
+ "dxf",
1161
+ "ecelp4800",
1162
+ "ecelp7470",
1163
+ "ecelp9600",
1164
+ "egg",
1165
+ "eol",
1166
+ "eot",
1167
+ "epub",
1168
+ "exe",
1169
+ "f4v",
1170
+ "fbs",
1171
+ "fh",
1172
+ "fla",
1173
+ "flac",
1174
+ "flatpak",
1175
+ "fli",
1176
+ "flv",
1177
+ "fpx",
1178
+ "fst",
1179
+ "fvt",
1180
+ "g3",
1181
+ "gh",
1182
+ "gif",
1183
+ "graffle",
1184
+ "gz",
1185
+ "gzip",
1186
+ "h261",
1187
+ "h263",
1188
+ "h264",
1189
+ "icns",
1190
+ "ico",
1191
+ "ief",
1192
+ "img",
1193
+ "ipa",
1194
+ "iso",
1195
+ "jar",
1196
+ "jpeg",
1197
+ "jpg",
1198
+ "jpgv",
1199
+ "jpm",
1200
+ "jxr",
1201
+ "key",
1202
+ "ktx",
1203
+ "lha",
1204
+ "lib",
1205
+ "lvp",
1206
+ "lz",
1207
+ "lzh",
1208
+ "lzma",
1209
+ "lzo",
1210
+ "m3u",
1211
+ "m4a",
1212
+ "m4v",
1213
+ "mar",
1214
+ "mdi",
1215
+ "mht",
1216
+ "mid",
1217
+ "midi",
1218
+ "mj2",
1219
+ "mka",
1220
+ "mkv",
1221
+ "mmr",
1222
+ "mng",
1223
+ "mobi",
1224
+ "mov",
1225
+ "movie",
1226
+ "mp3",
1227
+ "mp4",
1228
+ "mp4a",
1229
+ "mpeg",
1230
+ "mpg",
1231
+ "mpga",
1232
+ "mxu",
1233
+ "nef",
1234
+ "npx",
1235
+ "numbers",
1236
+ "nupkg",
1237
+ "o",
1238
+ "odp",
1239
+ "ods",
1240
+ "odt",
1241
+ "oga",
1242
+ "ogg",
1243
+ "ogv",
1244
+ "otf",
1245
+ "ott",
1246
+ "pages",
1247
+ "pbm",
1248
+ "pcx",
1249
+ "pdb",
1250
+ "pdf",
1251
+ "pea",
1252
+ "pgm",
1253
+ "pic",
1254
+ "png",
1255
+ "pnm",
1256
+ "pot",
1257
+ "potm",
1258
+ "potx",
1259
+ "ppa",
1260
+ "ppam",
1261
+ "ppm",
1262
+ "pps",
1263
+ "ppsm",
1264
+ "ppsx",
1265
+ "ppt",
1266
+ "pptm",
1267
+ "pptx",
1268
+ "psd",
1269
+ "pya",
1270
+ "pyc",
1271
+ "pyo",
1272
+ "pyv",
1273
+ "qt",
1274
+ "rar",
1275
+ "ras",
1276
+ "raw",
1277
+ "resources",
1278
+ "rgb",
1279
+ "rip",
1280
+ "rlc",
1281
+ "rmf",
1282
+ "rmvb",
1283
+ "rpm",
1284
+ "rtf",
1285
+ "rz",
1286
+ "s3m",
1287
+ "s7z",
1288
+ "scpt",
1289
+ "sgi",
1290
+ "shar",
1291
+ "snap",
1292
+ "sil",
1293
+ "sketch",
1294
+ "slk",
1295
+ "smv",
1296
+ "snk",
1297
+ "so",
1298
+ "stl",
1299
+ "suo",
1300
+ "sub",
1301
+ "swf",
1302
+ "tar",
1303
+ "tbz",
1304
+ "tbz2",
1305
+ "tga",
1306
+ "tgz",
1307
+ "thmx",
1308
+ "tif",
1309
+ "tiff",
1310
+ "tlz",
1311
+ "ttc",
1312
+ "ttf",
1313
+ "txz",
1314
+ "udf",
1315
+ "uvh",
1316
+ "uvi",
1317
+ "uvm",
1318
+ "uvp",
1319
+ "uvs",
1320
+ "uvu",
1321
+ "viv",
1322
+ "vob",
1323
+ "war",
1324
+ "wav",
1325
+ "wax",
1326
+ "wbmp",
1327
+ "wdp",
1328
+ "weba",
1329
+ "webm",
1330
+ "webp",
1331
+ "whl",
1332
+ "wim",
1333
+ "wm",
1334
+ "wma",
1335
+ "wmv",
1336
+ "wmx",
1337
+ "woff",
1338
+ "woff2",
1339
+ "wrm",
1340
+ "wvx",
1341
+ "xbm",
1342
+ "xif",
1343
+ "xla",
1344
+ "xlam",
1345
+ "xls",
1346
+ "xlsb",
1347
+ "xlsm",
1348
+ "xlsx",
1349
+ "xlt",
1350
+ "xltm",
1351
+ "xltx",
1352
+ "xm",
1353
+ "xmind",
1354
+ "xpi",
1355
+ "xpm",
1356
+ "xwd",
1357
+ "xz",
1358
+ "z",
1359
+ "zip",
1360
+ "zipx"
1361
+ ]);
1362
+ var isBinaryPath = (filePath) => binaryExtensions.has(sp.extname(filePath).slice(1).toLowerCase());
1363
+ var foreach = (val, fn) => {
1364
+ if (val instanceof Set) {
1365
+ val.forEach(fn);
1366
+ } else {
1367
+ fn(val);
1368
+ }
1369
+ };
1370
+ var addAndConvert = (main2, prop, item) => {
1371
+ let container = main2[prop];
1372
+ if (!(container instanceof Set)) {
1373
+ main2[prop] = container = /* @__PURE__ */ new Set([container]);
1374
+ }
1375
+ container.add(item);
1376
+ };
1377
+ var clearItem = (cont) => (key) => {
1378
+ const set = cont[key];
1379
+ if (set instanceof Set) {
1380
+ set.clear();
1381
+ } else {
1382
+ delete cont[key];
1383
+ }
1384
+ };
1385
+ var delFromSet = (main2, prop, item) => {
1386
+ const container = main2[prop];
1387
+ if (container instanceof Set) {
1388
+ container.delete(item);
1389
+ } else if (container === item) {
1390
+ delete main2[prop];
1391
+ }
1392
+ };
1393
+ var isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
1394
+ var FsWatchInstances = /* @__PURE__ */ new Map();
1395
+ function createFsWatchInstance(path9, options, listener, errHandler, emitRaw) {
1396
+ const handleEvent = (rawEvent, evPath) => {
1397
+ listener(path9);
1398
+ emitRaw(rawEvent, evPath, { watchedPath: path9 });
1399
+ if (evPath && path9 !== evPath) {
1400
+ fsWatchBroadcast(sp.resolve(path9, evPath), KEY_LISTENERS, sp.join(path9, evPath));
1401
+ }
1402
+ };
1403
+ try {
1404
+ return fs_watch(path9, {
1405
+ persistent: options.persistent
1406
+ }, handleEvent);
1407
+ } catch (error) {
1408
+ errHandler(error);
1409
+ return void 0;
1410
+ }
1411
+ }
1412
+ var fsWatchBroadcast = (fullPath, listenerType, val1, val2, val3) => {
1413
+ const cont = FsWatchInstances.get(fullPath);
1414
+ if (!cont)
1415
+ return;
1416
+ foreach(cont[listenerType], (listener) => {
1417
+ listener(val1, val2, val3);
1418
+ });
1419
+ };
1420
+ var setFsWatchListener = (path9, fullPath, options, handlers) => {
1421
+ const { listener, errHandler, rawEmitter } = handlers;
1422
+ let cont = FsWatchInstances.get(fullPath);
1423
+ let watcher;
1424
+ if (!options.persistent) {
1425
+ watcher = createFsWatchInstance(path9, options, listener, errHandler, rawEmitter);
1426
+ if (!watcher)
1427
+ return;
1428
+ return watcher.close.bind(watcher);
1429
+ }
1430
+ if (cont) {
1431
+ addAndConvert(cont, KEY_LISTENERS, listener);
1432
+ addAndConvert(cont, KEY_ERR, errHandler);
1433
+ addAndConvert(cont, KEY_RAW, rawEmitter);
1434
+ } else {
1435
+ watcher = createFsWatchInstance(
1436
+ path9,
1437
+ options,
1438
+ fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS),
1439
+ errHandler,
1440
+ // no need to use broadcast here
1441
+ fsWatchBroadcast.bind(null, fullPath, KEY_RAW)
1442
+ );
1443
+ if (!watcher)
1444
+ return;
1445
+ watcher.on(EV.ERROR, async (error) => {
1446
+ const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
1447
+ if (cont)
1448
+ cont.watcherUnusable = true;
1449
+ if (isWindows && error.code === "EPERM") {
1450
+ try {
1451
+ const fd = await open(path9, "r");
1452
+ await fd.close();
1453
+ broadcastErr(error);
1454
+ } catch (err) {
1455
+ }
1456
+ } else {
1457
+ broadcastErr(error);
1458
+ }
1459
+ });
1460
+ cont = {
1461
+ listeners: listener,
1462
+ errHandlers: errHandler,
1463
+ rawEmitters: rawEmitter,
1464
+ watcher
1465
+ };
1466
+ FsWatchInstances.set(fullPath, cont);
1467
+ }
1468
+ return () => {
1469
+ delFromSet(cont, KEY_LISTENERS, listener);
1470
+ delFromSet(cont, KEY_ERR, errHandler);
1471
+ delFromSet(cont, KEY_RAW, rawEmitter);
1472
+ if (isEmptySet(cont.listeners)) {
1473
+ cont.watcher.close();
1474
+ FsWatchInstances.delete(fullPath);
1475
+ HANDLER_KEYS.forEach(clearItem(cont));
1476
+ cont.watcher = void 0;
1477
+ Object.freeze(cont);
1478
+ }
1479
+ };
1480
+ };
1481
+ var FsWatchFileInstances = /* @__PURE__ */ new Map();
1482
+ var setFsWatchFileListener = (path9, fullPath, options, handlers) => {
1483
+ const { listener, rawEmitter } = handlers;
1484
+ let cont = FsWatchFileInstances.get(fullPath);
1485
+ const copts = cont && cont.options;
1486
+ if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
1487
+ unwatchFile(fullPath);
1488
+ cont = void 0;
1489
+ }
1490
+ if (cont) {
1491
+ addAndConvert(cont, KEY_LISTENERS, listener);
1492
+ addAndConvert(cont, KEY_RAW, rawEmitter);
1493
+ } else {
1494
+ cont = {
1495
+ listeners: listener,
1496
+ rawEmitters: rawEmitter,
1497
+ options,
1498
+ watcher: watchFile(fullPath, options, (curr, prev) => {
1499
+ foreach(cont.rawEmitters, (rawEmitter2) => {
1500
+ rawEmitter2(EV.CHANGE, fullPath, { curr, prev });
1501
+ });
1502
+ const currmtime = curr.mtimeMs;
1503
+ if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
1504
+ foreach(cont.listeners, (listener2) => listener2(path9, curr));
1505
+ }
1506
+ })
1507
+ };
1508
+ FsWatchFileInstances.set(fullPath, cont);
1509
+ }
1510
+ return () => {
1511
+ delFromSet(cont, KEY_LISTENERS, listener);
1512
+ delFromSet(cont, KEY_RAW, rawEmitter);
1513
+ if (isEmptySet(cont.listeners)) {
1514
+ FsWatchFileInstances.delete(fullPath);
1515
+ unwatchFile(fullPath);
1516
+ cont.options = cont.watcher = void 0;
1517
+ Object.freeze(cont);
1518
+ }
1519
+ };
1520
+ };
1521
+ var NodeFsHandler = class {
1522
+ fsw;
1523
+ _boundHandleError;
1524
+ constructor(fsW) {
1525
+ this.fsw = fsW;
1526
+ this._boundHandleError = (error) => fsW._handleError(error);
1527
+ }
1528
+ /**
1529
+ * Watch file for changes with fs_watchFile or fs_watch.
1530
+ * @param path to file or dir
1531
+ * @param listener on fs change
1532
+ * @returns closer for the watcher instance
1533
+ */
1534
+ _watchWithNodeFs(path9, listener) {
1535
+ const opts = this.fsw.options;
1536
+ const directory = sp.dirname(path9);
1537
+ const basename4 = sp.basename(path9);
1538
+ const parent = this.fsw._getWatchedDir(directory);
1539
+ parent.add(basename4);
1540
+ const absolutePath = sp.resolve(path9);
1541
+ const options = {
1542
+ persistent: opts.persistent
1543
+ };
1544
+ if (!listener)
1545
+ listener = EMPTY_FN;
1546
+ let closer;
1547
+ if (opts.usePolling) {
1548
+ const enableBin = opts.interval !== opts.binaryInterval;
1549
+ options.interval = enableBin && isBinaryPath(basename4) ? opts.binaryInterval : opts.interval;
1550
+ closer = setFsWatchFileListener(path9, absolutePath, options, {
1551
+ listener,
1552
+ rawEmitter: this.fsw._emitRaw
1553
+ });
1554
+ } else {
1555
+ closer = setFsWatchListener(path9, absolutePath, options, {
1556
+ listener,
1557
+ errHandler: this._boundHandleError,
1558
+ rawEmitter: this.fsw._emitRaw
1559
+ });
1560
+ }
1561
+ return closer;
1562
+ }
1563
+ /**
1564
+ * Watch a file and emit add event if warranted.
1565
+ * @returns closer for the watcher instance
1566
+ */
1567
+ _handleFile(file, stats, initialAdd) {
1568
+ if (this.fsw.closed) {
1569
+ return;
1570
+ }
1571
+ const dirname4 = sp.dirname(file);
1572
+ const basename4 = sp.basename(file);
1573
+ const parent = this.fsw._getWatchedDir(dirname4);
1574
+ let prevStats = stats;
1575
+ if (parent.has(basename4))
1576
+ return;
1577
+ const listener = async (path9, newStats) => {
1578
+ if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5))
1579
+ return;
1580
+ if (!newStats || newStats.mtimeMs === 0) {
1581
+ try {
1582
+ const newStats2 = await stat6(file);
1583
+ if (this.fsw.closed)
1584
+ return;
1585
+ const at = newStats2.atimeMs;
1586
+ const mt = newStats2.mtimeMs;
1587
+ if (!at || at <= mt || mt !== prevStats.mtimeMs) {
1588
+ this.fsw._emit(EV.CHANGE, file, newStats2);
1589
+ }
1590
+ if ((isMacos || isLinux || isFreeBSD) && prevStats.ino !== newStats2.ino) {
1591
+ this.fsw._closeFile(path9);
1592
+ prevStats = newStats2;
1593
+ const closer2 = this._watchWithNodeFs(file, listener);
1594
+ if (closer2)
1595
+ this.fsw._addPathCloser(path9, closer2);
1596
+ } else {
1597
+ prevStats = newStats2;
1598
+ }
1599
+ } catch (error) {
1600
+ this.fsw._remove(dirname4, basename4);
1601
+ }
1602
+ } else if (parent.has(basename4)) {
1603
+ const at = newStats.atimeMs;
1604
+ const mt = newStats.mtimeMs;
1605
+ if (!at || at <= mt || mt !== prevStats.mtimeMs) {
1606
+ this.fsw._emit(EV.CHANGE, file, newStats);
1607
+ }
1608
+ prevStats = newStats;
1609
+ }
1610
+ };
1611
+ const closer = this._watchWithNodeFs(file, listener);
1612
+ if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
1613
+ if (!this.fsw._throttle(EV.ADD, file, 0))
1614
+ return;
1615
+ this.fsw._emit(EV.ADD, file, stats);
1616
+ }
1617
+ return closer;
1618
+ }
1619
+ /**
1620
+ * Handle symlinks encountered while reading a dir.
1621
+ * @param entry returned by readdirp
1622
+ * @param directory path of dir being read
1623
+ * @param path of this item
1624
+ * @param item basename of this item
1625
+ * @returns true if no more processing is needed for this entry.
1626
+ */
1627
+ async _handleSymlink(entry, directory, path9, item) {
1628
+ if (this.fsw.closed) {
1629
+ return;
1630
+ }
1631
+ const full = entry.fullPath;
1632
+ const dir = this.fsw._getWatchedDir(directory);
1633
+ if (!this.fsw.options.followSymlinks) {
1634
+ this.fsw._incrReadyCount();
1635
+ let linkPath;
1636
+ try {
1637
+ linkPath = await fsrealpath(path9);
1638
+ } catch (e) {
1639
+ this.fsw._emitReady();
1640
+ return true;
1641
+ }
1642
+ if (this.fsw.closed)
1643
+ return;
1644
+ if (dir.has(item)) {
1645
+ if (this.fsw._symlinkPaths.get(full) !== linkPath) {
1646
+ this.fsw._symlinkPaths.set(full, linkPath);
1647
+ this.fsw._emit(EV.CHANGE, path9, entry.stats);
1648
+ }
1649
+ } else {
1650
+ dir.add(item);
1651
+ this.fsw._symlinkPaths.set(full, linkPath);
1652
+ this.fsw._emit(EV.ADD, path9, entry.stats);
1653
+ }
1654
+ this.fsw._emitReady();
1655
+ return true;
1656
+ }
1657
+ if (this.fsw._symlinkPaths.has(full)) {
1658
+ return true;
1659
+ }
1660
+ this.fsw._symlinkPaths.set(full, true);
1661
+ }
1662
+ _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
1663
+ directory = sp.join(directory, "");
1664
+ const throttleKey = target ? `${directory}:${target}` : directory;
1665
+ throttler = this.fsw._throttle("readdir", throttleKey, 1e3);
1666
+ if (!throttler)
1667
+ return;
1668
+ const previous = this.fsw._getWatchedDir(wh.path);
1669
+ const current = /* @__PURE__ */ new Set();
1670
+ let stream = this.fsw._readdirp(directory, {
1671
+ fileFilter: (entry) => wh.filterPath(entry),
1672
+ directoryFilter: (entry) => wh.filterDir(entry)
1673
+ });
1674
+ if (!stream)
1675
+ return;
1676
+ stream.on(STR_DATA, async (entry) => {
1677
+ if (this.fsw.closed) {
1678
+ stream = void 0;
1679
+ return;
1680
+ }
1681
+ const item = entry.path;
1682
+ let path9 = sp.join(directory, item);
1683
+ current.add(item);
1684
+ if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path9, item)) {
1685
+ return;
1686
+ }
1687
+ if (this.fsw.closed) {
1688
+ stream = void 0;
1689
+ return;
1690
+ }
1691
+ if (item === target || !target && !previous.has(item)) {
1692
+ this.fsw._incrReadyCount();
1693
+ path9 = sp.join(dir, sp.relative(dir, path9));
1694
+ this._addToNodeFs(path9, initialAdd, wh, depth + 1);
1695
+ }
1696
+ }).on(EV.ERROR, this._boundHandleError);
1697
+ return new Promise((resolve4, reject) => {
1698
+ if (!stream)
1699
+ return reject();
1700
+ stream.once(STR_END, () => {
1701
+ if (this.fsw.closed) {
1702
+ stream = void 0;
1703
+ return;
1704
+ }
1705
+ const wasThrottled = throttler ? throttler.clear() : false;
1706
+ resolve4(void 0);
1707
+ previous.getChildren().filter((item) => {
1708
+ return item !== directory && !current.has(item);
1709
+ }).forEach((item) => {
1710
+ this.fsw._remove(directory, item);
1711
+ });
1712
+ stream = void 0;
1713
+ if (wasThrottled)
1714
+ this._handleRead(directory, false, wh, target, dir, depth, throttler);
1715
+ });
1716
+ });
1717
+ }
1718
+ /**
1719
+ * Read directory to add / remove files from `@watched` list and re-read it on change.
1720
+ * @param dir fs path
1721
+ * @param stats
1722
+ * @param initialAdd
1723
+ * @param depth relative to user-supplied path
1724
+ * @param target child path targeted for watch
1725
+ * @param wh Common watch helpers for this path
1726
+ * @param realpath
1727
+ * @returns closer for the watcher instance.
1728
+ */
1729
+ async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath2) {
1730
+ const parentDir = this.fsw._getWatchedDir(sp.dirname(dir));
1731
+ const tracked = parentDir.has(sp.basename(dir));
1732
+ if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
1733
+ this.fsw._emit(EV.ADD_DIR, dir, stats);
1734
+ }
1735
+ parentDir.add(sp.basename(dir));
1736
+ this.fsw._getWatchedDir(dir);
1737
+ let throttler;
1738
+ let closer;
1739
+ const oDepth = this.fsw.options.depth;
1740
+ if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath2)) {
1741
+ if (!target) {
1742
+ await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
1743
+ if (this.fsw.closed)
1744
+ return;
1745
+ }
1746
+ closer = this._watchWithNodeFs(dir, (dirPath, stats2) => {
1747
+ if (stats2 && stats2.mtimeMs === 0)
1748
+ return;
1749
+ this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
1750
+ });
1751
+ }
1752
+ return closer;
1753
+ }
1754
+ /**
1755
+ * Handle added file, directory, or glob pattern.
1756
+ * Delegates call to _handleFile / _handleDir after checks.
1757
+ * @param path to file or ir
1758
+ * @param initialAdd was the file added at watch instantiation?
1759
+ * @param priorWh depth relative to user-supplied path
1760
+ * @param depth Child path actually targeted for watch
1761
+ * @param target Child path actually targeted for watch
1762
+ */
1763
+ async _addToNodeFs(path9, initialAdd, priorWh, depth, target) {
1764
+ const ready = this.fsw._emitReady;
1765
+ if (this.fsw._isIgnored(path9) || this.fsw.closed) {
1766
+ ready();
1767
+ return false;
1768
+ }
1769
+ const wh = this.fsw._getWatchHelpers(path9);
1770
+ if (priorWh) {
1771
+ wh.filterPath = (entry) => priorWh.filterPath(entry);
1772
+ wh.filterDir = (entry) => priorWh.filterDir(entry);
1773
+ }
1774
+ try {
1775
+ const stats = await statMethods[wh.statMethod](wh.watchPath);
1776
+ if (this.fsw.closed)
1777
+ return;
1778
+ if (this.fsw._isIgnored(wh.watchPath, stats)) {
1779
+ ready();
1780
+ return false;
1781
+ }
1782
+ const follow = this.fsw.options.followSymlinks;
1783
+ let closer;
1784
+ if (stats.isDirectory()) {
1785
+ const absPath = sp.resolve(path9);
1786
+ const targetPath = follow ? await fsrealpath(path9) : path9;
1787
+ if (this.fsw.closed)
1788
+ return;
1789
+ closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
1790
+ if (this.fsw.closed)
1791
+ return;
1792
+ if (absPath !== targetPath && targetPath !== void 0) {
1793
+ this.fsw._symlinkPaths.set(absPath, targetPath);
1794
+ }
1795
+ } else if (stats.isSymbolicLink()) {
1796
+ const targetPath = follow ? await fsrealpath(path9) : path9;
1797
+ if (this.fsw.closed)
1798
+ return;
1799
+ const parent = sp.dirname(wh.watchPath);
1800
+ this.fsw._getWatchedDir(parent).add(wh.watchPath);
1801
+ this.fsw._emit(EV.ADD, wh.watchPath, stats);
1802
+ closer = await this._handleDir(parent, stats, initialAdd, depth, path9, wh, targetPath);
1803
+ if (this.fsw.closed)
1804
+ return;
1805
+ if (targetPath !== void 0) {
1806
+ this.fsw._symlinkPaths.set(sp.resolve(path9), targetPath);
1807
+ }
1808
+ } else {
1809
+ closer = this._handleFile(wh.watchPath, stats, initialAdd);
1810
+ }
1811
+ ready();
1812
+ if (closer)
1813
+ this.fsw._addPathCloser(path9, closer);
1814
+ return false;
1815
+ } catch (error) {
1816
+ if (this.fsw._handleError(error)) {
1817
+ ready();
1818
+ return path9;
1819
+ }
1820
+ }
1821
+ }
1822
+ };
1823
+
1824
+ // node_modules/chokidar/index.js
1825
+ var SLASH = "/";
1826
+ var SLASH_SLASH = "//";
1827
+ var ONE_DOT = ".";
1828
+ var TWO_DOTS = "..";
1829
+ var STRING_TYPE = "string";
1830
+ var BACK_SLASH_RE = /\\/g;
1831
+ var DOUBLE_SLASH_RE = /\/\//g;
1832
+ var DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
1833
+ var REPLACER_RE = /^\.[/\\]/;
1834
+ function arrify(item) {
1835
+ return Array.isArray(item) ? item : [item];
1836
+ }
1837
+ var isMatcherObject = (matcher) => typeof matcher === "object" && matcher !== null && !(matcher instanceof RegExp);
1838
+ function createPattern(matcher) {
1839
+ if (typeof matcher === "function")
1840
+ return matcher;
1841
+ if (typeof matcher === "string")
1842
+ return (string) => matcher === string;
1843
+ if (matcher instanceof RegExp)
1844
+ return (string) => matcher.test(string);
1845
+ if (typeof matcher === "object" && matcher !== null) {
1846
+ return (string) => {
1847
+ if (matcher.path === string)
1848
+ return true;
1849
+ if (matcher.recursive) {
1850
+ const relative3 = sp2.relative(matcher.path, string);
1851
+ if (!relative3) {
1852
+ return false;
1853
+ }
1854
+ return !relative3.startsWith("..") && !sp2.isAbsolute(relative3);
1855
+ }
1856
+ return false;
1857
+ };
1858
+ }
1859
+ return () => false;
1860
+ }
1861
+ function normalizePath(path9) {
1862
+ if (typeof path9 !== "string")
1863
+ throw new Error("string expected");
1864
+ path9 = sp2.normalize(path9);
1865
+ path9 = path9.replace(/\\/g, "/");
1866
+ let prepend = false;
1867
+ if (path9.startsWith("//"))
1868
+ prepend = true;
1869
+ path9 = path9.replace(DOUBLE_SLASH_RE, "/");
1870
+ if (prepend)
1871
+ path9 = "/" + path9;
1872
+ return path9;
1873
+ }
1874
+ function matchPatterns(patterns, testString, stats) {
1875
+ const path9 = normalizePath(testString);
1876
+ for (let index = 0; index < patterns.length; index++) {
1877
+ const pattern = patterns[index];
1878
+ if (pattern(path9, stats)) {
1879
+ return true;
1880
+ }
1881
+ }
1882
+ return false;
1883
+ }
1884
+ function anymatch(matchers, testString) {
1885
+ if (matchers == null) {
1886
+ throw new TypeError("anymatch: specify first argument");
1887
+ }
1888
+ const matchersArray = arrify(matchers);
1889
+ const patterns = matchersArray.map((matcher) => createPattern(matcher));
1890
+ if (testString == null) {
1891
+ return (testString2, stats) => {
1892
+ return matchPatterns(patterns, testString2, stats);
1893
+ };
1894
+ }
1895
+ return matchPatterns(patterns, testString);
1896
+ }
1897
+ var unifyPaths = (paths_) => {
1898
+ const paths = arrify(paths_).flat();
1899
+ if (!paths.every((p) => typeof p === STRING_TYPE)) {
1900
+ throw new TypeError(`Non-string provided as watch path: ${paths}`);
1901
+ }
1902
+ return paths.map(normalizePathToUnix);
1903
+ };
1904
+ var toUnix = (string) => {
1905
+ let str = string.replace(BACK_SLASH_RE, SLASH);
1906
+ let prepend = false;
1907
+ if (str.startsWith(SLASH_SLASH)) {
1908
+ prepend = true;
1909
+ }
1910
+ str = str.replace(DOUBLE_SLASH_RE, SLASH);
1911
+ if (prepend) {
1912
+ str = SLASH + str;
1913
+ }
1914
+ return str;
1915
+ };
1916
+ var normalizePathToUnix = (path9) => toUnix(sp2.normalize(toUnix(path9)));
1917
+ var normalizeIgnored = (cwd = "") => (path9) => {
1918
+ if (typeof path9 === "string") {
1919
+ return normalizePathToUnix(sp2.isAbsolute(path9) ? path9 : sp2.join(cwd, path9));
1920
+ } else {
1921
+ return path9;
1922
+ }
1923
+ };
1924
+ var getAbsolutePath = (path9, cwd) => {
1925
+ if (sp2.isAbsolute(path9)) {
1926
+ return path9;
1927
+ }
1928
+ return sp2.join(cwd, path9);
1929
+ };
1930
+ var EMPTY_SET = Object.freeze(/* @__PURE__ */ new Set());
1931
+ var DirEntry = class {
1932
+ path;
1933
+ _removeWatcher;
1934
+ items;
1935
+ constructor(dir, removeWatcher) {
1936
+ this.path = dir;
1937
+ this._removeWatcher = removeWatcher;
1938
+ this.items = /* @__PURE__ */ new Set();
1939
+ }
1940
+ add(item) {
1941
+ const { items } = this;
1942
+ if (!items)
1943
+ return;
1944
+ if (item !== ONE_DOT && item !== TWO_DOTS)
1945
+ items.add(item);
1946
+ }
1947
+ async remove(item) {
1948
+ const { items } = this;
1949
+ if (!items)
1950
+ return;
1951
+ items.delete(item);
1952
+ if (items.size > 0)
1953
+ return;
1954
+ const dir = this.path;
1955
+ try {
1956
+ await readdir3(dir);
1957
+ } catch (err) {
1958
+ if (this._removeWatcher) {
1959
+ this._removeWatcher(sp2.dirname(dir), sp2.basename(dir));
1960
+ }
1961
+ }
1962
+ }
1963
+ has(item) {
1964
+ const { items } = this;
1965
+ if (!items)
1966
+ return;
1967
+ return items.has(item);
1968
+ }
1969
+ getChildren() {
1970
+ const { items } = this;
1971
+ if (!items)
1972
+ return [];
1973
+ return [...items.values()];
1974
+ }
1975
+ dispose() {
1976
+ this.items.clear();
1977
+ this.path = "";
1978
+ this._removeWatcher = EMPTY_FN;
1979
+ this.items = EMPTY_SET;
1980
+ Object.freeze(this);
1981
+ }
1982
+ };
1983
+ var STAT_METHOD_F = "stat";
1984
+ var STAT_METHOD_L = "lstat";
1985
+ var WatchHelper = class {
1986
+ fsw;
1987
+ path;
1988
+ watchPath;
1989
+ fullWatchPath;
1990
+ dirParts;
1991
+ followSymlinks;
1992
+ statMethod;
1993
+ constructor(path9, follow, fsw) {
1994
+ this.fsw = fsw;
1995
+ const watchPath = path9;
1996
+ this.path = path9 = path9.replace(REPLACER_RE, "");
1997
+ this.watchPath = watchPath;
1998
+ this.fullWatchPath = sp2.resolve(watchPath);
1999
+ this.dirParts = [];
2000
+ this.dirParts.forEach((parts) => {
2001
+ if (parts.length > 1)
2002
+ parts.pop();
2003
+ });
2004
+ this.followSymlinks = follow;
2005
+ this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
2006
+ }
2007
+ entryPath(entry) {
2008
+ return sp2.join(this.watchPath, sp2.relative(this.watchPath, entry.fullPath));
2009
+ }
2010
+ filterPath(entry) {
2011
+ const { stats } = entry;
2012
+ if (stats && stats.isSymbolicLink())
2013
+ return this.filterDir(entry);
2014
+ const resolvedPath = this.entryPath(entry);
2015
+ return this.fsw._isntIgnored(resolvedPath, stats) && this.fsw._hasReadPermissions(stats);
2016
+ }
2017
+ filterDir(entry) {
2018
+ return this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
2019
+ }
2020
+ };
2021
+ var FSWatcher = class extends EventEmitter {
2022
+ closed;
2023
+ options;
2024
+ _closers;
2025
+ _ignoredPaths;
2026
+ _throttled;
2027
+ _streams;
2028
+ _symlinkPaths;
2029
+ _watched;
2030
+ _pendingWrites;
2031
+ _pendingUnlinks;
2032
+ _readyCount;
2033
+ _emitReady;
2034
+ _closePromise;
2035
+ _userIgnored;
2036
+ _readyEmitted;
2037
+ _emitRaw;
2038
+ _boundRemove;
2039
+ _nodeFsHandler;
2040
+ // Not indenting methods for history sake; for now.
2041
+ constructor(_opts = {}) {
2042
+ super();
2043
+ this.closed = false;
2044
+ this._closers = /* @__PURE__ */ new Map();
2045
+ this._ignoredPaths = /* @__PURE__ */ new Set();
2046
+ this._throttled = /* @__PURE__ */ new Map();
2047
+ this._streams = /* @__PURE__ */ new Set();
2048
+ this._symlinkPaths = /* @__PURE__ */ new Map();
2049
+ this._watched = /* @__PURE__ */ new Map();
2050
+ this._pendingWrites = /* @__PURE__ */ new Map();
2051
+ this._pendingUnlinks = /* @__PURE__ */ new Map();
2052
+ this._readyCount = 0;
2053
+ this._readyEmitted = false;
2054
+ const awf = _opts.awaitWriteFinish;
2055
+ const DEF_AWF = { stabilityThreshold: 2e3, pollInterval: 100 };
2056
+ const opts = {
2057
+ // Defaults
2058
+ persistent: true,
2059
+ ignoreInitial: false,
2060
+ ignorePermissionErrors: false,
2061
+ interval: 100,
2062
+ binaryInterval: 300,
2063
+ followSymlinks: true,
2064
+ usePolling: false,
2065
+ // useAsync: false,
2066
+ atomic: true,
2067
+ // NOTE: overwritten later (depends on usePolling)
2068
+ ..._opts,
2069
+ // Change format
2070
+ ignored: _opts.ignored ? arrify(_opts.ignored) : arrify([]),
2071
+ awaitWriteFinish: awf === true ? DEF_AWF : typeof awf === "object" ? { ...DEF_AWF, ...awf } : false
2072
+ };
2073
+ if (isIBMi)
2074
+ opts.usePolling = true;
2075
+ if (opts.atomic === void 0)
2076
+ opts.atomic = !opts.usePolling;
2077
+ const envPoll = process.env.CHOKIDAR_USEPOLLING;
2078
+ if (envPoll !== void 0) {
2079
+ const envLower = envPoll.toLowerCase();
2080
+ if (envLower === "false" || envLower === "0")
2081
+ opts.usePolling = false;
2082
+ else if (envLower === "true" || envLower === "1")
2083
+ opts.usePolling = true;
2084
+ else
2085
+ opts.usePolling = !!envLower;
2086
+ }
2087
+ const envInterval = process.env.CHOKIDAR_INTERVAL;
2088
+ if (envInterval)
2089
+ opts.interval = Number.parseInt(envInterval, 10);
2090
+ let readyCalls = 0;
2091
+ this._emitReady = () => {
2092
+ readyCalls++;
2093
+ if (readyCalls >= this._readyCount) {
2094
+ this._emitReady = EMPTY_FN;
2095
+ this._readyEmitted = true;
2096
+ process.nextTick(() => this.emit(EVENTS.READY));
2097
+ }
2098
+ };
2099
+ this._emitRaw = (...args) => this.emit(EVENTS.RAW, ...args);
2100
+ this._boundRemove = this._remove.bind(this);
2101
+ this.options = opts;
2102
+ this._nodeFsHandler = new NodeFsHandler(this);
2103
+ Object.freeze(opts);
2104
+ }
2105
+ _addIgnoredPath(matcher) {
2106
+ if (isMatcherObject(matcher)) {
2107
+ for (const ignored of this._ignoredPaths) {
2108
+ if (isMatcherObject(ignored) && ignored.path === matcher.path && ignored.recursive === matcher.recursive) {
2109
+ return;
2110
+ }
2111
+ }
2112
+ }
2113
+ this._ignoredPaths.add(matcher);
2114
+ }
2115
+ _removeIgnoredPath(matcher) {
2116
+ this._ignoredPaths.delete(matcher);
2117
+ if (typeof matcher === "string") {
2118
+ for (const ignored of this._ignoredPaths) {
2119
+ if (isMatcherObject(ignored) && ignored.path === matcher) {
2120
+ this._ignoredPaths.delete(ignored);
2121
+ }
2122
+ }
2123
+ }
2124
+ }
2125
+ // Public methods
2126
+ /**
2127
+ * Adds paths to be watched on an existing FSWatcher instance.
2128
+ * @param paths_ file or file list. Other arguments are unused
2129
+ */
2130
+ add(paths_, _origAdd, _internal) {
2131
+ const { cwd } = this.options;
2132
+ this.closed = false;
2133
+ this._closePromise = void 0;
2134
+ let paths = unifyPaths(paths_);
2135
+ if (cwd) {
2136
+ paths = paths.map((path9) => {
2137
+ const absPath = getAbsolutePath(path9, cwd);
2138
+ return absPath;
2139
+ });
2140
+ }
2141
+ paths.forEach((path9) => {
2142
+ this._removeIgnoredPath(path9);
2143
+ });
2144
+ this._userIgnored = void 0;
2145
+ if (!this._readyCount)
2146
+ this._readyCount = 0;
2147
+ this._readyCount += paths.length;
2148
+ Promise.all(paths.map(async (path9) => {
2149
+ const res = await this._nodeFsHandler._addToNodeFs(path9, !_internal, void 0, 0, _origAdd);
2150
+ if (res)
2151
+ this._emitReady();
2152
+ return res;
2153
+ })).then((results) => {
2154
+ if (this.closed)
2155
+ return;
2156
+ results.forEach((item) => {
2157
+ if (item)
2158
+ this.add(sp2.dirname(item), sp2.basename(_origAdd || item));
2159
+ });
2160
+ });
2161
+ return this;
2162
+ }
2163
+ /**
2164
+ * Close watchers or start ignoring events from specified paths.
2165
+ */
2166
+ unwatch(paths_) {
2167
+ if (this.closed)
2168
+ return this;
2169
+ const paths = unifyPaths(paths_);
2170
+ const { cwd } = this.options;
2171
+ paths.forEach((path9) => {
2172
+ if (!sp2.isAbsolute(path9) && !this._closers.has(path9)) {
2173
+ if (cwd)
2174
+ path9 = sp2.join(cwd, path9);
2175
+ path9 = sp2.resolve(path9);
2176
+ }
2177
+ this._closePath(path9);
2178
+ this._addIgnoredPath(path9);
2179
+ if (this._watched.has(path9)) {
2180
+ this._addIgnoredPath({
2181
+ path: path9,
2182
+ recursive: true
2183
+ });
2184
+ }
2185
+ this._userIgnored = void 0;
2186
+ });
2187
+ return this;
2188
+ }
2189
+ /**
2190
+ * Close watchers and remove all listeners from watched paths.
2191
+ */
2192
+ close() {
2193
+ if (this._closePromise) {
2194
+ return this._closePromise;
2195
+ }
2196
+ this.closed = true;
2197
+ this.removeAllListeners();
2198
+ const closers = [];
2199
+ this._closers.forEach((closerList) => closerList.forEach((closer) => {
2200
+ const promise = closer();
2201
+ if (promise instanceof Promise)
2202
+ closers.push(promise);
2203
+ }));
2204
+ this._streams.forEach((stream) => stream.destroy());
2205
+ this._userIgnored = void 0;
2206
+ this._readyCount = 0;
2207
+ this._readyEmitted = false;
2208
+ this._watched.forEach((dirent) => dirent.dispose());
2209
+ this._closers.clear();
2210
+ this._watched.clear();
2211
+ this._streams.clear();
2212
+ this._symlinkPaths.clear();
2213
+ this._throttled.clear();
2214
+ this._closePromise = closers.length ? Promise.all(closers).then(() => void 0) : Promise.resolve();
2215
+ return this._closePromise;
2216
+ }
2217
+ /**
2218
+ * Expose list of watched paths
2219
+ * @returns for chaining
2220
+ */
2221
+ getWatched() {
2222
+ const watchList = {};
2223
+ this._watched.forEach((entry, dir) => {
2224
+ const key = this.options.cwd ? sp2.relative(this.options.cwd, dir) : dir;
2225
+ const index = key || ONE_DOT;
2226
+ watchList[index] = entry.getChildren().sort();
2227
+ });
2228
+ return watchList;
2229
+ }
2230
+ emitWithAll(event, args) {
2231
+ this.emit(event, ...args);
2232
+ if (event !== EVENTS.ERROR)
2233
+ this.emit(EVENTS.ALL, event, ...args);
2234
+ }
2235
+ // Common helpers
2236
+ // --------------
2237
+ /**
2238
+ * Normalize and emit events.
2239
+ * Calling _emit DOES NOT MEAN emit() would be called!
2240
+ * @param event Type of event
2241
+ * @param path File or directory path
2242
+ * @param stats arguments to be passed with event
2243
+ * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
2244
+ */
2245
+ async _emit(event, path9, stats) {
2246
+ if (this.closed)
2247
+ return;
2248
+ const opts = this.options;
2249
+ if (isWindows)
2250
+ path9 = sp2.normalize(path9);
2251
+ if (opts.cwd)
2252
+ path9 = sp2.relative(opts.cwd, path9);
2253
+ const args = [path9];
2254
+ if (stats != null)
2255
+ args.push(stats);
2256
+ const awf = opts.awaitWriteFinish;
2257
+ let pw;
2258
+ if (awf && (pw = this._pendingWrites.get(path9))) {
2259
+ pw.lastChange = /* @__PURE__ */ new Date();
2260
+ return this;
2261
+ }
2262
+ if (opts.atomic) {
2263
+ if (event === EVENTS.UNLINK) {
2264
+ this._pendingUnlinks.set(path9, [event, ...args]);
2265
+ setTimeout(() => {
2266
+ this._pendingUnlinks.forEach((entry, path10) => {
2267
+ this.emit(...entry);
2268
+ this.emit(EVENTS.ALL, ...entry);
2269
+ this._pendingUnlinks.delete(path10);
2270
+ });
2271
+ }, typeof opts.atomic === "number" ? opts.atomic : 100);
2272
+ return this;
2273
+ }
2274
+ if (event === EVENTS.ADD && this._pendingUnlinks.has(path9)) {
2275
+ event = EVENTS.CHANGE;
2276
+ this._pendingUnlinks.delete(path9);
2277
+ }
2278
+ }
2279
+ if (awf && (event === EVENTS.ADD || event === EVENTS.CHANGE) && this._readyEmitted) {
2280
+ const awfEmit = (err, stats2) => {
2281
+ if (err) {
2282
+ event = EVENTS.ERROR;
2283
+ args[0] = err;
2284
+ this.emitWithAll(event, args);
2285
+ } else if (stats2) {
2286
+ if (args.length > 1) {
2287
+ args[1] = stats2;
2288
+ } else {
2289
+ args.push(stats2);
2290
+ }
2291
+ this.emitWithAll(event, args);
2292
+ }
2293
+ };
2294
+ this._awaitWriteFinish(path9, awf.stabilityThreshold, event, awfEmit);
2295
+ return this;
2296
+ }
2297
+ if (event === EVENTS.CHANGE) {
2298
+ const isThrottled = !this._throttle(EVENTS.CHANGE, path9, 50);
2299
+ if (isThrottled)
2300
+ return this;
2301
+ }
2302
+ if (opts.alwaysStat && stats === void 0 && (event === EVENTS.ADD || event === EVENTS.ADD_DIR || event === EVENTS.CHANGE)) {
2303
+ const fullPath = opts.cwd ? sp2.join(opts.cwd, path9) : path9;
2304
+ let stats2;
2305
+ try {
2306
+ stats2 = await stat7(fullPath);
2307
+ } catch (err) {
2308
+ }
2309
+ if (!stats2 || this.closed)
2310
+ return;
2311
+ args.push(stats2);
2312
+ }
2313
+ this.emitWithAll(event, args);
2314
+ return this;
2315
+ }
2316
+ /**
2317
+ * Common handler for errors
2318
+ * @returns The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
2319
+ */
2320
+ _handleError(error) {
2321
+ const code = error && error.code;
2322
+ if (error && code !== "ENOENT" && code !== "ENOTDIR" && (!this.options.ignorePermissionErrors || code !== "EPERM" && code !== "EACCES")) {
2323
+ this.emit(EVENTS.ERROR, error);
2324
+ }
2325
+ return error || this.closed;
2326
+ }
2327
+ /**
2328
+ * Helper utility for throttling
2329
+ * @param actionType type being throttled
2330
+ * @param path being acted upon
2331
+ * @param timeout duration of time to suppress duplicate actions
2332
+ * @returns tracking object or false if action should be suppressed
2333
+ */
2334
+ _throttle(actionType, path9, timeout) {
2335
+ if (!this._throttled.has(actionType)) {
2336
+ this._throttled.set(actionType, /* @__PURE__ */ new Map());
2337
+ }
2338
+ const action = this._throttled.get(actionType);
2339
+ if (!action)
2340
+ throw new Error("invalid throttle");
2341
+ const actionPath = action.get(path9);
2342
+ if (actionPath) {
2343
+ actionPath.count++;
2344
+ return false;
2345
+ }
2346
+ let timeoutObject;
2347
+ const clear = () => {
2348
+ const item = action.get(path9);
2349
+ const count = item ? item.count : 0;
2350
+ action.delete(path9);
2351
+ clearTimeout(timeoutObject);
2352
+ if (item)
2353
+ clearTimeout(item.timeoutObject);
2354
+ return count;
2355
+ };
2356
+ timeoutObject = setTimeout(clear, timeout);
2357
+ const thr = { timeoutObject, clear, count: 0 };
2358
+ action.set(path9, thr);
2359
+ return thr;
2360
+ }
2361
+ _incrReadyCount() {
2362
+ return this._readyCount++;
2363
+ }
2364
+ /**
2365
+ * Awaits write operation to finish.
2366
+ * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
2367
+ * @param path being acted upon
2368
+ * @param threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
2369
+ * @param event
2370
+ * @param awfEmit Callback to be called when ready for event to be emitted.
2371
+ */
2372
+ _awaitWriteFinish(path9, threshold, event, awfEmit) {
2373
+ const awf = this.options.awaitWriteFinish;
2374
+ if (typeof awf !== "object")
2375
+ return;
2376
+ const pollInterval = awf.pollInterval;
2377
+ let timeoutHandler;
2378
+ let fullPath = path9;
2379
+ if (this.options.cwd && !sp2.isAbsolute(path9)) {
2380
+ fullPath = sp2.join(this.options.cwd, path9);
2381
+ }
2382
+ const now = /* @__PURE__ */ new Date();
2383
+ const writes = this._pendingWrites;
2384
+ function awaitWriteFinishFn(prevStat) {
2385
+ statcb(fullPath, (err, curStat) => {
2386
+ if (err || !writes.has(path9)) {
2387
+ if (err && err.code !== "ENOENT")
2388
+ awfEmit(err);
2389
+ return;
2390
+ }
2391
+ const now2 = Number(/* @__PURE__ */ new Date());
2392
+ if (prevStat && curStat.size !== prevStat.size) {
2393
+ writes.get(path9).lastChange = now2;
2394
+ }
2395
+ const pw = writes.get(path9);
2396
+ const df = now2 - pw.lastChange;
2397
+ if (df >= threshold) {
2398
+ writes.delete(path9);
2399
+ awfEmit(void 0, curStat);
2400
+ } else {
2401
+ timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat);
2402
+ }
2403
+ });
2404
+ }
2405
+ if (!writes.has(path9)) {
2406
+ writes.set(path9, {
2407
+ lastChange: now,
2408
+ cancelWait: () => {
2409
+ writes.delete(path9);
2410
+ clearTimeout(timeoutHandler);
2411
+ return event;
2412
+ }
2413
+ });
2414
+ timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval);
2415
+ }
2416
+ }
2417
+ /**
2418
+ * Determines whether user has asked to ignore this path.
2419
+ */
2420
+ _isIgnored(path9, stats) {
2421
+ if (this.options.atomic && DOT_RE.test(path9))
2422
+ return true;
2423
+ if (!this._userIgnored) {
2424
+ const { cwd } = this.options;
2425
+ const ign = this.options.ignored;
2426
+ const ignored = (ign || []).map(normalizeIgnored(cwd));
2427
+ const ignoredPaths = [...this._ignoredPaths];
2428
+ const list = [...ignoredPaths.map(normalizeIgnored(cwd)), ...ignored];
2429
+ this._userIgnored = anymatch(list, void 0);
2430
+ }
2431
+ return this._userIgnored(path9, stats);
2432
+ }
2433
+ _isntIgnored(path9, stat8) {
2434
+ return !this._isIgnored(path9, stat8);
2435
+ }
2436
+ /**
2437
+ * Provides a set of common helpers and properties relating to symlink handling.
2438
+ * @param path file or directory pattern being watched
2439
+ */
2440
+ _getWatchHelpers(path9) {
2441
+ return new WatchHelper(path9, this.options.followSymlinks, this);
2442
+ }
2443
+ // Directory helpers
2444
+ // -----------------
2445
+ /**
2446
+ * Provides directory tracking objects
2447
+ * @param directory path of the directory
2448
+ */
2449
+ _getWatchedDir(directory) {
2450
+ const dir = sp2.resolve(directory);
2451
+ if (!this._watched.has(dir))
2452
+ this._watched.set(dir, new DirEntry(dir, this._boundRemove));
2453
+ return this._watched.get(dir);
2454
+ }
2455
+ // File helpers
2456
+ // ------------
2457
+ /**
2458
+ * Check for read permissions: https://stackoverflow.com/a/11781404/1358405
2459
+ */
2460
+ _hasReadPermissions(stats) {
2461
+ if (this.options.ignorePermissionErrors)
2462
+ return true;
2463
+ return Boolean(Number(stats.mode) & 256);
2464
+ }
2465
+ /**
2466
+ * Handles emitting unlink events for
2467
+ * files and directories, and via recursion, for
2468
+ * files and directories within directories that are unlinked
2469
+ * @param directory within which the following item is located
2470
+ * @param item base path of item/directory
2471
+ */
2472
+ _remove(directory, item, isDirectory) {
2473
+ const path9 = sp2.join(directory, item);
2474
+ const fullPath = sp2.resolve(path9);
2475
+ isDirectory = isDirectory != null ? isDirectory : this._watched.has(path9) || this._watched.has(fullPath);
2476
+ if (!this._throttle("remove", path9, 100))
2477
+ return;
2478
+ if (!isDirectory && this._watched.size === 1) {
2479
+ this.add(directory, item, true);
2480
+ }
2481
+ const wp = this._getWatchedDir(path9);
2482
+ const nestedDirectoryChildren = wp.getChildren();
2483
+ nestedDirectoryChildren.forEach((nested) => this._remove(path9, nested));
2484
+ const parent = this._getWatchedDir(directory);
2485
+ const wasTracked = parent.has(item);
2486
+ parent.remove(item);
2487
+ if (this._symlinkPaths.has(fullPath)) {
2488
+ this._symlinkPaths.delete(fullPath);
2489
+ }
2490
+ let relPath = path9;
2491
+ if (this.options.cwd)
2492
+ relPath = sp2.relative(this.options.cwd, path9);
2493
+ if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
2494
+ const event = this._pendingWrites.get(relPath).cancelWait();
2495
+ if (event === EVENTS.ADD)
2496
+ return;
2497
+ }
2498
+ this._watched.delete(path9);
2499
+ this._watched.delete(fullPath);
2500
+ const eventName = isDirectory ? EVENTS.UNLINK_DIR : EVENTS.UNLINK;
2501
+ if (wasTracked && !this._isIgnored(path9))
2502
+ this._emit(eventName, path9);
2503
+ this._closePath(path9);
2504
+ }
2505
+ /**
2506
+ * Closes all watchers for a path
2507
+ */
2508
+ _closePath(path9) {
2509
+ this._closeFile(path9);
2510
+ const dir = sp2.dirname(path9);
2511
+ this._getWatchedDir(dir).remove(sp2.basename(path9));
2512
+ }
2513
+ /**
2514
+ * Closes only file-specific watchers
2515
+ */
2516
+ _closeFile(path9) {
2517
+ const closers = this._closers.get(path9);
2518
+ if (!closers)
2519
+ return;
2520
+ closers.forEach((closer) => closer());
2521
+ this._closers.delete(path9);
2522
+ }
2523
+ _addPathCloser(path9, closer) {
2524
+ if (!closer)
2525
+ return;
2526
+ let list = this._closers.get(path9);
2527
+ if (!list) {
2528
+ list = [];
2529
+ this._closers.set(path9, list);
2530
+ }
2531
+ list.push(closer);
2532
+ }
2533
+ _readdirp(root, opts) {
2534
+ if (this.closed)
2535
+ return;
2536
+ const options = { type: EVENTS.ALL, alwaysStat: true, lstat: true, ...opts, depth: 0 };
2537
+ let stream = readdirp(root, options);
2538
+ this._streams.add(stream);
2539
+ stream.once(STR_CLOSE, () => {
2540
+ stream = void 0;
2541
+ });
2542
+ stream.once(STR_END, () => {
2543
+ if (stream) {
2544
+ this._streams.delete(stream);
2545
+ stream = void 0;
2546
+ }
2547
+ });
2548
+ return stream;
2549
+ }
2550
+ };
2551
+ function watch(paths, options = {}) {
2552
+ const watcher = new FSWatcher(options);
2553
+ watcher.add(paths);
2554
+ return watcher;
2555
+ }
2556
+ var chokidar_default = { watch, FSWatcher };
2557
+
2558
+ // src/core/watch.ts
2559
+ import { $ as $7 } from "execa";
2560
+ var watchCommand = new Command10("watch").description(
2561
+ "Watches the src directory and rebuilds automatically on changes"
2562
+ ).action(() => {
2563
+ const cwd = process.cwd();
2564
+ const srcDir = path8.join(cwd, "src");
2565
+ console.log(`\u{1F440} Watching for changes in ./src...`);
2566
+ let isBuilding = false;
2567
+ let buildQueued = false;
2568
+ const runBuild = async () => {
2569
+ if (isBuilding) {
2570
+ buildQueued = true;
2571
+ return;
2572
+ }
2573
+ isBuilding = true;
2574
+ console.log(`
2575
+ \u23F3 Detected changes. Rebuilding...`);
2576
+ try {
2577
+ await $7({ stdio: "inherit" })`npx sse-tools build`;
2578
+ console.log(`\u2705 Build updated successfully! Waiting for changes...`);
2579
+ } catch (err) {
2580
+ console.error(`\u274C Build failed during watch.`);
2581
+ } finally {
2582
+ isBuilding = false;
2583
+ if (buildQueued) {
2584
+ buildQueued = false;
2585
+ runBuild();
2586
+ }
2587
+ }
2588
+ };
2589
+ const watcher = chokidar_default.watch(srcDir, {
2590
+ ignored: /(^|[\/\\])\../,
2591
+ // ignore dotfiles
2592
+ persistent: true,
2593
+ ignoreInitial: true
2594
+ // Don't trigger on startup
2595
+ });
2596
+ watcher.on("add", runBuild).on("change", runBuild).on("unlink", runBuild);
2597
+ });
2598
+
2599
+ // src/cli.ts
2600
+ async function main() {
2601
+ const program = new Command11();
2602
+ program.name("sse-tools").description("CLI utilities for managing and building MUI packages").version("1.0.0");
2603
+ program.addCommand(buildCommand);
2604
+ program.addCommand(publishCommand);
2605
+ program.addCommand(cleanCommand);
2606
+ program.addCommand(typecheckCommand);
2607
+ program.addCommand(packCommand);
2608
+ program.addCommand(versionCommand);
2609
+ program.addCommand(infoCommand);
2610
+ program.addCommand(linkCommand);
2611
+ program.addCommand(checkExportsCommand);
2612
+ program.addCommand(watchCommand);
2613
+ try {
2614
+ await program.parseAsync(process.argv);
2615
+ } catch (error) {
2616
+ console.error("Error executing command:");
2617
+ if (error instanceof Error) {
2618
+ console.error(error.message);
2619
+ }
2620
+ process.exit(1);
2621
+ }
2622
+ }
2623
+ main();
2624
+ /*! Bundled license information:
2625
+
2626
+ chokidar/index.js:
2627
+ (*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) *)
2628
+ */