zshy 0.0.1 → 0.0.3

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/out/index.cjs ADDED
@@ -0,0 +1,490 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
+ if (k2 === undefined) k2 = k;
5
+ var desc = Object.getOwnPropertyDescriptor(m, k);
6
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
+ desc = { enumerable: true, get: function() { return m[k]; } };
8
+ }
9
+ Object.defineProperty(o, k2, desc);
10
+ }) : (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ o[k2] = m[k];
13
+ }));
14
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
16
+ }) : function(o, v) {
17
+ o["default"] = v;
18
+ });
19
+ var __importStar = (this && this.__importStar) || (function () {
20
+ var ownKeys = function(o) {
21
+ ownKeys = Object.getOwnPropertyNames || function (o) {
22
+ var ar = [];
23
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
24
+ return ar;
25
+ };
26
+ return ownKeys(o);
27
+ };
28
+ return function (mod) {
29
+ if (mod && mod.__esModule) return mod;
30
+ var result = {};
31
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
32
+ __setModuleDefault(result, mod);
33
+ return result;
34
+ };
35
+ })();
36
+ var __importDefault = (this && this.__importDefault) || function (mod) {
37
+ return (mod && mod.__esModule) ? mod : { "default": mod };
38
+ };
39
+ Object.defineProperty(exports, "__esModule", { value: true });
40
+ const globby_1 = require("globby");
41
+ const table_1 = require("table");
42
+ const fs = __importStar(require("node:fs"));
43
+ const path = __importStar(require("node:path/posix"));
44
+ const ts = __importStar(require("typescript"));
45
+ const arg_1 = __importDefault(require("arg"));
46
+ const utils_ts_1 = require("./utils.js");
47
+ function isSourceFile(filePath) {
48
+ return (filePath.endsWith(".ts") ||
49
+ filePath.endsWith(".mts") ||
50
+ filePath.endsWith(".cts") ||
51
+ filePath.endsWith(".tsx"));
52
+ }
53
+ function removeExtension(filePath) {
54
+ return filePath.split(".").slice(0, -1).join(".") || filePath;
55
+ }
56
+ async function main() {
57
+ console.log("💎 Starting zshy build...");
58
+ ///////////////////////////////////
59
+ /// parse command line args ///
60
+ ///////////////////////////////////
61
+ // Parse command line arguments using arg library
62
+ let args;
63
+ try {
64
+ args = (0, arg_1.default)({
65
+ "--project": String,
66
+ "--help": Boolean,
67
+ // Aliases
68
+ "-p": "--project",
69
+ "-h": "--help",
70
+ });
71
+ }
72
+ catch (error) {
73
+ if (error instanceof Error) {
74
+ console.error(`❌ ${error.message}`);
75
+ }
76
+ console.error(`Use --help for usage information`);
77
+ process.exit(1);
78
+ }
79
+ // Handle help flag
80
+ if (args["--help"]) {
81
+ console.log(`
82
+ Usage: zshy [options]
83
+
84
+ Options:
85
+ -p, --project <path> Path to tsconfig.json file
86
+ -h, --help Show this help message
87
+
88
+ Examples:
89
+ zshy # Use ./tsconfig.json
90
+ zshy -p ./tsconfig.build.json # Use specific tsconfig file
91
+ zshy --project ./tsconfig.prod.json
92
+ `);
93
+ process.exit(0);
94
+ }
95
+ const projectPath = args["--project"];
96
+ if (projectPath) {
97
+ console.log(`⚙️ Using custom project path: ${projectPath}`);
98
+ }
99
+ ///////////////////////////////////
100
+ /// find and read pkg json ///
101
+ ///////////////////////////////////
102
+ // Find package.json by scanning up the file system
103
+ let packageJsonPath = "./package.json";
104
+ let currentDir = process.cwd();
105
+ while (currentDir !== path.dirname(currentDir)) {
106
+ const candidatePath = path.join(currentDir, "package.json");
107
+ if (fs.existsSync(candidatePath)) {
108
+ packageJsonPath = candidatePath;
109
+ break;
110
+ }
111
+ currentDir = path.dirname(currentDir);
112
+ }
113
+ if (!fs.existsSync(packageJsonPath)) {
114
+ console.error("❌ package.json not found in current directory or any parent directories");
115
+ process.exit(1);
116
+ }
117
+ // read package.json and extract the "zshy" exports config
118
+ // console.log("📦 Extracting entry points from package.json exports...");
119
+ const pkgJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8"));
120
+ const pkgJsonDir = path.dirname(packageJsonPath);
121
+ // print project root
122
+ console.log(`⚙️ Detected project root: ${pkgJsonDir}`);
123
+ console.log(`📦 Reading package.json from ./${path.relative(pkgJsonDir, packageJsonPath)}`);
124
+ /////////////////////////////////
125
+ /// parse zshy config ///
126
+ /////////////////////////////////
127
+ // const pkgJson = JSON.parse(fs.readFileSync("./package.json", "utf-8"));
128
+ const CONFIG_KEY = "zshy";
129
+ let config;
130
+ if (!pkgJson[CONFIG_KEY]) {
131
+ console.error(`❌ No "${CONFIG_KEY}" key found in package.json`);
132
+ process.exit(1);
133
+ }
134
+ if (typeof pkgJson[CONFIG_KEY] === "string") {
135
+ config = {
136
+ exports: { ".": pkgJson[CONFIG_KEY] },
137
+ };
138
+ }
139
+ else if (typeof pkgJson[CONFIG_KEY] === "object") {
140
+ config = { ...pkgJson[CONFIG_KEY] };
141
+ if (typeof config.exports === "string") {
142
+ config.exports = { ".": config.exports };
143
+ }
144
+ else if (typeof config.exports === "undefined") {
145
+ console.error(`❌ Missing "exports" key in package.json#${CONFIG_KEY}`);
146
+ process.exit(1);
147
+ }
148
+ else if (typeof config.exports !== "object") {
149
+ console.error(`❌ Invalid "exports" key in package.json#${CONFIG_KEY}`);
150
+ process.exit(1);
151
+ }
152
+ // {
153
+ // exports: { ".": pkgJson[CONFIG_KEY].exports },
154
+ // };
155
+ }
156
+ else if (typeof pkgJson[CONFIG_KEY] === "undefined") {
157
+ console.error(`❌ Missing "${CONFIG_KEY}" key in package.json`);
158
+ process.exit(1);
159
+ }
160
+ else {
161
+ console.error(`❌ Invalid "${CONFIG_KEY}" key in package.json, expected string or object`);
162
+ process.exit(1);
163
+ }
164
+ ///////////////////////////
165
+ /// read tsconfig ///
166
+ ///////////////////////////
167
+ // Determine tsconfig.json path
168
+ let tsconfigPath;
169
+ if (projectPath) {
170
+ // Resolve the provided project path against current working directory
171
+ const resolvedProjectPath = path.resolve(process.cwd(), projectPath);
172
+ if (fs.existsSync(resolvedProjectPath)) {
173
+ if (fs.statSync(resolvedProjectPath).isDirectory()) {
174
+ console.error(`❌ Project path must be a tsconfig.json file, not a directory: ${resolvedProjectPath}`);
175
+ process.exit(1);
176
+ }
177
+ else {
178
+ // Use the file directly
179
+ tsconfigPath = resolvedProjectPath;
180
+ }
181
+ }
182
+ else {
183
+ console.error(`❌ Project file not found: ${resolvedProjectPath}`);
184
+ process.exit(1);
185
+ }
186
+ }
187
+ else {
188
+ // Default to tsconfig.json in the package.json directory
189
+ tsconfigPath = path.join(pkgJsonDir, "tsconfig.json");
190
+ }
191
+ const _parsedConfig = (0, utils_ts_1.readTsconfig)(tsconfigPath);
192
+ if (!fs.existsSync(tsconfigPath)) {
193
+ // Check if tsconfig.json exists
194
+ console.error(`❌ tsconfig.json not found at ${path.resolve(tsconfigPath)}`);
195
+ process.exit(1);
196
+ }
197
+ console.log(`📁 Reading tsconfig from ./${path.relative(pkgJsonDir, tsconfigPath)}`);
198
+ // if (_parsedConfig.rootDir) {
199
+ // console.error(
200
+ // `❌ rootDir is determined from your set of entrypoints; you can remove it from your tsconfig.json.`,
201
+ // );
202
+ // process.exit(1);
203
+ // }
204
+ // if (_parsedConfig.declarationDir) {
205
+ // console.error(
206
+ // `❌ declarationDir is not supported in zshy; you should remove it from your tsconfig.json.`,
207
+ // );
208
+ // process.exit(1);
209
+ // }
210
+ // set/override compiler options
211
+ delete _parsedConfig.customConditions; // can't be set for CommonJS builds
212
+ const outDir = path.resolve(pkgJsonDir, _parsedConfig?.outDir || "./dist");
213
+ const relOutDir = path.relative(pkgJsonDir, outDir);
214
+ const declarationDir = path.resolve(pkgJsonDir, _parsedConfig?.declarationDir || relOutDir);
215
+ const relDeclarationDir = path.relative(pkgJsonDir, declarationDir);
216
+ const tsconfigJson = {
217
+ ..._parsedConfig,
218
+ outDir,
219
+ target: _parsedConfig.target ?? ts.ScriptTarget.ES2020, // ensure compatible target for CommonJS
220
+ skipLibCheck: true, // skip library checks to reduce errors
221
+ declaration: true,
222
+ noEmit: false,
223
+ emitDeclarationOnly: false,
224
+ rewriteRelativeImportExtensions: true,
225
+ verbatimModuleSyntax: false,
226
+ };
227
+ if (relOutDir === "") {
228
+ if (!pkgJson.files) {
229
+ console.log('⚠️ You\'re building your code to the project root. This means your compiled files will be generated alongside your source files.\n ➜ Setting "files" in package.json to exclude TypeScript source from the published package.');
230
+ pkgJson.files = [
231
+ "**/*.js",
232
+ "**/*.mjs",
233
+ "**/*.cjs",
234
+ "**/*.d.ts",
235
+ "**/*.d.mts",
236
+ "**/*.d.cts",
237
+ ];
238
+ }
239
+ else {
240
+ console.warn(`⚠️ You're building your code to the project root. This means your compiled files will be generated alongside your source files.
241
+ ➜ Ensure that your "files" in package.json excludes TypeScript source files, or your users may experience .d.ts resolution issues in some environments:
242
+
243
+ "files": ["**/*.js", "**/*.mjs", "**/*.cjs", "**/*.d.ts", "**/*.d.mts", "**/*.d.cts"],
244
+ `);
245
+ }
246
+ }
247
+ else {
248
+ if (!pkgJson.files) {
249
+ console.log(`⚠️ The "files" key is missing in package.json. Setting to "${relOutDir}".`);
250
+ pkgJson.files = [relOutDir];
251
+ if (relOutDir !== relDeclarationDir) {
252
+ pkgJson.files.push(relDeclarationDir);
253
+ }
254
+ }
255
+ }
256
+ /////////////////////////////////
257
+ /// extract entry points ///
258
+ /////////////////////////////////
259
+ // Extract entry points from zshy exports config
260
+ console.log("➡️ Determining entrypoints...");
261
+ const entryPatterns = [];
262
+ const rows = [["Subpath", "Entrypoint"]];
263
+ for (const [exportPath, sourcePath] of Object.entries(config.exports)) {
264
+ if (exportPath.includes("package.json"))
265
+ continue;
266
+ let cleanExportPath;
267
+ if (exportPath === ".") {
268
+ cleanExportPath = pkgJson.name;
269
+ }
270
+ else if (exportPath.startsWith("./")) {
271
+ cleanExportPath = pkgJson.name + "/" + exportPath.slice(2);
272
+ }
273
+ else {
274
+ console.error(`⚠️ Invalid subpath export "${exportPath}" — should start with "./"`);
275
+ process.exit(1);
276
+ }
277
+ if (typeof sourcePath === "string") {
278
+ if (sourcePath.includes("*")) {
279
+ if (!sourcePath.endsWith("/*")) {
280
+ console.error(`❌ Wildcard paths should not contain file extensions: ${sourcePath}`);
281
+ process.exit(1);
282
+ }
283
+ const pattern = sourcePath.slice(0, -2) + "/*.{ts,tsx,mts,cts}";
284
+ const wildcardFiles = await (0, globby_1.globby)([pattern], {
285
+ ignore: ["**/*.d.ts"],
286
+ cwd: pkgJsonDir,
287
+ deep: 1,
288
+ });
289
+ entryPatterns.push(...wildcardFiles);
290
+ rows.push([
291
+ `"${cleanExportPath}"`,
292
+ `${sourcePath} (${wildcardFiles.length} matches)`,
293
+ ]);
294
+ }
295
+ else if (isSourceFile(sourcePath)) {
296
+ entryPatterns.push(sourcePath);
297
+ rows.push([`"${cleanExportPath}"`, sourcePath]);
298
+ }
299
+ }
300
+ }
301
+ console.log(" " + (0, table_1.table)(rows).split("\n").join("\n ").trim());
302
+ ///////////////////////////////
303
+ /// compute entry points ///
304
+ ///////////////////////////////
305
+ // compute entry points
306
+ const entryPoints = await (0, utils_ts_1.getEntryPoints)(entryPatterns);
307
+ // disallow .mts and .cts files
308
+ if (entryPoints.some((ep) => ep.endsWith(".mts") || ep.endsWith(".cts"))) {
309
+ console.error("❌ Source files with .mts or .cts extensions are not supported. Please use regular .ts files.");
310
+ process.exit(1);
311
+ }
312
+ if (entryPoints.length === 0) {
313
+ console.error("❌ No entry points found matching the specified patterns in package.json#zshy exports");
314
+ process.exit(1);
315
+ }
316
+ ///////////////////////////////
317
+ /// compute root dir ///
318
+ ///////////////////////////////
319
+ // Compute common ancestor directory for all entry points
320
+ let rootDir;
321
+ if (tsconfigJson.rootDir) {
322
+ rootDir = path.resolve(tsconfigPath, tsconfigJson.rootDir);
323
+ }
324
+ else {
325
+ // compute rootDir from entrypoints
326
+ rootDir =
327
+ entryPoints.length > 0
328
+ ? entryPoints.reduce((common, entryPoint) => {
329
+ const entryDir = path.dirname(path.resolve(entryPoint));
330
+ const commonDir = path.resolve(common);
331
+ // Find the longest common path
332
+ const entryParts = entryDir.split(path.sep);
333
+ const commonParts = commonDir.split(path.sep);
334
+ let i = 0;
335
+ while (i < entryParts.length &&
336
+ i < commonParts.length &&
337
+ entryParts[i] === commonParts[i]) {
338
+ i++;
339
+ }
340
+ return commonParts.slice(0, i).join(path.sep) || path.sep;
341
+ }, path.dirname(path.resolve(entryPoints[0])))
342
+ : process.cwd();
343
+ }
344
+ // console.dir(_commonAncestor, { depth: null });
345
+ const relRootDir = path.relative(pkgJsonDir, rootDir);
346
+ console.log(`📂 Transpiling ${relRootDir ? `./${relRootDir}` : "."} (rootDir) to ${relOutDir ? `./${relOutDir}` : "."} (outDir)`);
347
+ if (relDeclarationDir !== relOutDir) {
348
+ console.log(`📂 Writing declaration files to ${relDeclarationDir ? `./${relDeclarationDir}` : "."} (declarationDir)`);
349
+ }
350
+ const isTypeModule = pkgJson.type === "module";
351
+ if (isTypeModule) {
352
+ console.log(`🟨 Package is an ES module (package.json#type is \"module\")`);
353
+ }
354
+ else {
355
+ console.log(`🐢 Package is a CommonJS module (${pkgJson.type === "commonjs" ? 'package.json#type is "commonjs"' : 'package.json#type not set to "module"'})`);
356
+ }
357
+ ///////////////////////////////
358
+ /// compile tsc ///
359
+ ///////////////////////////////
360
+ try {
361
+ // CJS
362
+ console.log(`🧱 Building CJS...${isTypeModule ? ` (rewriting .ts -> .cjs/.d.cts)` : ``}`);
363
+ await (0, utils_ts_1.compileProject)({
364
+ configPath: tsconfigPath,
365
+ mode: isTypeModule ? "cts" : "ts",
366
+ compilerOptions: {
367
+ ...tsconfigJson,
368
+ module: ts.ModuleKind.CommonJS,
369
+ moduleResolution: ts.ModuleResolutionKind.Node10,
370
+ outDir,
371
+ },
372
+ }, entryPoints);
373
+ // ESM
374
+ console.log(`🧱 Building ESM...${isTypeModule ? `` : ` (rewriting .ts -> .mjs/.d.mts)`}`);
375
+ await (0, utils_ts_1.compileProject)({
376
+ configPath: tsconfigPath,
377
+ mode: isTypeModule ? "ts" : "mts",
378
+ compilerOptions: {
379
+ ...tsconfigJson,
380
+ module: ts.ModuleKind.ESNext,
381
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
382
+ outDir,
383
+ },
384
+ }, entryPoints);
385
+ ///////////////////////////////
386
+ /// generate exports ///
387
+ ///////////////////////////////
388
+ // generate package.json exports
389
+ console.log("📦 Updating package.json exports...");
390
+ // Generate exports based on zshy config
391
+ const newExports = {};
392
+ const sourceDialects = config.sourceDialects || [];
393
+ for (const [exportPath, sourcePath] of Object.entries(config.exports)) {
394
+ if (exportPath.includes("package.json")) {
395
+ newExports[exportPath] = sourcePath;
396
+ continue;
397
+ }
398
+ if (typeof sourcePath === "string") {
399
+ if (sourcePath.endsWith("/*")) {
400
+ // Handle wildcard exports
401
+ const relSourcePath = "./" +
402
+ path.relative(pkgJsonDir, path.resolve(outDir, sourcePath.slice(0, -2))) +
403
+ "/*";
404
+ newExports[exportPath] = {
405
+ import: relSourcePath,
406
+ require: relSourcePath,
407
+ };
408
+ for (const sd of sourceDialects) {
409
+ newExports[exportPath] = {
410
+ [sd]: sourcePath,
411
+ ...newExports[exportPath],
412
+ };
413
+ }
414
+ }
415
+ else if (isSourceFile(sourcePath)) {
416
+ // Handle regular TypeScript entry points
417
+ // const basePath = sourcePath.slice(0, -3); // ./v4/index.ts
418
+ const absSourcePath = path.resolve(pkgJsonDir, sourcePath); // /path/to/v4/index.ts
419
+ const sourcePathRelativeToRootDir = path.relative(rootDir, absSourcePath); // index.ts
420
+ const outPath = path.resolve(pkgJsonDir, outDir, sourcePathRelativeToRootDir); // /path/to/dist/index.ts
421
+ const outPathNoExt = removeExtension(outPath); // /path/to/dist/index
422
+ // For declaration files, use declarationDir if it's different from outDir
423
+ const declarationPath = path.resolve(pkgJsonDir, declarationDir, sourcePathRelativeToRootDir); // /path/to/types/index.ts
424
+ const declarationPathNoExt = removeExtension(declarationPath); // /path/to/types/index
425
+ const esmFile = isTypeModule
426
+ ? `${outPathNoExt}.js`
427
+ : `${outPathNoExt}.mjs`; // ./v4/index.js or ./v4/index.mjs
428
+ const cjsFile = isTypeModule
429
+ ? `${outPathNoExt}.cjs`
430
+ : `${outPathNoExt}.js`;
431
+ const dtsFile = isTypeModule
432
+ ? `${declarationPathNoExt}.d.cts`
433
+ : `${declarationPathNoExt}.d.ts`;
434
+ const relEsmFile = "./" + path.relative(pkgJsonDir, esmFile);
435
+ const relCjsFile = "./" + path.relative(pkgJsonDir, cjsFile);
436
+ const relDtsFile = "./" + path.relative(pkgJsonDir, dtsFile);
437
+ newExports[exportPath] = {
438
+ types: relDtsFile,
439
+ import: relEsmFile,
440
+ require: relCjsFile,
441
+ // import: {
442
+ // types: relDtsFile,
443
+ // default: relEsmFile,
444
+ // },
445
+ // require: {
446
+ // types: relDtsFile,
447
+ // default: relCjsFile,
448
+ // },
449
+ };
450
+ if (exportPath === ".") {
451
+ pkgJson.main = relCjsFile;
452
+ pkgJson.module = relEsmFile;
453
+ pkgJson.types = relDtsFile;
454
+ }
455
+ for (const sd of sourceDialects) {
456
+ newExports[exportPath] = {
457
+ [sd]: sourcePath,
458
+ ...newExports[exportPath],
459
+ };
460
+ }
461
+ }
462
+ }
463
+ }
464
+ ///////////////////////////////
465
+ /// write pkg json ///
466
+ ///////////////////////////////
467
+ // Update package.json with new exports
468
+ pkgJson.exports = newExports;
469
+ fs.writeFileSync(packageJsonPath, JSON.stringify(pkgJson, null, 2) + "\n");
470
+ // console.log("✅ Updating package.json#exports");
471
+ console.log(" " + JSON.stringify(newExports, null, 2).split("\n").join("\n "));
472
+ // // run `@arethetypeswrong/cli --pack .` to check types
473
+ // console.log("🔍 Checking types with @arethetypeswrong/cli...");
474
+ // const { execSync } = await import("node:child_process");
475
+ // execSync(`npx @arethetypeswrong/cli --pack ${pkgJsonDir}`, {
476
+ // stdio: "inherit",
477
+ // cwd: pkgJsonDir,
478
+ // });
479
+ console.log("🎉 Build complete!");
480
+ }
481
+ catch (error) {
482
+ console.error("❌ Build failed:", error);
483
+ process.exit(1);
484
+ }
485
+ }
486
+ // Run the script
487
+ main().catch((error) => {
488
+ console.error("❌ Script failed:", error);
489
+ process.exit(1);
490
+ });
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/out/index.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};