### PathsConfig Initialization Example Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/types.md Provides an example of initializing a `PathsConfig` object with path mappings and directory configurations. This setup is used by the path resolver transformer. ```typescript const pathsConfig: PathsConfig = { baseUrl: ".", paths: { "@/*": ["src/*"], "@utils": ["src/utils/index.ts"], }, tsconfigDir: process.cwd(), rootDir: "./src", }; ``` -------------------------------- ### Example Configuration with Multiple Exports Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/configuration.md An example zshy configuration defining the root export, a utils export, and wildcard exports for plugins. ```jsonc { "zshy": { "exports": { ".": "./src/index.ts", "./utils": "./src/utils.ts", "./plugins/*": "./src/plugins/*" } } } ``` -------------------------------- ### Example RawConfig JSON Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/types.md Illustrates a sample configuration object in JSONC format that conforms to the RawConfig interface. This example shows how to define exports, bin, cjs, and conditions. ```jsonc { "zshy": { "exports": { ".": "./src/index.ts", "./utils": "./src/utils.ts" }, "bin": "./src/cli.ts", "cjs": true, "conditions": { "@zod/source": "src" } } } ``` -------------------------------- ### Example RawConfig in package.json Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/api-reference/main.md Illustrates how to configure zshy settings within a package.json file. This example shows the usage of 'exports', 'bin', 'conditions', and 'cjs' fields. ```jsonc { "name": "my-lib", "zshy": { "exports": { ".": "./src/index.ts", "./utils": "./src/utils.ts", "./plugins/*": "./src/plugins/*" }, "bin": { "my-cli": "./src/cli.ts" }, "conditions": { "@zod/source": "src" }, "cjs": true } } ``` -------------------------------- ### CLI Entrypoint Shebang Example Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/configuration.md Example of a TypeScript CLI entrypoint file that includes the required shebang line and imports the main function. ```typescript // src/cli.ts #!/usr/bin/env node import { main } from "./index.js"; main(process.argv.slice(2)); ``` -------------------------------- ### Complete zshy Configuration Reference Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/configuration.md This example shows all available configuration options for zshy, including exports, bin entrypoints, conditions, and tsconfig. ```json { "zshy": { // Required if no "bin" is specified "exports": { ".": "./src/index.ts", // Root export "./utils": "./src/utils.ts", // Subpath export "./plugins/*": "./src/plugins/*", // Shallow wildcard (1 level) "./components/**/*": "./src/components/**/*" // Deep wildcard (recursive) }, // Optional: CLI entrypoint(s) "bin": "./src/cli.ts", // Single CLI // or "bin": { "my-cli": "./src/cli.ts", // Named CLI entries "my-other": "./src/other-cli.ts" }, // Optional: CommonJS build (default: true) "cjs": true, // Optional: Custom export conditions "conditions": { "@zod/source": "src", // Points to original .ts file "my-esm": "esm", // Points to .js (ESM output) "my-cjs": "cjs" // Points to .cjs (CJS output) }, // Optional: Alternative tsconfig location "tsconfig": "./build/tsconfig.json", // Optional: Prevent automatic package.json modification "noEdit": false } } ``` -------------------------------- ### Usage Example for Extension Rewrite Transformer Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/api-reference/transformers.md Demonstrates how to use the `createExtensionRewriteTransformer` to process TypeScript files. This setup involves creating a transformer instance and applying it during the TypeScript program's emit phase. ```typescript import { createExtensionRewriteTransformer } from "./tx-extension-rewrite.js"; import * as ts from "typescript"; const transformer = createExtensionRewriteTransformer({ rootDir: "./src", ext: ".js", onAssetImport: (assetPath) => { console.log(`Asset imported: ${assetPath}`); }, }); const compilerOptions: ts.CompilerOptions = { // Add your compiler options here }; const program = ts.createProgram(["./src/index.ts"], compilerOptions); const emitResult = program.emit(undefined, undefined, undefined, undefined, { before: [transformer], }); ``` -------------------------------- ### Generated Main Field Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/configuration.md Example of the 'main' field in package.json, specifying the CommonJS entrypoint. ```jsonc { "main": "./dist/index.cjs" } ``` -------------------------------- ### Example Generated Exports Map Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/api-reference/main.md This example demonstrates the ordering of conditions in the 'exports' field of package.json, where custom conditions are placed before standard conditions. ```jsonc { "exports": { ".": { "@zod/source": "./src/index.ts", // custom condition first "types": "./dist/index.d.cts", // standard conditions follow "import": "./dist/index.js", "require": "./dist/index.cjs" } } } ``` -------------------------------- ### Generated Bin Field (Single CLI) Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/configuration.md Example of the 'bin' field in package.json, specifying a single CLI entrypoint. ```jsonc { "bin": "./dist/cli.cjs" } ``` -------------------------------- ### Usage Example for compileProject Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/api-reference/compile.md Demonstrates how to use the compileProject function with custom build context and project options. Ensure necessary imports are included. ```typescript import { compileProject, type BuildContext, type ProjectOptions } from "./compile.js"; import * as ts from "typescript"; const buildContext: BuildContext = { writtenFiles: new Set(), copiedAssets: new Set(), errorCount: 0, warningCount: 0, }; const config: ProjectOptions = { configPath: "./tsconfig.json", ext: "cjs", format: "cjs", verbose: true, dryRun: false, pkgJsonDir: process.cwd(), rootDir: "./src", cjsInterop: true, compilerOptions: { outDir: "./dist", module: ts.ModuleKind.CommonJS, moduleResolution: ts.ModuleResolutionKind.Node10, // ... other options }, }; await compileProject(config, ["./src/index.ts", "./src/utils.ts"], buildContext); console.log(`Written files: ${buildContext.writtenFiles.size}`); console.log(`Errors: ${buildContext.errorCount}, Warnings: ${buildContext.warningCount}`); ``` -------------------------------- ### Logger Usage Example Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/api-reference/utils.md Demonstrates how to use the global logger, set a prefix, and log messages. Also shows how to disable logging with setSilent. ```typescript import { log, setSilent } from "./utils.js"; log.prefix = "» "; log.info("Starting build"); // » Starting build log.warn("Some warning"); // » Some warning log.error("An error occurred"); // » An error occurred setSilent(true); log.info("This won't print"); // (no output) ``` -------------------------------- ### BuildContext Initialization Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/api-reference/compile.md Provides an example of how to initialize a BuildContext object with default empty values for tracking compilation progress. ```typescript const ctx: BuildContext = { writtenFiles: new Set(), copiedAssets: new Set(), errorCount: 0, warningCount: 0, }; ``` -------------------------------- ### Install Zshy Dev Dependency Source: https://github.com/colinhacks/zshy/blob/main/README.md Install zshy as a development dependency using npm, yarn, or pnpm. ```bash npm install --save-dev zshy ``` ```bash yarn add --dev zshy ``` ```bash pnpm add --save-dev zshy ``` -------------------------------- ### Generated Module Field Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/configuration.md Example of the 'module' field in package.json, specifying the ESM entrypoint. ```jsonc { "module": "./dist/index.js" } ``` -------------------------------- ### View Zshy Build Output Source: https://github.com/colinhacks/zshy/blob/main/README.md This is an example of the terminal output when running a zshy build, showing detected entrypoints and resolved paths. ```bash $ npx zshy → Starting zshy build... 🐒 → Detected project root: /path/to/my-pkg → Reading package.json from ./package.json → Reading tsconfig from ./tsconfig.json → Determining entrypoints... ╔════════════════════╤═════════════════════════════╗ ║ Subpath │ Entrypoint ║ ╟────────────────────┼─────────────────────────────╢ ║ "my-pkg" │ ./src/index.ts ║ ║ "my-pkg/utils" │ ./src/utils.ts ║ ║ "my-pkg/plugins/*" │ ./src/plugins/* (5 matches) ║ ╚════════════════════╧═════════════════════════════╝ → Resolved build paths: ╔══════════╤════════════════╗ ║ Location │ Resolved path ║ ╟──────────┼────────────────╢ ║ rootDir │ ./src ║ ║ outDir │ ./dist ║ ╚══════════╧════════════════╝ → Package is ES module (package.json#/type is "module") → Building CJS... (rewriting .ts -> .cjs/.d.cts) → Building ESM... → Updating package.json exports... → Build complete! ✅ ``` -------------------------------- ### CJS Interop Transformer Usage Example Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/api-reference/transformers.md Illustrates the source code and the compiled output when using the `createCjsInteropTransformer`. The example shows how a default export function is transformed and how consumers can use `require()` to access it. ```typescript // Source: src/index.ts export default function greet(name: string) { return `Hello, ${name}`; } ``` ```javascript // Compiled output: dist/index.cjs var __exports = {}; function greet(name) { return `Hello, ${name}`; } __export(exports, "default", { value: greet }); module.exports = exports.default; // ← Added by transformer ``` ```javascript // Consumer can now use: const greet = require("pkg"); greet("world"); // Works! ``` -------------------------------- ### Generated Bin Field (Multiple CLIs) Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/configuration.md Example of the 'bin' field in package.json, specifying multiple CLI entrypoints with custom names. ```jsonc { "bin": { "my-cli": "./dist/cli.cjs", "other": "./dist/other.cjs" } } ``` -------------------------------- ### Invalid zshy Config Type Example Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/errors.md The 'zshy' key in package.json must be a string or an object. Examples show invalid types like numbers, booleans, and arrays. ```json { "zshy": 123, "zshy": true, "zshy": ["src/index.ts"] } ``` -------------------------------- ### Correct tsconfig Path vs. Directory Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/errors.md Ensure the --project flag points to the tsconfig.json file, not a directory. This example shows the correct and incorrect usage. ```bash zshy --project ./build/tsconfig.json # ✓ Correct zshy --project ./build # ✗ Incorrect (directory) ``` -------------------------------- ### Valid bin Types Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/errors.md Examples of correct 'bin' property types within the 'zshy' configuration, including string and object forms. ```json { "zshy": { "bin": "./src/cli.ts" } } ``` ```json { "zshy": { "bin": { "my-cli": "./src/cli.ts" } } } ``` -------------------------------- ### Generated Types Field Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/configuration.md Example of the 'types' field in package.json, specifying the TypeScript type definition entrypoint. ```jsonc { "types": "./dist/index.d.cts" } ``` -------------------------------- ### Import Meta Shim Transformer Usage Example Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/api-reference/transformers.md Demonstrates how `import.meta` properties are transformed in CJS output while remaining unchanged in ESM output. This enables cross-module code portability. ```typescript // Source: src/cli.ts console.log(import.meta.dirname); // Works in both ESM and CJS export function getConfigDir() { return import.meta.dirname; } // CJS output: dist/cli.cjs console.log(__dirname); // Transformed exports.getConfigDir = getConfigDir; function getConfigDir() { return __dirname; } // ESM output: dist/cli.js console.log(import.meta.dirname); // Unchanged export function getConfigDir() { return import.meta.dirname; } ``` -------------------------------- ### Invalid bin Type Example Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/errors.md The 'bin' property within the 'zshy' configuration must be a string or an object. ```json { "zshy": { "bin": ["./src/cli.ts"] } } ``` -------------------------------- ### Import Path Rewriting Examples Source: https://github.com/colinhacks/zshy/blob/main/README.md Illustrates how zshy rewrites relative import and export statements to match the generated file extensions, depending on the module type. ```typescript | Original path | Result (ESM) | Result (CJS) | | ------------------ | ------------------ | ------------------- | | `from "./util"` | `from "./util.js"` | `from "./util.cjs"` | | `from "./util.ts"` | `from "./util.js"` | `from "./util.cjs"` | | `from "./util.js"` | `from "./util.js"` | `from "./util.cjs"` | ``` -------------------------------- ### Export Equals Transformation Example Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/api-reference/transformers.md Demonstrates the transformation of CommonJS `export =` to ESM `export default` and the corresponding CJS output. ```typescript // Source: src/index.ts (CJS-style) function helper() { } export = helper; // ESM output: dist/index.js function helper() { } export default helper; // CJS output: dist/index.cjs function helper() { } exports.default = helper; module.exports = exports.default; ``` -------------------------------- ### Paths Resolver Transformer Usage Example Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/api-reference/transformers.md Illustrates how to configure and use the `createPathsResolverTransformer` to resolve module aliases like `@/*` to relative paths. Shows the transformation from an aliased import to a relative one. ```typescript import { createPathsResolverTransformer, type PathsConfig } from "./tx-paths-resolver.js"; import * as ts from "typescript"; const config: PathsConfig = { baseUrl: ".", paths: { "@/*": ["src/*"], "@utils": ["src/utils/index.ts"], }, tsconfigDir: process.cwd(), rootDir: "./src", }; const transformer = createPathsResolverTransformer(config); // In source code: // import { log } from "@/utils"; // // Transformed to: // import { log } from "./utils.js"; ``` -------------------------------- ### Extension Rewriting Example Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/index.md Demonstrates how imports are rewritten during compilation for both ESM and CJS output formats. Note that asset imports like JSON are not rewritten. ```typescript // Source import { util } from "./utils"; // Extensionless import { tool } from "./tool.ts"; // .ts extension import config from "./config.json"; // Asset import // ESM Output import { util } from "./utils.js"; import { tool } from "./tool.js"; import config from "./config.json"; // CJS Output import { util } from "./utils.cjs"; import { tool } from "./tool.cjs"; import config from "./config.json"; ``` -------------------------------- ### Generated Package.json Exports Map Source: https://github.com/colinhacks/zshy/blob/main/README.md Example of the 'exports' map generated in package.json after a zshy build, including types, import, and require conditions. ```diff // package.json { // ... + "exports": { + ".": { + "types": "./dist/index.d.cts", + "import": "./dist/index.js", + "require": "./dist/index.cjs" + }, + "./utils": { + "types": "./dist/utils.d.cts", + "import": "./dist/utils.js", + "require": "./dist/utils.cjs" + }, + "./plugins/*": { + "types": "./dist/src/plugins/*", + "import": "./dist/src/plugins/*", + "require": "./dist/src/plugins/*" + } +} } ``` -------------------------------- ### Enable Verbose Logging Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/index.md Enables detailed logging for all build steps in zshy. Use this option to get more insights into the build process. ```bash zshy --verbose ``` -------------------------------- ### Example of JsrExportEntry Mapping Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/types.md Illustrates how wildcard exports are expanded into explicit JsrExportEntry objects for JSR compatibility. This is useful when dealing with patterns like './plugins/*' that need to be resolved to specific files. ```typescript // Input: "zshy": { "exports": { "./plugins/*": "./src/plugins/*" } } // With matched files: ["./src/plugins/auth.ts", "./src/plugins/oauth.ts"] // Resulting entries: // [ // { exportPath: "./plugins/auth", sourcePath: "./src/plugins/auth.ts" }, // { exportPath: "./plugins/oauth", sourcePath: "./src/plugins/oauth.ts" } // ] ``` -------------------------------- ### main Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/index.md Async entry point for the zshy build process. Orchestrates the entire build pipeline. ```APIDOC ## main() ### Description Async entry point for the build process. Orchestrates parsing CLI arguments, reading configuration, compiling code, copying assets, and generating package metadata. ### Signature `main(): Promise` ### Returns A promise that resolves when the build is complete. ``` -------------------------------- ### Main Entry Point Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/README.md The primary function to initiate the complete build pipeline. ```APIDOC ## main ### Description Completes the build pipeline. ### Signature `main(): Promise` ``` -------------------------------- ### Invalid Condition Value Example Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/errors.md Custom conditions in 'zshy.conditions' must use 'esm', 'cjs', 'src', or null. This example shows an invalid value. ```json { "zshy": { "exports": { ".": "./src/index.ts" }, "conditions": { "my-condition": "invalid" } } } ``` -------------------------------- ### main() Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/api-reference/main.md Executes the complete zshy build pipeline, including parsing configuration, resolving entrypoints, compiling TypeScript, generating package.json, and outputting files. ```APIDOC ## main() ### Description Executes the complete zshy build pipeline. ### Method `async` ### Parameters None ### Return type `Promise` — Resolves when the build completes successfully; rejects with an error if build fails. ### Throws/Rejects - Exits with code 1 if configuration is invalid - Exits with code 1 if required files (package.json, tsconfig.json) are not found - Exits with code 1 if TypeScript compilation errors are encountered (unless `--fail-threshold` is overridden) - Exits with code 1 if entrypoints cannot be resolved ### CLI Flags #### Parameters - **--help, -h** (boolean) - Optional - Display usage information and exit - **--project, -p** (string) - Optional - Path to tsconfig.json file. Default: `./tsconfig.json` - **--verbose** (boolean) - Optional - Enable detailed logging output - **--silent** (boolean) - Optional - Suppress all console output - **--dry-run** (boolean) - Optional - Preview build output without writing files - **--fail-threshold** (string) - Optional - Exit code behavior: `"error"` (exit on errors), `"warn"` (exit on warnings), `"never"` (always succeed`). Default: `"error"` ### Usage Examples ```typescript import { main } from "./main.js"; // Run the build await main(); ``` ``` -------------------------------- ### Single CLI Bin Entrypoint Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/configuration.md Configure a single command-line interface entrypoint using a string value for the 'bin' option. The CLI name defaults to the package.json#/name. ```jsonc { "zshy": { "bin": "./src/cli.ts" } } ``` -------------------------------- ### CJS Interop Declaration Transformer Usage Example Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/api-reference/transformers.md Shows a class declaration in a source TypeScript file and its corresponding transformed .d.cts file, illustrating how `export =` is used for CommonJS compatibility. The example also demonstrates how to use the transformed type definition with `require()`. ```typescript // Source: src/utils.ts export default class Logger { log(msg: string) { console.log(msg); } } ``` ```typescript // Generated: dist/utils.d.cts declare class Logger { log(msg: string): void; } export = Logger; ``` ```typescript // Type definition allows: const Logger = require("pkg"); const logger: typeof Logger = new Logger(); ``` -------------------------------- ### No Entrypoints Found Error Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/errors.md This error occurs when neither the 'exports' nor 'bin' fields in package.json match any files. Ensure that the specified paths exist and are relative to the package.json directory. ```jsonc { "zshy": { "exports": { ".": "./nonexistent/index.ts" // ✗ File not found } } } ``` -------------------------------- ### setSilent Usage Example Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/api-reference/utils.md Shows how to call setSilent with true to suppress all subsequent log messages. ```typescript import { setSilent } from "./utils.js"; setSilent(true); // All log.info(), log.error(), log.warn() calls now produce no output ``` -------------------------------- ### Run Build with npm Source: https://github.com/colinhacks/zshy/blob/main/README.md Execute the build process after adding the 'build' script to your package.json. ```bash $ npm run build ``` -------------------------------- ### Valid Condition Values Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/errors.md Examples of valid condition values for 'zshy.conditions', including 'src', 'esm', and 'cjs'. ```json { "conditions": { "my-src-condition": "src", "my-esm-condition": "esm", "my-cjs-condition": "cjs" } } ``` -------------------------------- ### Configure Multiple CLI Entrypoints Source: https://github.com/colinhacks/zshy/blob/main/README.md For packages with multiple CLI tools, 'zshy/bin' can be an object mapping command names to their source files. ```json { // package.json "name": "my-cli", "version": "1.0.0", "type": "module", "zshy": { "bin": { "my-cli": "./src/cli.ts", "other": "./src/other.ts" } } } ``` -------------------------------- ### Invalid exports Type Example Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/errors.md The 'exports' property within the 'zshy' configuration must be a string or an object. ```json { "zshy": { "exports": 123 } } ``` -------------------------------- ### Multiple CLI Bin Entrypoints Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/configuration.md Define multiple command-line interface entrypoints using an object for the 'bin' option, mapping CLI names to their source files. ```jsonc { "zshy": { "bin": { "my-cli": "./src/cli.ts", "my-other": "./src/other.ts" } } } ``` -------------------------------- ### Flat Build Configuration Source: https://github.com/colinhacks/zshy/blob/main/README.md Provides configuration steps for creating a 'flat build' to support older environments or non-Node.js runtimes that do not support `package.json#/exports`. ```jsonc { // ... "exclude": ["**/*.ts", "**/*.tsx", "**/*.cts", "**/*.mts", "node_modules"] } ``` -------------------------------- ### Configure Single CLI Entrypoint Source: https://github.com/colinhacks/zshy/blob/main/README.md Specify a single CLI entrypoint in 'zshy/bin' for your package. Zshy will build it and automatically set the 'bin' field in package.json. ```diff { // package.json "name": "my-cli", "version": "1.0.0", "type": "module", "zshy": { + "bin": "./src/cli.ts" } } ``` -------------------------------- ### Package.json Exports for ESM-only Build Source: https://github.com/colinhacks/zshy/blob/main/README.md Example of the 'exports' map in package.json when CommonJS is disabled, showing only 'types' and 'import' conditions. ```json { // package.json "exports": { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" } } } ``` -------------------------------- ### Minimal zshy Configuration Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/configuration.md Use the shorthand string form to specify the root export entrypoint for your library. ```json { "name": "my-lib", "zshy": "./src/index.ts" } ``` -------------------------------- ### Valid exports Types Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/errors.md Examples of correct 'exports' property types within the 'zshy' configuration, including string and object forms. ```json { "zshy": { "exports": "./src/index.ts" } } ``` ```json { "zshy": { "exports": { ".": "./src/index.ts" } } } ``` -------------------------------- ### Configure Multiple Entrypoints in package.json Source: https://github.com/colinhacks/zshy/blob/main/README.md Define multiple entrypoints, including wildcard patterns, for zshy within the 'zshy.exports' object in your package.json. ```json // package.json { "name": "my-pkg", "version": "1.0.0", "zshy": { "exports": { ".": "./src/index.ts", "./utils": "./src/utils.ts", "./plugins/*": "./src/plugins/*", // wildcard "./components/**/*": "./src/components/**/*" // deep wildcard } } } ``` -------------------------------- ### Zshy CLI Help Source: https://github.com/colinhacks/zshy/blob/main/README.md Displays the available command-line options for the Zshy tool, including project path, verbosity, and dry-run capabilities. ```sh $ npx zshy --help Usage: zshy [options] Options: -h, --help Show this help message -p, --project Path to tsconfig (default: ./tsconfig.json) --verbose Enable verbose output --dry-run Don't write any files or update package.json --fail-threshold When to exit with non-zero error code "error" (default) "warn" "never" ``` -------------------------------- ### Generated Package.json Multiple Bin Fields Source: https://github.com/colinhacks/zshy/blob/main/README.md Demonstrates the 'bin' field in package.json when multiple CLI entrypoints are configured in 'zshy/bin'. ```diff { // package.json "name": "my-cli", "version": "1.0.0", "zshy": { "exports": "./src/index.ts", "bin": { "my-cli": "./src/cli.ts", "other": "./src/other.ts" } }, "bin": { "my-cli": "./dist/cli.cjs", "other": "./dist/other.cjs" } } ``` -------------------------------- ### Generated Exports Field Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/configuration.md Example of the standard Node.js exports field automatically generated by Zshy, including type definitions and module conditions. ```jsonc { "exports": { ".": { "types": "./dist/index.d.cts", "import": "./dist/index.js", "require": "./dist/index.cjs" } } } ``` -------------------------------- ### Generated Exports Map with Custom Conditions Source: https://github.com/colinhacks/zshy/blob/main/README.md Example of how zshy adds custom conditions to the package.json 'exports' map based on the zshy configuration. ```json // package.json { "exports": { ".": { "my-src-condition": "./src/index.ts", "my-esm-condition": "./dist/index.js", "my-cjs-condition": "./dist/index.cjs" "types": "./dist/index.d.cts", "import": "./dist/index.js", "require": "./dist/index.cjs" } } } ``` -------------------------------- ### Standard zshy Configuration Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/configuration.md Configure multiple export entrypoints using the object form, specifying paths for the root and subpaths. ```json { "name": "my-lib", "zshy": { "exports": { ".": "./src/index.ts", "./utils": "./src/utils.ts" } } } ``` -------------------------------- ### Configuration Path Utility Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/README.md Finds the path to a configuration file. ```APIDOC ## findConfigPath ### Description Finds the path to a configuration file with the given name. ### Signature `findConfigPath(name: string): string | null` ### Parameters - `name`: The name of the configuration file to find. ``` -------------------------------- ### Import Assets in TypeScript Source: https://github.com/colinhacks/zshy/blob/main/test/basic/src/assets/README.md Demonstrates how to import CSS and JSON assets in TypeScript files. Ensure assets are correctly placed within the project structure. ```typescript import './assets/styles.css'; import config from './assets/config.json'; ``` -------------------------------- ### Invalid Subpath Export Error Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/errors.md Triggered when an export key in package.json does not start with './'. Prefix all subpath export keys with './' for valid configurations. ```jsonc { "zshy": { "exports": { "utils": "./src/utils.ts" // ✗ Must be "./utils" } } } ``` ```jsonc { "exports": { "./utils": "./src/utils.ts" // ✓ Correct } } ``` -------------------------------- ### Preview Build Output Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/index.md Performs a dry run of the zshy build process. This command previews the build output without actually writing any files to disk. ```bash zshy --dry-run ``` -------------------------------- ### Import TypeScript Module Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/types.md Import the entire TypeScript module to access its types and functions. This is a common setup for projects interacting with the TypeScript compiler API. ```typescript import * as ts from "typescript"; ``` -------------------------------- ### Build zshy Project Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/index.md Runs the build script for zshy. This command executes `tsx src/index.ts` to build the project itself using zshy. ```bash npm run build ``` -------------------------------- ### Package.json Exports Configuration Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/index.md Shows how to define entry points and exports for a zshy project within the package.json file. This includes root exports, subpath exports, wildcard exports, and CLI binary definitions. ```json { "zshy": { "exports": { ".": "./src/index.ts", // Root export "./utils": "./src/utils.ts", // Subpath "./plugins/*": "./src/plugins/*" // Wildcard }, "bin": "./src/cli.ts" // CLI entry } } ``` -------------------------------- ### CommonJS Import Error Example Source: https://github.com/colinhacks/zshy/blob/main/README.md Illustrates the 'Masquerading as ESM' error that occurs when CommonJS files try to require ESM modules. This is avoided by using `.d.cts` for type declarations. ```ts import mod from "pkg"; ^^^^^ // ^ The current file is a CommonJS module whose imports will produce 'require' calls; however, the referenced file is an ECMAScript module and cannot be imported with 'require'. Consider writing a dynamic 'import("pkg")' call instead. ``` -------------------------------- ### Run Zshy Build Source: https://github.com/colinhacks/zshy/blob/main/README.md Execute a build using npx zshy. Use the --dry-run flag to preview changes without writing files. ```bash $ npx zshy # use --dry-run to try it out without writing/updating files → Starting zshy build 🐒 → Detected project root: /Users/colinmcd94/Documents/projects/zshy → Reading package.json from ./package.json → Reading tsconfig from ./tsconfig.json → Cleaning up outDir... → Determining entrypoints... ╔════════════╤════════════════╗ ║ Subpath │ Entrypoint ║ ╟────────────┼────────────────╢ ║ "my-pkg" │ ./src/index.ts ║ ╚════════════╧════════════════╝ → Resolved build paths: ╔══════════╤════════════════╗ ║ Location │ Resolved path ║ ╟──────────┼────────────────╢ ║ rootDir │ ./src ║ ║ outDir │ ./dist ║ ╚══════════╧════════════════╝ → Package is an ES module (package.json#/type is "module") → Building CJS... (rewriting .ts -> .cjs/.d.cts) → Building ESM... → Updating package.json#/exports... → Updating package.json#/bin... → Build complete! ✅ ``` -------------------------------- ### Get Relative POSIX Path Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/api-reference/utils.md Calculates the relative path between two directories in POSIX format. This is helpful when you need to reference a file or directory from a different location within a project. ```typescript export const relativePosix = (from: string, to: string): string ``` ```typescript relativePosix("/project/src", "/project/dist/index.js") // → "dist/index.js" relativePosix("/project/src/utils", "/project/dist/utils/helpers.js") // → "../../dist/utils/helpers.js" ``` -------------------------------- ### Configure Single Entrypoint in package.json Source: https://github.com/colinhacks/zshy/blob/main/README.md Specify a single TypeScript entrypoint for zshy in the 'zshy' field of your package.json. ```json // package.json { "name": "my-pkg", "version": "1.0.0", "zshy": "./src/index.ts" } ``` -------------------------------- ### Provide exports or bin for zshy Config Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/errors.md If the 'zshy' key is an object, it must include either an 'exports' or a 'bin' property. ```json { "zshy": { "exports": { ".": "./src/index.ts" } } } ``` ```json { "zshy": { "bin": "./src/cli.ts" } } ``` -------------------------------- ### CJS Interop Declaration Transformer Transformation Example Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/api-reference/transformers.md Demonstrates the transformation of a default export function declaration in a TypeScript input file to the CommonJS-compatible `export =` syntax in a .d.cts output file. ```typescript // Input: export default function greet(name: string): string; export default function greet(name: string): string; ``` ```typescript // Output: .d.cts file declare function greet(name: string): string; export = greet; // CommonJS-compatible export syntax ``` -------------------------------- ### CJS Disabled Without Module Type Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/errors.md If 'cjs: false' is used, the package.json must have '"type": "module"'. This example shows the invalid configuration and its resolution. ```jsonc { // Missing: "type": "module" "zshy": { "cjs": false // ✗ Invalid without type: module } } ``` ```jsonc { "type": "module", // ✓ Required "zshy": { "cjs": false } } ``` -------------------------------- ### Zshy Build Output Structure Source: https://github.com/colinhacks/zshy/blob/main/README.md Illustrates the file structure generated by Zshy after a successful build, including .js, .cjs, and .d.ts files for both ESM and CJS outputs. ```bash $ tree . ├── package.json ├── src │ └── index.ts └── dist # generated ├── index.js ├── index.cjs ├── index.d.ts └── index.d.cts ``` -------------------------------- ### ProjectOptions Interface Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/api-reference/compile.md Defines the structure for configuring a single compilation build, including TypeScript compiler settings, output formats, and file paths. ```APIDOC ## ProjectOptions Configuration for a single compilation build (CJS or ESM). ### Interface Definition ```typescript export interface ProjectOptions { configPath: string; compilerOptions: ts.CompilerOptions & Required>; ext: "cjs" | "js" | "mjs"; format: "cjs" | "esm"; pkgJsonDir: string; rootDir: string; verbose: boolean; dryRun: boolean; cjsInterop?: boolean; paths?: Record; baseUrl?: string; } ``` ### Fields | Field | Type | Required | Description | |---|---|---|---| | `configPath` | string | yes | Path to tsconfig.json file | | `compilerOptions` | `ts.CompilerOptions` | yes | TypeScript compiler options (must include `module`, `moduleResolution`, `outDir`) | | `ext` | `"cjs" | "js" | "mjs"` | yes | Output file extension for compiled JavaScript. Use `"cjs"` for CommonJS in ESM packages, `"js"` for CJS packages, `"mjs"` for ESM in CJS packages. | | `format` | `"cjs" | "esm"` | yes | Output module format. Controls which transformers are applied. | | `pkgJsonDir` | string | yes | Directory containing package.json (used for relative path display) | | `rootDir` | string | yes | Source root directory (used for asset path resolution) | | `verbose` | boolean | yes | Enable detailed logging during compilation | | `dryRun` | boolean | yes | If true, do not write files to disk | | `cjsInterop` | boolean | no | If true and format is "cjs", apply CJS interop transformer for single default exports | | `paths` | `Record` | no | TypeScript `paths` configuration for module alias resolution | | `baseUrl` | string | no | TypeScript `baseUrl` for path resolution (relative to tsconfig directory) | ``` -------------------------------- ### Analyze Exports in TypeScript Source File Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/api-reference/transformers.md Use this function to analyze export statements within a TypeScript source file. It identifies default exports, named exports, and type-only exports. Ensure you have the 'typescript' package installed. ```typescript import { analyzeExports } from "./tx-analyze-exports.js"; import * as ts from "typescript"; const source = ts.createSourceFile( "test.ts", ` export function helper() {} export default class App {} export type Config = {}; `, ts.ScriptTarget.Latest, true ); const analysis = analyzeExports(source); console.log(analysis.defaultExportNode); // ExportAssignment node for class console.log(analysis.hasNamedExports); // true (helper function) console.log(analysis.hasTypeOnlyExports); // true (Config type) ``` -------------------------------- ### Define Exports with Wildcards Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/configuration.md Use wildcard patterns in exports to automatically discover and create corresponding exports for files matching the pattern. Files in __tests__ directories or matching .test.* or .spec.* are excluded. ```jsonc { "zshy": { "exports": { "./plugins/*": "./src/plugins/*" } } } ``` -------------------------------- ### Find Configuration File Path Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/api-reference/utils.md Locates a specified configuration file by searching upwards from the current working directory. Returns the absolute path if found, otherwise null. Ensure the utility is imported correctly. ```typescript export function findConfigPath(fileName: string): string | null ``` ```typescript import { findConfigPath } from "./utils.js"; const pkgPath = findConfigPath("package.json"); if (pkgPath) { console.log("Found at:", pkgPath); // e.g., "/project/package.json" } else { console.log("Not found"); } ``` -------------------------------- ### Generated Package.json Bin Field Source: https://github.com/colinhacks/zshy/blob/main/README.md Shows the 'bin' field automatically added to package.json after configuring a CLI entrypoint in 'zshy/bin'. ```diff { // package.json "name": "my-cli", "version": "1.0.0", "zshy": { "exports": "./src/index.ts", "bin": "./src/cli.ts" }, + "bin": { + "my-cli": "./dist/cli.cjs" // CLI entrypoint + } } ``` -------------------------------- ### toPosix() Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/api-reference/utils.md Converts a given file path to the POSIX format, ensuring all path separators are forward slashes. ```APIDOC ## toPosix() ### Description Convert file path to POSIX format (forward slashes). ### Signature ```typescript export const toPosix = (p: string): string ``` ### Parameters #### Path Parameters - **p** (string) - Required - File path with possible backslashes ### Return type `string` — Path with all separators converted to forward slashes. ### Usage Example ```typescript toPosix("src\\utils\\index.ts") // "src/utils/index.ts" toPosix("src/utils/index.ts") // "src/utils/index.ts" (no change) ``` ``` -------------------------------- ### Add Build Script to package.json Source: https://github.com/colinhacks/zshy/blob/main/README.md Integrate the 'zshy' command into your package.json scripts for easy execution via 'npm run build'. ```diff { // ... "scripts": { + "build": "zshy" } } ``` -------------------------------- ### Zshy Package.json Configuration for Exports Source: https://github.com/colinhacks/zshy/blob/main/README.md Configure package exports using zshy in package.json. Supports direct file paths, wildcard shallow matches ('/*'), and wildcard deep matches ('/**/*'). ```jsonc // package.json { "name": "my-pkg", "version": "1.0.0", "zshy": { "exports": { ".": "./src/index.ts", "./utils": "./src/utils.ts", "./plugins/*": "./src/plugins/*", "./components/*": "./src/components/**/*" } } } ``` -------------------------------- ### Add zshy Config to package.json Source: https://github.com/colinhacks/zshy/blob/main/_autodocs/errors.md When the 'zshy' key is missing in package.json, add it with a string value for a single entrypoint or an object for multiple exports. ```json { "zshy": "./src/index.ts" } ``` ```json { "zshy": { "exports": { ".": "./src/index.ts", "./utils": "./src/utils.ts" } } } ```