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