@powerlines/core 0.48.53 → 0.48.54
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/constants/api.mjs.map +1 -1
- package/dist/constants/commands.mjs.map +1 -1
- package/dist/constants/devtools.mjs.map +1 -1
- package/dist/constants/environments.mjs.map +1 -1
- package/dist/constants/extensions.mjs.map +1 -1
- package/dist/constants/fs.mjs.map +1 -1
- package/dist/constants/hooks.mjs.map +1 -1
- package/dist/constants/log-level.mjs.map +1 -1
- package/dist/constants/meta.mjs.map +1 -1
- package/dist/constants/plugin.mjs.map +1 -1
- package/dist/context/base-context.mjs.map +1 -1
- package/dist/context/context.mjs.map +1 -1
- package/dist/context/environment-context.mjs.map +1 -1
- package/dist/context/execution-context.mjs.map +1 -1
- package/dist/context/plugin-context.mjs.map +1 -1
- package/dist/lib/config.mjs.map +1 -1
- package/dist/lib/context-helpers.mjs.map +1 -1
- package/dist/lib/entry.mjs.map +1 -1
- package/dist/lib/environment.mjs.map +1 -1
- package/dist/lib/events.mjs.map +1 -1
- package/dist/lib/generate-types.mjs.map +1 -1
- package/dist/lib/hooks.mjs.map +1 -1
- package/dist/lib/install-dependencies.mjs.map +1 -1
- package/dist/lib/meta.mjs.map +1 -1
- package/dist/lib/plugins.mjs.map +1 -1
- package/dist/lib/resolver.mjs.map +1 -1
- package/dist/lib/streaming-channel.mjs.map +1 -1
- package/dist/lib/typescript/ts-morph.mjs.map +1 -1
- package/dist/lib/typescript/tsconfig.mjs.map +1 -1
- package/dist/lib/unplugin/helpers.mjs.map +1 -1
- package/dist/lib/unplugin/module-resolution.mjs.map +1 -1
- package/dist/lib/unplugin/plugin.mjs.map +1 -1
- package/dist/lib/utilities/file-header.mjs.map +1 -1
- package/dist/lib/utilities/format.cjs +7 -1
- package/dist/lib/utilities/format.d.cts.map +1 -1
- package/dist/lib/utilities/format.d.mts.map +1 -1
- package/dist/lib/utilities/format.mjs +6 -1
- package/dist/lib/utilities/format.mjs.map +1 -1
- package/dist/lib/utilities/source-file.mjs.map +1 -1
- package/dist/lib/utilities/source-map.mjs.map +1 -1
- package/dist/lib/utilities/write-file.mjs.map +1 -1
- package/dist/lib/vfs.cjs +1 -1
- package/dist/lib/vfs.mjs +1 -1
- package/dist/lib/vfs.mjs.map +1 -1
- package/dist/plugin-base.mjs.map +1 -1
- package/dist/plugin-utils/build-helpers.mjs.map +1 -1
- package/dist/plugin-utils/combine-plugins.mjs.map +1 -1
- package/dist/plugin-utils/context-helpers.mjs.map +1 -1
- package/dist/plugin-utils/docs-helper.mjs.map +1 -1
- package/dist/plugin-utils/enable-plugin.mjs.map +1 -1
- package/dist/plugin-utils/extend.mjs.map +1 -1
- package/dist/plugin-utils/filter.mjs.map +1 -1
- package/dist/plugin-utils/format-package-json.mjs.map +1 -1
- package/dist/plugin-utils/format.mjs.map +1 -1
- package/dist/plugin-utils/get-config-path.mjs.map +1 -1
- package/dist/plugin-utils/helpers.mjs.map +1 -1
- package/dist/plugin-utils/install.mjs.map +1 -1
- package/dist/plugin-utils/logging.mjs.map +1 -1
- package/dist/plugin-utils/merge.mjs.map +1 -1
- package/dist/plugin-utils/modules.mjs.map +1 -1
- package/dist/plugin-utils/paths.mjs.map +1 -1
- package/dist/plugin-utils/virtual.mjs.map +1 -1
- package/dist/storage/base.mjs.map +1 -1
- package/dist/storage/file-system.mjs.map +1 -1
- package/dist/storage/helpers.mjs.map +1 -1
- package/dist/storage/virtual.mjs.map +1 -1
- package/package.json +10 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"environment-context.mjs","names":["#hooks","#execution"],"sources":["../../src/context/environment-context.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { omit } from \"@stryke/helpers/omit\";\nimport { isFunction } from \"@stryke/type-checks/is-function\";\nimport { isObject } from \"@stryke/type-checks/is-object\";\nimport { isSetObject } from \"@stryke/type-checks/is-set-object\";\nimport { ArrayValues } from \"@stryke/types/array\";\nimport { uuid } from \"@stryke/unique-id/uuid\";\nimport {\n DEFAULT_ENVIRONMENT,\n GLOBAL_ENVIRONMENT,\n PLUGIN_NON_HOOK_FIELDS\n} from \"../constants\";\nimport { extractHooks } from \"../lib/hooks\";\nimport { resolvePlugins } from \"../lib/plugins\";\nimport {\n dedupeHooklist,\n formatConfig,\n isPlugin,\n isPluginConfig,\n isPluginHookField,\n mergeConfig\n} from \"../plugin-utils\";\nimport type {\n EnvironmentContext,\n EnvironmentPlugin,\n EnvironmentResolvedConfig,\n ExecutionContext,\n ExecutionOptions,\n HooksList,\n HooksListItem,\n InferOverridableConfig,\n Logger,\n LoggerOptions,\n PluginConfig,\n PluginContext,\n ResolvedConfig,\n SelectHookResult,\n SelectHooksOptions\n} from \"../types\";\nimport { PowerlinesContext } from \"./context\";\nimport { createPluginContext } from \"./plugin-context\";\n\nexport class PowerlinesEnvironmentContext<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig,\n TSystemContext = unknown\n>\n extends PowerlinesContext<\n EnvironmentResolvedConfig<TResolvedConfig>,\n TSystemContext\n >\n implements EnvironmentContext<TResolvedConfig, TSystemContext>\n{\n /**\n * The hooks registered by plugins in this environment\n */\n #hooks: Record<\n string,\n HooksList<PluginContext<TResolvedConfig, TSystemContext>>\n > = {};\n\n /**\n * The execution context associated with this environment, which provides access to the project configuration, environment, and utility functions for performing the build. The execution context is used to manage the state and behavior of the build process across multiple environments, allowing for hooks to be called at different stages of the build and for environment-specific configurations to be applied.\n */\n #execution: ExecutionContext<TResolvedConfig, TSystemContext>;\n\n /**\n * Create a new context from the config.\n *\n * @param execution - The execution context for the build process, which provides access to the project configuration, environment, and utility functions for performing the build. The context is used to manage the state and behavior of the build process, allowing for hooks to be called at different stages of the build and for environment-specific configurations to be applied.\n * @param options - The resolved execution options.\n * @param config - The user configuration options.\n * @param overriddenConfig - The configuration options that should override all other configuration sources, such as CLI flags or environment variables. This is used to ensure that certain configuration values take precedence over any other settings defined in the user configuration or environment configuration, allowing for dynamic overrides based on the execution context.\n * @returns A promise that resolves to an instance of the PowerlinesEnvironmentContext class, initialized with the provided configuration and environment data.\n */\n public static async from<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig,\n TSystemContext = unknown\n >(\n execution: ExecutionContext<TResolvedConfig, TSystemContext>,\n options: ExecutionOptions,\n config: TResolvedConfig,\n overriddenConfig: InferOverridableConfig<\n EnvironmentResolvedConfig<TResolvedConfig>\n >\n ): Promise<PowerlinesEnvironmentContext<TResolvedConfig, TSystemContext>> {\n const context = new PowerlinesEnvironmentContext<\n TResolvedConfig,\n TSystemContext\n >(execution, options, config, overriddenConfig);\n await context.init();\n\n return context;\n }\n\n /**\n * The configuration options provided by plugins added by the user (and other plugins)\n */\n protected override environmentConfig: EnvironmentResolvedConfig<TResolvedConfig>[\"environment\"] =\n {} as EnvironmentResolvedConfig<TResolvedConfig>[\"environment\"];\n\n /**\n * The list of plugins applied to this environment\n */\n public plugins: EnvironmentPlugin<TResolvedConfig, TSystemContext>[] = [];\n\n /**\n * The unique identifier of the environment associated with this context, which can be used for logging and other purposes to distinguish between different environments in the same process.\n */\n public get id(): string {\n return this.config.environment.id;\n }\n\n /**\n * The hooks registered by plugins in this environment\n */\n public get hooks(): Record<\n string,\n HooksList<PluginContext<TResolvedConfig, TSystemContext>>\n > {\n return this.#hooks;\n }\n\n /**\n * The execution context associated with this environment, which provides access to the project configuration, environment, and utility functions for performing the build. The execution context is used to manage the state and behavior of the build process across multiple environments, allowing for hooks to be called at different stages of the build and for environment-specific configurations to be applied.\n *\n * @danger\n * This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.\n *\n * @internal\n */\n public get unstable_execution(): ExecutionContext<\n TResolvedConfig,\n TSystemContext\n > {\n return this.#execution;\n }\n\n /**\n * A setter function to populate the environment config values provided during execution of the command, such as CLI flags or other parameters that may be relevant to the command being executed. This function can be used to update the context with the environment configuration values, which may be used during the configuration resolution process to ensure that the final configuration reflects both the user configuration and any environment configuration provided during execution.\n *\n * @param config - The environment configuration values to set.\n * @returns A promise that resolves when the environment configuration values have been set.\n */\n public async setEnvironmentConfig(\n config: EnvironmentResolvedConfig<TResolvedConfig>[\"environment\"]\n ): Promise<void> {\n this.logger.debug({\n meta: { category: \"config\" },\n message: `Updating environment configuration object: \\n${formatConfig(config)}`\n });\n\n this.environmentConfig = config;\n await this.resolveConfig();\n }\n\n /**\n * Create a new logger instance\n *\n * @param options - The configuration options to use for the logger instance, which can be used to customize the appearance and behavior of the log messages generated by the logger. This is typically the name of the plugin or module that is creating the logger instance.\n * @returns A logger client instance that can be used to generate log messages with consistent formatting and metadata.\n */\n public override createLogger(options: LoggerOptions): Logger {\n return super.createLogger({\n ...options,\n environment: this.environmentConfig?.name || this.config.environment?.name\n });\n }\n\n /**\n * Extend the base logger with additional configuration options\n *\n * @param options - The configuration options to extend the base logger with, which can be used to add additional metadata or customize the appearance of log messages generated by the logger. This is typically the name of the plugin or module that is creating the logger instance, as well as any additional metadata such as the plugin category or environment.\n * @returns A new logger client instance that extends the base logger with the provided configuration options.\n */\n public override extendLogger(options: LoggerOptions): Logger {\n return super.extendLogger({\n ...options,\n environment: this.environmentConfig?.name || this.config.environment?.name\n });\n }\n\n /**\n * A function used internally to add a plugin to the context and update the configuration options\n *\n * @danger\n * This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.\n *\n * @internal\n */\n public async unstable_addPlugin(\n plugin: PluginConfig<PluginContext<TResolvedConfig, TSystemContext>>\n ): Promise<void> {\n const plugins = await resolvePlugins<TResolvedConfig, TSystemContext>(\n this,\n plugin,\n {\n skipLogging: !!(\n this.environmentConfig?.name &&\n this.environmentConfig.name !== DEFAULT_ENVIRONMENT &&\n this.environmentConfig.name !== GLOBAL_ENVIRONMENT\n )\n }\n );\n for (const plugin of plugins) {\n let resolvedPlugin = plugin as EnvironmentPlugin<\n TResolvedConfig,\n TSystemContext\n >;\n if (isFunction(plugin.applyToEnvironment)) {\n const result = (await Promise.resolve(\n plugin.applyToEnvironment(this.config.environment) as Promise<any>\n )) as\n | boolean\n | PluginConfig<PluginContext<TResolvedConfig, TSystemContext>>;\n\n if (!result || (isObject(result) && Object.keys(result).length === 0)) {\n return;\n }\n\n if (\n isPluginConfig<PluginContext<TResolvedConfig, TSystemContext>>(result)\n ) {\n return this.unstable_addPlugin(result);\n }\n\n resolvedPlugin = (\n isPlugin<PluginContext<TResolvedConfig, TSystemContext>>(result)\n ? result\n : plugin\n ) as EnvironmentPlugin<TResolvedConfig, TSystemContext>;\n }\n\n const id = uuid();\n const context = createPluginContext<TResolvedConfig, TSystemContext>(\n id,\n resolvedPlugin,\n this\n );\n\n resolvedPlugin[\"~internal\"] = {\n id,\n context\n };\n\n this.plugins.push(resolvedPlugin);\n\n this.#hooks = Object.entries(\n Object.keys(resolvedPlugin)\n .filter(\n key =>\n key !== \"~internal\" &&\n !PLUGIN_NON_HOOK_FIELDS.includes(\n key as ArrayValues<typeof PLUGIN_NON_HOOK_FIELDS>\n )\n )\n .reduce(\n (ret, key) =>\n extractHooks<TResolvedConfig, TSystemContext>(\n context,\n ret,\n resolvedPlugin,\n key\n ),\n this.hooks\n )\n ).reduce(\n (ret, [key, value]) => {\n if (isSetObject(value)) {\n Object.entries(value).forEach(([type, list]) => {\n ret[key] ??= {};\n ret[key][type as keyof (typeof ret)[typeof key]] =\n dedupeHooklist<PluginContext<TResolvedConfig, TSystemContext>>(\n list\n );\n });\n }\n\n return ret;\n },\n {} as Record<\n string,\n HooksList<PluginContext<TResolvedConfig, TSystemContext>>\n >\n );\n }\n }\n\n /**\n * Retrieves the hook handlers for a specific hook name\n */\n public selectHooks<TKey extends string>(\n key: TKey,\n options?: SelectHooksOptions\n ): SelectHookResult<PluginContext<TResolvedConfig, TSystemContext>, TKey> {\n const result = [] as SelectHookResult<\n PluginContext<TResolvedConfig, TSystemContext>,\n TKey\n >;\n\n if (\n isPluginHookField<PluginContext<TResolvedConfig, TSystemContext>>(key) &&\n this.hooks[key]\n ) {\n if (this.hooks[key]) {\n if (options?.order) {\n const mapHooksToResult = (\n hooksList: HooksListItem<\n PluginContext<TResolvedConfig, TSystemContext>,\n TKey\n >[]\n ): SelectHookResult<\n PluginContext<TResolvedConfig, TSystemContext>,\n TKey\n > =>\n hooksList.map(hook => {\n const plugin = this.plugins.find(\n p => p.name === hook.plugin.name\n );\n if (!plugin) {\n throw new Error(\n `Could not find plugin context for plugin \"${\n hook.plugin.name\n }\".`\n );\n }\n\n return {\n handler: hook.handler,\n plugin: hook.plugin,\n context: plugin[\"~internal\"].context\n };\n });\n\n if (options?.order === \"pre\") {\n result.push(...mapHooksToResult(this.hooks[key].preOrdered ?? []));\n result.push(...mapHooksToResult(this.hooks[key].preEnforced ?? []));\n } else if (options?.order === \"post\") {\n result.push(...mapHooksToResult(this.hooks[key].postOrdered ?? []));\n result.push(\n ...mapHooksToResult(this.hooks[key].postEnforced ?? [])\n );\n } else {\n result.push(...mapHooksToResult(this.hooks[key].normal ?? []));\n }\n } else {\n result.push(...this.selectHooks(key, { order: \"pre\" }));\n result.push(...this.selectHooks(key, { order: \"normal\" }));\n result.push(...this.selectHooks(key, { order: \"post\" }));\n }\n }\n }\n\n return result;\n }\n\n /**\n * A function to add a plugin to the context and update the configuration options. This function is used internally when applying plugins to the environment, and it ensures that the plugin is added to the list of plugins in the context and that any hooks or configuration options provided by the plugin are properly integrated into the context's state.\n *\n * @remarks\n * This function is used internally when applying plugins to the environment, and it ensures that the plugin is added to the list of plugins in the context and that any hooks or configuration options provided by the plugin are properly integrated into the context's state. It should not be called directly by external code, as it is intended for internal use only and may be subject to change without warning.\n *\n * @param execution - The execution context for the build process, which provides access to the project configuration, environment, and utility functions for performing the build. The context is used to manage the state and behavior of the build process, allowing for hooks to be called at different stages of the build and for environment-specific configurations to be applied.\n * @param options - The configuration options for the plugin, which may include properties such as the plugin name, hooks, and any other relevant metadata or settings that should be associated with the plugin when it is added to the context.\n * @param config - The resolved configuration for the environment, which may include properties such as the environment name, SSR settings, and other relevant configuration options that may affect how the plugin is applied to the environment.\n * @param overriddenConfig - The configuration options that should override all other configuration sources, such as CLI flags or environment variables. This is used to ensure that certain configuration values take precedence over any other settings defined in the user configuration or environment configuration, allowing for dynamic overrides based on the execution context.\n * @returns A promise that resolves when the plugin has been added to the context and the configuration has been updated accordingly.\n */\n protected constructor(\n execution: ExecutionContext<TResolvedConfig, TSystemContext>,\n options: ExecutionOptions,\n config: TResolvedConfig,\n overriddenConfig: InferOverridableConfig<\n EnvironmentResolvedConfig<TResolvedConfig>\n >\n ) {\n super(options);\n\n this.#execution = execution;\n this.userConfig = config.userConfig ?? {};\n this.inlineConfig =\n config.inlineConfig ?? ({} as TResolvedConfig[\"inlineConfig\"]);\n this.pluginConfig = config.pluginConfig ?? {};\n this.overriddenConfig = overriddenConfig;\n }\n\n /**\n * A function to merge the various configuration objects (initial, user, inline, and plugin) into a single resolved configuration object that can be used throughout the Powerlines process. This function takes into account the different sources of configuration and their respective priorities, ensuring that the final configuration reflects the intended settings for the project. The merged configuration is then returned as a new object that can be accessed through the `config` property of the context.\n *\n * @returns The merged configuration object that combines the initial, user, inline, and plugin configurations.\n */\n protected override mergeConfig(): EnvironmentResolvedConfig<TResolvedConfig> {\n return mergeConfig(\n {\n ...omit(this.environmentConfig ?? {}, [\n \"name\",\n \"ssr\",\n \"preview\",\n \"consumer\",\n \"runtime\"\n ]),\n environment: {\n name: this.environmentConfig?.name || DEFAULT_ENVIRONMENT\n },\n environmentConfig: this.environmentConfig ?? {}\n },\n super.mergeConfig()\n ) as EnvironmentResolvedCon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-context.mjs","names":["#hooks","#execution"],"sources":["../../src/context/environment-context.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n 🗲 Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { omit } from \"@stryke/helpers/omit\";\nimport { isFunction } from \"@stryke/type-checks/is-function\";\nimport { isObject } from \"@stryke/type-checks/is-object\";\nimport { isSetObject } from \"@stryke/type-checks/is-set-object\";\nimport { ArrayValues } from \"@stryke/types/array\";\nimport { uuid } from \"@stryke/unique-id/uuid\";\nimport {\n DEFAULT_ENVIRONMENT,\n GLOBAL_ENVIRONMENT,\n PLUGIN_NON_HOOK_FIELDS\n} from \"../constants\";\nimport { extractHooks } from \"../lib/hooks\";\nimport { resolvePlugins } from \"../lib/plugins\";\nimport {\n dedupeHooklist,\n formatConfig,\n isPlugin,\n isPluginConfig,\n isPluginHookField,\n mergeConfig\n} from \"../plugin-utils\";\nimport type {\n EnvironmentContext,\n EnvironmentPlugin,\n EnvironmentResolvedConfig,\n ExecutionContext,\n ExecutionOptions,\n HooksList,\n HooksListItem,\n InferOverridableConfig,\n Logger,\n LoggerOptions,\n PluginConfig,\n PluginContext,\n ResolvedConfig,\n SelectHookResult,\n SelectHooksOptions\n} from \"../types\";\nimport { PowerlinesContext } from \"./context\";\nimport { createPluginContext } from \"./plugin-context\";\n\nexport class PowerlinesEnvironmentContext<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig,\n TSystemContext = unknown\n>\n extends PowerlinesContext<\n EnvironmentResolvedConfig<TResolvedConfig>,\n TSystemContext\n >\n implements EnvironmentContext<TResolvedConfig, TSystemContext>\n{\n /**\n * The hooks registered by plugins in this environment\n */\n #hooks: Record<\n string,\n HooksList<PluginContext<TResolvedConfig, TSystemContext>>\n > = {};\n\n /**\n * The execution context associated with this environment, which provides access to the project configuration, environment, and utility functions for performing the build. The execution context is used to manage the state and behavior of the build process across multiple environments, allowing for hooks to be called at different stages of the build and for environment-specific configurations to be applied.\n */\n #execution: ExecutionContext<TResolvedConfig, TSystemContext>;\n\n /**\n * Create a new context from the config.\n *\n * @param execution - The execution context for the build process, which provides access to the project configuration, environment, and utility functions for performing the build. The context is used to manage the state and behavior of the build process, allowing for hooks to be called at different stages of the build and for environment-specific configurations to be applied.\n * @param options - The resolved execution options.\n * @param config - The user configuration options.\n * @param overriddenConfig - The configuration options that should override all other configuration sources, such as CLI flags or environment variables. This is used to ensure that certain configuration values take precedence over any other settings defined in the user configuration or environment configuration, allowing for dynamic overrides based on the execution context.\n * @returns A promise that resolves to an instance of the PowerlinesEnvironmentContext class, initialized with the provided configuration and environment data.\n */\n public static async from<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig,\n TSystemContext = unknown\n >(\n execution: ExecutionContext<TResolvedConfig, TSystemContext>,\n options: ExecutionOptions,\n config: TResolvedConfig,\n overriddenConfig: InferOverridableConfig<\n EnvironmentResolvedConfig<TResolvedConfig>\n >\n ): Promise<PowerlinesEnvironmentContext<TResolvedConfig, TSystemContext>> {\n const context = new PowerlinesEnvironmentContext<\n TResolvedConfig,\n TSystemContext\n >(execution, options, config, overriddenConfig);\n await context.init();\n\n return context;\n }\n\n /**\n * The configuration options provided by plugins added by the user (and other plugins)\n */\n protected override environmentConfig: EnvironmentResolvedConfig<TResolvedConfig>[\"environment\"] =\n {} as EnvironmentResolvedConfig<TResolvedConfig>[\"environment\"];\n\n /**\n * The list of plugins applied to this environment\n */\n public plugins: EnvironmentPlugin<TResolvedConfig, TSystemContext>[] = [];\n\n /**\n * The unique identifier of the environment associated with this context, which can be used for logging and other purposes to distinguish between different environments in the same process.\n */\n public get id(): string {\n return this.config.environment.id;\n }\n\n /**\n * The hooks registered by plugins in this environment\n */\n public get hooks(): Record<\n string,\n HooksList<PluginContext<TResolvedConfig, TSystemContext>>\n > {\n return this.#hooks;\n }\n\n /**\n * The execution context associated with this environment, which provides access to the project configuration, environment, and utility functions for performing the build. The execution context is used to manage the state and behavior of the build process across multiple environments, allowing for hooks to be called at different stages of the build and for environment-specific configurations to be applied.\n *\n * @danger\n * This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.\n *\n * @internal\n */\n public get unstable_execution(): ExecutionContext<\n TResolvedConfig,\n TSystemContext\n > {\n return this.#execution;\n }\n\n /**\n * A setter function to populate the environment config values provided during execution of the command, such as CLI flags or other parameters that may be relevant to the command being executed. This function can be used to update the context with the environment configuration values, which may be used during the configuration resolution process to ensure that the final configuration reflects both the user configuration and any environment configuration provided during execution.\n *\n * @param config - The environment configuration values to set.\n * @returns A promise that resolves when the environment configuration values have been set.\n */\n public async setEnvironmentConfig(\n config: EnvironmentResolvedConfig<TResolvedConfig>[\"environment\"]\n ): Promise<void> {\n this.logger.debug({\n meta: { category: \"config\" },\n message: `Updating environment configuration object: \\n${formatConfig(config)}`\n });\n\n this.environmentConfig = config;\n await this.resolveConfig();\n }\n\n /**\n * Create a new logger instance\n *\n * @param options - The configuration options to use for the logger instance, which can be used to customize the appearance and behavior of the log messages generated by the logger. This is typically the name of the plugin or module that is creating the logger instance.\n * @returns A logger client instance that can be used to generate log messages with consistent formatting and metadata.\n */\n public override createLogger(options: LoggerOptions): Logger {\n return super.createLogger({\n ...options,\n environment: this.environmentConfig?.name || this.config.environment?.name\n });\n }\n\n /**\n * Extend the base logger with additional configuration options\n *\n * @param options - The configuration options to extend the base logger with, which can be used to add additional metadata or customize the appearance of log messages generated by the logger. This is typically the name of the plugin or module that is creating the logger instance, as well as any additional metadata such as the plugin category or environment.\n * @returns A new logger client instance that extends the base logger with the provided configuration options.\n */\n public override extendLogger(options: LoggerOptions): Logger {\n return super.extendLogger({\n ...options,\n environment: this.environmentConfig?.name || this.config.environment?.name\n });\n }\n\n /**\n * A function used internally to add a plugin to the context and update the configuration options\n *\n * @danger\n * This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.\n *\n * @internal\n */\n public async unstable_addPlugin(\n plugin: PluginConfig<PluginContext<TResolvedConfig, TSystemContext>>\n ): Promise<void> {\n const plugins = await resolvePlugins<TResolvedConfig, TSystemContext>(\n this,\n plugin,\n {\n skipLogging: !!(\n this.environmentConfig?.name &&\n this.environmentConfig.name !== DEFAULT_ENVIRONMENT &&\n this.environmentConfig.name !== GLOBAL_ENVIRONMENT\n )\n }\n );\n for (const plugin of plugins) {\n let resolvedPlugin = plugin as EnvironmentPlugin<\n TResolvedConfig,\n TSystemContext\n >;\n if (isFunction(plugin.applyToEnvironment)) {\n const result = (await Promise.resolve(\n plugin.applyToEnvironment(this.config.environment) as Promise<any>\n )) as\n | boolean\n | PluginConfig<PluginContext<TResolvedConfig, TSystemContext>>;\n\n if (!result || (isObject(result) && Object.keys(result).length === 0)) {\n return;\n }\n\n if (\n isPluginConfig<PluginContext<TResolvedConfig, TSystemContext>>(result)\n ) {\n return this.unstable_addPlugin(result);\n }\n\n resolvedPlugin = (\n isPlugin<PluginContext<TResolvedConfig, TSystemContext>>(result)\n ? result\n : plugin\n ) as EnvironmentPlugin<TResolvedConfig, TSystemContext>;\n }\n\n const id = uuid();\n const context = createPluginContext<TResolvedConfig, TSystemContext>(\n id,\n resolvedPlugin,\n this\n );\n\n resolvedPlugin[\"~internal\"] = {\n id,\n context\n };\n\n this.plugins.push(resolvedPlugin);\n\n this.#hooks = Object.entries(\n Object.keys(resolvedPlugin)\n .filter(\n key =>\n key !== \"~internal\" &&\n !PLUGIN_NON_HOOK_FIELDS.includes(\n key as ArrayValues<typeof PLUGIN_NON_HOOK_FIELDS>\n )\n )\n .reduce(\n (ret, key) =>\n extractHooks<TResolvedConfig, TSystemContext>(\n context,\n ret,\n resolvedPlugin,\n key\n ),\n this.hooks\n )\n ).reduce(\n (ret, [key, value]) => {\n if (isSetObject(value)) {\n Object.entries(value).forEach(([type, list]) => {\n ret[key] ??= {};\n ret[key][type as keyof (typeof ret)[typeof key]] =\n dedupeHooklist<PluginContext<TResolvedConfig, TSystemContext>>(\n list\n );\n });\n }\n\n return ret;\n },\n {} as Record<\n string,\n HooksList<PluginContext<TResolvedConfig, TSystemContext>>\n >\n );\n }\n }\n\n /**\n * Retrieves the hook handlers for a specific hook name\n */\n public selectHooks<TKey extends string>(\n key: TKey,\n options?: SelectHooksOptions\n ): SelectHookResult<PluginContext<TResolvedConfig, TSystemContext>, TKey> {\n const result = [] as SelectHookResult<\n PluginContext<TResolvedConfig, TSystemContext>,\n TKey\n >;\n\n if (\n isPluginHookField<PluginContext<TResolvedConfig, TSystemContext>>(key) &&\n this.hooks[key]\n ) {\n if (this.hooks[key]) {\n if (options?.order) {\n const mapHooksToResult = (\n hooksList: HooksListItem<\n PluginContext<TResolvedConfig, TSystemContext>,\n TKey\n >[]\n ): SelectHookResult<\n PluginContext<TResolvedConfig, TSystemContext>,\n TKey\n > =>\n hooksList.map(hook => {\n const plugin = this.plugins.find(\n p => p.name === hook.plugin.name\n );\n if (!plugin) {\n throw new Error(\n `Could not find plugin context for plugin \"${\n hook.plugin.name\n }\".`\n );\n }\n\n return {\n handler: hook.handler,\n plugin: hook.plugin,\n context: plugin[\"~internal\"].context\n };\n });\n\n if (options?.order === \"pre\") {\n result.push(...mapHooksToResult(this.hooks[key].preOrdered ?? []));\n result.push(...mapHooksToResult(this.hooks[key].preEnforced ?? []));\n } else if (options?.order === \"post\") {\n result.push(...mapHooksToResult(this.hooks[key].postOrdered ?? []));\n result.push(\n ...mapHooksToResult(this.hooks[key].postEnforced ?? [])\n );\n } else {\n result.push(...mapHooksToResult(this.hooks[key].normal ?? []));\n }\n } else {\n result.push(...this.selectHooks(key, { order: \"pre\" }));\n result.push(...this.selectHooks(key, { order: \"normal\" }));\n result.push(...this.selectHooks(key, { order: \"post\" }));\n }\n }\n }\n\n return result;\n }\n\n /**\n * A function to add a plugin to the context and update the configuration options. This function is used internally when applying plugins to the environment, and it ensures that the plugin is added to the list of plugins in the context and that any hooks or configuration options provided by the plugin are properly integrated into the context's state.\n *\n * @remarks\n * This function is used internally when applying plugins to the environment, and it ensures that the plugin is added to the list of plugins in the context and that any hooks or configuration options provided by the plugin are properly integrated into the context's state. It should not be called directly by external code, as it is intended for internal use only and may be subject to change without warning.\n *\n * @param execution - The execution context for the build process, which provides access to the project configuration, environment, and utility functions for performing the build. The context is used to manage the state and behavior of the build process, allowing for hooks to be called at different stages of the build and for environment-specific configurations to be applied.\n * @param options - The configuration options for the plugin, which may include properties such as the plugin name, hooks, and any other relevant metadata or settings that should be associated with the plugin when it is added to the context.\n * @param config - The resolved configuration for the environment, which may include properties such as the environment name, SSR settings, and other relevant configuration options that may affect how the plugin is applied to the environment.\n * @param overriddenConfig - The configuration options that should override all other configuration sources, such as CLI flags or environment variables. This is used to ensure that certain configuration values take precedence over any other settings defined in the user configuration or environment configuration, allowing for dynamic overrides based on the execution context.\n * @returns A promise that resolves when the plugin has been added to the context and the configuration has been updated accordingly.\n */\n protected constructor(\n execution: ExecutionContext<TResolvedConfig, TSystemContext>,\n options: ExecutionOptions,\n config: TResolvedConfig,\n overriddenConfig: InferOverridableConfig<\n EnvironmentResolvedConfig<TResolvedConfig>\n >\n ) {\n super(options);\n\n this.#execution = execution;\n this.userConfig = config.userConfig ?? {};\n this.inlineConfig =\n config.inlineConfig ?? ({} as TResolvedConfig[\"inlineConfig\"]);\n this.pluginConfig = config.pluginConfig ?? {};\n this.overriddenConfig = overriddenConfig;\n }\n\n /**\n * A function to merge the various configuration objects (initial, user, inline, and plugin) into a single resolved configuration object that can be used throughout the Powerlines process. This function takes into account the different sources of configuration and their respective priorities, ensuring that the final configuration reflects the intended settings for the project. The merged configuration is then returned as a new object that can be accessed through the `config` property of the context.\n *\n * @returns The merged configuration object that combines the initial, user, inline, and plugin configurations.\n */\n protected override mergeConfig(): EnvironmentResolvedConfig<TResolvedConfig> {\n return mergeConfig(\n {\n ...omit(this.environmentConfig ?? {}, [\n \"name\",\n \"ssr\",\n \"preview\",\n \"consumer\",\n \"runtime\"\n ]),\n environment: {\n name: this.environmentConfig?.name || DEFAULT_ENVIRONMENT\n },\n environmentConfig: this.environmentConfig ?? {}\n },\n super.mergeConfig()\n ) as EnvironmentResolvedConfig<TResolvedConfig>;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA2DA,IAAa,+BAAb,MAAa,qCAIH,kBAKV;;;;CAIE,SAGI,CAAC;;;;CAKL;;;;;;;;;;CAWA,aAAoB,KAIlB,WACA,SACA,QACA,kBAGwE;EACxE,MAAM,UAAU,IAAI,6BAGlB,WAAW,SAAS,QAAQ,gBAAgB;EAC9C,MAAM,QAAQ,KAAK;EAEnB,OAAO;CACT;;;;CAKA,AAAmB,oBACjB,CAAC;;;;CAKH,AAAO,UAAgE,CAAC;;;;CAKxE,IAAW,KAAa;EACtB,OAAO,KAAK,OAAO,YAAY;CACjC;;;;CAKA,IAAW,QAGT;EACA,OAAO,KAAKA;CACd;;;;;;;;;CAUA,IAAW,qBAGT;EACA,OAAO,KAAKC;CACd;;;;;;;CAQA,MAAa,qBACX,QACe;EACf,KAAK,OAAO,MAAM;GAChB,MAAM,EAAE,UAAU,SAAS;GAC3B,SAAS,gDAAgD,aAAa,MAAM;EAC9E,CAAC;EAED,KAAK,oBAAoB;EACzB,MAAM,KAAK,cAAc;CAC3B;;;;;;;CAQA,AAAgB,aAAa,SAAgC;EAC3D,OAAO,MAAM,aAAa;GACxB,GAAG;GACH,aAAa,KAAK,mBAAmB,QAAQ,KAAK,OAAO,aAAa;EACxE,CAAC;CACH;;;;;;;CAQA,AAAgB,aAAa,SAAgC;EAC3D,OAAO,MAAM,aAAa;GACxB,GAAG;GACH,aAAa,KAAK,mBAAmB,QAAQ,KAAK,OAAO,aAAa;EACxE,CAAC;CACH;;;;;;;;;CAUA,MAAa,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mB,cAA0D;EAC3E,OAAO,YACL;GACE,GAAG,KAAK,KAAK,qBAAqB,CAAC,GAAG;IACpC;IACA;IACA;IACA;IACA;GACF,CAAC;GACD,aAAa,EACX,MAAM,KAAK,mBAAmB,kBAChC;GACA,mBAAmB,KAAK,qBAAqB,CAAC;EAChD,GACA,MAAM,YAAY,CACpB;CACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"execution-context.mjs","names":["#environments","#plugins"],"sources":["../../src/context/execution-context.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { toArray } from \"@stryke/convert/to-array\";\nimport { existsSync } from \"@stryke/fs/exists\";\nimport { readJsonFile } from \"@stryke/fs/json\";\nimport { deepClone } from \"@stryke/helpers/deep-clone\";\nimport { joinPaths } from \"@stryke/path/join\";\nimport { isObject } from \"@stryke/type-checks/is-object\";\nimport { PackageJson } from \"@stryke/types/package-json\";\nimport chalk from \"chalk\";\nimport {\n DEFAULT_ENVIRONMENT,\n GLOBAL_ENVIRONMENT\n} from \"../constants/environments\";\nimport {\n createDefaultEnvironment,\n createEnvironment\n} from \"../lib/environment\";\nimport { resolvePlugins } from \"../lib/plugins\";\nimport type {\n EnvironmentResolvedConfig,\n ExecutionContext,\n ExecutionOptions,\n InferOverridableConfig,\n Logger,\n LoggerOptions,\n Plugin,\n PluginConfig,\n PluginContext,\n ResolvedConfig,\n VirtualFileSystemInterface\n} from \"../types\";\nimport { PowerlinesContext } from \"./context\";\nimport { PowerlinesEnvironmentContext } from \"./environment-context\";\n\nexport class PowerlinesExecutionContext<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig,\n TSystemContext = unknown\n>\n extends PowerlinesContext<TResolvedConfig, TSystemContext>\n implements ExecutionContext<TResolvedConfig, TSystemContext>\n{\n /**\n * A record of all environments by name\n */\n #environments: Record<\n string,\n PowerlinesEnvironmentContext<TResolvedConfig, TSystemContext>\n > = {};\n\n /**\n * The plugins added to this execution context, which may be used to track the plugins that have been added to the context and ensure that they are properly registered and executed during the build process. This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.\n */\n #plugins: Plugin<PluginContext<TResolvedConfig, TSystemContext>>[] = [];\n\n /**\n * Create a new Storm context from the workspace root and user config.\n *\n * @param options - The execution options to create the context with.\n * @param inlineConfig - The inline configuration for the context.\n * @returns A promise that resolves to the new context.\n */\n public static async from<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig,\n TSystemContext = unknown\n >(\n options: ExecutionOptions,\n inlineConfig?: TResolvedConfig[\"inlineConfig\"],\n system?: TSystemContext\n ): Promise<ExecutionContext<TResolvedConfig, TSystemContext>> {\n const context = new PowerlinesExecutionContext<\n TResolvedConfig,\n TSystemContext\n >(options);\n if (system) {\n context.system = system;\n }\n\n await context.init();\n\n if (inlineConfig) {\n await context.setInlineConfig(inlineConfig);\n }\n\n return context;\n }\n\n /**\n * The unique identifier of the execution context, which can be used for logging and other purposes to distinguish between different executions in the same process.\n */\n public get id(): string {\n return this.executionId;\n }\n\n /**\n * A record of all environments by name\n */\n public get environments(): Record<\n string,\n PowerlinesEnvironmentContext<TResolvedConfig, TSystemContext>\n > {\n return this.#environments;\n }\n\n public get plugins(): Array<\n Plugin<PluginContext<TResolvedConfig, TSystemContext>>\n > {\n return this.#plugins;\n }\n\n /**\n * The virtual file system interface for the project\n */\n public override get fs(): VirtualFileSystemInterface {\n throw new Error(\n \"The virtual file system is not available on the execution context. Please use the environment context instead.\"\n );\n }\n\n /**\n * Creates a new instance.\n *\n * @param options - The options to use for creating the context, including the resolved configuration and workspace settings.\n */\n protected constructor(options: ExecutionOptions) {\n super(options);\n }\n\n /**\n * A setter function to populate the inline config values provided during execution of the command, such as CLI flags or other parameters that may be relevant to the command being executed. This function can be used to update the context with the inline configuration values, which may be used during the configuration resolution process to ensure that the final configuration reflects both the user configuration and any inline configuration provided during execution.\n *\n * @param config - The inline configuration values to set.\n * @returns A promise that resolves when the inline configuration values have been set.\n */\n public override async setInlineConfig(\n config: TResolvedConfig[\"inlineConfig\"]\n ): Promise<void> {\n await super.setInlineConfig(config);\n if (this.inlineConfig.command === \"new\") {\n const workspacePackageJsonPath = joinPaths(this.cwd, \"package.json\");\n if (!existsSync(workspacePackageJsonPath)) {\n throw new Error(\n `The workspace package.json file could not be found at ${workspacePackageJsonPath}`\n );\n }\n\n this.packageJson = await readJsonFile<PackageJson>(\n workspacePackageJsonPath\n );\n }\n }\n\n /**\n * Create a new logger instance\n *\n * @param options - The configuration options to use for the logger instance, which can be used to customize the appearance and behavior of the log messages generated by the logger. This is typically the name of the plugin or module that is creating the logger instance.\n * @returns A logger client instance that can be used to generate log messages with consistent formatting and metadata.\n */\n public override createLogger(options: LoggerOptions): Logger {\n return super.createLogger({\n ...options,\n executionId: this.id,\n configIndex: this.options.configIndex\n });\n }\n\n /**\n * Extend the base logger with additional configuration options\n *\n * @param options - The configuration options to extend the base logger with, which can be used to add additional metadata or customize the appearance of log messages generated by the logger. This is typically the name of the plugin or module that is creating the logger instance, as well as any additional metadata such as the plugin category or environment.\n * @returns A new logger client instance that extends the base logger with the provided configuration options.\n */\n public override extendLogger(options: LoggerOptions): Logger {\n return super.extendLogger({\n ...options,\n executionId: this.id,\n configIndex: this.options.configIndex\n });\n }\n\n /**\n * A function to copy the context and update the fields for a specific environment\n *\n * @param environment - The environment configuration to use.\n * @returns A new context instance with the updated environment.\n */\n public async createEnvironment(\n environment: EnvironmentResolvedConfig<TResolvedConfig>[\"environment\"]\n ): Promise<PowerlinesEnvironmentContext<TResolvedConfig, TSystemContext>> {\n const context = await PowerlinesEnvironmentContext.from<\n TResolvedConfig,\n TSystemContext\n >(\n this,\n deepClone(this.options),\n deepClone(this.config) as TResolvedConfig,\n deepClone(this.overriddenConfig) as InferOverridableConfig<\n EnvironmentResolvedConfig<TResolvedConfig>\n >\n );\n\n context.tsconfig = this.tsconfig;\n context.system = this.system;\n\n context.dependencies = deepClone<typeof this.dependencies>(\n this.dependencies\n );\n context.devDependencies = deepClone<typeof this.devDependencies>(\n this.devDependencies\n );\n context.persistedMeta = deepClone<typeof this.persistedMeta>(\n this.persistedMeta\n );\n context.resolvePatterns = deepClone<typeof this.resolvePatterns>(\n this.resolvePatterns\n );\n\n context.powerlinesPath ??= this.powerlinesPath;\n context.resolver ??= this.resolver;\n\n await context.setEnvironmentConfig(\n deepClone(\n environment\n ) as EnvironmentResolvedConfig<TResolvedConfig>[\"environment\"]\n );\n\n context.plugins = [];\n for (const plugin of this.plugins) {\n await context.unstable_addPlugin(plugin);\n }\n\n for (const [key, value] of Object.entries(this)) {\n if (\n ![\n \"fs\",\n \"system\",\n \"options\",\n \"config\",\n \"inlineConfig\",\n \"userConfig\",\n \"pluginConfig\",\n \"overriddenConfig\",\n \"environmentConfig\",\n \"dependencies\",\n \"devDependencies\",\n \"persistedMeta\",\n \"packageJson\",\n \"projectJson\",\n \"tsconfig\",\n \"resolver\",\n \"plugins\",\n \"environments\"\n ].includes(key)\n ) {\n if (isObject(value) || Array.isArray(value)) {\n (context as any)[key] = deepClone(value);\n } else {\n (context as any)[key] = value;\n }\n }\n }\n\n return context;\n }\n\n /**\n * Update the context using a new inline configuration options\n */\n public override async resolveConfig() {\n await super.resolveConfig();\n\n await Promise.all(\n toArray(\n this.config.environments &&\n Object.keys(this.config.environments).length > 0\n ? Object.keys(this.config.environments).map(name =>\n createEnvironment(name, this.config)\n )\n : createDefaultEnvironment(this.config)\n ).map(async env => {\n this.#environments[env.name] = await this.createEnvironment(env);\n })\n );\n }\n\n /**\n * Get an environment by name, or the default environment if no name is provided\n *\n * @param name - The name of the environment to retrieve.\n * @returns The requested environment context.\n */\n public async getEnvironment(name?: string) {\n let environment:\n | PowerlinesEnvironmentContext<TResolvedConfig, TSystemContext>\n | undefined;\n if (name) {\n environment = this.environments[name];\n }\n\n if (Object.keys(this.environments).length === 1) {\n environment = this.environments[Object.keys(this.environments)[0]!];\n\n this.trace({\n meta: { category: \"plugins\" },\n message: `Applying the only configured environment: ${chalk.bold.cyanBright(\n environment?.config.environment?.name\n )}`\n });\n }\n\n if (!environment) {\n if (name) {\n throw new Error(`Environment \"${name}\" not found.`);\n }\n\n environment = await this.createEnvironment(\n createDefaultEnvironment(this.config)\n );\n\n this.warn({\n meta: { category: \"plugins\" },\n message: `No environment specified, and no default environment found. Using a temporary default environment: ${chalk.bold.cyanBright(\n environment.config.environment?.name\n )}`\n });\n }\n\n return environment;\n }\n\n /**\n * A safe version of `getEnvironment` that returns `undefined` if the environment is not found\n *\n * @param name - The name of the environment to retrieve.\n * @returns The requested environment context or `undefined` if not found.\n */\n public async getEnvironmentSafe(\n name?: string\n ): Promise<\n PowerlinesEnvironmentContext<TResolvedConfig, TSystemContext> | undefined\n > {\n try {\n return await this.getEnvironment(name);\n } catch {\n return undefined;\n }\n }\n\n /**\n * A function to merge all configured environments into a single context.\n *\n * @remarks\n * If only one environment is configured, that environment will be returned directly.\n *\n * @returns A promise that resolves to a merged/global environment context.\n */\n public async toEnvironment(): Promise<\n PowerlinesEnvironmentContext<TResolvedConfig, TSystemContext>\n > {\n let environment: PowerlinesEnvironmentContext<\n TResolvedConfig,\n TSystemContext\n >;\n if (Object.keys(this.environments).length > 1) {\n environment = await this.createEnvironment(\n createEnvironment<TResolvedConfig>(GLOBAL_ENVIRONMENT, this.config)\n );\n\n this.debug({\n meta: { category: \"plugins\" },\n message: `Combined all ${Object.keys(this.environments).length} environments into a single global context.`\n });\n } else {\n environment = await this.getEnvironment();\n }\n\n return environment;\n }\n\n /**\n * A function used internally to add a plugin to the context and update the configuration options\n *\n * @danger\n * This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.\n *\n * @internal\n */\n public async unstable_addPlugin(\n plugin: PluginConfig<PluginContext<TResolvedConfig, TSystemContext>>\n ) {\n this.plugins.push(\n ...(await resolvePlugins<TResolvedConfig, TSystemContext>(this, plugin, {\n skipLogging:\n Object.keys(this.environments).filter(\n key =>\n key && key !== DEFAULT_ENVIRONMENT && key !== GLOBAL_ENVIRONMENT\n ).length > 0\n }))\n );\n\n await Promise.all(\n Object.keys(this.environments).map(async name => {\n await this.environments[name]!.unstable_addPlugin(plugin);\n })\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAmDA,IAAa,6BAAb,MAAa,mCAIH,kBAEV;;;;CAIE,gBAGI,CAAC;;;;CAKL,WAAqE,CAAC;;;;;;;;CAStE,aAAoB,KAIlB,SACA,cACA,QAC4D;EAC5D,MAAM,UAAU,IAAI,2BAGlB,OAAO;EACT,IAAI,QACF,QAAQ,SAAS;EAGnB,MAAM,QAAQ,KAAK;EAEnB,IAAI,cACF,MAAM,QAAQ,gBAAgB,YAAY;EAG5C,OAAO;CACT;;;;CAKA,IAAW,KAAa;EACtB,OAAO,KAAK;CACd;;;;CAKA,IAAW,eAGT;EACA,OAAO,KAAKA;CACd;CAEA,IAAW,UAET;EACA,OAAO,KAAKC;CACd;;;;CAKA,IAAoB,KAAiC;EACnD,MAAM,IAAI,MACR,gHACF;CACF;;;;;;CAOA,AAAU,YAAY,SAA2B;EAC/C,MAAM,OAAO;CACf;;;;;;;CAQA,MAAsB,gBACpB,QACe;EACf,MAAM,MAAM,gBAAgB,MAAM;EAClC,IAAI,KAAK,aAAa,YAAY,OAAO;GACvC,MAAM,2BAA2B,UAAU,KAAK,KAAK,cAAc;GACnE,IAAI,CAAC,WAAW,wBAAwB,GACtC,MAAM,IAAI,MACR,yDAAyD,0BAC3D;GAGF,KAAK,cAAc,MAAM,aACvB,wBACF;EACF;CACF;;;;;;;CAQA,AAAgB,aAAa,S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,OAAO;GACjE,CAAC;EACH,OACE,cAAc,MAAM,KAAK,eAAe;EAG1C,OAAO;CACT;;;;;;;;;CAUA,MAAa,mBACX,QACA;EACA,KAAK,QAAQ,KACX,GAAI,MAAM,eAAgD,MAAM,QAAQ,EACtE,aACE,OAAO,KAAK,KAAK,YAAY,CAAC,CAAC,QAC7B,QACE,OAAO,qBAA+B,oBAC1C,CAAC,CAAC,SAAS,EACf,CAAC,CACH;EAEA,MAAM,QAAQ,IACZ,OAAO,KAAK,KAAK,YAAY,CAAC,CAAC,IAAI,OAAM,SAAQ;GAC/C,MAAM,KAAK,aAAa,KAAK,CAAE,mBAAmB,MAAM;EAC1D,CAAC,CACH;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"execution-context.mjs","names":["#environments","#plugins"],"sources":["../../src/context/execution-context.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n 🗲 Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { toArray } from \"@stryke/convert/to-array\";\nimport { existsSync } from \"@stryke/fs/exists\";\nimport { readJsonFile } from \"@stryke/fs/json\";\nimport { deepClone } from \"@stryke/helpers/deep-clone\";\nimport { joinPaths } from \"@stryke/path/join\";\nimport { isObject } from \"@stryke/type-checks/is-object\";\nimport { PackageJson } from \"@stryke/types/package-json\";\nimport chalk from \"chalk\";\nimport {\n DEFAULT_ENVIRONMENT,\n GLOBAL_ENVIRONMENT\n} from \"../constants/environments\";\nimport {\n createDefaultEnvironment,\n createEnvironment\n} from \"../lib/environment\";\nimport { resolvePlugins } from \"../lib/plugins\";\nimport type {\n EnvironmentResolvedConfig,\n ExecutionContext,\n ExecutionOptions,\n InferOverridableConfig,\n Logger,\n LoggerOptions,\n Plugin,\n PluginConfig,\n PluginContext,\n ResolvedConfig,\n VirtualFileSystemInterface\n} from \"../types\";\nimport { PowerlinesContext } from \"./context\";\nimport { PowerlinesEnvironmentContext } from \"./environment-context\";\n\nexport class PowerlinesExecutionContext<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig,\n TSystemContext = unknown\n>\n extends PowerlinesContext<TResolvedConfig, TSystemContext>\n implements ExecutionContext<TResolvedConfig, TSystemContext>\n{\n /**\n * A record of all environments by name\n */\n #environments: Record<\n string,\n PowerlinesEnvironmentContext<TResolvedConfig, TSystemContext>\n > = {};\n\n /**\n * The plugins added to this execution context, which may be used to track the plugins that have been added to the context and ensure that they are properly registered and executed during the build process. This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.\n */\n #plugins: Plugin<PluginContext<TResolvedConfig, TSystemContext>>[] = [];\n\n /**\n * Create a new Storm context from the workspace root and user config.\n *\n * @param options - The execution options to create the context with.\n * @param inlineConfig - The inline configuration for the context.\n * @returns A promise that resolves to the new context.\n */\n public static async from<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig,\n TSystemContext = unknown\n >(\n options: ExecutionOptions,\n inlineConfig?: TResolvedConfig[\"inlineConfig\"],\n system?: TSystemContext\n ): Promise<ExecutionContext<TResolvedConfig, TSystemContext>> {\n const context = new PowerlinesExecutionContext<\n TResolvedConfig,\n TSystemContext\n >(options);\n if (system) {\n context.system = system;\n }\n\n await context.init();\n\n if (inlineConfig) {\n await context.setInlineConfig(inlineConfig);\n }\n\n return context;\n }\n\n /**\n * The unique identifier of the execution context, which can be used for logging and other purposes to distinguish between different executions in the same process.\n */\n public get id(): string {\n return this.executionId;\n }\n\n /**\n * A record of all environments by name\n */\n public get environments(): Record<\n string,\n PowerlinesEnvironmentContext<TResolvedConfig, TSystemContext>\n > {\n return this.#environments;\n }\n\n public get plugins(): Array<\n Plugin<PluginContext<TResolvedConfig, TSystemContext>>\n > {\n return this.#plugins;\n }\n\n /**\n * The virtual file system interface for the project\n */\n public override get fs(): VirtualFileSystemInterface {\n throw new Error(\n \"The virtual file system is not available on the execution context. Please use the environment context instead.\"\n );\n }\n\n /**\n * Creates a new instance.\n *\n * @param options - The options to use for creating the context, including the resolved configuration and workspace settings.\n */\n protected constructor(options: ExecutionOptions) {\n super(options);\n }\n\n /**\n * A setter function to populate the inline config values provided during execution of the command, such as CLI flags or other parameters that may be relevant to the command being executed. This function can be used to update the context with the inline configuration values, which may be used during the configuration resolution process to ensure that the final configuration reflects both the user configuration and any inline configuration provided during execution.\n *\n * @param config - The inline configuration values to set.\n * @returns A promise that resolves when the inline configuration values have been set.\n */\n public override async setInlineConfig(\n config: TResolvedConfig[\"inlineConfig\"]\n ): Promise<void> {\n await super.setInlineConfig(config);\n if (this.inlineConfig.command === \"new\") {\n const workspacePackageJsonPath = joinPaths(this.cwd, \"package.json\");\n if (!existsSync(workspacePackageJsonPath)) {\n throw new Error(\n `The workspace package.json file could not be found at ${workspacePackageJsonPath}`\n );\n }\n\n this.packageJson = await readJsonFile<PackageJson>(\n workspacePackageJsonPath\n );\n }\n }\n\n /**\n * Create a new logger instance\n *\n * @param options - The configuration options to use for the logger instance, which can be used to customize the appearance and behavior of the log messages generated by the logger. This is typically the name of the plugin or module that is creating the logger instance.\n * @returns A logger client instance that can be used to generate log messages with consistent formatting and metadata.\n */\n public override createLogger(options: LoggerOptions): Logger {\n return super.createLogger({\n ...options,\n executionId: this.id,\n configIndex: this.options.configIndex\n });\n }\n\n /**\n * Extend the base logger with additional configuration options\n *\n * @param options - The configuration options to extend the base logger with, which can be used to add additional metadata or customize the appearance of log messages generated by the logger. This is typically the name of the plugin or module that is creating the logger instance, as well as any additional metadata such as the plugin category or environment.\n * @returns A new logger client instance that extends the base logger with the provided configuration options.\n */\n public override extendLogger(options: LoggerOptions): Logger {\n return super.extendLogger({\n ...options,\n executionId: this.id,\n configIndex: this.options.configIndex\n });\n }\n\n /**\n * A function to copy the context and update the fields for a specific environment\n *\n * @param environment - The environment configuration to use.\n * @returns A new context instance with the updated environment.\n */\n public async createEnvironment(\n environment: EnvironmentResolvedConfig<TResolvedConfig>[\"environment\"]\n ): Promise<PowerlinesEnvironmentContext<TResolvedConfig, TSystemContext>> {\n const context = await PowerlinesEnvironmentContext.from<\n TResolvedConfig,\n TSystemContext\n >(\n this,\n deepClone(this.options),\n deepClone(this.config) as TResolvedConfig,\n deepClone(this.overriddenConfig) as InferOverridableConfig<\n EnvironmentResolvedConfig<TResolvedConfig>\n >\n );\n\n context.tsconfig = this.tsconfig;\n context.system = this.system;\n\n context.dependencies = deepClone<typeof this.dependencies>(\n this.dependencies\n );\n context.devDependencies = deepClone<typeof this.devDependencies>(\n this.devDependencies\n );\n context.persistedMeta = deepClone<typeof this.persistedMeta>(\n this.persistedMeta\n );\n context.resolvePatterns = deepClone<typeof this.resolvePatterns>(\n this.resolvePatterns\n );\n\n context.powerlinesPath ??= this.powerlinesPath;\n context.resolver ??= this.resolver;\n\n await context.setEnvironmentConfig(\n deepClone(\n environment\n ) as EnvironmentResolvedConfig<TResolvedConfig>[\"environment\"]\n );\n\n context.plugins = [];\n for (const plugin of this.plugins) {\n await context.unstable_addPlugin(plugin);\n }\n\n for (const [key, value] of Object.entries(this)) {\n if (\n ![\n \"fs\",\n \"system\",\n \"options\",\n \"config\",\n \"inlineConfig\",\n \"userConfig\",\n \"pluginConfig\",\n \"overriddenConfig\",\n \"environmentConfig\",\n \"dependencies\",\n \"devDependencies\",\n \"persistedMeta\",\n \"packageJson\",\n \"projectJson\",\n \"tsconfig\",\n \"resolver\",\n \"plugins\",\n \"environments\"\n ].includes(key)\n ) {\n if (isObject(value) || Array.isArray(value)) {\n (context as any)[key] = deepClone(value);\n } else {\n (context as any)[key] = value;\n }\n }\n }\n\n return context;\n }\n\n /**\n * Update the context using a new inline configuration options\n */\n public override async resolveConfig() {\n await super.resolveConfig();\n\n await Promise.all(\n toArray(\n this.config.environments &&\n Object.keys(this.config.environments).length > 0\n ? Object.keys(this.config.environments).map(name =>\n createEnvironment(name, this.config)\n )\n : createDefaultEnvironment(this.config)\n ).map(async env => {\n this.#environments[env.name] = await this.createEnvironment(env);\n })\n );\n }\n\n /**\n * Get an environment by name, or the default environment if no name is provided\n *\n * @param name - The name of the environment to retrieve.\n * @returns The requested environment context.\n */\n public async getEnvironment(name?: string) {\n let environment:\n | PowerlinesEnvironmentContext<TResolvedConfig, TSystemContext>\n | undefined;\n if (name) {\n environment = this.environments[name];\n }\n\n if (Object.keys(this.environments).length === 1) {\n environment = this.environments[Object.keys(this.environments)[0]!];\n\n this.trace({\n meta: { category: \"plugins\" },\n message: `Applying the only configured environment: ${chalk.bold.cyanBright(\n environment?.config.environment?.name\n )}`\n });\n }\n\n if (!environment) {\n if (name) {\n throw new Error(`Environment \"${name}\" not found.`);\n }\n\n environment = await this.createEnvironment(\n createDefaultEnvironment(this.config)\n );\n\n this.warn({\n meta: { category: \"plugins\" },\n message: `No environment specified, and no default environment found. Using a temporary default environment: ${chalk.bold.cyanBright(\n environment.config.environment?.name\n )}`\n });\n }\n\n return environment;\n }\n\n /**\n * A safe version of `getEnvironment` that returns `undefined` if the environment is not found\n *\n * @param name - The name of the environment to retrieve.\n * @returns The requested environment context or `undefined` if not found.\n */\n public async getEnvironmentSafe(\n name?: string\n ): Promise<\n PowerlinesEnvironmentContext<TResolvedConfig, TSystemContext> | undefined\n > {\n try {\n return await this.getEnvironment(name);\n } catch {\n return undefined;\n }\n }\n\n /**\n * A function to merge all configured environments into a single context.\n *\n * @remarks\n * If only one environment is configured, that environment will be returned directly.\n *\n * @returns A promise that resolves to a merged/global environment context.\n */\n public async toEnvironment(): Promise<\n PowerlinesEnvironmentContext<TResolvedConfig, TSystemContext>\n > {\n let environment: PowerlinesEnvironmentContext<\n TResolvedConfig,\n TSystemContext\n >;\n if (Object.keys(this.environments).length > 1) {\n environment = await this.createEnvironment(\n createEnvironment<TResolvedConfig>(GLOBAL_ENVIRONMENT, this.config)\n );\n\n this.debug({\n meta: { category: \"plugins\" },\n message: `Combined all ${Object.keys(this.environments).length} environments into a single global context.`\n });\n } else {\n environment = await this.getEnvironment();\n }\n\n return environment;\n }\n\n /**\n * A function used internally to add a plugin to the context and update the configuration options\n *\n * @danger\n * This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.\n *\n * @internal\n */\n public async unstable_addPlugin(\n plugin: PluginConfig<PluginContext<TResolvedConfig, TSystemContext>>\n ) {\n this.plugins.push(\n ...(await resolvePlugins<TResolvedConfig, TSystemContext>(this, plugin, {\n skipLogging:\n Object.keys(this.environments).filter(\n key =>\n key && key !== DEFAULT_ENVIRONMENT && key !== GLOBAL_ENVIRONMENT\n ).length > 0\n }))\n );\n\n await Promise.all(\n Object.keys(this.environments).map(async name => {\n await this.environments[name]!.unstable_addPlugin(plugin);\n })\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAmDA,IAAa,6BAAb,MAAa,mCAIH,kBAEV;;;;CAIE,gBAGI,CAAC;;;;CAKL,WAAqE,CAAC;;;;;;;;CAStE,aAAoB,KAIlB,SACA,cACA,QAC4D;EAC5D,MAAM,UAAU,IAAI,2BAGlB,OAAO;EACT,IAAI,QACF,QAAQ,SAAS;EAGnB,MAAM,QAAQ,KAAK;EAEnB,IAAI,cACF,MAAM,QAAQ,gBAAgB,YAAY;EAG5C,OAAO;CACT;;;;CAKA,IAAW,KAAa;EACtB,OAAO,KAAK;CACd;;;;CAKA,IAAW,eAGT;EACA,OAAO,KAAKA;CACd;CAEA,IAAW,UAET;EACA,OAAO,KAAKC;CACd;;;;CAKA,IAAoB,KAAiC;EACnD,MAAM,IAAI,MACR,gHACF;CACF;;;;;;CAOA,AAAU,YAAY,SAA2B;EAC/C,MAAM,OAAO;CACf;;;;;;;CAQA,MAAsB,gBACpB,QACe;EACf,MAAM,MAAM,gBAAgB,MAAM;EAClC,IAAI,KAAK,aAAa,YAAY,OAAO;G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CAAC,SAAS,GAAG;GAC7C,cAAc,MAAM,KAAK,kBACvB,kBAAmC,oBAAoB,KAAK,MAAM,CACpE;GAEA,KAAK,MAAM;IACT,MAAM,EAAE,UAAU,UAAU;IAC5B,SAAS,gBAAgB,OAAO,KAAK,KAAK,YAAY,CAAC,CAAC,OAAO;GACjE,CAAC;EACH,OACE,cAAc,MAAM,KAAK,eAAe;EAG1C,OAAO;CACT;;;;;;;;;CAUA,MAAa,mBACX,QACA;EACA,KAAK,QAAQ,KACX,GAAI,MAAM,eAAgD,MAAM,QAAQ,EACtE,aACE,OAAO,KAAK,KAAK,YAAY,CAAC,CAAC,QAC7B,QACE,OAAO,qBAA+B,oBAC1C,CAAC,CAAC,SAAS,EACf,CAAC,CACH;EAEA,MAAM,QAAQ,IACZ,OAAO,KAAK,KAAK,YAAY,CAAC,CAAC,IAAI,OAAM,SAAQ;GAC/C,MAAM,KAAK,aAAa,KAAK,CAAE,mBAAmB,MAAM;EAC1D,CAAC,CACH;CACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin-context.mjs","names":[],"sources":["../../src/context/plugin-context.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n
|
|
1
|
+
{"version":3,"file":"plugin-context.mjs","names":[],"sources":["../../src/context/plugin-context.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n 🗲 Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { isSetObject } from \"@stryke/type-checks/is-set-object\";\nimport { isString } from \"@stryke/type-checks/is-string\";\nimport { UnpluginMessage } from \"unplugin\";\nimport type {\n EnvironmentContext,\n LoggerMessage,\n LogLevel,\n Plugin,\n PluginContext,\n ResolvedConfig\n} from \"../types\";\nimport { PowerlinesEnvironmentContext } from \"./environment-context\";\n\n/**\n * Create a Proxy-based PluginContext\n *\n * @param pluginId - The unique identifier of the plugin\n * @param plugin - The plugin instance\n * @param environment - The environment context\n * @returns The proxied plugin context\n */\nexport function createPluginContext<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig,\n TSystemContext = unknown\n>(\n pluginId: string,\n plugin: Plugin<PluginContext<TResolvedConfig, TSystemContext>>,\n environment: PowerlinesEnvironmentContext<TResolvedConfig, TSystemContext>\n): PluginContext<TResolvedConfig, TSystemContext> {\n const logger = environment.extendLogger({\n plugin: plugin.name\n });\n\n const normalizeMessage = (\n message: string | UnpluginMessage\n ): LoggerMessage => {\n return {\n meta: {\n ...(isSetObject(message) ? message.meta : {}),\n environment: environment.config.environment.name,\n plugin: plugin.name\n },\n message: isString(message) ? message : message.message\n };\n };\n\n return new Proxy({} as PluginContext<TResolvedConfig, TSystemContext>, {\n get(_, prop) {\n if (prop === \"environment\") {\n return environment;\n }\n\n if (prop === \"id\") {\n return pluginId;\n }\n\n if (prop === \"logger\") {\n return logger;\n }\n\n if (prop === \"log\") {\n return (type: LogLevel, message: string | UnpluginMessage) => {\n logger.log(type, normalizeMessage(message));\n };\n }\n\n if (prop === \"fatal\") {\n return (message: string | UnpluginMessage) => {\n logger.error(normalizeMessage(message));\n };\n }\n\n if (prop === \"error\") {\n return (message: string | UnpluginMessage) => {\n logger.error(normalizeMessage(message));\n };\n }\n\n if (prop === \"warn\") {\n return (message: string | UnpluginMessage) => {\n logger.warn(normalizeMessage(message));\n };\n }\n\n if (prop === \"info\") {\n return (message: string | UnpluginMessage) => {\n logger.info(normalizeMessage(message));\n };\n }\n\n if (prop === \"debug\") {\n return (message: string | UnpluginMessage) => {\n logger.debug(normalizeMessage(message));\n };\n }\n\n if (prop === \"trace\") {\n return (message: string | UnpluginMessage) => {\n logger.trace(normalizeMessage(message));\n };\n }\n\n return environment[\n prop as keyof EnvironmentContext<TResolvedConfig, TSystemContext>\n ];\n },\n set(_, prop, value) {\n if (prop === \"unstable_addPlugin\") {\n logger.warn(\n \"Plugins should not be calling the 'addPlugin' function directly. This function is meant to be used internally by Powerlines and may cause unexpected behavior if used incorrectly.\"\n );\n return false;\n }\n\n if (\n [\n \"id\",\n \"environment\",\n \"config\",\n \"log\",\n \"logger\",\n \"error\",\n \"warn\",\n \"plugins\",\n \"hooks\",\n \"fs\",\n \"selectHooks\"\n ].includes(prop as string)\n ) {\n logger.warn(`Cannot set the read-only \"${String(prop)}\" property`);\n\n return false;\n }\n\n (environment as Record<string, any>)[prop as string] = value;\n return true;\n }\n });\n}\n"],"mappings":";;;;;;;;;;;;AAuCA,SAAgB,oBAId,UACA,QACA,aACgD;CAChD,MAAM,SAAS,YAAY,aAAa,EACtC,QAAQ,OAAO,KACjB,CAAC;CAED,MAAM,oBACJ,YACkB;EAClB,OAAO;GACL,MAAM;IACJ,GAAI,YAAY,OAAO,IAAI,QAAQ,OAAO,CAAC;IAC3C,aAAa,YAAY,OAAO,YAAY;IAC5C,QAAQ,OAAO;GACjB;GACA,SAAS,SAAS,OAAO,IAAI,UAAU,QAAQ;EACjD;CACF;CAEA,OAAO,IAAI,MAAM,CAAC,GAAqD;EACrE,IAAI,GAAG,MAAM;GACX,IAAI,SAAS,eACX,OAAO;GAGT,IAAI,SAAS,MACX,OAAO;GAGT,IAAI,SAAS,UACX,OAAO;GAGT,IAAI,SAAS,OACX,QAAQ,MAAgB,YAAsC;IAC5D,OAAO,IAAI,MAAM,iBAAiB,OAAO,CAAC;GAC5C;GAGF,IAAI,SAAS,SACX,QAAQ,YAAsC;IAC5C,OAAO,MAAM,iBAAiB,OAAO,CAAC;GACxC;GAGF,IAAI,SAAS,SACX,QAAQ,YAAsC;IAC5C,OAAO,MAAM,iBAAiB,OAAO,CAAC;GACxC;GAGF,IAAI,SAAS,QACX,QAAQ,YAAsC;IAC5C,OAAO,KAAK,iBAAiB,OAAO,CAAC;GACvC;GAGF,IAAI,SAAS,QACX,QAAQ,YAAsC;IAC5C,OAAO,KAAK,iBAAiB,OAAO,CAAC;GACvC;GAGF,IAAI,SAAS,SACX,QAAQ,YAAsC;IAC5C,OAAO,MAAM,iBAAiB,OAAO,CAAC;GACxC;GAGF,IAAI,SAAS,SACX,QAAQ,YAAsC;IAC5C,OAAO,MAAM,iBAAiB,OAAO,CAAC;GACxC;GAGF,OAAO,YACL;EAEJ;EACA,IAAI,GAAG,MAAM,OAAO;GAClB,IAAI,SAAS,sBAAsB;IACjC,OAAO,KACL,oLACF;IACA,OAAO;GACT;GAEA,IACE;IACE;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;GACF,CAAC,CAAC,SAAS,IAAc,GACzB;IACA,OAAO,KAAK,6BAA6B,OAAO,IAAI,EAAE,WAAW;IAEjE,OAAO;GACT;GAEA,AAAC,YAAoC,QAAkB;GACvD,OAAO;EACT;CACF,CAAC;AACH"}
|
package/dist/lib/config.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.mjs","names":["loadConfigC12"],"sources":["../../src/lib/config.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport {\n getWorkspaceConfig,\n tryGetWorkspaceConfig\n} from \"@storm-software/config-tools/get-config\";\nimport {\n isDevelopment,\n isProduction,\n isTest\n} from \"@stryke/env/environment-checks\";\nimport { getEnvPaths } from \"@stryke/env/get-env-paths\";\nimport { existsSync } from \"@stryke/fs/exists\";\nimport { isFile } from \"@stryke/fs/is-file\";\nimport { readJsonFile } from \"@stryke/fs/json\";\nimport { appendPath } from \"@stryke/path/append\";\nimport { findFilePath, relativePath } from \"@stryke/path/file-path-fns\";\nimport { joinPaths } from \"@stryke/path/join-paths\";\nimport { replacePath } from \"@stryke/path/replace\";\nimport { camelCase } from \"@stryke/string-format/camel-case\";\nimport { kebabCase } from \"@stryke/string-format/kebab-case\";\nimport { isFunction } from \"@stryke/type-checks/is-function\";\nimport { isSetObject } from \"@stryke/type-checks/is-set-object\";\nimport { PartialKeys } from \"@stryke/types/base\";\nimport { PackageJson } from \"@stryke/types/package-json\";\nimport { loadConfig as loadConfigC12 } from \"c12\";\nimport defu from \"defu\";\nimport { resolveLogLevel } from \"../plugin-utils/logging\";\nimport type {\n FrameworkOptions,\n InlineConfig,\n Mode,\n ParsedUserConfig,\n UserConfig,\n UserConfigExport,\n UserConfigFn,\n UserConfigFnObject,\n UserConfigFnPromise,\n WorkspaceConfig\n} from \"../types/config\";\nimport { Context } from \"../types/context\";\nimport { LogLevelResolvedConfig } from \"../types/logging\";\nimport { createResolver } from \"./resolver\";\n\nexport function normalizeBasePath(base: string = \"/\"): string {\n let out = base.startsWith(\"/\") ? base : `/${base}`;\n if (!out.endsWith(\"/\")) out = `${out}/`;\n return out.replace(/\\/+/g, \"/\");\n}\n\nexport interface ResolvePackageConfigsResult {\n /**\n * The parsed `package.json` file for the project, if it exists. This file typically contains metadata about the project, such as its name, version, dependencies, and other information relevant to the build process.\n */\n packageJson?: PackageJson;\n\n /**\n * The parsed `project.json` file for the project, if it exists. This file is an optional configuration file that can be used to store additional configuration or metadata specific to the project, and is not required for all projects.\n */\n projectJson?: Record<string, unknown>;\n}\n\n/**\n * Resolve the package configurations for the project by loading the `package.json` and `project.json` files, if they exist. This function will look for these files in the project root and parse their contents as JavaScript objects. The parsed contents will be stored in the context for later use by plugins and other parts of the build process.\n *\n * @remarks\n * The `package.json` file is typically used to store metadata about the project, such as its name, version, dependencies, and other information. The `project.json` file is an optional file that can be used to store additional configuration or metadata specific to the project, and is not required for all projects.\n *\n * @param cwd - The current working directory to look for the package configurations. Defaults to the `cwd` specified in the context configuration.\n * @param root - The root directory of the project to look for the package configurations. Defaults to the `root` specified in the context configuration.\n * @returns A promise that resolves when the package configurations have been loaded and stored in the context.\n */\nexport async function resolvePackageConfigs(\n cwd: string,\n root: string\n): Promise<ResolvePackageConfigsResult> {\n const result: ResolvePackageConfigsResult = {};\n if (cwd || root) {\n const projectJsonPath = joinPaths(\n appendPath(root || \".\", cwd || \".\"),\n \"project.json\"\n );\n if (existsSync(projectJsonPath)) {\n result.projectJson = await readJsonFile(projectJsonPath);\n }\n\n const packageJsonPath = joinPaths(\n appendPath(root || \".\", cwd || \".\"),\n \"package.json\"\n );\n if (existsSync(packageJsonPath)) {\n result.packageJson = await readJsonFile<PackageJson>(packageJsonPath);\n }\n }\n\n return result;\n}\n\n/**\n * Resolve the root directory for the project based on the provided options. This function will determine the root directory by checking the provided `root` option, and if it is not provided, it will look for a configuration file (such as `powerlines.config.ts`) in the current working directory. If a configuration file is found, the root directory will be set to the directory containing that file. If no configuration file is found, the root directory will default to the current working directory.\n *\n * @param cwd - The current working directory to use as the base for resolving the root directory. This is typically the directory from which the Powerlines process was executed.\n * @param root - An optional root directory to use for the project. If provided, this will be used as the root directory instead of looking for a configuration file. This can be an absolute or relative path, and if it is relative, it will be resolved based on the current working directory.\n * @param configFile - An optional path to a configuration file to look for when resolving the root directory. If provided, this file will be used to determine the root directory if the `root` option is not provided. This can be an absolute or relative path, and if it is relative, it will be resolved based on the current working directory.\n * @returns The resolved root directory for the project, which will be used as the base for resolving other paths and configurations throughout the Powerlines process. This will typically be an absolute path to the root directory of the project.\n */\nexport function resolveRoot(\n cwd: string,\n root?: string,\n configFile?: string\n): string {\n let result = root || \".\";\n if (!root) {\n if (configFile) {\n const configFilePath = appendPath(configFile, cwd);\n if (!existsSync(configFilePath)) {\n throw new Error(\n `The user-provided configuration file at \"${configFile}\" does not exist. Please ensure this path is correct and try again.`\n );\n }\n if (!isFile(configFile)) {\n throw new Error(\n `The user-provided configuration file at \"${\n configFile\n }\" is not a file. Please ensure this path is correct and try again.`\n );\n }\n\n result = relativePath(cwd, findFilePath(configFile));\n }\n } else {\n result = replacePath(root, cwd);\n }\n\n return result;\n}\n\n/**\n * Retrieve the workspace configuration for the current project, if it exists. This function will look for a configuration file in the project root and return its contents as a JavaScript object. If no configuration file is found, it will return undefined.\n *\n * @param cwd - The current working directory to start searching from. This is typically the directory from which the Powerlines process was executed.\n * @param root - An optional root directory to use as the base for searching for the configuration file. If provided, this will be used as the starting point for searching for the configuration file instead of the current working directory. This can be an absolute or relative path, and if it is relative, it will be resolved based on the current working directory.\n * @returns A promise that resolves to the workspace configuration object, or undefined if no configuration file is found.\n */\nexport async function tryResolveWorkspaceConfig(\n cwd: string,\n root?: string\n): Promise<WorkspaceConfig | undefined> {\n return tryGetWorkspaceConfig(false, {\n cwd: root ? appendPath(root, cwd) : undefined,\n workspaceRoot: cwd\n });\n}\n\n/**\n * Determine the default mode for the current execution based on the environment and workspace configuration. This function will check the `NODE_ENV` environment variable to determine if the current environment is development, production, or test. If `NODE_ENV` is not set, it will look for a `mode` property in the workspace configuration file. If no mode is specified in the workspace configuration, it will default to \"production\".\n *\n * @remarks\n * The mode is used to determine which configuration file to load (e.g., `powerlines.development.config.js` for development mode, `powerlines.production.config.js` for production mode, etc.) and can also be used by plugins and other parts of the build process to conditionally apply certain behaviors based on the current mode.\n *\n * @param cwd - The current working directory to start searching from. This is typically the directory from which the Powerlines process was executed.\n * @param root - An optional root directory to use as the base for searching for the workspace configuration. If provided, this will be used as the starting point for searching for the workspace configuration instead of the current working directory. This can be an absolute or relative path, and if it is relative, it will be resolved based on the current working directory.\n * @returns A promise that resolves to the default mode for the current execution, which can be \"development\", \"production\", or \"test\".\n */\nexport async function getDefaultMode(\n cwd: string,\n root?: string\n): Promise<Mode> {\n const workspaceConfig = await tryResolveWorkspaceConfig(cwd, root);\n\n return isProduction\n ? \"production\"\n : isDevelopment\n ? \"development\"\n : isTest\n ? \"test\"\n : workspaceConfig?.mode || \"production\";\n}\n\n/**\n * Determine the default log level for the current execution based on the environment and workspace configuration. This function will check the `logLevel` property in the workspace configuration file and resolve it to a `LogLevelResolvedConfig` value. If no log level is specified in the workspace configuration, it will default to \"info\" for development mode and \"warn\" for production mode.\n *\n * @remarks\n * The log level is used to determine which log messages should be output during the execution of the Powerlines process. For example, if the log level is set to \"warn\", only messages with a level of \"warn\", \"error\", or \"fatal\" will be output, while messages with a level of \"info\", \"debug\", or \"trace\" will be suppressed. This allows users to control the verbosity of the logs and focus on the most relevant information based on their current needs.\n *\n * @param cwd - The current working directory to start searching from. This is typically the directory from which the Powerlines process was executed.\n * @param root - An optional root directory to use as the base for searching for the workspace configuration. If provided, this will be used as the starting point for searching for the workspace configuration instead of the current working directory. This can be an absolute or relative path, and if it is relative, it will be resolved based on the current working directory.\n * @returns A promise that resolves to the default log level for the current execution, which can be \"fatal\", \"error\", \"warn\", \"info\", \"debug\", or \"trace\".\n */\nexport async function getDefaultLogLevel(\n cwd: string,\n root?: string\n): Promise<LogLevelResolvedConfig> {\n const workspaceConfig = await tryResolveWorkspaceConfig(cwd, root);\n\n return resolveLogLevel(\n workspaceConfig?.logLevel\n ? workspaceConfig.logLevel === \"success\" ||\n workspaceConfig.logLevel === \"performance\"\n ? \"info\"\n : workspaceConfig.logLevel === \"all\"\n ? \"debug\"\n : workspaceConfig.logLevel === \"fatal\"\n ? \"error\"\n : workspaceConfig.logLevel\n : undefined,\n workspaceConfig?.mode || (await getDefaultMode(cwd, root))\n );\n}\n\n/**\n * Load the user configuration file for the project and set up the context with the loaded configuration. This function will be called during the initialization of the context to load the user configuration file based on the provided options and set up the context accordingly. It will also set up the resolver for loading modules from the user configuration file and ensure that the context is properly initialized with the loaded configuration.\n *\n * @remarks\n * This method will set up the resolver and load the user configuration file based on the provided options. It is called during the construction of the context and can also be called when cloning the context to ensure that the new context has the same configuration and resolver setup.\n *\n * @param cwd - The current working directory to start searching from. This is typically the directory from which the Powerlines process was executed.\n * @param root - The root directory of the project to look for the configuration file. This is typically the root directory of the project, which may be different from the current working directory if the process was executed from a subdirectory.\n * @param framework - The name of the framework to use when looking for configuration files (default is \"powerlines\"). This is used to determine the naming convention for the configuration files to look for (e.g., `powerlines.development.config.js` for the \"powerlines\" framework in development mode).\n * @param orgId - The name of the organization to use when looking for configuration files (optional). This can be used to further customize the naming convention for the configuration files to look for (e.g., `powerlines.myorg.development.config.js` for the \"powerlines\" framework in development mode with an organization of \"myorg\").\n * @param inlineConfig - The inline configuration options provided during the execution of a Powerlines command, which can include properties such as the project root, mode, and an explicit path to a configuration file. This is used to determine how the context should be initialized and which configuration file should be loaded for the execution.\n * @returns A promise that resolves when the context has been successfully initialized with the loaded configuration and resolver setup.\n * @throws Will throw an error if no configuration file is found in the project root or current working directory. This ensures that the context cannot be initialized without a valid configuration, which is essential for the proper functioning of the Powerlines process.\n */\nexport async function loadParsedConfig(\n cwd: string,\n root: string,\n framework: string,\n orgId: string,\n inlineConfig: InlineConfig\n) {\n const mode = inlineConfig.mode || (await getDefaultMode(cwd, root));\n\n const configFile = await loadUserConfigFile(\n cwd,\n root,\n mode,\n inlineConfig.command,\n { name: framework, orgId },\n inlineConfig.configFile\n );\n if (!configFile) {\n throw new Error(\n `No configuration file found in ${appendPath(\n root,\n cwd\n )}. Please ensure you have a valid configuration file in your project.`\n );\n }\n\n return configFile;\n}\n\nexport type PartiallyResolvedContext<TContext extends Context = Context> = Omit<\n TContext,\n \"config\" | \"tsconfig\" | \"entry\" | \"fs\" | \"compiler\" | \"unimport\"\n> &\n Partial<TContext> & {\n config: TContext[\"config\"];\n };\n\n/**\n * Loads the workspace configuration.\n *\n * @param cwd - The root directory of the workspace.\n * @param root - The current working directory to start searching from.\n * @returns A promise that resolves to the loaded workspace configuration.\n */\nexport async function loadWorkspaceConfig(\n cwd: string,\n root: string\n): Promise<WorkspaceConfig> {\n return defu(\n {\n workspaceRoot: cwd\n },\n await getWorkspaceConfig(true, {\n cwd: root,\n workspaceRoot: cwd,\n useDefault: true\n })\n );\n}\n\n/**\n * Loads the user configuration file for the project.\n *\n * @remarks\n * This function will attempt to locate and load the user configuration file for the project based on the provided parameters. It will look for configuration files in various formats (e.g., `.ts`, `.js`, `.mts`, `.mjs`) and with different naming conventions (e.g., `powerlines.config.ts`, `powerlines.development.config.js`, etc.) in the project root and current working directory. If a configuration file is found, it will be loaded using a Jiti resolver, and the resulting configuration object will be returned. If no configuration file is found, an empty configuration object will be returned.\n *\n * @param cwd - The current working directory to start searching from.\n * @param root - The root directory of the project.\n * @param mode - The mode to determine which configuration file to load (e.g., \"development\", \"test\", \"production\").\n * @param command - The command being executed (e.g., \"build\", \"dev\", \"test\"), which can be used to further customize the configuration loading logic if needed.\n * @param framework - The name of the framework to use when looking for configuration files (default is \"powerlines\").\n * @param configFile - An explicit path to a configuration file to load (optional). If provided, this file will be loaded instead of searching for configuration files based on the mode and framework.\n * @returns A promise that resolves to the resolved user configuration.\n */\nexport async function loadUserConfigFile(\n cwd: string,\n root: string,\n mode: Mode,\n command: string,\n framework?: PartialKeys<FrameworkOptions, \"orgId\">,\n configFile?: string\n): Promise<ParsedUserConfig> {\n const frameworkName = kebabCase(framework?.name || \"powerlines\");\n const frameworkOrgId = kebabCase(framework?.orgId || \"storm-software\");\n\n let resolvedUserConfig: Partial<ParsedUserConfig> = {};\n\n let resolvedUserConfigFile: string | undefined;\n if (configFile) {\n resolvedUserConfigFile = existsSync(replacePath(configFile, root))\n ? replacePath(configFile, root)\n : existsSync(\n joinPaths(appendPath(root, cwd), replacePath(configFile, root))\n )\n ? joinPaths(appendPath(root, cwd), replacePath(configFile, root))\n : existsSync(joinPaths(appendPath(root, cwd), configFile))\n ? joinPaths(appendPath(root, cwd), configFile)\n : undefined;\n }\n\n if (!resolvedUserConfigFile) {\n resolvedUserConfigFile = existsSync(\n joinPaths(appendPath(root, cwd), `${frameworkName}.${mode}.config.ts`)\n )\n ? joinPaths(appendPath(root, cwd), `${frameworkName}.${mode}.config.ts`)\n : existsSync(\n joinPaths(\n appendPath(root, cwd),\n `${frameworkName}.${mode}.config.js`\n )\n )\n ? joinPaths(appendPath(root, cwd), `${frameworkName}.${mode}.config.js`)\n : existsSync(\n joinPaths(\n appendPath(root, cwd),\n `${frameworkName}.${mode}.config.mts`\n )\n )\n ? joinPaths(\n appendPath(root, cwd),\n `${frameworkName}.${mode}.config.mts`\n )\n : existsSync(\n joinPaths(\n appendPath(root, cwd),\n `${frameworkName}.${mode}.config.mjs`\n )\n )\n ? joinPaths(\n appendPath(root, cwd),\n `${frameworkName}.${mode}.config.mjs`\n )\n : existsSync(\n joinPaths(appendPath(root, cwd), `${frameworkName}.config.ts`)\n )\n ? joinPaths(appendPath(root, cwd), `${frameworkName}.config.ts`)\n : existsSync(\n joinPaths(\n appendPath(root, cwd),\n `${frameworkName}.config.js`\n )\n )\n ? joinPaths(appendPath(root, cwd), `${frameworkName}.config.js`)\n : existsSync(\n joinPaths(\n appendPath(root, cwd),\n `${frameworkName}.config.mts`\n )\n )\n ? joinPaths(\n appendPath(root, cwd),\n `${frameworkName}.config.mts`\n )\n : existsSync(\n joinPaths(\n appendPath(root, cwd),\n `${frameworkName}.config.mjs`\n )\n )\n ? joinPaths(\n appendPath(root, cwd),\n `${frameworkName}.config.mjs`\n )\n : undefined;\n }\n\n const envPaths = getEnvPaths({\n orgId: frameworkOrgId,\n appId: frameworkName,\n workspaceRoot: cwd\n });\n\n const jiti = createResolver({\n cwd,\n root,\n cacheDir: envPaths.cache,\n mode\n });\n\n if (resolvedUserConfigFile) {\n const resolved = await jiti.import<{ default: UserConfigExport }>(\n jiti.esmResolve(resolvedUserConfigFile)\n );\n if (resolved?.default) {\n let config = {};\n if (isFunction(resolved.default)) {\n config = await Promise.resolve(\n resolved.default({ root, cwd, mode, command })\n );\n } else if (\n isSetObject(resolved.default) ||\n Array.isArray(resolved.default)\n ) {\n config = resolved.default;\n }\n\n if (isSetObject(config) || Array.isArray(config)) {\n resolvedUserConfig = {\n ...config,\n config,\n configFile: resolvedUserConfigFile\n };\n }\n }\n }\n\n const result = await loadConfigC12({\n cwd: root,\n name: frameworkName,\n envName: mode,\n globalRc: true,\n packageJson: camelCase(frameworkName),\n dotenv: true,\n jiti\n });\n\n return defu(\n {\n config: {\n root,\n cwd,\n framework\n }\n },\n resolvedUserConfig,\n isSetObject(result?.config) ? { ...result.config, ...result } : {}\n ) as ParsedUserConfig;\n}\n\n/**\n * Type helper to make it easier to use `powerlines.config.ts` files. Accepts a direct {@link UserConfig} object, or a function that returns it. The function receives a {@link ConfigParams} object.\n *\n * @example\n * ```ts\n * import { defineConfig } from 'powerlines';\n *\n * export default defineConfig({\n * // Your configuration here\n * });\n *\n * // Or with a function\n * export default defineConfig((env) => {\n * console.log(`Running command: ${env.command} in mode: ${env.mode}`);\n * return {\n * // Your configuration here\n * };\n * });\n * ```\n */\nexport function defineConfig(config: UserConfig): UserConfig;\nexport function defineConfig(config: UserConfig[]): UserConfig[];\nexport function defineConfig(config: Promise<UserConfig>): Promise<UserConfig>;\nexport function defineConfig(\n config: Promise<UserConfig[]>\n): Promise<UserConfig[]>;\nexport function defineConfig(config: UserConfigFnObject): UserConfigFnObject;\nexport function defineConfig(config: UserConfigFnPromise): UserConfigFnPromise;\nexport function defineConfig(config: UserConfigFn): UserConfigFn;\nexport function defineConfig(config: UserConfigExport): UserConfigExport;\nexport function defineConfig(config: UserConfigExport): UserConfigExport {\n return config;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA4DA,SAAgB,kBAAkB,OAAe,KAAa;CAC5D,IAAI,MAAM,KAAK,WAAW,GAAG,IAAI,OAAO,IAAI;CAC5C,IAAI,CAAC,IAAI,SAAS,GAAG,GAAG,MAAM,GAAG,IAAI;CACrC,OAAO,IAAI,QAAQ,QAAQ,GAAG;AAChC;;;;;;;;;;;AAw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AAQ,CAAC,CAC/C;QACK,IACL,YAAY,SAAS,OAAO,KAC5B,MAAM,QAAQ,SAAS,OAAO,GAE9B,SAAS,SAAS;GAGpB,IAAI,YAAY,MAAM,KAAK,MAAM,QAAQ,MAAM,GAC7C,qBAAqB;IACnB,GAAG;IACH;IACA,YAAY;GACd;EAEJ;CACF;CAEA,MAAM,SAAS,MAAMA,WAAc;EACjC,KAAK;EACL,MAAM;EACN,SAAS;EACT,UAAU;EACV,aAAa,UAAU,aAAa;EACpC,QAAQ;EACR;CACF,CAAC;CAED,OAAO,KACL,EACE,QAAQ;EACN;EACA;EACA;CACF,EACF,GACA,oBACA,YAAY,QAAQ,MAAM,IAAI;EAAE,GAAG,OAAO;EAAQ,GAAG;CAAO,IAAI,CAAC,CACnE;AACF;AAgCA,SAAgB,aAAa,QAA4C;CACvE,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"config.mjs","names":["loadConfigC12"],"sources":["../../src/lib/config.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n 🗲 Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport {\n getWorkspaceConfig,\n tryGetWorkspaceConfig\n} from \"@storm-software/config-tools/get-config\";\nimport {\n isDevelopment,\n isProduction,\n isTest\n} from \"@stryke/env/environment-checks\";\nimport { getEnvPaths } from \"@stryke/env/get-env-paths\";\nimport { existsSync } from \"@stryke/fs/exists\";\nimport { isFile } from \"@stryke/fs/is-file\";\nimport { readJsonFile } from \"@stryke/fs/json\";\nimport { appendPath } from \"@stryke/path/append\";\nimport { findFilePath, relativePath } from \"@stryke/path/file-path-fns\";\nimport { joinPaths } from \"@stryke/path/join-paths\";\nimport { replacePath } from \"@stryke/path/replace\";\nimport { camelCase } from \"@stryke/string-format/camel-case\";\nimport { kebabCase } from \"@stryke/string-format/kebab-case\";\nimport { isFunction } from \"@stryke/type-checks/is-function\";\nimport { isSetObject } from \"@stryke/type-checks/is-set-object\";\nimport { PartialKeys } from \"@stryke/types/base\";\nimport { PackageJson } from \"@stryke/types/package-json\";\nimport { loadConfig as loadConfigC12 } from \"c12\";\nimport defu from \"defu\";\nimport { resolveLogLevel } from \"../plugin-utils/logging\";\nimport type {\n FrameworkOptions,\n InlineConfig,\n Mode,\n ParsedUserConfig,\n UserConfig,\n UserConfigExport,\n UserConfigFn,\n UserConfigFnObject,\n UserConfigFnPromise,\n WorkspaceConfig\n} from \"../types/config\";\nimport { Context } from \"../types/context\";\nimport { LogLevelResolvedConfig } from \"../types/logging\";\nimport { createResolver } from \"./resolver\";\n\nexport function normalizeBasePath(base: string = \"/\"): string {\n let out = base.startsWith(\"/\") ? base : `/${base}`;\n if (!out.endsWith(\"/\")) out = `${out}/`;\n return out.replace(/\\/+/g, \"/\");\n}\n\nexport interface ResolvePackageConfigsResult {\n /**\n * The parsed `package.json` file for the project, if it exists. This file typically contains metadata about the project, such as its name, version, dependencies, and other information relevant to the build process.\n */\n packageJson?: PackageJson;\n\n /**\n * The parsed `project.json` file for the project, if it exists. This file is an optional configuration file that can be used to store additional configuration or metadata specific to the project, and is not required for all projects.\n */\n projectJson?: Record<string, unknown>;\n}\n\n/**\n * Resolve the package configurations for the project by loading the `package.json` and `project.json` files, if they exist. This function will look for these files in the project root and parse their contents as JavaScript objects. The parsed contents will be stored in the context for later use by plugins and other parts of the build process.\n *\n * @remarks\n * The `package.json` file is typically used to store metadata about the project, such as its name, version, dependencies, and other information. The `project.json` file is an optional file that can be used to store additional configuration or metadata specific to the project, and is not required for all projects.\n *\n * @param cwd - The current working directory to look for the package configurations. Defaults to the `cwd` specified in the context configuration.\n * @param root - The root directory of the project to look for the package configurations. Defaults to the `root` specified in the context configuration.\n * @returns A promise that resolves when the package configurations have been loaded and stored in the context.\n */\nexport async function resolvePackageConfigs(\n cwd: string,\n root: string\n): Promise<ResolvePackageConfigsResult> {\n const result: ResolvePackageConfigsResult = {};\n if (cwd || root) {\n const projectJsonPath = joinPaths(\n appendPath(root || \".\", cwd || \".\"),\n \"project.json\"\n );\n if (existsSync(projectJsonPath)) {\n result.projectJson = await readJsonFile(projectJsonPath);\n }\n\n const packageJsonPath = joinPaths(\n appendPath(root || \".\", cwd || \".\"),\n \"package.json\"\n );\n if (existsSync(packageJsonPath)) {\n result.packageJson = await readJsonFile<PackageJson>(packageJsonPath);\n }\n }\n\n return result;\n}\n\n/**\n * Resolve the root directory for the project based on the provided options. This function will determine the root directory by checking the provided `root` option, and if it is not provided, it will look for a configuration file (such as `powerlines.config.ts`) in the current working directory. If a configuration file is found, the root directory will be set to the directory containing that file. If no configuration file is found, the root directory will default to the current working directory.\n *\n * @param cwd - The current working directory to use as the base for resolving the root directory. This is typically the directory from which the Powerlines process was executed.\n * @param root - An optional root directory to use for the project. If provided, this will be used as the root directory instead of looking for a configuration file. This can be an absolute or relative path, and if it is relative, it will be resolved based on the current working directory.\n * @param configFile - An optional path to a configuration file to look for when resolving the root directory. If provided, this file will be used to determine the root directory if the `root` option is not provided. This can be an absolute or relative path, and if it is relative, it will be resolved based on the current working directory.\n * @returns The resolved root directory for the project, which will be used as the base for resolving other paths and configurations throughout the Powerlines process. This will typically be an absolute path to the root directory of the project.\n */\nexport function resolveRoot(\n cwd: string,\n root?: string,\n configFile?: string\n): string {\n let result = root || \".\";\n if (!root) {\n if (configFile) {\n const configFilePath = appendPath(configFile, cwd);\n if (!existsSync(configFilePath)) {\n throw new Error(\n `The user-provided configuration file at \"${configFile}\" does not exist. Please ensure this path is correct and try again.`\n );\n }\n if (!isFile(configFile)) {\n throw new Error(\n `The user-provided configuration file at \"${\n configFile\n }\" is not a file. Please ensure this path is correct and try again.`\n );\n }\n\n result = relativePath(cwd, findFilePath(configFile));\n }\n } else {\n result = replacePath(root, cwd);\n }\n\n return result;\n}\n\n/**\n * Retrieve the workspace configuration for the current project, if it exists. This function will look for a configuration file in the project root and return its contents as a JavaScript object. If no configuration file is found, it will return undefined.\n *\n * @param cwd - The current working directory to start searching from. This is typically the directory from which the Powerlines process was executed.\n * @param root - An optional root directory to use as the base for searching for the configuration file. If provided, this will be used as the starting point for searching for the configuration file instead of the current working directory. This can be an absolute or relative path, and if it is relative, it will be resolved based on the current working directory.\n * @returns A promise that resolves to the workspace configuration object, or undefined if no configuration file is found.\n */\nexport async function tryResolveWorkspaceConfig(\n cwd: string,\n root?: string\n): Promise<WorkspaceConfig | undefined> {\n return tryGetWorkspaceConfig(false, {\n cwd: root ? appendPath(root, cwd) : undefined,\n workspaceRoot: cwd\n });\n}\n\n/**\n * Determine the default mode for the current execution based on the environment and workspace configuration. This function will check the `NODE_ENV` environment variable to determine if the current environment is development, production, or test. If `NODE_ENV` is not set, it will look for a `mode` property in the workspace configuration file. If no mode is specified in the workspace configuration, it will default to \"production\".\n *\n * @remarks\n * The mode is used to determine which configuration file to load (e.g., `powerlines.development.config.js` for development mode, `powerlines.production.config.js` for production mode, etc.) and can also be used by plugins and other parts of the build process to conditionally apply certain behaviors based on the current mode.\n *\n * @param cwd - The current working directory to start searching from. This is typically the directory from which the Powerlines process was executed.\n * @param root - An optional root directory to use as the base for searching for the workspace configuration. If provided, this will be used as the starting point for searching for the workspace configuration instead of the current working directory. This can be an absolute or relative path, and if it is relative, it will be resolved based on the current working directory.\n * @returns A promise that resolves to the default mode for the current execution, which can be \"development\", \"production\", or \"test\".\n */\nexport async function getDefaultMode(\n cwd: string,\n root?: string\n): Promise<Mode> {\n const workspaceConfig = await tryResolveWorkspaceConfig(cwd, root);\n\n return isProduction\n ? \"production\"\n : isDevelopment\n ? \"development\"\n : isTest\n ? \"test\"\n : workspaceConfig?.mode || \"production\";\n}\n\n/**\n * Determine the default log level for the current execution based on the environment and workspace configuration. This function will check the `logLevel` property in the workspace configuration file and resolve it to a `LogLevelResolvedConfig` value. If no log level is specified in the workspace configuration, it will default to \"info\" for development mode and \"warn\" for production mode.\n *\n * @remarks\n * The log level is used to determine which log messages should be output during the execution of the Powerlines process. For example, if the log level is set to \"warn\", only messages with a level of \"warn\", \"error\", or \"fatal\" will be output, while messages with a level of \"info\", \"debug\", or \"trace\" will be suppressed. This allows users to control the verbosity of the logs and focus on the most relevant information based on their current needs.\n *\n * @param cwd - The current working directory to start searching from. This is typically the directory from which the Powerlines process was executed.\n * @param root - An optional root directory to use as the base for searching for the workspace configuration. If provided, this will be used as the starting point for searching for the workspace configuration instead of the current working directory. This can be an absolute or relative path, and if it is relative, it will be resolved based on the current working directory.\n * @returns A promise that resolves to the default log level for the current execution, which can be \"fatal\", \"error\", \"warn\", \"info\", \"debug\", or \"trace\".\n */\nexport async function getDefaultLogLevel(\n cwd: string,\n root?: string\n): Promise<LogLevelResolvedConfig> {\n const workspaceConfig = await tryResolveWorkspaceConfig(cwd, root);\n\n return resolveLogLevel(\n workspaceConfig?.logLevel\n ? workspaceConfig.logLevel === \"success\" ||\n workspaceConfig.logLevel === \"performance\"\n ? \"info\"\n : workspaceConfig.logLevel === \"all\"\n ? \"debug\"\n : workspaceConfig.logLevel === \"fatal\"\n ? \"error\"\n : workspaceConfig.logLevel\n : undefined,\n workspaceConfig?.mode || (await getDefaultMode(cwd, root))\n );\n}\n\n/**\n * Load the user configuration file for the project and set up the context with the loaded configuration. This function will be called during the initialization of the context to load the user configuration file based on the provided options and set up the context accordingly. It will also set up the resolver for loading modules from the user configuration file and ensure that the context is properly initialized with the loaded configuration.\n *\n * @remarks\n * This method will set up the resolver and load the user configuration file based on the provided options. It is called during the construction of the context and can also be called when cloning the context to ensure that the new context has the same configuration and resolver setup.\n *\n * @param cwd - The current working directory to start searching from. This is typically the directory from which the Powerlines process was executed.\n * @param root - The root directory of the project to look for the configuration file. This is typically the root directory of the project, which may be different from the current working directory if the process was executed from a subdirectory.\n * @param framework - The name of the framework to use when looking for configuration files (default is \"powerlines\"). This is used to determine the naming convention for the configuration files to look for (e.g., `powerlines.development.config.js` for the \"powerlines\" framework in development mode).\n * @param orgId - The name of the organization to use when looking for configuration files (optional). This can be used to further customize the naming convention for the configuration files to look for (e.g., `powerlines.myorg.development.config.js` for the \"powerlines\" framework in development mode with an organization of \"myorg\").\n * @param inlineConfig - The inline configuration options provided during the execution of a Powerlines command, which can include properties such as the project root, mode, and an explicit path to a configuration file. This is used to determine how the context should be initialized and which configuration file should be loaded for the execution.\n * @returns A promise that resolves when the context has been successfully initialized with the loaded configuration and resolver setup.\n * @throws Will throw an error if no configuration file is found in the project root or current working directory. This ensures that the context cannot be initialized without a valid configuration, which is essential for the proper functioning of the Powerlines process.\n */\nexport async function loadParsedConfig(\n cwd: string,\n root: string,\n framework: string,\n orgId: string,\n inlineConfig: InlineConfig\n) {\n const mode = inlineConfig.mode || (await getDefaultMode(cwd, root));\n\n const configFile = await loadUserConfigFile(\n cwd,\n root,\n mode,\n inlineConfig.command,\n { name: framework, orgId },\n inlineConfig.configFile\n );\n if (!configFile) {\n throw new Error(\n `No configuration file found in ${appendPath(\n root,\n cwd\n )}. Please ensure you have a valid configuration file in your project.`\n );\n }\n\n return configFile;\n}\n\nexport type PartiallyResolvedContext<TContext extends Context = Context> = Omit<\n TContext,\n \"config\" | \"tsconfig\" | \"entry\" | \"fs\" | \"compiler\" | \"unimport\"\n> &\n Partial<TContext> & {\n config: TContext[\"config\"];\n };\n\n/**\n * Loads the workspace configuration.\n *\n * @param cwd - The root directory of the workspace.\n * @param root - The current working directory to start searching from.\n * @returns A promise that resolves to the loaded workspace configuration.\n */\nexport async function loadWorkspaceConfig(\n cwd: string,\n root: string\n): Promise<WorkspaceConfig> {\n return defu(\n {\n workspaceRoot: cwd\n },\n await getWorkspaceConfig(true, {\n cwd: root,\n workspaceRoot: cwd,\n useDefault: true\n })\n );\n}\n\n/**\n * Loads the user configuration file for the project.\n *\n * @remarks\n * This function will attempt to locate and load the user configuration file for the project based on the provided parameters. It will look for configuration files in various formats (e.g., `.ts`, `.js`, `.mts`, `.mjs`) and with different naming conventions (e.g., `powerlines.config.ts`, `powerlines.development.config.js`, etc.) in the project root and current working directory. If a configuration file is found, it will be loaded using a Jiti resolver, and the resulting configuration object will be returned. If no configuration file is found, an empty configuration object will be returned.\n *\n * @param cwd - The current working directory to start searching from.\n * @param root - The root directory of the project.\n * @param mode - The mode to determine which configuration file to load (e.g., \"development\", \"test\", \"production\").\n * @param command - The command being executed (e.g., \"build\", \"dev\", \"test\"), which can be used to further customize the configuration loading logic if needed.\n * @param framework - The name of the framework to use when looking for configuration files (default is \"powerlines\").\n * @param configFile - An explicit path to a configuration file to load (optional). If provided, this file will be loaded instead of searching for configuration files based on the mode and framework.\n * @returns A promise that resolves to the resolved user configuration.\n */\nexport async function loadUserConfigFile(\n cwd: string,\n root: string,\n mode: Mode,\n command: string,\n framework?: PartialKeys<FrameworkOptions, \"orgId\">,\n configFile?: string\n): Promise<ParsedUserConfig> {\n const frameworkName = kebabCase(framework?.name || \"powerlines\");\n const frameworkOrgId = kebabCase(framework?.orgId || \"storm-software\");\n\n let resolvedUserConfig: Partial<ParsedUserConfig> = {};\n\n let resolvedUserConfigFile: string | undefined;\n if (configFile) {\n resolvedUserConfigFile = existsSync(replacePath(configFile, root))\n ? replacePath(configFile, root)\n : existsSync(\n joinPaths(appendPath(root, cwd), replacePath(configFile, root))\n )\n ? joinPaths(appendPath(root, cwd), replacePath(configFile, root))\n : existsSync(joinPaths(appendPath(root, cwd), configFile))\n ? joinPaths(appendPath(root, cwd), configFile)\n : undefined;\n }\n\n if (!resolvedUserConfigFile) {\n resolvedUserConfigFile = existsSync(\n joinPaths(appendPath(root, cwd), `${frameworkName}.${mode}.config.ts`)\n )\n ? joinPaths(appendPath(root, cwd), `${frameworkName}.${mode}.config.ts`)\n : existsSync(\n joinPaths(\n appendPath(root, cwd),\n `${frameworkName}.${mode}.config.js`\n )\n )\n ? joinPaths(appendPath(root, cwd), `${frameworkName}.${mode}.config.js`)\n : existsSync(\n joinPaths(\n appendPath(root, cwd),\n `${frameworkName}.${mode}.config.mts`\n )\n )\n ? joinPaths(\n appendPath(root, cwd),\n `${frameworkName}.${mode}.config.mts`\n )\n : existsSync(\n joinPaths(\n appendPath(root, cwd),\n `${frameworkName}.${mode}.config.mjs`\n )\n )\n ? joinPaths(\n appendPath(root, cwd),\n `${frameworkName}.${mode}.config.mjs`\n )\n : existsSync(\n joinPaths(appendPath(root, cwd), `${frameworkName}.config.ts`)\n )\n ? joinPaths(appendPath(root, cwd), `${frameworkName}.config.ts`)\n : existsSync(\n joinPaths(\n appendPath(root, cwd),\n `${frameworkName}.config.js`\n )\n )\n ? joinPaths(appendPath(root, cwd), `${frameworkName}.config.js`)\n : existsSync(\n joinPaths(\n appendPath(root, cwd),\n `${frameworkName}.config.mts`\n )\n )\n ? joinPaths(\n appendPath(root, cwd),\n `${frameworkName}.config.mts`\n )\n : existsSync(\n joinPaths(\n appendPath(root, cwd),\n `${frameworkName}.config.mjs`\n )\n )\n ? joinPaths(\n appendPath(root, cwd),\n `${frameworkName}.config.mjs`\n )\n : undefined;\n }\n\n const envPaths = getEnvPaths({\n orgId: frameworkOrgId,\n appId: frameworkName,\n workspaceRoot: cwd\n });\n\n const jiti = createResolver({\n cwd,\n root,\n cacheDir: envPaths.cache,\n mode\n });\n\n if (resolvedUserConfigFile) {\n const resolved = await jiti.import<{ default: UserConfigExport }>(\n jiti.esmResolve(resolvedUserConfigFile)\n );\n if (resolved?.default) {\n let config = {};\n if (isFunction(resolved.default)) {\n config = await Promise.resolve(\n resolved.default({ root, cwd, mode, command })\n );\n } else if (\n isSetObject(resolved.default) ||\n Array.isArray(resolved.default)\n ) {\n config = resolved.default;\n }\n\n if (isSetObject(config) || Array.isArray(config)) {\n resolvedUserConfig = {\n ...config,\n config,\n configFile: resolvedUserConfigFile\n };\n }\n }\n }\n\n const result = await loadConfigC12({\n cwd: root,\n name: frameworkName,\n envName: mode,\n globalRc: true,\n packageJson: camelCase(frameworkName),\n dotenv: true,\n jiti\n });\n\n return defu(\n {\n config: {\n root,\n cwd,\n framework\n }\n },\n resolvedUserConfig,\n isSetObject(result?.config) ? { ...result.config, ...result } : {}\n ) as ParsedUserConfig;\n}\n\n/**\n * Type helper to make it easier to use `powerlines.config.ts` files. Accepts a direct {@link UserConfig} object, or a function that returns it. The function receives a {@link ConfigParams} object.\n *\n * @example\n * ```ts\n * import { defineConfig } from 'powerlines';\n *\n * export default defineConfig({\n * // Your configuration here\n * });\n *\n * // Or with a function\n * export default defineConfig((env) => {\n * console.log(`Running command: ${env.command} in mode: ${env.mode}`);\n * return {\n * // Your configuration here\n * };\n * });\n * ```\n */\nexport function defineConfig(config: UserConfig): UserConfig;\nexport function defineConfig(config: UserConfig[]): UserConfig[];\nexport function defineConfig(config: Promise<UserConfig>): Promise<UserConfig>;\nexport function defineConfig(\n config: Promise<UserConfig[]>\n): Promise<UserConfig[]>;\nexport function defineConfig(config: UserConfigFnObject): UserConfigFnObject;\nexport function defineConfig(config: UserConfigFnPromise): UserConfigFnPromise;\nexport function defineConfig(config: UserConfigFn): UserConfigFn;\nexport function defineConfig(config: UserConfigExport): UserConfigExport;\nexport function defineConfig(config: UserConfigExport): UserConfigExport {\n return config;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA4DA,SAAgB,kBAAkB,OAAe,KAAa;CAC5D,IAAI,MAAM,KAAK,WAAW,GAAG,IAAI,OAAO,IAAI;CAC5C,IAAI,CAAC,IAAI,SAAS,GAAG,GAAG,MAAM,GAAG,IAAI;CACrC,OAAO,IAAI,QAAQ,QAAQ,GAAG;AAChC;;;;;;;;;;;AAwBA,eAAsB,sBACpB,KACA,MACsC;CACtC,MAAM,SAAsC,CAAC;CAC7C,IAAI,OAAO,MAAM;EACf,MAAM,kBAAkB,UACtB,WAAW,QAAQ,KAAK,OAAO,GAAG,GAClC,cACF;EACA,IAAI,WAAW,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;IACnB,GAAG;IACH;IACA,YAAY;GACd;EAEJ;CACF;CAEA,MAAM,SAAS,MAAMA,WAAc;EACjC,KAAK;EACL,MAAM;EACN,SAAS;EACT,UAAU;EACV,aAAa,UAAU,aAAa;EACpC,QAAQ;EACR;CACF,CAAC;CAED,OAAO,KACL,EACE,QAAQ;EACN;EACA;EACA;CACF,EACF,GACA,oBACA,YAAY,QAAQ,MAAM,IAAI;EAAE,GAAG,OAAO;EAAQ,GAAG;CAAO,IAAI,CAAC,CACnE;AACF;AAgCA,SAAgB,aAAa,QAA4C;CACvE,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context-helpers.mjs","names":[],"sources":["../../src/lib/context-helpers.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n
|
|
1
|
+
{"version":3,"file":"context-helpers.mjs","names":[],"sources":["../../src/lib/context-helpers.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n 🗲 Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { toArray } from \"@stryke/convert/to-array\";\nimport { titleCase } from \"@stryke/string-format/title-case\";\nimport { isSetString } from \"@stryke/type-checks/is-set-string\";\nimport { colorText } from \"../plugin-utils/logging\";\nimport type {\n ExecutionContext,\n InferOverridableConfig,\n PluginConfig,\n PluginContext,\n ResolvedConfig\n} from \"../types\";\nimport { mergeConfigs } from \"./hooks\";\n\nexport function getConfigProps<TResolvedConfig extends ResolvedConfig>(\n config:\n | TResolvedConfig[\"userConfig\"]\n | TResolvedConfig[\"inlineConfig\"]\n | TResolvedConfig[\"pluginConfig\"]\n | InferOverridableConfig<TResolvedConfig> = {}\n) {\n return {\n input: isSetString(config.input) ? [config.input] : config.input,\n ...config\n };\n}\n\nexport async function resolvePluginConfig<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig,\n TSystemContext = unknown,\n TContext extends ExecutionContext<TResolvedConfig, TSystemContext> =\n ExecutionContext<TResolvedConfig, TSystemContext>\n>(context: TContext) {\n const timer = context.timer(\n `${titleCase(context.config.command)} Execution - Initialization`\n );\n\n for (const plugin of (\n context.config.plugins as PluginConfig<\n PluginContext<TResolvedConfig, TSystemContext>\n >[]\n ).flatMap(p => toArray(p)) ?? []) {\n await context.unstable_addPlugin(plugin);\n }\n\n if (context.plugins.length === 0) {\n context.warn({\n meta: {\n category: \"plugins\"\n },\n message:\n \"No Powerlines plugins were specified in the options. Please ensure this is correct, as it is generally not recommended.\"\n });\n } else {\n const pluginNumberWidth =\n context.plugins.length >= 10 ? String(context.plugins.length).length : 1;\n\n context.info({\n meta: {\n category: \"plugins\"\n },\n message: `Loaded ${context.plugins.length} ${titleCase(\n context.config.framework?.name ?? \"powerlines\"\n )} plugin${context.plugins.length > 1 ? \"s\" : \"\"}: \\n${context.plugins\n .map(\n (plugin, index) =>\n `${String(index + 1).padStart(\n pluginNumberWidth,\n \"0\"\n )}. ${colorText(plugin.name)}`\n )\n .join(\"\\n\")}`\n });\n }\n\n const pluginConfig = await context.callHook(\"config\", {\n environment: await context.getEnvironment(),\n sequential: true,\n result: \"merge\",\n merge: mergeConfigs\n });\n if (pluginConfig) {\n await context.setPluginConfig(\n pluginConfig as TContext[\"config\"][\"pluginConfig\"]\n );\n } else {\n context.debug({\n meta: {\n category: \"config\"\n },\n message: \"No plugin configuration was returned from the config hook.\"\n });\n }\n\n timer();\n}\n"],"mappings":";;;;;;;AA+BA,SAAgB,eACd,SAI8C,CAAC,GAC/C;CACA,OAAO;EACL,OAAO,YAAY,OAAO,KAAK,IAAI,CAAC,OAAO,KAAK,IAAI,OAAO;EAC3D,GAAG;CACL;AACF;AAEA,eAAsB,oBAKpB,SAAmB;CACnB,MAAM,QAAQ,QAAQ,MACpB,GAAG,UAAU,QAAQ,OAAO,OAAO,EAAE,4BACvC;CAEA,KAAK,MAAM,UACT,QAAQ,OAAO,QAGf,SAAQ,MAAK,QAAQ,CAAC,CAAC,KAAK,CAAC,GAC7B,MAAM,QAAQ,mBAAmB,MAAM;CAGzC,IAAI,QAAQ,QAAQ,WAAW,GAC7B,QAAQ,KAAK;EACX,MAAM,EACJ,UAAU,UACZ;EACA,SACE;CACJ,CAAC;MACI;EACL,MAAM,oBACJ,QAAQ,QAAQ,UAAU,KAAK,OAAO,QAAQ,QAAQ,MAAM,CAAC,CAAC,SAAS;EAEzE,QAAQ,KAAK;GACX,MAAM,EACJ,UAAU,UACZ;GACA,SAAS,UAAU,QAAQ,QAAQ,OAAO,GAAG,UAC3C,QAAQ,OAAO,WAAW,QAAQ,YACpC,EAAE,SAAS,QAAQ,QAAQ,SAAS,IAAI,MAAM,GAAG,MAAM,QAAQ,QAC5D,KACE,QAAQ,UACP,GAAG,OAAO,QAAQ,CAAC,CAAC,CAAC,SACnB,mBACA,GACF,EAAE,IAAI,UAAU,OAAO,IAAI,GAC/B,CAAC,CACA,KAAK,IAAI;EACd,CAAC;CACH;CAEA,MAAM,eAAe,MAAM,QAAQ,SAAS,UAAU;EACpD,aAAa,MAAM,QAAQ,eAAe;EAC1C,YAAY;EACZ,QAAQ;EACR,OAAO;CACT,CAAC;CACD,IAAI,cACF,MAAM,QAAQ,gBACZ,YACF;MAEA,QAAQ,MAAM;EACZ,MAAM,EACJ,UAAU,SACZ;EACA,SAAS;CACX,CAAC;CAGH,MAAM;AACR"}
|
package/dist/lib/entry.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"entry.mjs","names":[],"sources":["../../src/lib/entry.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { extractFileReference } from \"@stryke/convert/extract-file-reference\";\nimport { toArray } from \"@stryke/convert/to-array\";\nimport { murmurhash } from \"@stryke/hash\";\nimport { getUniqueBy } from \"@stryke/helpers/get-unique\";\nimport { appendPath } from \"@stryke/path/append\";\nimport { isAbsolutePath } from \"@stryke/path/is-type\";\nimport { joinPaths } from \"@stryke/path/join-paths\";\nimport { replaceExtension, replacePath } from \"@stryke/path/replace\";\nimport { isObject } from \"@stryke/type-checks/is-object\";\nimport { isSetString } from \"@stryke/type-checks/is-set-string\";\nimport { isString } from \"@stryke/type-checks/is-string\";\nimport type {\n FileReference,\n FileReferenceParameter\n} from \"@stryke/types/configuration\";\nimport { replacePathTokens } from \"../plugin-utils/paths\";\nimport {\n Config,\n ResolvedConfig,\n ResolvedEntryFileReference\n} from \"../types/config\";\nimport type { UnresolvedContext } from \"../types/context\";\n\nexport function resolveEntryOutput<TContext extends UnresolvedContext>(\n context: TContext,\n fileReference: FileReference\n): string {\n return replaceExtension(\n replacePath(\n replacePath(\n replacePath(\n replacePath(\n replacePath(\n fileReference.file,\n joinPaths(context.config.cwd, context.config.root, \"src\")\n ),\n joinPaths(context.config.cwd, context.config.root)\n ),\n joinPaths(context.config.root, \"src\")\n ),\n context.config.root\n ),\n \"src\"\n )\n );\n}\n\nexport function resolveInput<TContext extends UnresolvedContext>(\n context: TContext,\n fileReference: FileReference,\n input?: FileReferenceParameter,\n output?: string\n): ResolvedEntryFileReference {\n return {\n ...fileReference,\n input: isSetString(input) ? { file: String(input) } : fileReference,\n output: output || resolveEntryOutput(context, fileReference)\n };\n}\n\n/**\n * Resolves multiple file references into their corresponding resolved entry file references.\n *\n * @param context - The current context\n * @param fileReferences - The file references to resolve.\n * @returns A promise that resolves to an array of resolved entry file references .\n */\nexport async function resolveInputs<TContext extends UnresolvedContext>(\n context: TContext,\n fileReferences:\n | FileReferenceParameter\n | FileReferenceParameter[]\n | Record<string, FileReferenceParameter | FileReferenceParameter[]>\n): Promise<ResolvedEntryFileReference[]> {\n return (\n await Promise.all(\n (isObject(fileReferences) && !isFileReference(fileReferences)\n ? Object.values(fileReferences).flat()\n : toArray(fileReferences)\n )\n .map(async entry => {\n if (isResolvedEntryFileReference(entry)) {\n return {\n ...entry,\n output: entry.output\n ? replacePathTokens(context, entry.output)\n : undefined,\n file: replacePathTokens(context, entry.file)\n };\n }\n\n let typeDefinition: FileReference;\n if (isString(entry)) {\n typeDefinition = extractFileReference(\n replacePathTokens(context, entry)\n )!;\n } else {\n typeDefinition = entry;\n typeDefinition.file = replacePathTokens(\n context,\n typeDefinition.file\n );\n }\n\n const filePath = isAbsolutePath(typeDefinition.file)\n ? typeDefinition.file\n : appendPath(typeDefinition.file, context.config.root);\n if (await context.fs.isFile(filePath)) {\n return resolveInput(\n context,\n {\n file: replacePath(filePath, context.config.root),\n export: typeDefinition.export\n },\n (entry as ResolvedEntryFileReference).input,\n (entry as ResolvedEntryFileReference).output\n );\n }\n\n return (\n await context.fs.glob(appendPath(filePath, context.config.cwd))\n ).map(file =>\n resolveInput(\n context,\n {\n file: replacePath(file, context.config.root),\n export: typeDefinition.export\n },\n (entry as ResolvedEntryFileReference).input,\n (entry as ResolvedEntryFileReference).output\n )\n );\n })\n .flat()\n .filter(Boolean)\n )\n ).flat();\n}\n\n/**\n * Resolves multiple file references into their corresponding resolved entry file references.\n *\n * @param context - The current context\n * @param fileReferences - The file references to resolve.\n * @returns An array of resolved entry file references.\n */\nexport function resolveInputsSync<TContext extends UnresolvedContext>(\n context: TContext,\n fileReferences:\n | FileReferenceParameter\n | FileReferenceParameter[]\n | Record<string, FileReferenceParameter | FileReferenceParameter[]>\n): ResolvedEntryFileReference[] {\n return (\n isObject(fileReferences) && !isFileReference(fileReferences)\n ? Object.values(fileReferences).flat()\n : toArray(fileReferences)\n )\n .map(entry => {\n if (isResolvedEntryFileReference(entry)) {\n return {\n ...entry,\n output: entry.output\n ? replacePathTokens(context, entry.output)\n : undefined,\n file: replacePathTokens(context, entry.file)\n };\n }\n\n let typeDefinition: FileReference;\n if (isString(entry)) {\n typeDefinition = extractFileReference(\n replacePathTokens(context, entry)\n )!;\n } else {\n typeDefinition = entry;\n typeDefinition.file = replacePathTokens(context, typeDefinition.file);\n }\n\n const filePath = isAbsolutePath(typeDefinition.file)\n ? typeDefinition.file\n : appendPath(typeDefinition.file, context.config.root);\n if (context.fs.isFileSync(filePath)) {\n return resolveInput(context, {\n file: appendPath(filePath, context.config.cwd),\n export: typeDefinition.export\n });\n }\n\n return context.fs\n .globSync(appendPath(filePath, context.config.cwd))\n .map(file =>\n resolveInput(context, {\n file,\n export: typeDefinition.export\n })\n );\n })\n .flat()\n .filter(Boolean);\n}\n\n/**\n * Checks if the provided entry is a file reference.\n *\n * @param entry - The entry to check.\n * @returns True if the entry is a file reference, false otherwise.\n */\nexport function isFileReference(entry: any): entry is FileReference {\n return !isString(entry) && entry.file !== undefined;\n}\n\n/**\n * Checks if the provided entry is a resolved entry file reference.\n *\n * @param entry - The entry to check.\n * @returns True if the entry is a resolved entry file reference, false otherwise.\n */\nexport function isResolvedEntryFileReference(\n entry: FileReferenceParameter | ResolvedEntryFileReference\n): entry is ResolvedEntryFileReference {\n return (\n isFileReference(entry) &&\n (entry as ResolvedEntryFileReference).output !== undefined\n );\n}\n\n/**\n * Get unique inputs from the provided list.\n *\n * @param inputs - The entry points to process.\n * @returns An array of unique inputs (by file path or content hash).\n */\nexport function getUniqueInputs(\n inputs: Config[\"input\"] = []\n): ResolvedConfig[\"input\"] {\n return isObject(inputs)\n ? inputs\n : getUniqueBy(toArray(inputs), (item: FileReferenceParameter) =>\n is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,CAAC,CACN,OAAO,OAAO;AACnB;;;;;;;AAQA,SAAgB,gBAAgB,OAAoC;CAClE,OAAO,CAAC,SAAS,KAAK,KAAK,MAAM,SAAS;AAC5C;;;;;;;AAQA,SAAgB,6BACd,OACqC;CACrC,OACE,gBAAgB,KAAK,KACpB,MAAqC,WAAW;AAErD;;;;;;;AAQA,SAAgB,gBACd,SAA0B,CAAC,GACF;CACzB,OAAO,SAAS,MAAM,IAClB,SACA,YAAY,QAAQ,MAAM,IAAI,SAC5B,YAAY,IAAI,IAAI,OAAO,WAAW,QAAQ,CAAC,GAAG,EAAE,WAAW,GAAG,CAAC,CACrE;AACN"}
|
|
1
|
+
{"version":3,"file":"entry.mjs","names":[],"sources":["../../src/lib/entry.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n 🗲 Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { extractFileReference } from \"@stryke/convert/extract-file-reference\";\nimport { toArray } from \"@stryke/convert/to-array\";\nimport { murmurhash } from \"@stryke/hash\";\nimport { getUniqueBy } from \"@stryke/helpers/get-unique\";\nimport { appendPath } from \"@stryke/path/append\";\nimport { isAbsolutePath } from \"@stryke/path/is-type\";\nimport { joinPaths } from \"@stryke/path/join-paths\";\nimport { replaceExtension, replacePath } from \"@stryke/path/replace\";\nimport { isObject } from \"@stryke/type-checks/is-object\";\nimport { isSetString } from \"@stryke/type-checks/is-set-string\";\nimport { isString } from \"@stryke/type-checks/is-string\";\nimport type {\n FileReference,\n FileReferenceParameter\n} from \"@stryke/types/configuration\";\nimport { replacePathTokens } from \"../plugin-utils/paths\";\nimport {\n Config,\n ResolvedConfig,\n ResolvedEntryFileReference\n} from \"../types/config\";\nimport type { UnresolvedContext } from \"../types/context\";\n\nexport function resolveEntryOutput<TContext extends UnresolvedContext>(\n context: TContext,\n fileReference: FileReference\n): string {\n return replaceExtension(\n replacePath(\n replacePath(\n replacePath(\n replacePath(\n replacePath(\n fileReference.file,\n joinPaths(context.config.cwd, context.config.root, \"src\")\n ),\n joinPaths(context.config.cwd, context.config.root)\n ),\n joinPaths(context.config.root, \"src\")\n ),\n context.config.root\n ),\n \"src\"\n )\n );\n}\n\nexport function resolveInput<TContext extends UnresolvedContext>(\n context: TContext,\n fileReference: FileReference,\n input?: FileReferenceParameter,\n output?: string\n): ResolvedEntryFileReference {\n return {\n ...fileReference,\n input: isSetString(input) ? { file: String(input) } : fileReference,\n output: output || resolveEntryOutput(context, fileReference)\n };\n}\n\n/**\n * Resolves multiple file references into their corresponding resolved entry file references.\n *\n * @param context - The current context\n * @param fileReferences - The file references to resolve.\n * @returns A promise that resolves to an array of resolved entry file references .\n */\nexport async function resolveInputs<TContext extends UnresolvedContext>(\n context: TContext,\n fileReferences:\n | FileReferenceParameter\n | FileReferenceParameter[]\n | Record<string, FileReferenceParameter | FileReferenceParameter[]>\n): Promise<ResolvedEntryFileReference[]> {\n return (\n await Promise.all(\n (isObject(fileReferences) && !isFileReference(fileReferences)\n ? Object.values(fileReferences).flat()\n : toArray(fileReferences)\n )\n .map(async entry => {\n if (isResolvedEntryFileReference(entry)) {\n return {\n ...entry,\n output: entry.output\n ? replacePathTokens(context, entry.output)\n : undefined,\n file: replacePathTokens(context, entry.file)\n };\n }\n\n let typeDefinition: FileReference;\n if (isString(entry)) {\n typeDefinition = extractFileReference(\n replacePathTokens(context, entry)\n )!;\n } else {\n typeDefinition = entry;\n typeDefinition.file = replacePathTokens(\n context,\n typeDefinition.file\n );\n }\n\n const filePath = isAbsolutePath(typeDefinition.file)\n ? typeDefinition.file\n : appendPath(typeDefinition.file, context.config.root);\n if (await context.fs.isFile(filePath)) {\n return resolveInput(\n context,\n {\n file: replacePath(filePath, context.config.root),\n export: typeDefinition.export\n },\n (entry as ResolvedEntryFileReference).input,\n (entry as ResolvedEntryFileReference).output\n );\n }\n\n return (\n await context.fs.glob(appendPath(filePath, context.config.cwd))\n ).map(file =>\n resolveInput(\n context,\n {\n file: replacePath(file, context.config.root),\n export: typeDefinition.export\n },\n (entry as ResolvedEntryFileReference).input,\n (entry as ResolvedEntryFileReference).output\n )\n );\n })\n .flat()\n .filter(Boolean)\n )\n ).flat();\n}\n\n/**\n * Resolves multiple file references into their corresponding resolved entry file references.\n *\n * @param context - The current context\n * @param fileReferences - The file references to resolve.\n * @returns An array of resolved entry file references.\n */\nexport function resolveInputsSync<TContext extends UnresolvedContext>(\n context: TContext,\n fileReferences:\n | FileReferenceParameter\n | FileReferenceParameter[]\n | Record<string, FileReferenceParameter | FileReferenceParameter[]>\n): ResolvedEntryFileReference[] {\n return (\n isObject(fileReferences) && !isFileReference(fileReferences)\n ? Object.values(fileReferences).flat()\n : toArray(fileReferences)\n )\n .map(entry => {\n if (isResolvedEntryFileReference(entry)) {\n return {\n ...entry,\n output: entry.output\n ? replacePathTokens(context, entry.output)\n : undefined,\n file: replacePathTokens(context, entry.file)\n };\n }\n\n let typeDefinition: FileReference;\n if (isString(entry)) {\n typeDefinition = extractFileReference(\n replacePathTokens(context, entry)\n )!;\n } else {\n typeDefinition = entry;\n typeDefinition.file = replacePathTokens(context, typeDefinition.file);\n }\n\n const filePath = isAbsolutePath(typeDefinition.file)\n ? typeDefinition.file\n : appendPath(typeDefinition.file, context.config.root);\n if (context.fs.isFileSync(filePath)) {\n return resolveInput(context, {\n file: appendPath(filePath, context.config.cwd),\n export: typeDefinition.export\n });\n }\n\n return context.fs\n .globSync(appendPath(filePath, context.config.cwd))\n .map(file =>\n resolveInput(context, {\n file,\n export: typeDefinition.export\n })\n );\n })\n .flat()\n .filter(Boolean);\n}\n\n/**\n * Checks if the provided entry is a file reference.\n *\n * @param entry - The entry to check.\n * @returns True if the entry is a file reference, false otherwise.\n */\nexport function isFileReference(entry: any): entry is FileReference {\n return !isString(entry) && entry.file !== undefined;\n}\n\n/**\n * Checks if the provided entry is a resolved entry file reference.\n *\n * @param entry - The entry to check.\n * @returns True if the entry is a resolved entry file reference, false otherwise.\n */\nexport function isResolvedEntryFileReference(\n entry: FileReferenceParameter | ResolvedEntryFileReference\n): entry is ResolvedEntryFileReference {\n return (\n isFileReference(entry) &&\n (entry as ResolvedEntryFileReference).output !== undefined\n );\n}\n\n/**\n * Get unique inputs from the provided list.\n *\n * @param inputs - The entry points to process.\n * @returns An array of unique inputs (by file path or content hash).\n */\nexport function getUniqueInputs(\n inputs: Config[\"input\"] = []\n): ResolvedConfig[\"input\"] {\n return isObject(inputs)\n ? inputs\n : getUniqueBy(toArray(inputs), (item: FileReferenceParameter) =>\n isSetString(item) ? item : murmurhash(item ?? {}, { maxLength: 24 })\n );\n}\n"],"mappings":";;;;;;;;;;;;;;AAyCA,SAAgB,mBACd,SACA,eACQ;CACR,OAAO,iBACL,YACE,YACE,YACE,YACE,YACE,cAAc,MACd,UAAU,QAAQ,OAAO,KAAK,QAAQ,OAAO,MAAM,KAAK,CAC1D,GACA,UAAU,QAAQ,OAAO,KAAK,QAAQ,OAAO,IAAI,CACnD,GACA,UAAU,QAAQ,OAAO,MAAM,KAAK,CACtC,GACA,QAAQ,OAAO,IACjB,GACA,KACF,CACF;AACF;AAEA,SAAgB,aACd,SACA,eACA,OACA,QAC4B;CAC5B,OAAO;EACL,GAAG;EACH,OAAO,YAAY,KAAK,IAAI,EAAE,MAAM,OAAO,KAAK,EAAE,IAAI;EACtD,QAAQ,UAAU,mBAAmB,SAAS,aAAa;CAC7D;AACF;;;;;;;;AASA,eAAsB,cACpB,SACA,gBAIuC;CACvC,QACE,MAAM,QAAQ,KACX,SAAS,cAAc,KAAK,CAAC,gBAAgB,cAAc,IACxD,OAAO,OAAO,cAAc,CAAC,CAAC,KAAK,IACnC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ACJ,IAAI,SAAS,KAAK,GAChB,iBAAiB,qBACf,kBAAkB,SAAS,KAAK,CAClC;OACK;GACL,iBAAiB;GACjB,eAAe,OAAO,kBAAkB,SAAS,eAAe,IAAI;EACtE;EAEA,MAAM,WAAW,eAAe,eAAe,IAAI,IAC/C,eAAe,OACf,WAAW,eAAe,MAAM,QAAQ,OAAO,IAAI;EACvD,IAAI,QAAQ,GAAG,WAAW,QAAQ,GAChC,OAAO,aAAa,SAAS;GAC3B,MAAM,WAAW,UAAU,QAAQ,OAAO,GAAG;GAC7C,QAAQ,eAAe;EACzB,CAAC;EAGH,OAAO,QAAQ,GACZ,SAAS,WAAW,UAAU,QAAQ,OAAO,GAAG,CAAC,CAAC,CAClD,KAAI,SACH,aAAa,SAAS;GACpB;GACA,QAAQ,eAAe;EACzB,CAAC,CACH;CACJ,CAAC,CAAC,CACD,KAAK,CAAC,CACN,OAAO,OAAO;AACnB;;;;;;;AAQA,SAAgB,gBAAgB,OAAoC;CAClE,OAAO,CAAC,SAAS,KAAK,KAAK,MAAM,SAAS;AAC5C;;;;;;;AAQA,SAAgB,6BACd,OACqC;CACrC,OACE,gBAAgB,KAAK,KACpB,MAAqC,WAAW;AAErD;;;;;;;AAQA,SAAgB,gBACd,SAA0B,CAAC,GACF;CACzB,OAAO,SAAS,MAAM,IAClB,SACA,YAAY,QAAQ,MAAM,IAAI,SAC5B,YAAY,IAAI,IAAI,OAAO,WAAW,QAAQ,CAAC,GAAG,EAAE,WAAW,GAAG,CAAC,CACrE;AACN"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"environment.mjs","names":[],"sources":["../../src/lib/environment.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n
|
|
1
|
+
{"version":3,"file":"environment.mjs","names":[],"sources":["../../src/lib/environment.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n 🗲 Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { titleCase } from \"@stryke/string-format/title-case\";\nimport { isSet } from \"@stryke/type-checks/is-set\";\nimport { MaybePromise } from \"@stryke/types/base\";\nimport { uuid } from \"@stryke/unique-id/uuid\";\nimport defu from \"defu\";\nimport { DEFAULT_ENVIRONMENT } from \"../constants\";\nimport type {\n EnvironmentContext,\n EnvironmentResolvedConfig,\n ExecutionContext,\n ResolvedConfig\n} from \"../types\";\nimport { callHook } from \"./hooks\";\n\nexport function createEnvironment<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig\n>(name: string, config: TResolvedConfig) {\n return defu(config.environments?.[name] ?? {}, {\n id: uuid(),\n name,\n title: config.title ?? titleCase(config.name),\n ssr: false,\n resolve: {\n mainFields:\n config.platform === \"browser\"\n ? [\"browser\", \"module\", \"jsnext:main\", \"jsnext\"]\n : [\"module\", \"jsnext:main\", \"jsnext\"]\n },\n consumer: config.platform === \"browser\" ? \"client\" : \"server\",\n preview:\n config.platform === \"browser\"\n ? {\n port: 5173,\n open: true,\n strictPort: false,\n // https: false,\n host: \"localhost\",\n allowedHosts: [\".\"],\n cors: true,\n headers: {}\n }\n : undefined\n }) as unknown as EnvironmentResolvedConfig<TResolvedConfig>[\"environment\"];\n}\n\nexport function createDefaultEnvironment<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig\n>(config: TResolvedConfig) {\n return createEnvironment<TResolvedConfig>(DEFAULT_ENVIRONMENT, config);\n}\n\nexport async function getEnvironments<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig,\n TSystemContext = unknown\n>(\n context: ExecutionContext<TResolvedConfig, TSystemContext>\n): Promise<EnvironmentContext<TResolvedConfig, TSystemContext>[]> {\n if (\n !context.config.environments ||\n Object.keys(context.config.environments).length <= 1\n ) {\n context.debug({\n meta: {\n category: \"config\"\n },\n message:\n \"No environments are configured for this Powerlines project. Using the default environment.\"\n });\n\n return [await context.getEnvironment()];\n }\n\n context.debug({\n meta: {\n category: \"config\"\n },\n message: `Found ${\n Object.keys(context.config.environments).length\n } configured environment(s) for this Powerlines project.`\n });\n\n return (\n await Promise.all(\n Object.entries(context.config.environments).map(\n async ([name, config]) => {\n const environment = await context.getEnvironmentSafe(name);\n if (!environment) {\n const resolvedEnvironment = await callHook(\n context,\n \"configEnvironment\",\n {\n environment: name\n },\n name,\n config\n );\n\n if (resolvedEnvironment) {\n context.environments[name] = await context.createEnvironment(\n resolvedEnvironment as EnvironmentResolvedConfig<TResolvedConfig>[\"environment\"]\n );\n }\n }\n\n return context.environments[name];\n }\n )\n )\n ).filter(env => isSet(env));\n}\n\nexport async function executeEnvironments<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig,\n TSystemContext = unknown\n>(\n context: ExecutionContext<TResolvedConfig, TSystemContext>,\n handle: (\n env: EnvironmentContext<TResolvedConfig, TSystemContext>\n ) => MaybePromise<void>\n) {\n await Promise.all(\n (await getEnvironments(context)).map(async env =>\n Promise.resolve(handle(env))\n )\n );\n}\n"],"mappings":";;;;;;;;;AAgCA,SAAgB,kBAEd,MAAc,QAAyB;CACvC,OAAO,KAAK,OAAO,eAAe,SAAS,CAAC,GAAG;EAC7C,IAAI,KAAK;EACT;EACA,OAAO,OAAO,SAAS,UAAU,OAAO,IAAI;EAC5C,KAAK;EACL,SAAS,EACP,YACE,OAAO,aAAa,YAChB;GAAC;GAAW;GAAU;GAAe;EAAQ,IAC7C;GAAC;GAAU;GAAe;EAAQ,EAC1C;EACA,UAAU,OAAO,aAAa,YAAY,WAAW;EACrD,SACE,OAAO,aAAa,YAChB;GACE,MAAM;GACN,MAAM;GACN,YAAY;GAEZ,MAAM;GACN,cAAc,CAAC,GAAG;GAClB,MAAM;GACN,SAAS,CAAC;EACZ,IACA;CACR,CAAC;AACH;AAEA,SAAgB,yBAEd,QAAyB;CACzB,OAAO,kBAAmC,qBAAqB,MAAM;AACvE;AAEA,eAAsB,gBAIpB,SACgE;CAChE,IACE,CAAC,QAAQ,OAAO,gBAChB,OAAO,KAAK,QAAQ,OAAO,YAAY,CAAC,CAAC,UAAU,GACnD;EACA,QAAQ,MAAM;GACZ,MAAM,EACJ,UAAU,SACZ;GACA,SACE;EACJ,CAAC;EAED,OAAO,CAAC,MAAM,QAAQ,eAAe,CAAC;CACxC;CAEA,QAAQ,MAAM;EACZ,MAAM,EACJ,UAAU,SACZ;EACA,SAAS,SACP,OAAO,KAAK,QAAQ,OAAO,YAAY,CAAC,CAAC,OAC1C;CACH,CAAC;CAED,QACE,MAAM,QAAQ,IACZ,OAAO,QAAQ,QAAQ,OAAO,YAAY,CAAC,CAAC,IAC1C,OAAO,CAAC,MAAM,YAAY;EAExB,IAAI,CAAC,MADqB,QAAQ,mBAAmB,IAAI,GACvC;GAChB,MAAM,sBAAsB,MAAM,SAChC,SACA,qBACA,EACE,aAAa,KACf,GACA,MACA,MACF;GAEA,IAAI,qBACF,QAAQ,aAAa,QAAQ,MAAM,QAAQ,kBACzC,mBACF;EAEJ;EAEA,OAAO,QAAQ,aAAa;CAC9B,CACF,CACF,EAAC,CACD,QAAO,QAAO,MAAM,GAAG,CAAC;AAC5B;AAEA,eAAsB,oBAIpB,SACA,QAGA;CACA,MAAM,QAAQ,KACX,MAAM,gBAAgB,OAAO,EAAC,CAAE,IAAI,OAAM,QACzC,QAAQ,QAAQ,OAAO,GAAG,CAAC,CAC7B,CACF;AACF"}
|
package/dist/lib/events.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"events.mjs","names":[],"sources":["../../src/lib/events.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n
|
|
1
|
+
{"version":3,"file":"events.mjs","names":[],"sources":["../../src/lib/events.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n 🗲 Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport type { EventEmitter, EventsMap, EventUnsubscribe } from \"devframe/types\";\n\n/**\n * Create event emitter.\n */\nexport function createEventEmitter<\n Events extends EventsMap\n>(): EventEmitter<Events> {\n const _listeners: Partial<{ [E in keyof Events]: Events[E][] }> = {};\n\n function emit<K extends keyof Events>(\n event: K,\n ...args: Parameters<Events[K]>\n ) {\n const callbacks = _listeners[event] || [];\n for (let i = 0, length = callbacks.length; i < length; i++) {\n const callback = callbacks[i];\n if (callback) {\n // eslint-disable-next-line ts/no-unsafe-call\n callback(...args);\n }\n }\n }\n function emitOnce<K extends keyof Events>(\n event: K,\n ...args: Parameters<Events[K]>\n ) {\n emit(event, ...args);\n delete _listeners[event];\n }\n function on<K extends keyof Events>(\n event: K,\n cb: Events[K]\n ): EventUnsubscribe {\n (_listeners[event] ||= [] as Events[K][]).push(cb);\n return () => {\n _listeners[event] = _listeners[event]?.filter(i => cb !== i);\n };\n }\n function once<K extends keyof Events>(event: K, cb: Events[K]) {\n const unsubscribe = on(event, ((...args: Parameters<Events[K]>) => {\n unsubscribe();\n\n // eslint-disable-next-line ts/no-unsafe-call\n return cb(...args);\n }) as Events[K]);\n\n return unsubscribe;\n }\n\n return {\n _listeners,\n emit,\n emitOnce,\n on,\n once\n };\n}\n"],"mappings":";;;;AAuBA,SAAgB,qBAEU;CACxB,MAAM,aAA4D,CAAC;CAEnE,SAAS,KACP,OACA,GAAG,MACH;EACA,MAAM,YAAY,WAAW,UAAU,CAAC;EACxC,KAAK,IAAI,IAAI,GAAG,SAAS,UAAU,QAAQ,IAAI,QAAQ,KAAK;GAC1D,MAAM,WAAW,UAAU;GAC3B,IAAI,UAEF,SAAS,GAAG,IAAI;EAEpB;CACF;CACA,SAAS,SACP,OACA,GAAG,MACH;EACA,KAAK,OAAO,GAAG,IAAI;EACnB,OAAO,WAAW;CACpB;CACA,SAAS,GACP,OACA,IACkB;EAClB,CAAC,WAAW,WAAW,CAAC,EAAgB,CAAE,KAAK,EAAE;EACjD,aAAa;GACX,WAAW,SAAS,WAAW,MAAM,EAAE,QAAO,MAAK,OAAO,CAAC;EAC7D;CACF;CACA,SAAS,KAA6B,OAAU,IAAe;EAC7D,MAAM,cAAc,GAAG,SAAS,GAAG,SAAgC;GACjE,YAAY;GAGZ,OAAO,GAAG,GAAG,IAAI;EACnB,EAAe;EAEf,OAAO;CACT;CAEA,OAAO;EACL;EACA;EACA;EACA;EACA;CACF;AACF"}
|