All files / src pack-config.ts

100% Statements 26/26
100% Branches 12/12
100% Functions 4/4
100% Lines 26/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      1x 8x 8x 1x 8x 1x 7x 6x 6x 8x 8x 8x 8x 2x 1x 1x 2x 2x 8x 2x 2x 8x 2x 2x 8x 8x  
import type { Esmx } from './core';
 
/**
 * Package configuration interface.
 * Used to package build artifacts into standard npm .tgz format packages.
 *
 * Features:
 * - **Standardization**: Uses npm standard .tgz packaging format
 * - **Completeness**: Contains all necessary files including module source code, type declarations, and configuration files
 * - **Compatibility**: Fully compatible with npm ecosystem, supporting standard package management workflows
 *
 * Use Cases:
 * - Module packaging and publishing
 * - Version release management
 * - CI/CD process integration
 *
 * @example
 * ```ts
 * // entry.node.ts
 * import type { EsmxOptions } from '@esmx/core';
 *
 * export default {
 *   modules: {
 *     // Configure modules to export
 *     exports: [
 *       'root:src/components/button.vue',
 *       'root:src/utils/format.ts',
 *       'pkg:vue',
 *       'pkg:vue-router'
 *     ]
 *   },
 *   // Packaging configuration
 *   pack: {
 *     // Enable packaging functionality
 *     enable: true,
 *
 *     // Output multiple versions simultaneously
 *     outputs: [
 *       'dist/versions/latest.tgz',
 *       'dist/versions/1.0.0.tgz'
 *     ],
 *
 *     // Customize package.json
 *     packageJson: async (esmx, pkg) => {
 *       pkg.name = '@your-scope/your-app';
 *       pkg.version = '1.0.0';
 *       // Add build scripts
 *       pkg.scripts = {
 *         "prepare": "npm run build",
 *         "build": "npm run build:dts && npm run build:ssr",
 *         "build:ssr": "esmx build",
 *         "build:dts": "tsc --declaration --emitDeclarationOnly --outDir dist/src"
 *       };
 *       return pkg;
 *     },
 *
 *     // Pre-packaging preparation
 *     onBefore: async (esmx, pkg) => {
 *       // Add necessary files
 *       await fs.writeFile('dist/README.md', '# Your App\n\nModule export description...');
 *       // Execute type checking
 *       await runTypeCheck();
 *     },
 *
 *     // Post-packaging processing
 *     onAfter: async (esmx, pkg, file) => {
 *       // Publish to private npm registry
 *       await publishToRegistry(file, {
 *         registry: 'https://npm.your-registry.com/'
 *       });
 *       // Or deploy to static server
 *       await uploadToServer(file, 'https://static.example.com/packages');
 *     }
 *   }
 * } satisfies EsmxOptions;
 * ```
 */
export interface PackConfig {
    /**
     * Whether to enable packaging functionality.
     * When enabled, build artifacts will be packaged into standard npm .tgz format packages.
     * @default false
     */
    enable?: boolean;
 
    /**
     * Specify the output package file path.
     * Supports the following configuration methods:
     * - string: Single output path, e.g., 'dist/versions/my-app.tgz'
     * - string[]: Multiple output paths for generating multiple versions simultaneously
     * - boolean: When true, uses default path 'dist/client/versions/latest.tgz'
     *
     * @example
     * ```ts
     * // Single output
     * outputs: 'dist/app.tgz'
     *
     * // Multiple versions
     * outputs: [
     *   'dist/versions/latest.tgz',
     *   'dist/versions/1.0.0.tgz'
     * ]
     *
     * // Use default path
     * outputs: true
     * ```
     *
     * @default 'dist/client/versions/latest.tgz'
     */
    outputs?: string | string[] | boolean;
 
    /**
     * package.json processing function.
     * Called before packaging to customize the content of package.json.
     *
     * Common use cases:
     * - Modify package name and version
     * - Add or update dependencies
     * - Add custom fields
     * - Configure publishing related information
     *
     * @param esmx - Esmx instance
     * @param pkgJson - Original package.json content
     * @returns Processed package.json content
     *
     * @example
     * ```ts
     * packageJson: async (esmx, pkg) => {
     *   // Set package information
     *   pkg.name = 'my-app';
     *   pkg.version = '1.0.0';
     *   pkg.description = 'My Application';
     *
     *   // Add dependencies
     *   pkg.dependencies = {
     *     'vue': '^3.0.0',
     *     'express': '^4.17.1'
     *   };
     *
     *   // Add publishing configuration
     *   pkg.publishConfig = {
     *     registry: 'https://registry.example.com'
     *   };
     *
     *   return pkg;
     * }
     * ```
     */
    packageJson?: (
        esmx: Esmx,
        pkgJson: Record<string, any>
    ) => Promise<Record<string, any>>;
 
    /**
     * Pre-packaging hook function.
     * Called before generating .tgz file to execute preparation work.
     *
     * Common use cases:
     * - Add additional files (README, LICENSE, etc.)
     * - Execute tests or build validation
     * - Generate documentation or metadata
     * - Clean up temporary files
     *
     * @param esmx - Esmx instance
     * @param pkgJson - Processed package.json content
     *
     * @example
     * ```ts
     * onBefore: async (esmx, pkg) => {
     *   // Add documentation
     *   await fs.writeFile('dist/README.md', '# My App');
     *   await fs.writeFile('dist/LICENSE', 'MIT License');
     *
     *   // Execute tests
     *   await runTests();
     *
     *   // Generate documentation
     *   await generateDocs();
     * }
     * ```
     */
    onBefore?: (esmx: Esmx, pkgJson: Record<string, any>) => Promise<void>;
 
    /**
     * Post-packaging hook function.
     * Called after .tgz file is generated to handle packaging artifacts.
     *
     * Common use cases:
     * - Publish to npm registry (public or private)
     * - Upload to static asset server
     * - Execute version management
     * - Trigger CI/CD processes
     *
     * @param esmx - Esmx instance
     * @param pkgJson - Final package.json content
     * @param file - Generated .tgz file content
     *
     * @example
     * ```ts
     * onAfter: async (esmx, pkg, file) => {
     *   // Publish to npm private registry
     *   await publishToRegistry(file, {
     *     registry: 'https://registry.example.com'
     *   });
     *
     *   // Upload to static asset server
     *   await uploadToServer(file, 'https://assets.example.com/packages');
     *
     *   // Create version tag
     *   await createGitTag(pkg.version);
     *
     *   // Trigger deployment process
     *   await triggerDeploy(pkg.version);
     * }
     * ```
     */
    onAfter?: (
        esmx: Esmx,
        pkgJson: Record<string, any>,
        file: Buffer
    ) => Promise<void>;
}
 
/**
 * Internal interface after PackConfig configuration is parsed.
 * Standardizes user configuration, sets default values, for internal framework use.
 *
 * Main processing:
 * - Ensure all optional fields have default values
 * - Unify output path format
 * - Standardize callback functions
 */
export interface ParsedPackConfig {
    /**
     * Whether to enable packaging functionality.
     * Always has a definite boolean value after parsing.
     * @default false
     */
    enable: boolean;
 
    /**
     * Parsed output file path list.
     * Converts all output formats uniformly to string arrays:
     * - Boolean true → ['dist/client/versions/latest.tgz']
     * - String → [input string]
     * - String array → remains unchanged
     */
    outputs: string[];
 
    /**
     * Standardized package.json processing function.
     * Uses default function when not configured, keeping original content unchanged.
     */
    packageJson: (
        esmx: Esmx,
        pkgJson: Record<string, any>
    ) => Promise<Record<string, any>>;
 
    /**
     * Standardized pre-packaging hook function.
     * Uses empty function when not configured.
     */
    onBefore: (esmx: Esmx, pkgJson: Record<string, any>) => Promise<void>;
 
    /**
     * Standardized post-packaging hook function.
     * Uses empty function when not configured.
     */
    onAfter: (
        esmx: Esmx,
        pkgJson: Record<string, any>,
        file: Buffer
    ) => Promise<void>;
}
 
export function parsePackConfig(config: PackConfig = {}): ParsedPackConfig {
    const outputs: string[] = [];
    if (typeof config.outputs === 'string') {
        outputs.push(config.outputs);
    } else if (Array.isArray(config.outputs)) {
        outputs.push(...config.outputs);
    } else if (config.outputs !== false) {
        outputs.push('dist/client/versions/latest.tgz');
    }
    return {
        enable: config.enable ?? false,
        outputs,
        async packageJson(esmx, pkgJson) {
            if (config.packageJson) {
                pkgJson = await config.packageJson(esmx, pkgJson);
            }
            return pkgJson;
        },
        async onBefore(esmx, pkgJson: Record<string, any>) {
            await config.onBefore?.(esmx, pkgJson);
        },
        async onAfter(esmx, pkgJson, file) {
            await config.onAfter?.(esmx, pkgJson, file);
        }
    };
}