| import { resolve } from "node:path"; | ||
| import picomatch from "picomatch"; | ||
| import { Parser } from "acorn"; | ||
| //#region src/utils/general.ts | ||
| function toArray(array) { | ||
| array = array || []; | ||
| if (Array.isArray(array)) return array; | ||
| return [array]; | ||
| } | ||
| //#endregion | ||
| //#region src/utils/filter.ts | ||
| const BACKSLASH_REGEX = /\\/g; | ||
| function normalize$1(path$1) { | ||
| return path$1.replace(BACKSLASH_REGEX, "/"); | ||
| } | ||
| const ABSOLUTE_PATH_REGEX = /^(?:\/|(?:[A-Z]:)?[/\\|])/i; | ||
| function isAbsolute$1(path$1) { | ||
| return ABSOLUTE_PATH_REGEX.test(path$1); | ||
| } | ||
| function getMatcherString(glob, cwd) { | ||
| if (glob.startsWith("**") || isAbsolute$1(glob)) return normalize$1(glob); | ||
| return normalize$1(resolve(cwd, glob)); | ||
| } | ||
| function patternToIdFilter(pattern) { | ||
| if (pattern instanceof RegExp) return (id) => { | ||
| const normalizedId = normalize$1(id); | ||
| const result = pattern.test(normalizedId); | ||
| pattern.lastIndex = 0; | ||
| return result; | ||
| }; | ||
| const matcher = picomatch(getMatcherString(pattern, process.cwd()), { dot: true }); | ||
| return (id) => { | ||
| return matcher(normalize$1(id)); | ||
| }; | ||
| } | ||
| function patternToCodeFilter(pattern) { | ||
| if (pattern instanceof RegExp) return (code) => { | ||
| const result = pattern.test(code); | ||
| pattern.lastIndex = 0; | ||
| return result; | ||
| }; | ||
| return (code) => code.includes(pattern); | ||
| } | ||
| function createFilter(exclude, include) { | ||
| if (!exclude && !include) return; | ||
| return (input) => { | ||
| if (exclude?.some((filter) => filter(input))) return false; | ||
| if (include?.some((filter) => filter(input))) return true; | ||
| return !(include && include.length > 0); | ||
| }; | ||
| } | ||
| function normalizeFilter(filter) { | ||
| if (typeof filter === "string" || filter instanceof RegExp) return { include: [filter] }; | ||
| if (Array.isArray(filter)) return { include: filter }; | ||
| return { | ||
| exclude: filter.exclude ? toArray(filter.exclude) : void 0, | ||
| include: filter.include ? toArray(filter.include) : void 0 | ||
| }; | ||
| } | ||
| function createIdFilter(filter) { | ||
| if (!filter) return; | ||
| const { exclude, include } = normalizeFilter(filter); | ||
| const excludeFilter = exclude?.map(patternToIdFilter); | ||
| const includeFilter = include?.map(patternToIdFilter); | ||
| return createFilter(excludeFilter, includeFilter); | ||
| } | ||
| function createCodeFilter(filter) { | ||
| if (!filter) return; | ||
| const { exclude, include } = normalizeFilter(filter); | ||
| const excludeFilter = exclude?.map(patternToCodeFilter); | ||
| const includeFilter = include?.map(patternToCodeFilter); | ||
| return createFilter(excludeFilter, includeFilter); | ||
| } | ||
| function createFilterForId(filter) { | ||
| const filterFunction = createIdFilter(filter); | ||
| return filterFunction ? (id) => !!filterFunction(id) : void 0; | ||
| } | ||
| function createFilterForTransform(idFilter, codeFilter) { | ||
| if (!idFilter && !codeFilter) return; | ||
| const idFilterFunction = createIdFilter(idFilter); | ||
| const codeFilterFunction = createCodeFilter(codeFilter); | ||
| return (id, code) => { | ||
| let fallback = true; | ||
| if (idFilterFunction) fallback &&= idFilterFunction(id); | ||
| if (!fallback) return false; | ||
| if (codeFilterFunction) fallback &&= codeFilterFunction(code); | ||
| return fallback; | ||
| }; | ||
| } | ||
| function normalizeObjectHook(name, hook) { | ||
| let handler; | ||
| let filter; | ||
| if (typeof hook === "function") handler = hook; | ||
| else { | ||
| handler = hook.handler; | ||
| const hookFilter = hook.filter; | ||
| if (name === "resolveId" || name === "load") filter = createFilterForId(hookFilter?.id); | ||
| else filter = createFilterForTransform(hookFilter?.id, hookFilter?.code); | ||
| } | ||
| return { | ||
| handler, | ||
| filter: filter || (() => true) | ||
| }; | ||
| } | ||
| //#endregion | ||
| //#region src/utils/context.ts | ||
| function parse(code, opts = {}) { | ||
| return Parser.parse(code, { | ||
| sourceType: "module", | ||
| ecmaVersion: "latest", | ||
| locations: true, | ||
| ...opts | ||
| }); | ||
| } | ||
| //#endregion | ||
| export { normalizeObjectHook as n, toArray as r, parse as t }; |
| import { t as parse } from "./context-BA9Bk3zk.mjs"; | ||
| import { createRequire } from "node:module"; | ||
| import { resolve } from "node:path"; | ||
| import { Buffer } from "node:buffer"; | ||
| import process from "node:process"; | ||
| //#region src/webpack/context.ts | ||
| function contextOptionsFromCompilation(compilation) { | ||
| return { | ||
| addWatchFile(file) { | ||
| (compilation.fileDependencies ?? compilation.compilationDependencies).add(file); | ||
| }, | ||
| getWatchFiles() { | ||
| return Array.from(compilation.fileDependencies ?? compilation.compilationDependencies); | ||
| } | ||
| }; | ||
| } | ||
| const require = createRequire(import.meta.url); | ||
| function getSource(fileSource) { | ||
| return new (require("webpack")).sources.RawSource(typeof fileSource === "string" ? fileSource : Buffer.from(fileSource.buffer)); | ||
| } | ||
| function createBuildContext(options, compiler, compilation, loaderContext) { | ||
| return { | ||
| parse, | ||
| addWatchFile(id) { | ||
| options.addWatchFile(resolve(process.cwd(), id)); | ||
| }, | ||
| emitFile(emittedFile) { | ||
| const outFileName = emittedFile.fileName || emittedFile.name; | ||
| if (emittedFile.source && outFileName) { | ||
| if (!compilation) throw new Error("unplugin/webpack: emitFile outside supported hooks (buildStart, buildEnd, load, transform, watchChange)"); | ||
| compilation.emitAsset(outFileName, getSource(emittedFile.source)); | ||
| } | ||
| }, | ||
| getWatchFiles() { | ||
| return options.getWatchFiles(); | ||
| }, | ||
| getNativeBuildContext() { | ||
| return { | ||
| framework: "webpack", | ||
| compiler, | ||
| compilation, | ||
| loaderContext | ||
| }; | ||
| } | ||
| }; | ||
| } | ||
| function createContext(loader) { | ||
| return { | ||
| error: (error) => loader.emitError(normalizeMessage(error)), | ||
| warn: (message) => loader.emitWarning(normalizeMessage(message)) | ||
| }; | ||
| } | ||
| function normalizeMessage(error) { | ||
| const err = new Error(typeof error === "string" ? error : error.message); | ||
| if (typeof error === "object") { | ||
| err.stack = error.stack; | ||
| err.cause = error.meta; | ||
| } | ||
| return err; | ||
| } | ||
| //#endregion | ||
| export { normalizeMessage as i, createBuildContext as n, createContext as r, contextOptionsFromCompilation as t }; |
| import { t as parse } from "./context-BA9Bk3zk.mjs"; | ||
| import { resolve } from "node:path"; | ||
| import { Buffer } from "node:buffer"; | ||
| //#region src/rspack/context.ts | ||
| function createBuildContext(compiler, compilation, loaderContext) { | ||
| return { | ||
| getNativeBuildContext() { | ||
| return { | ||
| framework: "rspack", | ||
| compiler, | ||
| compilation, | ||
| loaderContext | ||
| }; | ||
| }, | ||
| addWatchFile(file) { | ||
| const cwd = process.cwd(); | ||
| compilation.fileDependencies.add(resolve(cwd, file)); | ||
| }, | ||
| getWatchFiles() { | ||
| return Array.from(compilation.fileDependencies); | ||
| }, | ||
| parse, | ||
| emitFile(emittedFile) { | ||
| const outFileName = emittedFile.fileName || emittedFile.name; | ||
| if (emittedFile.source && outFileName) { | ||
| const { sources } = compilation.compiler.webpack; | ||
| compilation.emitAsset(outFileName, new sources.RawSource(typeof emittedFile.source === "string" ? emittedFile.source : Buffer.from(emittedFile.source))); | ||
| } | ||
| } | ||
| }; | ||
| } | ||
| function createContext(loader) { | ||
| return { | ||
| error: (error) => loader.emitError(normalizeMessage(error)), | ||
| warn: (message) => loader.emitWarning(normalizeMessage(message)) | ||
| }; | ||
| } | ||
| function normalizeMessage(error) { | ||
| const err = new Error(typeof error === "string" ? error : error.message); | ||
| if (typeof error === "object") { | ||
| err.stack = error.stack; | ||
| err.cause = error.meta; | ||
| } | ||
| return err; | ||
| } | ||
| //#endregion | ||
| export { createContext as n, normalizeMessage as r, createBuildContext as t }; |
+208
| import { Options } from "acorn"; | ||
| import VirtualModulesPlugin from "webpack-virtual-modules"; | ||
| import { CompilationContext, JsPlugin } from "@farmfe/core"; | ||
| import { Compilation, Compiler as RspackCompiler, LoaderContext, RspackPluginInstance } from "@rspack/core"; | ||
| import { BunPlugin, PluginBuilder } from "bun"; | ||
| import { BuildOptions, Loader, Plugin as EsbuildPlugin, PluginBuild } from "esbuild"; | ||
| import { Plugin as RolldownPlugin } from "rolldown"; | ||
| import { AstNode, EmittedAsset, Plugin as RollupPlugin, PluginContextMeta, SourceMapInput } from "rollup"; | ||
| import { Plugin as UnloaderPlugin } from "unloader"; | ||
| import { Plugin as VitePlugin } from "vite"; | ||
| import { Compilation as Compilation$1, Compiler as WebpackCompiler, LoaderContext as LoaderContext$1, WebpackPluginInstance } from "webpack"; | ||
| //#region src/types.d.ts | ||
| type Thenable<T> = T | Promise<T>; | ||
| /** | ||
| * Null or whatever | ||
| */ | ||
| type Nullable<T> = T | null | undefined; | ||
| /** | ||
| * Array, or not yet | ||
| */ | ||
| type Arrayable<T> = T | Array<T>; | ||
| interface SourceMapCompact { | ||
| file?: string | undefined; | ||
| mappings: string; | ||
| names: string[]; | ||
| sourceRoot?: string | undefined; | ||
| sources: string[]; | ||
| sourcesContent?: (string | null)[] | undefined; | ||
| version: number; | ||
| } | ||
| type TransformResult = string | { | ||
| code: string; | ||
| map?: SourceMapInput | SourceMapCompact | null | undefined; | ||
| } | null | undefined | void; | ||
| interface ExternalIdResult { | ||
| id: string; | ||
| external?: boolean | undefined; | ||
| } | ||
| type NativeBuildContext = { | ||
| framework: "webpack"; | ||
| compiler: WebpackCompiler; | ||
| compilation?: Compilation$1 | undefined; | ||
| loaderContext?: LoaderContext$1<{ | ||
| unpluginName: string; | ||
| }> | undefined; | ||
| } | { | ||
| framework: "esbuild"; | ||
| build: PluginBuild; | ||
| } | { | ||
| framework: "rspack"; | ||
| compiler: RspackCompiler; | ||
| compilation: Compilation; | ||
| loaderContext?: LoaderContext | undefined; | ||
| } | { | ||
| framework: "farm"; | ||
| context: CompilationContext; | ||
| } | { | ||
| framework: "bun"; | ||
| build: PluginBuilder; | ||
| }; | ||
| interface UnpluginBuildContext { | ||
| addWatchFile: (id: string) => void; | ||
| emitFile: (emittedFile: EmittedAsset) => void; | ||
| getWatchFiles: () => string[]; | ||
| parse: (input: string, options?: Partial<Options>) => AstNode; | ||
| getNativeBuildContext?: (() => NativeBuildContext) | undefined; | ||
| } | ||
| type StringOrRegExp = string | RegExp; | ||
| type FilterPattern = Arrayable<StringOrRegExp>; | ||
| type StringFilter = FilterPattern | { | ||
| include?: FilterPattern | undefined; | ||
| exclude?: FilterPattern | undefined; | ||
| }; | ||
| interface HookFilter { | ||
| id?: StringFilter | undefined; | ||
| code?: StringFilter | undefined; | ||
| } | ||
| interface ObjectHook<T extends HookFnMap[keyof HookFnMap], F extends keyof HookFilter> { | ||
| filter?: Pick<HookFilter, F> | undefined; | ||
| handler: T; | ||
| } | ||
| type Hook<T extends HookFnMap[keyof HookFnMap], F extends keyof HookFilter> = T | ObjectHook<T, F>; | ||
| interface HookFnMap { | ||
| buildStart: (this: UnpluginBuildContext) => Thenable<void>; | ||
| buildEnd: (this: UnpluginBuildContext) => Thenable<void>; | ||
| transform: (this: UnpluginBuildContext & UnpluginContext, code: string, id: string) => Thenable<TransformResult>; | ||
| load: (this: UnpluginBuildContext & UnpluginContext, id: string) => Thenable<TransformResult>; | ||
| resolveId: (this: UnpluginBuildContext & UnpluginContext, id: string, importer: string | undefined, options: { | ||
| isEntry: boolean; | ||
| }) => Thenable<string | ExternalIdResult | null | undefined>; | ||
| writeBundle: (this: void) => Thenable<void>; | ||
| } | ||
| interface UnpluginOptions { | ||
| name: string; | ||
| enforce?: "post" | "pre" | undefined; | ||
| buildStart?: HookFnMap["buildStart"] | undefined; | ||
| buildEnd?: HookFnMap["buildEnd"] | undefined; | ||
| transform?: Hook<HookFnMap["transform"], "code" | "id"> | undefined; | ||
| load?: Hook<HookFnMap["load"], "id"> | undefined; | ||
| resolveId?: Hook<HookFnMap["resolveId"], "id"> | undefined; | ||
| writeBundle?: HookFnMap["writeBundle"] | undefined; | ||
| watchChange?: ((this: UnpluginBuildContext, id: string, change: { | ||
| event: "create" | "update" | "delete"; | ||
| }) => void) | undefined; | ||
| /** | ||
| * Custom predicate function to filter modules to be loaded. | ||
| * When omitted, all modules will be included (might have potential perf impact on Webpack). | ||
| * | ||
| * @deprecated Use `load.filter` instead. | ||
| */ | ||
| loadInclude?: ((id: string) => boolean | null | undefined) | undefined; | ||
| /** | ||
| * Custom predicate function to filter modules to be transformed. | ||
| * When omitted, all modules will be included (might have potential perf impact on Webpack). | ||
| * | ||
| * @deprecated Use `transform.filter` instead. | ||
| */ | ||
| transformInclude?: ((id: string) => boolean | null | undefined) | undefined; | ||
| rollup?: Partial<RollupPlugin> | undefined; | ||
| webpack?: ((compiler: WebpackCompiler) => void) | undefined; | ||
| rspack?: ((compiler: RspackCompiler) => void) | undefined; | ||
| vite?: Partial<VitePlugin> | undefined; | ||
| unloader?: Partial<UnloaderPlugin> | undefined; | ||
| rolldown?: Partial<RolldownPlugin> | undefined; | ||
| esbuild?: { | ||
| onResolveFilter?: RegExp | undefined; | ||
| onLoadFilter?: RegExp | undefined; | ||
| loader?: Loader | ((code: string, id: string) => Loader) | undefined; | ||
| setup?: ((build: PluginBuild) => void | Promise<void>) | undefined; | ||
| config?: ((options: BuildOptions) => void) | undefined; | ||
| } | undefined; | ||
| farm?: Partial<JsPlugin> | undefined; | ||
| bun?: Partial<BunPlugin> | undefined; | ||
| } | ||
| interface ResolvedUnpluginOptions extends UnpluginOptions { | ||
| __vfs?: VirtualModulesPlugin | undefined; | ||
| __vfsModules?: Map<string, Promise<unknown>> | Set<string> | undefined; | ||
| __virtualModulePrefix: string; | ||
| } | ||
| type UnpluginFactory<UserOptions, Nested extends boolean = boolean> = (options: UserOptions, meta: UnpluginContextMeta) => Nested extends true ? Array<UnpluginOptions> : UnpluginOptions; | ||
| type UnpluginFactoryOutput<UserOptions, Return> = undefined extends UserOptions ? (options?: UserOptions | undefined) => Return : (options: UserOptions) => Return; | ||
| interface UnpluginInstance<UserOptions, Nested extends boolean = boolean> { | ||
| rollup: UnpluginFactoryOutput<UserOptions, Nested extends true ? Array<RollupPlugin> : RollupPlugin>; | ||
| vite: UnpluginFactoryOutput<UserOptions, Nested extends true ? Array<VitePlugin> : VitePlugin>; | ||
| rolldown: UnpluginFactoryOutput<UserOptions, Nested extends true ? Array<RolldownPlugin> : RolldownPlugin>; | ||
| webpack: UnpluginFactoryOutput<UserOptions, WebpackPluginInstance>; | ||
| rspack: UnpluginFactoryOutput<UserOptions, RspackPluginInstance>; | ||
| esbuild: UnpluginFactoryOutput<UserOptions, EsbuildPlugin>; | ||
| unloader: UnpluginFactoryOutput<UserOptions, Nested extends true ? Array<UnloaderPlugin> : UnloaderPlugin>; | ||
| farm: UnpluginFactoryOutput<UserOptions, JsPlugin>; | ||
| bun: UnpluginFactoryOutput<UserOptions, BunPlugin>; | ||
| raw: UnpluginFactory<UserOptions, Nested>; | ||
| } | ||
| type UnpluginContextMeta = Partial<PluginContextMeta> & ({ | ||
| framework: "rollup" | "vite" | "rolldown" | "farm" | "unloader"; | ||
| } | { | ||
| framework: "webpack"; | ||
| webpack: { | ||
| compiler: WebpackCompiler; | ||
| }; | ||
| } | { | ||
| framework: "esbuild"; | ||
| /** Set the host plugin name of esbuild when returning multiple plugins */ | ||
| esbuildHostName?: string | undefined; | ||
| } | { | ||
| framework: "bun"; | ||
| /** Set the host plugin name of bun when returning multiple plugins */ | ||
| bunHostName?: string | undefined; | ||
| } | { | ||
| framework: "rspack"; | ||
| rspack: { | ||
| compiler: RspackCompiler; | ||
| }; | ||
| }); | ||
| interface UnpluginMessage { | ||
| name?: string | undefined; | ||
| id?: string | undefined; | ||
| message: string; | ||
| stack?: string | undefined; | ||
| code?: string | undefined; | ||
| plugin?: string | undefined; | ||
| pluginCode?: unknown | undefined; | ||
| loc?: { | ||
| column: number; | ||
| file?: string | undefined; | ||
| line: number; | ||
| } | undefined; | ||
| meta?: any; | ||
| } | ||
| interface UnpluginContext { | ||
| error: (message: string | UnpluginMessage) => void; | ||
| warn: (message: string | UnpluginMessage) => void; | ||
| } | ||
| //#endregion | ||
| //#region src/define.d.ts | ||
| declare function createUnplugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions, Nested>; | ||
| declare function createEsbuildPlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["esbuild"]; | ||
| declare function createRollupPlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["rollup"]; | ||
| declare function createVitePlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["vite"]; | ||
| declare function createRolldownPlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["rolldown"]; | ||
| declare function createWebpackPlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["webpack"]; | ||
| declare function createRspackPlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["rspack"]; | ||
| declare function createFarmPlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["farm"]; | ||
| declare function createUnloaderPlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["unloader"]; | ||
| declare function createBunPlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["bun"]; | ||
| //#endregion | ||
| export { Arrayable, type BunPlugin, type EsbuildPlugin, ExternalIdResult, FilterPattern, Hook, HookFilter, HookFnMap, NativeBuildContext, Nullable, ObjectHook, ResolvedUnpluginOptions, type RolldownPlugin, type RollupPlugin, type RspackCompiler, type RspackPluginInstance, SourceMapCompact, StringFilter, StringOrRegExp, Thenable, TransformResult, type UnloaderPlugin, UnpluginBuildContext, UnpluginContext, UnpluginContextMeta, UnpluginFactory, UnpluginFactoryOutput, UnpluginInstance, UnpluginMessage, UnpluginOptions, type VitePlugin, type WebpackCompiler, type WebpackPluginInstance, createBunPlugin, createEsbuildPlugin, createFarmPlugin, createRolldownPlugin, createRollupPlugin, createRspackPlugin, createUnloaderPlugin, createUnplugin, createVitePlugin, createWebpackPlugin }; |
+1214
| import { n as normalizeObjectHook, r as toArray, t as parse } from "./context-BA9Bk3zk.mjs"; | ||
| import { n as transformUse, t as normalizeAbsolutePath } from "./webpack-like-BEGRU-K6.mjs"; | ||
| import { r as normalizeMessage$1, t as createBuildContext$1 } from "./context-DTC5O8j3.mjs"; | ||
| import { i as isVirtualModuleId, n as decodeVirtualModuleId, r as encodeVirtualModuleId, t as FakeVirtualModulesPlugin } from "./utils-C0A28-Cs.mjs"; | ||
| import { i as normalizeMessage, n as createBuildContext, t as contextOptionsFromCompilation } from "./context-DCMwCoy8.mjs"; | ||
| import path, { extname, isAbsolute, resolve } from "node:path"; | ||
| import fs from "node:fs"; | ||
| import * as acorn from "acorn"; | ||
| import { Buffer } from "node:buffer"; | ||
| import remapping from "@jridgewell/remapping"; | ||
| import * as querystring from "node:querystring"; | ||
| import process$1 from "node:process"; | ||
| import VirtualModulesPlugin from "webpack-virtual-modules"; | ||
| //#region src/bun/utils.ts | ||
| const ExtToLoader$1 = { | ||
| ".js": "js", | ||
| ".mjs": "js", | ||
| ".cjs": "js", | ||
| ".jsx": "jsx", | ||
| ".ts": "ts", | ||
| ".cts": "ts", | ||
| ".mts": "ts", | ||
| ".tsx": "tsx", | ||
| ".css": "css", | ||
| ".less": "css", | ||
| ".stylus": "css", | ||
| ".scss": "css", | ||
| ".sass": "css", | ||
| ".json": "json", | ||
| ".txt": "text" | ||
| }; | ||
| function guessLoader$1(id) { | ||
| return ExtToLoader$1[path.extname(id).toLowerCase()] || "js"; | ||
| } | ||
| function createBuildContext$3(build) { | ||
| const watchFiles = []; | ||
| return { | ||
| addWatchFile(file) { | ||
| watchFiles.push(file); | ||
| }, | ||
| getWatchFiles() { | ||
| return watchFiles; | ||
| }, | ||
| emitFile(emittedFile) { | ||
| const outFileName = emittedFile.fileName || emittedFile.name; | ||
| const outdir = build?.config?.outdir; | ||
| if (outdir && emittedFile.source && outFileName) { | ||
| const outPath = path.resolve(outdir, outFileName); | ||
| const outDir = path.dirname(outPath); | ||
| if (!fs.existsSync(outDir)) fs.mkdirSync(outDir, { recursive: true }); | ||
| fs.writeFileSync(outPath, emittedFile.source); | ||
| } | ||
| }, | ||
| parse(code, opts = {}) { | ||
| return acorn.parse(code, { | ||
| sourceType: "module", | ||
| ecmaVersion: "latest", | ||
| locations: true, | ||
| ...opts | ||
| }); | ||
| }, | ||
| getNativeBuildContext() { | ||
| return { | ||
| framework: "bun", | ||
| build | ||
| }; | ||
| } | ||
| }; | ||
| } | ||
| function createPluginContext$1(buildContext) { | ||
| const errors = []; | ||
| const warnings = []; | ||
| return { | ||
| errors, | ||
| warnings, | ||
| mixedContext: { | ||
| ...buildContext, | ||
| error(error) { | ||
| errors.push(error); | ||
| }, | ||
| warn(warning) { | ||
| warnings.push(warning); | ||
| } | ||
| } | ||
| }; | ||
| } | ||
| //#endregion | ||
| //#region src/bun/index.ts | ||
| function getBunPlugin(factory) { | ||
| return (userOptions) => { | ||
| if (typeof Bun === "undefined") throw new ReferenceError("Bun is not supported in this environment"); | ||
| if (!Bun.semver.satisfies(Bun.version, ">=1.2.22")) throw new Error("Bun 1.2.22 or higher is required, please upgrade Bun"); | ||
| const meta = { framework: "bun" }; | ||
| const plugins = toArray(factory(userOptions, meta)); | ||
| return { | ||
| name: (plugins.length === 1 ? plugins[0].name : meta.bunHostName) ?? `unplugin-host:${plugins.map((p) => p.name).join(":")}`, | ||
| async setup(build) { | ||
| const context = createBuildContext$3(build); | ||
| if (plugins.some((plugin) => plugin.buildStart)) build.onStart(async () => { | ||
| for (const plugin of plugins) if (plugin.buildStart) await plugin.buildStart.call(context); | ||
| }); | ||
| const resolveIdHooks = plugins.filter((plugin) => plugin.resolveId).map((plugin) => ({ | ||
| plugin, | ||
| ...normalizeObjectHook("resolveId", plugin.resolveId) | ||
| })); | ||
| const loadHooks = plugins.filter((plugin) => plugin.load).map((plugin) => ({ | ||
| plugin, | ||
| ...normalizeObjectHook("load", plugin.load) | ||
| })); | ||
| const transformHooks = plugins.filter((plugin) => plugin.transform || plugin.transformInclude).map((plugin) => ({ | ||
| plugin, | ||
| ...normalizeObjectHook("transform", plugin.transform) | ||
| })); | ||
| const virtualModulePlugins = /* @__PURE__ */ new Set(); | ||
| for (const plugin of plugins) if (plugin.resolveId && plugin.load) virtualModulePlugins.add(plugin.name); | ||
| if (resolveIdHooks.length) build.onResolve({ filter: /.*/ }, async (args) => { | ||
| if (build.config?.external?.includes(args.path)) return; | ||
| for (const { plugin, handler, filter } of resolveIdHooks) { | ||
| if (!filter(args.path)) continue; | ||
| const { mixedContext, errors, warnings } = createPluginContext$1(context); | ||
| const isEntry = args.kind === "entry-point-run" || args.kind === "entry-point-build"; | ||
| const result = await handler.call(mixedContext, args.path, isEntry ? void 0 : args.importer, { isEntry }); | ||
| for (const warning of warnings) console.warn("[unplugin]", typeof warning === "string" ? warning : warning.message); | ||
| if (errors.length > 0) { | ||
| const errorMessage = errors.map((e) => typeof e === "string" ? e : e.message).join("\n"); | ||
| throw new Error(`[unplugin] ${plugin.name}: ${errorMessage}`); | ||
| } | ||
| if (typeof result === "string") { | ||
| if (!isAbsolute(result)) return { | ||
| path: result, | ||
| namespace: plugin.name | ||
| }; | ||
| return { path: result }; | ||
| } else if (typeof result === "object" && result !== null) { | ||
| if (!isAbsolute(result.id)) return { | ||
| path: result.id, | ||
| external: result.external, | ||
| namespace: plugin.name | ||
| }; | ||
| return { | ||
| path: result.id, | ||
| external: result.external | ||
| }; | ||
| } | ||
| } | ||
| }); | ||
| async function processLoadTransform(id, namespace, loader) { | ||
| let code; | ||
| let hasResult = false; | ||
| const namespaceLoadHooks = namespace === "file" ? loadHooks : loadHooks.filter((h) => h.plugin.name === namespace); | ||
| for (const { plugin, handler, filter } of namespaceLoadHooks) { | ||
| if (plugin.loadInclude && !plugin.loadInclude(id)) continue; | ||
| if (!filter(id)) continue; | ||
| const { mixedContext, errors, warnings } = createPluginContext$1(context); | ||
| const result = await handler.call(mixedContext, id); | ||
| for (const warning of warnings) console.warn("[unplugin]", typeof warning === "string" ? warning : warning.message); | ||
| if (errors.length > 0) { | ||
| const errorMessage = errors.map((e) => typeof e === "string" ? e : e.message).join("\n"); | ||
| throw new Error(`[unplugin] ${plugin.name}: ${errorMessage}`); | ||
| } | ||
| if (typeof result === "string") { | ||
| code = result; | ||
| hasResult = true; | ||
| break; | ||
| } else if (typeof result === "object" && result !== null) { | ||
| code = result.code; | ||
| hasResult = true; | ||
| break; | ||
| } | ||
| } | ||
| if (!hasResult && namespace === "file" && transformHooks.length > 0) code = await Bun.file(id).text(); | ||
| if (code !== void 0) { | ||
| const namespaceTransformHooks = namespace === "file" ? transformHooks : transformHooks.filter((h) => h.plugin.name === namespace); | ||
| for (const { plugin, handler, filter } of namespaceTransformHooks) { | ||
| if (plugin.transformInclude && !plugin.transformInclude(id)) continue; | ||
| if (!filter(id, code)) continue; | ||
| const { mixedContext, errors, warnings } = createPluginContext$1(context); | ||
| const result = await handler.call(mixedContext, code, id); | ||
| for (const warning of warnings) console.warn("[unplugin]", typeof warning === "string" ? warning : warning.message); | ||
| if (errors.length > 0) { | ||
| const errorMessage = errors.map((e) => typeof e === "string" ? e : e.message).join("\n"); | ||
| throw new Error(`[unplugin] ${plugin.name}: ${errorMessage}`); | ||
| } | ||
| if (typeof result === "string") { | ||
| code = result; | ||
| hasResult = true; | ||
| } else if (typeof result === "object" && result !== null) { | ||
| code = result.code; | ||
| hasResult = true; | ||
| } | ||
| } | ||
| } | ||
| if (hasResult && code !== void 0) return { | ||
| contents: code, | ||
| loader: loader ?? guessLoader$1(id) | ||
| }; | ||
| } | ||
| if (loadHooks.length || transformHooks.length) build.onLoad({ | ||
| filter: /.*/, | ||
| namespace: "file" | ||
| }, async (args) => { | ||
| return processLoadTransform(args.path, "file", args.loader); | ||
| }); | ||
| for (const pluginName of virtualModulePlugins) build.onLoad({ | ||
| filter: /.*/, | ||
| namespace: pluginName | ||
| }, async (args) => { | ||
| return processLoadTransform(args.path, pluginName, args.loader); | ||
| }); | ||
| if (plugins.some((plugin) => plugin.buildEnd || plugin.writeBundle)) build.onEnd(async () => { | ||
| for (const plugin of plugins) { | ||
| if (plugin.buildEnd) await plugin.buildEnd.call(context); | ||
| if (plugin.writeBundle) await plugin.writeBundle(); | ||
| } | ||
| }); | ||
| } | ||
| }; | ||
| }; | ||
| } | ||
| //#endregion | ||
| //#region src/esbuild/utils.ts | ||
| const ExtToLoader = { | ||
| ".js": "js", | ||
| ".mjs": "js", | ||
| ".cjs": "js", | ||
| ".jsx": "jsx", | ||
| ".ts": "ts", | ||
| ".cts": "ts", | ||
| ".mts": "ts", | ||
| ".tsx": "tsx", | ||
| ".css": "css", | ||
| ".less": "css", | ||
| ".stylus": "css", | ||
| ".scss": "css", | ||
| ".sass": "css", | ||
| ".json": "json", | ||
| ".txt": "text" | ||
| }; | ||
| function guessLoader(code, id) { | ||
| return ExtToLoader[path.extname(id).toLowerCase()] || "js"; | ||
| } | ||
| function unwrapLoader(loader, code, id) { | ||
| if (typeof loader === "function") return loader(code, id); | ||
| return loader; | ||
| } | ||
| function fixSourceMap(map) { | ||
| if (!Object.prototype.hasOwnProperty.call(map, "toString")) Object.defineProperty(map, "toString", { | ||
| enumerable: false, | ||
| value: function toString() { | ||
| return JSON.stringify(this); | ||
| } | ||
| }); | ||
| if (!Object.prototype.hasOwnProperty.call(map, "toUrl")) Object.defineProperty(map, "toUrl", { | ||
| enumerable: false, | ||
| value: function toUrl() { | ||
| return `data:application/json;charset=utf-8;base64,${Buffer.from(this.toString()).toString("base64")}`; | ||
| } | ||
| }); | ||
| return map; | ||
| } | ||
| const nullSourceMap = { | ||
| names: [], | ||
| sources: [], | ||
| mappings: "", | ||
| version: 3 | ||
| }; | ||
| function combineSourcemaps(filename, sourcemapList) { | ||
| sourcemapList = sourcemapList.filter((m) => m.sources); | ||
| if (sourcemapList.length === 0 || sourcemapList.every((m) => m.sources.length === 0)) return { ...nullSourceMap }; | ||
| let map; | ||
| let mapIndex = 1; | ||
| if (sourcemapList.slice(0, -1).find((m) => m.sources.length !== 1) === void 0) map = remapping(sourcemapList, () => null, true); | ||
| else map = remapping(sourcemapList[0], (sourcefile) => { | ||
| if (sourcefile === filename && sourcemapList[mapIndex]) return sourcemapList[mapIndex++]; | ||
| else return { ...nullSourceMap }; | ||
| }, true); | ||
| if (!map.file) delete map.file; | ||
| return map; | ||
| } | ||
| function createBuildContext$2(build) { | ||
| const watchFiles = []; | ||
| const { initialOptions } = build; | ||
| return { | ||
| parse, | ||
| addWatchFile() { | ||
| throw new Error("unplugin/esbuild: addWatchFile outside supported hooks (resolveId, load, transform)"); | ||
| }, | ||
| emitFile(emittedFile) { | ||
| const outFileName = emittedFile.fileName || emittedFile.name; | ||
| if (initialOptions.outdir && emittedFile.source && outFileName) { | ||
| const outPath = path.resolve(initialOptions.outdir, outFileName); | ||
| const outDir = path.dirname(outPath); | ||
| if (!fs.existsSync(outDir)) fs.mkdirSync(outDir, { recursive: true }); | ||
| fs.writeFileSync(outPath, emittedFile.source); | ||
| } | ||
| }, | ||
| getWatchFiles() { | ||
| return watchFiles; | ||
| }, | ||
| getNativeBuildContext() { | ||
| return { | ||
| framework: "esbuild", | ||
| build | ||
| }; | ||
| } | ||
| }; | ||
| } | ||
| function createPluginContext(context) { | ||
| const errors = []; | ||
| const warnings = []; | ||
| const pluginContext = { | ||
| error(message) { | ||
| errors.push(normalizeMessage$2(message)); | ||
| }, | ||
| warn(message) { | ||
| warnings.push(normalizeMessage$2(message)); | ||
| } | ||
| }; | ||
| return { | ||
| errors, | ||
| warnings, | ||
| mixedContext: { | ||
| ...context, | ||
| ...pluginContext, | ||
| addWatchFile(id) { | ||
| context.getWatchFiles().push(id); | ||
| } | ||
| } | ||
| }; | ||
| } | ||
| function normalizeMessage$2(message) { | ||
| if (typeof message === "string") message = { message }; | ||
| return { | ||
| id: message.id, | ||
| pluginName: message.plugin, | ||
| text: message.message, | ||
| location: message.loc ? { | ||
| file: message.loc.file, | ||
| line: message.loc.line, | ||
| column: message.loc.column | ||
| } : null, | ||
| detail: message.meta, | ||
| notes: [] | ||
| }; | ||
| } | ||
| function processCodeWithSourceMap(map, code) { | ||
| if (map) { | ||
| if (!map.sourcesContent || map.sourcesContent.length === 0) map.sourcesContent = [code]; | ||
| map = fixSourceMap(map); | ||
| code += `\n//# sourceMappingURL=${map.toUrl()}`; | ||
| } | ||
| return code; | ||
| } | ||
| //#endregion | ||
| //#region src/esbuild/index.ts | ||
| function getEsbuildPlugin(factory) { | ||
| return (userOptions) => { | ||
| const meta = { framework: "esbuild" }; | ||
| const plugins = toArray(factory(userOptions, meta)); | ||
| const setupPlugins = async (build) => { | ||
| const setup = buildSetup(); | ||
| const loaders = []; | ||
| for (const plugin of plugins) { | ||
| const loader = {}; | ||
| await setup(plugin)({ | ||
| ...build, | ||
| onLoad(_options, callback) { | ||
| loader.options = _options; | ||
| loader.onLoadCb = callback; | ||
| }, | ||
| onTransform(_options, callback) { | ||
| loader.options ||= _options; | ||
| loader.onTransformCb = callback; | ||
| } | ||
| }, build); | ||
| if (loader.onLoadCb || loader.onTransformCb) loaders.push(loader); | ||
| } | ||
| if (loaders.length) build.onLoad(loaders.length === 1 ? loaders[0].options : { filter: /.*/ }, async (args) => { | ||
| function checkFilter(options) { | ||
| return loaders.length === 1 || !options?.filter || options.filter.test(args.path); | ||
| } | ||
| let result; | ||
| for (const { options, onLoadCb } of loaders) { | ||
| if (!checkFilter(options)) continue; | ||
| if (onLoadCb) result = await onLoadCb(args); | ||
| if (result?.contents) break; | ||
| } | ||
| let fsContentsCache; | ||
| for (const { options, onTransformCb } of loaders) { | ||
| if (!checkFilter(options)) continue; | ||
| if (onTransformCb) { | ||
| const _result = await onTransformCb({ | ||
| ...result, | ||
| ...args, | ||
| async getContents() { | ||
| if (result?.contents) return result.contents; | ||
| if (fsContentsCache) return fsContentsCache; | ||
| return fsContentsCache = await fs.promises.readFile(args.path, "utf8"); | ||
| } | ||
| }); | ||
| if (_result?.contents) result = _result; | ||
| } | ||
| } | ||
| if (result?.contents) return result; | ||
| }); | ||
| }; | ||
| return { | ||
| name: (plugins.length === 1 ? plugins[0].name : meta.esbuildHostName) ?? `unplugin-host:${plugins.map((p) => p.name).join(":")}`, | ||
| setup: setupPlugins | ||
| }; | ||
| }; | ||
| } | ||
| function buildSetup() { | ||
| return (plugin) => { | ||
| return (build, rawBuild) => { | ||
| const context = createBuildContext$2(rawBuild); | ||
| const { onStart, onEnd, onResolve, onLoad, onTransform, initialOptions } = build; | ||
| const onResolveFilter = plugin.esbuild?.onResolveFilter ?? /.*/; | ||
| const onLoadFilter = plugin.esbuild?.onLoadFilter ?? /.*/; | ||
| const loader = plugin.esbuild?.loader ?? guessLoader; | ||
| plugin.esbuild?.config?.call(context, initialOptions); | ||
| if (plugin.buildStart) onStart(() => plugin.buildStart.call(context)); | ||
| if (plugin.buildEnd || plugin.writeBundle) onEnd(async () => { | ||
| if (plugin.buildEnd) await plugin.buildEnd.call(context); | ||
| if (plugin.writeBundle) await plugin.writeBundle(); | ||
| }); | ||
| if (plugin.resolveId) onResolve({ filter: onResolveFilter }, async (args) => { | ||
| const id = args.path; | ||
| if (initialOptions.external?.includes(id)) return; | ||
| const { handler, filter } = normalizeObjectHook("resolveId", plugin.resolveId); | ||
| if (!filter(id)) return; | ||
| const { errors, warnings, mixedContext } = createPluginContext(context); | ||
| const isEntry = args.kind === "entry-point"; | ||
| const result = await handler.call(mixedContext, id, isEntry ? void 0 : args.importer, { isEntry }); | ||
| if (typeof result === "string") return { | ||
| path: result, | ||
| namespace: plugin.name, | ||
| errors, | ||
| warnings, | ||
| watchFiles: mixedContext.getWatchFiles() | ||
| }; | ||
| else if (typeof result === "object" && result !== null) return { | ||
| path: result.id, | ||
| external: result.external, | ||
| namespace: plugin.name, | ||
| errors, | ||
| warnings, | ||
| watchFiles: mixedContext.getWatchFiles() | ||
| }; | ||
| }); | ||
| if (plugin.load) onLoad({ filter: onLoadFilter }, async (args) => { | ||
| const { handler, filter } = normalizeObjectHook("load", plugin.load); | ||
| const id = args.path + (args.suffix || ""); | ||
| if (plugin.loadInclude && !plugin.loadInclude(id)) return; | ||
| if (!filter(id)) return; | ||
| const { errors, warnings, mixedContext } = createPluginContext(context); | ||
| let code; | ||
| let map; | ||
| const result = await handler.call(mixedContext, id); | ||
| if (typeof result === "string") code = result; | ||
| else if (typeof result === "object" && result !== null) { | ||
| code = result.code; | ||
| map = result.map; | ||
| } | ||
| if (code === void 0) return null; | ||
| if (map) code = processCodeWithSourceMap(map, code); | ||
| const resolveDir = path.dirname(args.path); | ||
| return { | ||
| contents: code, | ||
| errors, | ||
| warnings, | ||
| watchFiles: mixedContext.getWatchFiles(), | ||
| loader: unwrapLoader(loader, code, args.path), | ||
| resolveDir | ||
| }; | ||
| }); | ||
| if (plugin.transform) onTransform({ filter: onLoadFilter }, async (args) => { | ||
| const { handler, filter } = normalizeObjectHook("transform", plugin.transform); | ||
| const id = args.path + (args.suffix || ""); | ||
| if (plugin.transformInclude && !plugin.transformInclude(id)) return; | ||
| let code = await args.getContents(); | ||
| if (!filter(id, code)) return; | ||
| const { mixedContext, errors, warnings } = createPluginContext(context); | ||
| const resolveDir = path.dirname(args.path); | ||
| let map; | ||
| const result = await handler.call(mixedContext, code, id); | ||
| if (typeof result === "string") code = result; | ||
| else if (typeof result === "object" && result !== null) { | ||
| code = result.code; | ||
| if (map && result.map) map = combineSourcemaps(args.path, [result.map === "string" ? JSON.parse(result.map) : result.map, map]); | ||
| else if (typeof result.map === "string") map = JSON.parse(result.map); | ||
| else map = result.map; | ||
| } | ||
| if (code) { | ||
| if (map) code = processCodeWithSourceMap(map, code); | ||
| return { | ||
| contents: code, | ||
| errors, | ||
| warnings, | ||
| watchFiles: mixedContext.getWatchFiles(), | ||
| loader: unwrapLoader(loader, code, args.path), | ||
| resolveDir | ||
| }; | ||
| } | ||
| }); | ||
| if (plugin.esbuild?.setup) return plugin.esbuild.setup(rawBuild); | ||
| }; | ||
| }; | ||
| } | ||
| //#endregion | ||
| //#region src/farm/context.ts | ||
| function createFarmContext(context, currentResolveId) { | ||
| return { | ||
| parse, | ||
| addWatchFile(id) { | ||
| context.addWatchFile(id, currentResolveId || id); | ||
| }, | ||
| emitFile(emittedFile) { | ||
| const outFileName = emittedFile.fileName || emittedFile.name; | ||
| if (emittedFile.source && outFileName) context.emitFile({ | ||
| resolvedPath: outFileName, | ||
| name: outFileName, | ||
| content: [...Buffer.from(emittedFile.source)], | ||
| resourceType: extname(outFileName) | ||
| }); | ||
| }, | ||
| getWatchFiles() { | ||
| return context.getWatchFiles(); | ||
| }, | ||
| getNativeBuildContext() { | ||
| return { | ||
| framework: "farm", | ||
| context | ||
| }; | ||
| } | ||
| }; | ||
| } | ||
| function unpluginContext(context) { | ||
| return { | ||
| error: (error) => context.error(typeof error === "string" ? new Error(error) : error), | ||
| warn: (error) => context.warn(typeof error === "string" ? new Error(error) : error) | ||
| }; | ||
| } | ||
| //#endregion | ||
| //#region src/farm/utils.ts | ||
| function convertEnforceToPriority(value) { | ||
| const defaultPriority = 100; | ||
| const enforceToPriority = { | ||
| pre: 102, | ||
| post: 98 | ||
| }; | ||
| return enforceToPriority[value] !== void 0 ? enforceToPriority[value] : defaultPriority; | ||
| } | ||
| function convertWatchEventChange(value) { | ||
| return { | ||
| Added: "create", | ||
| Updated: "update", | ||
| Removed: "delete" | ||
| }[value]; | ||
| } | ||
| function isString(variable) { | ||
| return typeof variable === "string"; | ||
| } | ||
| function isObject(variable) { | ||
| return typeof variable === "object" && variable !== null; | ||
| } | ||
| function customParseQueryString(url) { | ||
| if (!url) return []; | ||
| const queryString = url.split("?")[1]; | ||
| const parsedParams = querystring.parse(queryString); | ||
| const paramsArray = []; | ||
| for (const key in parsedParams) paramsArray.push([key, parsedParams[key]]); | ||
| return paramsArray; | ||
| } | ||
| function encodeStr(str) { | ||
| const len = str.length; | ||
| if (len === 0) return str; | ||
| const firstNullIndex = str.indexOf("\0"); | ||
| if (firstNullIndex === -1) return str; | ||
| const result = Array.from({ length: len + countNulls(str, firstNullIndex) }); | ||
| let pos = 0; | ||
| for (let i = 0; i < firstNullIndex; i++) result[pos++] = str[i]; | ||
| for (let i = firstNullIndex; i < len; i++) { | ||
| const char = str[i]; | ||
| if (char === "\0") { | ||
| result[pos++] = "\\"; | ||
| result[pos++] = "0"; | ||
| } else result[pos++] = char; | ||
| } | ||
| return path.posix.normalize(result.join("")); | ||
| } | ||
| function decodeStr(str) { | ||
| const len = str.length; | ||
| if (len === 0) return str; | ||
| const firstIndex = str.indexOf("\\0"); | ||
| if (firstIndex === -1) return str; | ||
| const result = Array.from({ length: len - countBackslashZeros(str, firstIndex) }); | ||
| let pos = 0; | ||
| for (let i$1 = 0; i$1 < firstIndex; i$1++) result[pos++] = str[i$1]; | ||
| let i = firstIndex; | ||
| while (i < len) if (str[i] === "\\" && str[i + 1] === "0") { | ||
| result[pos++] = "\0"; | ||
| i += 2; | ||
| } else result[pos++] = str[i++]; | ||
| return path.posix.normalize(result.join("")); | ||
| } | ||
| function getContentValue(content) { | ||
| if (content === null || content === void 0) throw new Error("Content cannot be null or undefined"); | ||
| return encodeStr(typeof content === "string" ? content : content.code || ""); | ||
| } | ||
| function countNulls(str, startIndex) { | ||
| let count = 0; | ||
| const len = str.length; | ||
| for (let i = startIndex; i < len; i++) if (str[i] === "\0") count++; | ||
| return count; | ||
| } | ||
| function countBackslashZeros(str, startIndex) { | ||
| let count = 0; | ||
| const len = str.length; | ||
| for (let i = startIndex; i < len - 1; i++) if (str[i] === "\\" && str[i + 1] === "0") { | ||
| count++; | ||
| i++; | ||
| } | ||
| return count; | ||
| } | ||
| function removeQuery(pathe) { | ||
| const queryIndex = pathe.indexOf("?"); | ||
| if (queryIndex !== -1) return path.posix.normalize(pathe.slice(0, queryIndex)); | ||
| return path.posix.normalize(pathe); | ||
| } | ||
| function isStartsWithSlash(str) { | ||
| return str?.startsWith("/"); | ||
| } | ||
| function appendQuery(id, query) { | ||
| if (!query.length) return id; | ||
| return `${id}?${stringifyQuery(query)}`; | ||
| } | ||
| function stringifyQuery(query) { | ||
| if (!query.length) return ""; | ||
| let queryStr = ""; | ||
| for (const [key, value] of query) queryStr += `${key}${value ? `=${value}` : ""}&`; | ||
| return `${queryStr.slice(0, -1)}`; | ||
| } | ||
| const CSS_LANGS_RES = [ | ||
| [/\.(less)(?:$|\?)/, "less"], | ||
| [/\.(scss|sass)(?:$|\?)/, "sass"], | ||
| [/\.(styl|stylus)(?:$|\?)/, "stylus"], | ||
| [/\.(css)(?:$|\?)/, "css"] | ||
| ]; | ||
| const JS_LANGS_RES = [ | ||
| [/\.(js|mjs|cjs)(?:$|\?)/, "js"], | ||
| [/\.(jsx)(?:$|\?)/, "jsx"], | ||
| [/\.(ts|cts|mts)(?:$|\?)/, "ts"], | ||
| [/\.(tsx)(?:$|\?)/, "tsx"] | ||
| ]; | ||
| function getCssModuleType(id) { | ||
| for (const [reg, lang] of CSS_LANGS_RES) if (reg.test(id)) return lang; | ||
| return null; | ||
| } | ||
| function getJsModuleType(id) { | ||
| for (const [reg, lang] of JS_LANGS_RES) if (reg.test(id)) return lang; | ||
| return null; | ||
| } | ||
| function formatLoadModuleType(id) { | ||
| const cssModuleType = getCssModuleType(id); | ||
| if (cssModuleType) return cssModuleType; | ||
| const jsModuleType = getJsModuleType(id); | ||
| if (jsModuleType) return jsModuleType; | ||
| return "js"; | ||
| } | ||
| function formatTransformModuleType(id) { | ||
| return formatLoadModuleType(id); | ||
| } | ||
| //#endregion | ||
| //#region src/farm/index.ts | ||
| function getFarmPlugin(factory) { | ||
| return ((userOptions) => { | ||
| const plugins = toArray(factory(userOptions, { framework: "farm" })).map((rawPlugin) => { | ||
| const plugin = toFarmPlugin(rawPlugin, userOptions); | ||
| if (rawPlugin.farm) Object.assign(plugin, rawPlugin.farm); | ||
| return plugin; | ||
| }); | ||
| return plugins.length === 1 ? plugins[0] : plugins; | ||
| }); | ||
| } | ||
| function toFarmPlugin(plugin, options) { | ||
| const farmPlugin = { | ||
| name: plugin.name, | ||
| priority: convertEnforceToPriority(plugin.enforce) | ||
| }; | ||
| if (plugin.farm) Object.keys(plugin.farm).forEach((key) => { | ||
| const value = plugin.farm[key]; | ||
| if (value) Reflect.set(farmPlugin, key, value); | ||
| }); | ||
| if (plugin.buildStart) { | ||
| const _buildStart = plugin.buildStart; | ||
| farmPlugin.buildStart = { async executor(_, context) { | ||
| await _buildStart.call(createFarmContext(context)); | ||
| } }; | ||
| } | ||
| if (plugin.resolveId) { | ||
| const _resolveId = plugin.resolveId; | ||
| let filters = []; | ||
| if (options) filters = options?.filters ?? []; | ||
| farmPlugin.resolve = { | ||
| filters: { | ||
| sources: filters.length ? filters : [".*"], | ||
| importers: [".*"] | ||
| }, | ||
| async executor(params, context) { | ||
| const resolvedIdPath = path.resolve(params.importer ?? ""); | ||
| const id = decodeStr(params.source); | ||
| const { handler, filter } = normalizeObjectHook("resolveId", _resolveId); | ||
| if (!filter(id)) return null; | ||
| let isEntry = false; | ||
| if (isObject(params.kind) && "entry" in params.kind) isEntry = params.kind.entry === "index"; | ||
| const farmContext = createFarmContext(context, resolvedIdPath); | ||
| const resolveIdResult = await handler.call(Object.assign(unpluginContext(context), farmContext), id, resolvedIdPath ?? null, { isEntry }); | ||
| if (isString(resolveIdResult)) return { | ||
| resolvedPath: removeQuery(encodeStr(resolveIdResult)), | ||
| query: customParseQueryString(resolveIdResult), | ||
| sideEffects: true, | ||
| external: false, | ||
| meta: {} | ||
| }; | ||
| if (isObject(resolveIdResult)) return { | ||
| resolvedPath: removeQuery(encodeStr(resolveIdResult?.id)), | ||
| query: customParseQueryString(resolveIdResult?.id), | ||
| sideEffects: false, | ||
| external: Boolean(resolveIdResult?.external), | ||
| meta: {} | ||
| }; | ||
| if (!isStartsWithSlash(params.source)) return null; | ||
| } | ||
| }; | ||
| } | ||
| if (plugin.load) { | ||
| const _load = plugin.load; | ||
| farmPlugin.load = { | ||
| filters: { resolvedPaths: [".*"] }, | ||
| async executor(params, context) { | ||
| const id = appendQuery(decodeStr(params.resolvedPath), params.query); | ||
| const loader = formatTransformModuleType(id); | ||
| if (plugin.loadInclude && !plugin.loadInclude?.(id)) return null; | ||
| const { handler, filter } = normalizeObjectHook("load", _load); | ||
| if (!filter(id)) return null; | ||
| const farmContext = createFarmContext(context, id); | ||
| return { | ||
| content: getContentValue(await handler.call(Object.assign(unpluginContext(context), farmContext), id)), | ||
| moduleType: loader | ||
| }; | ||
| } | ||
| }; | ||
| } | ||
| if (plugin.transform) { | ||
| const _transform = plugin.transform; | ||
| farmPlugin.transform = { | ||
| filters: { | ||
| resolvedPaths: [".*"], | ||
| moduleTypes: [".*"] | ||
| }, | ||
| async executor(params, context) { | ||
| const id = appendQuery(decodeStr(params.resolvedPath), params.query); | ||
| const loader = formatTransformModuleType(id); | ||
| if (plugin.transformInclude && !plugin.transformInclude(id)) return null; | ||
| const { handler, filter } = normalizeObjectHook("transform", _transform); | ||
| if (!filter(id, params.content)) return null; | ||
| const farmContext = createFarmContext(context, id); | ||
| const resource = await handler.call(Object.assign(unpluginContext(context), farmContext), params.content, id); | ||
| if (resource && typeof resource !== "string") return { | ||
| content: getContentValue(resource), | ||
| moduleType: loader, | ||
| sourceMap: typeof resource.map === "object" && resource.map !== null ? JSON.stringify(resource.map) : void 0 | ||
| }; | ||
| } | ||
| }; | ||
| } | ||
| if (plugin.watchChange) { | ||
| const _watchChange = plugin.watchChange; | ||
| farmPlugin.updateModules = { async executor(param, context) { | ||
| const updatePathContent = param.paths[0]; | ||
| const ModifiedPath = updatePathContent[0]; | ||
| const eventChange = convertWatchEventChange(updatePathContent[1]); | ||
| await _watchChange.call(createFarmContext(context), ModifiedPath, { event: eventChange }); | ||
| } }; | ||
| } | ||
| if (plugin.buildEnd) { | ||
| const _buildEnd = plugin.buildEnd; | ||
| farmPlugin.buildEnd = { async executor(_, context) { | ||
| await _buildEnd.call(createFarmContext(context)); | ||
| } }; | ||
| } | ||
| if (plugin.writeBundle) { | ||
| const _writeBundle = plugin.writeBundle; | ||
| farmPlugin.finish = { async executor() { | ||
| await _writeBundle(); | ||
| } }; | ||
| } | ||
| return farmPlugin; | ||
| } | ||
| //#endregion | ||
| //#region src/rollup/index.ts | ||
| function getRollupPlugin(factory) { | ||
| return ((userOptions) => { | ||
| const plugins = toArray(factory(userOptions, { framework: "rollup" })).map((plugin) => toRollupPlugin(plugin, "rollup")); | ||
| return plugins.length === 1 ? plugins[0] : plugins; | ||
| }); | ||
| } | ||
| function toRollupPlugin(plugin, key) { | ||
| const nativeFilter = key === "rolldown"; | ||
| if (plugin.resolveId && !nativeFilter && typeof plugin.resolveId === "object" && plugin.resolveId.filter) { | ||
| const resolveIdHook = plugin.resolveId; | ||
| const { handler, filter } = normalizeObjectHook("load", resolveIdHook); | ||
| replaceHookHandler("resolveId", resolveIdHook, function(...args) { | ||
| const [id] = args; | ||
| if (!supportNativeFilter(this, key) && !filter(id)) return; | ||
| return handler.apply(this, args); | ||
| }); | ||
| } | ||
| if (plugin.load && (plugin.loadInclude || !nativeFilter && typeof plugin.load === "object" && plugin.load.filter)) { | ||
| const loadHook = plugin.load; | ||
| const { handler, filter } = normalizeObjectHook("load", loadHook); | ||
| replaceHookHandler("load", loadHook, function(...args) { | ||
| const [id] = args; | ||
| if (plugin.loadInclude && !plugin.loadInclude(id)) return; | ||
| if (!supportNativeFilter(this, key) && !filter(id)) return; | ||
| return handler.apply(this, args); | ||
| }); | ||
| } | ||
| if (plugin.transform && (plugin.transformInclude || !nativeFilter && typeof plugin.transform === "object" && plugin.transform.filter)) { | ||
| const transformHook = plugin.transform; | ||
| const { handler, filter } = normalizeObjectHook("transform", transformHook); | ||
| replaceHookHandler("transform", transformHook, function(...args) { | ||
| const [code, id] = args; | ||
| if (plugin.transformInclude && !plugin.transformInclude(id)) return; | ||
| if (!supportNativeFilter(this, key) && !filter(id, code)) return; | ||
| return handler.apply(this, args); | ||
| }); | ||
| } | ||
| if (plugin[key]) Object.assign(plugin, plugin[key]); | ||
| return plugin; | ||
| function replaceHookHandler(name, hook, handler) { | ||
| if (typeof hook === "function") plugin[name] = handler; | ||
| else hook.handler = handler; | ||
| } | ||
| } | ||
| function supportNativeFilter(context, framework) { | ||
| if (framework === "unloader") return false; | ||
| if (framework === "vite") return !!context?.meta?.viteVersion; | ||
| if (framework === "rolldown") return true; | ||
| const rollupVersion = context?.meta?.rollupVersion; | ||
| if (!rollupVersion) return false; | ||
| const [major, minor] = rollupVersion.split("."); | ||
| return Number(major) > 4 || Number(major) === 4 && Number(minor) >= 40; | ||
| } | ||
| //#endregion | ||
| //#region src/rolldown/index.ts | ||
| function getRolldownPlugin(factory) { | ||
| return ((userOptions) => { | ||
| const plugins = toArray(factory(userOptions, { framework: "rolldown" })).map((rawPlugin) => { | ||
| return toRollupPlugin(rawPlugin, "rolldown"); | ||
| }); | ||
| return plugins.length === 1 ? plugins[0] : plugins; | ||
| }); | ||
| } | ||
| //#endregion | ||
| //#region src/rspack/index.ts | ||
| const TRANSFORM_LOADER$1 = resolve(import.meta.dirname, "rspack/loaders/transform.mjs"); | ||
| const LOAD_LOADER$1 = resolve(import.meta.dirname, "rspack/loaders/load.mjs"); | ||
| function getRspackPlugin(factory) { | ||
| return (userOptions) => { | ||
| return { apply(compiler) { | ||
| const VIRTUAL_MODULE_PREFIX = resolve(compiler.options.context ?? process.cwd(), "node_modules/.virtual", compiler.rspack.experiments.VirtualModulesPlugin ? "" : process.pid.toString()); | ||
| const meta = { | ||
| framework: "rspack", | ||
| rspack: { compiler } | ||
| }; | ||
| const rawPlugins = toArray(factory(userOptions, meta)); | ||
| for (const rawPlugin of rawPlugins) { | ||
| const plugin = Object.assign(rawPlugin, { | ||
| __unpluginMeta: meta, | ||
| __virtualModulePrefix: VIRTUAL_MODULE_PREFIX | ||
| }); | ||
| const externalModules = /* @__PURE__ */ new Set(); | ||
| if (plugin.resolveId) { | ||
| const createPlugin = (plugin$1) => { | ||
| if (compiler.rspack.experiments.VirtualModulesPlugin) return new compiler.rspack.experiments.VirtualModulesPlugin(); | ||
| return new FakeVirtualModulesPlugin(plugin$1); | ||
| }; | ||
| const vfs = createPlugin(plugin); | ||
| vfs.apply(compiler); | ||
| const vfsModules = /* @__PURE__ */ new Map(); | ||
| plugin.__vfsModules = vfsModules; | ||
| plugin.__vfs = vfs; | ||
| compiler.hooks.compilation.tap(plugin.name, (compilation, { normalModuleFactory }) => { | ||
| normalModuleFactory.hooks.resolve.tapPromise(plugin.name, async (resolveData) => { | ||
| const id = normalizeAbsolutePath(resolveData.request); | ||
| const requestContext = resolveData.contextInfo; | ||
| let importer = requestContext.issuer !== "" ? requestContext.issuer : void 0; | ||
| const isEntry = requestContext.issuer === ""; | ||
| if (importer?.startsWith(plugin.__virtualModulePrefix)) importer = decodeURIComponent(importer.slice(plugin.__virtualModulePrefix.length)); | ||
| const context = createBuildContext$1(compiler, compilation); | ||
| let error; | ||
| const pluginContext = { | ||
| error(msg) { | ||
| if (error == null) error = normalizeMessage$1(msg); | ||
| else console.error(`unplugin/rspack: multiple errors returned from resolveId hook: ${msg}`); | ||
| }, | ||
| warn(msg) { | ||
| console.warn(`unplugin/rspack: warning from resolveId hook: ${msg}`); | ||
| } | ||
| }; | ||
| const { handler, filter } = normalizeObjectHook("resolveId", plugin.resolveId); | ||
| if (!filter(id)) return; | ||
| const resolveIdResult = await handler.call({ | ||
| ...context, | ||
| ...pluginContext | ||
| }, id, importer, { isEntry }); | ||
| if (error != null) throw error; | ||
| if (resolveIdResult == null) return; | ||
| let resolved = typeof resolveIdResult === "string" ? resolveIdResult : resolveIdResult.id; | ||
| if (typeof resolveIdResult === "string" ? false : resolveIdResult.external === true) externalModules.add(resolved); | ||
| let isVirtual = true; | ||
| try { | ||
| (compiler.inputFileSystem?.statSync ?? fs.statSync)(resolved); | ||
| isVirtual = false; | ||
| } catch { | ||
| isVirtual = !isVirtualModuleId(resolved, plugin); | ||
| } | ||
| if (isVirtual) { | ||
| const encodedVirtualPath = encodeVirtualModuleId(resolved, plugin); | ||
| if (!vfsModules.has(resolved)) { | ||
| const fsPromise = Promise.resolve(vfs.writeModule(encodedVirtualPath, "")); | ||
| vfsModules.set(resolved, fsPromise); | ||
| await fsPromise; | ||
| } else await vfsModules.get(resolved); | ||
| resolved = encodedVirtualPath; | ||
| } | ||
| resolveData.request = resolved; | ||
| }); | ||
| }); | ||
| } | ||
| if (plugin.load) compiler.options.module.rules.unshift({ | ||
| enforce: plugin.enforce, | ||
| include(id) { | ||
| if (isVirtualModuleId(id, plugin)) id = decodeVirtualModuleId(id, plugin); | ||
| if (plugin.loadInclude && !plugin.loadInclude(id)) return false; | ||
| const { filter } = normalizeObjectHook("load", plugin.load); | ||
| if (!filter(id)) return false; | ||
| return !externalModules.has(id); | ||
| }, | ||
| use: [{ | ||
| loader: LOAD_LOADER$1, | ||
| options: { plugin } | ||
| }], | ||
| type: "javascript/auto" | ||
| }); | ||
| if (plugin.transform) compiler.options.module.rules.unshift({ | ||
| enforce: plugin.enforce, | ||
| use(data) { | ||
| return transformUse(data, plugin, TRANSFORM_LOADER$1); | ||
| } | ||
| }); | ||
| if (plugin.rspack) plugin.rspack(compiler); | ||
| if (plugin.watchChange || plugin.buildStart) compiler.hooks.make.tapPromise(plugin.name, async (compilation) => { | ||
| const context = createBuildContext$1(compiler, compilation); | ||
| if (plugin.watchChange && (compiler.modifiedFiles || compiler.removedFiles)) { | ||
| const promises = []; | ||
| if (compiler.modifiedFiles) compiler.modifiedFiles.forEach((file) => promises.push(Promise.resolve(plugin.watchChange.call(context, file, { event: "update" })))); | ||
| if (compiler.removedFiles) compiler.removedFiles.forEach((file) => promises.push(Promise.resolve(plugin.watchChange.call(context, file, { event: "delete" })))); | ||
| await Promise.all(promises); | ||
| } | ||
| if (plugin.buildStart) return await plugin.buildStart.call(context); | ||
| }); | ||
| if (plugin.buildEnd) compiler.hooks.emit.tapPromise(plugin.name, async (compilation) => { | ||
| await plugin.buildEnd.call(createBuildContext$1(compiler, compilation)); | ||
| }); | ||
| if (plugin.writeBundle) compiler.hooks.afterEmit.tapPromise(plugin.name, async () => { | ||
| await plugin.writeBundle(); | ||
| }); | ||
| } | ||
| } }; | ||
| }; | ||
| } | ||
| //#endregion | ||
| //#region src/unloader/index.ts | ||
| function getUnloaderPlugin(factory) { | ||
| return ((userOptions) => { | ||
| const plugins = toArray(factory(userOptions, { framework: "unloader" })).map((rawPlugin) => { | ||
| return toRollupPlugin(rawPlugin, "unloader"); | ||
| }); | ||
| return plugins.length === 1 ? plugins[0] : plugins; | ||
| }); | ||
| } | ||
| //#endregion | ||
| //#region src/vite/index.ts | ||
| function getVitePlugin(factory) { | ||
| return ((userOptions) => { | ||
| const plugins = toArray(factory(userOptions, { framework: "vite" })).map((rawPlugin) => { | ||
| return toRollupPlugin(rawPlugin, "vite"); | ||
| }); | ||
| return plugins.length === 1 ? plugins[0] : plugins; | ||
| }); | ||
| } | ||
| //#endregion | ||
| //#region src/webpack/index.ts | ||
| const TRANSFORM_LOADER = resolve(import.meta.dirname, "webpack/loaders/transform.mjs"); | ||
| const LOAD_LOADER = resolve(import.meta.dirname, "webpack/loaders/load.mjs"); | ||
| function getWebpackPlugin(factory) { | ||
| return (userOptions) => { | ||
| return { apply(compiler) { | ||
| const VIRTUAL_MODULE_PREFIX = resolve(compiler.options.context ?? process$1.cwd(), "_virtual_"); | ||
| const meta = { | ||
| framework: "webpack", | ||
| webpack: { compiler } | ||
| }; | ||
| const rawPlugins = toArray(factory(userOptions, meta)); | ||
| for (const rawPlugin of rawPlugins) { | ||
| const plugin = Object.assign(rawPlugin, { | ||
| __unpluginMeta: meta, | ||
| __virtualModulePrefix: VIRTUAL_MODULE_PREFIX | ||
| }); | ||
| const externalModules = /* @__PURE__ */ new Set(); | ||
| if (plugin.resolveId) { | ||
| let vfs = compiler.options.plugins.find((i) => i instanceof VirtualModulesPlugin); | ||
| if (!vfs) { | ||
| vfs = new VirtualModulesPlugin(); | ||
| compiler.options.plugins.push(vfs); | ||
| } | ||
| const vfsModules = /* @__PURE__ */ new Set(); | ||
| plugin.__vfsModules = vfsModules; | ||
| plugin.__vfs = vfs; | ||
| const resolverPlugin = { apply(resolver) { | ||
| const target = resolver.ensureHook("resolve"); | ||
| resolver.getHook("resolve").tapAsync(plugin.name, async (request, resolveContext, callback) => { | ||
| if (!request.request) return callback(); | ||
| if (normalizeAbsolutePath(request.request).startsWith(plugin.__virtualModulePrefix)) return callback(); | ||
| const id = normalizeAbsolutePath(request.request); | ||
| const requestContext = request.context; | ||
| let importer = requestContext.issuer !== "" ? requestContext.issuer : void 0; | ||
| const isEntry = requestContext.issuer === ""; | ||
| if (importer?.startsWith(plugin.__virtualModulePrefix)) importer = decodeURIComponent(importer.slice(plugin.__virtualModulePrefix.length)); | ||
| const fileDependencies = /* @__PURE__ */ new Set(); | ||
| const context = createBuildContext({ | ||
| addWatchFile(file) { | ||
| fileDependencies.add(file); | ||
| resolveContext.fileDependencies?.add(file); | ||
| }, | ||
| getWatchFiles() { | ||
| return Array.from(fileDependencies); | ||
| } | ||
| }, compiler); | ||
| let error; | ||
| const pluginContext = { | ||
| error(msg) { | ||
| if (error == null) error = normalizeMessage(msg); | ||
| else console.error(`unplugin/webpack: multiple errors returned from resolveId hook: ${msg}`); | ||
| }, | ||
| warn(msg) { | ||
| console.warn(`unplugin/webpack: warning from resolveId hook: ${msg}`); | ||
| } | ||
| }; | ||
| const { handler, filter } = normalizeObjectHook("resolveId", plugin.resolveId); | ||
| if (!filter(id)) return callback(); | ||
| const resolveIdResult = await handler.call({ | ||
| ...context, | ||
| ...pluginContext | ||
| }, id, importer, { isEntry }); | ||
| if (error != null) return callback(error); | ||
| if (resolveIdResult == null) return callback(); | ||
| let resolved = typeof resolveIdResult === "string" ? resolveIdResult : resolveIdResult.id; | ||
| if (typeof resolveIdResult === "string" ? false : resolveIdResult.external === true) externalModules.add(resolved); | ||
| if (!fs.existsSync(resolved)) { | ||
| resolved = normalizeAbsolutePath(plugin.__virtualModulePrefix + encodeURIComponent(resolved)); | ||
| if (!vfsModules.has(resolved)) { | ||
| plugin.__vfs.writeModule(resolved, ""); | ||
| vfsModules.add(resolved); | ||
| } | ||
| } | ||
| const newRequest = { | ||
| ...request, | ||
| request: resolved | ||
| }; | ||
| resolver.doResolve(target, newRequest, null, resolveContext, callback); | ||
| }); | ||
| } }; | ||
| compiler.options.resolve.plugins = compiler.options.resolve.plugins || []; | ||
| compiler.options.resolve.plugins.push(resolverPlugin); | ||
| } | ||
| if (plugin.load) compiler.options.module.rules.unshift({ | ||
| include(id) { | ||
| return shouldLoad(id, plugin, externalModules); | ||
| }, | ||
| enforce: plugin.enforce, | ||
| use: [{ | ||
| loader: LOAD_LOADER, | ||
| options: { plugin } | ||
| }], | ||
| type: "javascript/auto" | ||
| }); | ||
| if (plugin.transform) compiler.options.module.rules.unshift({ | ||
| enforce: plugin.enforce, | ||
| use(data) { | ||
| return transformUse(data, plugin, TRANSFORM_LOADER); | ||
| } | ||
| }); | ||
| if (plugin.webpack) plugin.webpack(compiler); | ||
| if (plugin.watchChange || plugin.buildStart) compiler.hooks.make.tapPromise(plugin.name, async (compilation) => { | ||
| const context = createBuildContext(contextOptionsFromCompilation(compilation), compiler, compilation); | ||
| if (plugin.watchChange && (compiler.modifiedFiles || compiler.removedFiles)) { | ||
| const promises = []; | ||
| if (compiler.modifiedFiles) compiler.modifiedFiles.forEach((file) => promises.push(Promise.resolve(plugin.watchChange.call(context, file, { event: "update" })))); | ||
| if (compiler.removedFiles) compiler.removedFiles.forEach((file) => promises.push(Promise.resolve(plugin.watchChange.call(context, file, { event: "delete" })))); | ||
| await Promise.all(promises); | ||
| } | ||
| if (plugin.buildStart) return await plugin.buildStart.call(context); | ||
| }); | ||
| if (plugin.buildEnd) compiler.hooks.emit.tapPromise(plugin.name, async (compilation) => { | ||
| await plugin.buildEnd.call(createBuildContext(contextOptionsFromCompilation(compilation), compiler, compilation)); | ||
| }); | ||
| if (plugin.writeBundle) compiler.hooks.afterEmit.tapPromise(plugin.name, async () => { | ||
| await plugin.writeBundle(); | ||
| }); | ||
| } | ||
| } }; | ||
| }; | ||
| } | ||
| function shouldLoad(id, plugin, externalModules) { | ||
| if (id.startsWith(plugin.__virtualModulePrefix)) id = decodeURIComponent(id.slice(plugin.__virtualModulePrefix.length)); | ||
| if (plugin.loadInclude && !plugin.loadInclude(id)) return false; | ||
| const { filter } = normalizeObjectHook("load", plugin.load); | ||
| if (!filter(id)) return false; | ||
| return !externalModules.has(id); | ||
| } | ||
| //#endregion | ||
| //#region src/define.ts | ||
| function createUnplugin(factory) { | ||
| return { | ||
| get esbuild() { | ||
| return getEsbuildPlugin(factory); | ||
| }, | ||
| get rollup() { | ||
| return getRollupPlugin(factory); | ||
| }, | ||
| get vite() { | ||
| return getVitePlugin(factory); | ||
| }, | ||
| get rolldown() { | ||
| return getRolldownPlugin(factory); | ||
| }, | ||
| get webpack() { | ||
| return getWebpackPlugin(factory); | ||
| }, | ||
| get rspack() { | ||
| return getRspackPlugin(factory); | ||
| }, | ||
| get farm() { | ||
| return getFarmPlugin(factory); | ||
| }, | ||
| get unloader() { | ||
| return getUnloaderPlugin(factory); | ||
| }, | ||
| get bun() { | ||
| return getBunPlugin(factory); | ||
| }, | ||
| get raw() { | ||
| return factory; | ||
| } | ||
| }; | ||
| } | ||
| function createEsbuildPlugin(factory) { | ||
| return getEsbuildPlugin(factory); | ||
| } | ||
| function createRollupPlugin(factory) { | ||
| return getRollupPlugin(factory); | ||
| } | ||
| function createVitePlugin(factory) { | ||
| return getVitePlugin(factory); | ||
| } | ||
| function createRolldownPlugin(factory) { | ||
| return getRolldownPlugin(factory); | ||
| } | ||
| function createWebpackPlugin(factory) { | ||
| return getWebpackPlugin(factory); | ||
| } | ||
| function createRspackPlugin(factory) { | ||
| return getRspackPlugin(factory); | ||
| } | ||
| function createFarmPlugin(factory) { | ||
| return getFarmPlugin(factory); | ||
| } | ||
| function createUnloaderPlugin(factory) { | ||
| return getUnloaderPlugin(factory); | ||
| } | ||
| function createBunPlugin(factory) { | ||
| return getBunPlugin(factory); | ||
| } | ||
| //#endregion | ||
| export { createBunPlugin, createEsbuildPlugin, createFarmPlugin, createRolldownPlugin, createRollupPlugin, createRspackPlugin, createUnloaderPlugin, createUnplugin, createVitePlugin, createWebpackPlugin }; |
| import { LoaderContext } from "@rspack/core"; | ||
| //#region src/rspack/loaders/load.d.ts | ||
| declare function load(this: LoaderContext, source: string, map: any): Promise<void>; | ||
| //#endregion | ||
| export { load as default }; |
| import { n as normalizeObjectHook } from "../../context-BA9Bk3zk.mjs"; | ||
| import { t as normalizeAbsolutePath } from "../../webpack-like-BEGRU-K6.mjs"; | ||
| import { n as createContext, t as createBuildContext } from "../../context-DTC5O8j3.mjs"; | ||
| import { i as isVirtualModuleId, n as decodeVirtualModuleId } from "../../utils-C0A28-Cs.mjs"; | ||
| //#region src/rspack/loaders/load.ts | ||
| async function load(source, map) { | ||
| const callback = this.async(); | ||
| const { plugin } = this.query; | ||
| let id = this.resource; | ||
| if (!plugin?.load || !id) return callback(null, source, map); | ||
| if (isVirtualModuleId(id, plugin)) id = decodeVirtualModuleId(id, plugin); | ||
| const context = createContext(this); | ||
| const { handler } = normalizeObjectHook("load", plugin.load); | ||
| try { | ||
| const res = await handler.call(Object.assign({}, this._compilation && createBuildContext(this._compiler, this._compilation, this), context), normalizeAbsolutePath(id)); | ||
| if (res == null) callback(null, source, map); | ||
| else if (typeof res !== "string") callback(null, res.code, res.map ?? map); | ||
| else callback(null, res, map); | ||
| } catch (error) { | ||
| if (error instanceof Error) callback(error); | ||
| else callback(new Error(String(error))); | ||
| } | ||
| } | ||
| //#endregion | ||
| export { load as default }; |
| import { LoaderContext } from "@rspack/core"; | ||
| //#region src/rspack/loaders/transform.d.ts | ||
| declare function transform(this: LoaderContext, source: string, map: any): Promise<void>; | ||
| //#endregion | ||
| export { transform as default }; |
| import { n as normalizeObjectHook } from "../../context-BA9Bk3zk.mjs"; | ||
| import { n as createContext, t as createBuildContext } from "../../context-DTC5O8j3.mjs"; | ||
| //#region src/rspack/loaders/transform.ts | ||
| async function transform(source, map) { | ||
| const callback = this.async(); | ||
| const { plugin } = this.query; | ||
| if (!plugin?.transform) return callback(null, source, map); | ||
| const id = this.resource; | ||
| const context = createContext(this); | ||
| const { handler, filter } = normalizeObjectHook("transform", plugin.transform); | ||
| if (!filter(this.resource, source)) return callback(null, source, map); | ||
| try { | ||
| const res = await handler.call(Object.assign({}, this._compilation && createBuildContext(this._compiler, this._compilation, this), context), source, id); | ||
| if (res == null) callback(null, source, map); | ||
| else if (typeof res !== "string") callback(null, res.code, map == null ? map : res.map || map); | ||
| else callback(null, res, map); | ||
| } catch (error) { | ||
| if (error instanceof Error) callback(error); | ||
| else callback(new Error(String(error))); | ||
| } | ||
| } | ||
| //#endregion | ||
| export { transform as default }; |
| import { basename, dirname, resolve } from "node:path"; | ||
| import fs from "node:fs"; | ||
| //#region src/rspack/utils.ts | ||
| function encodeVirtualModuleId(id, plugin) { | ||
| return resolve(plugin.__virtualModulePrefix, encodeURIComponent(id)); | ||
| } | ||
| function decodeVirtualModuleId(encoded, _plugin) { | ||
| return decodeURIComponent(basename(encoded)); | ||
| } | ||
| function isVirtualModuleId(encoded, plugin) { | ||
| return dirname(encoded) === plugin.__virtualModulePrefix; | ||
| } | ||
| var FakeVirtualModulesPlugin = class FakeVirtualModulesPlugin { | ||
| name = "FakeVirtualModulesPlugin"; | ||
| static counters = /* @__PURE__ */ new Map(); | ||
| static initCleanup = false; | ||
| constructor(plugin) { | ||
| this.plugin = plugin; | ||
| if (!FakeVirtualModulesPlugin.initCleanup) { | ||
| FakeVirtualModulesPlugin.initCleanup = true; | ||
| process.once("exit", () => { | ||
| FakeVirtualModulesPlugin.counters.forEach((_, dir) => { | ||
| fs.rmSync(dir, { | ||
| recursive: true, | ||
| force: true | ||
| }); | ||
| }); | ||
| }); | ||
| } | ||
| } | ||
| apply(compiler) { | ||
| const dir = this.plugin.__virtualModulePrefix; | ||
| if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); | ||
| const counter = FakeVirtualModulesPlugin.counters.get(dir) ?? 0; | ||
| FakeVirtualModulesPlugin.counters.set(dir, counter + 1); | ||
| compiler.hooks.shutdown.tap(this.name, () => { | ||
| const counter$1 = (FakeVirtualModulesPlugin.counters.get(dir) ?? 1) - 1; | ||
| if (counter$1 === 0) { | ||
| FakeVirtualModulesPlugin.counters.delete(dir); | ||
| fs.rmSync(dir, { | ||
| recursive: true, | ||
| force: true | ||
| }); | ||
| } else FakeVirtualModulesPlugin.counters.set(dir, counter$1); | ||
| }); | ||
| } | ||
| async writeModule(file) { | ||
| return fs.promises.writeFile(file, ""); | ||
| } | ||
| }; | ||
| //#endregion | ||
| export { isVirtualModuleId as i, decodeVirtualModuleId as n, encodeVirtualModuleId as r, FakeVirtualModulesPlugin as t }; |
| import { n as normalizeObjectHook } from "./context-BA9Bk3zk.mjs"; | ||
| import { isAbsolute, normalize } from "node:path"; | ||
| //#region src/utils/webpack-like.ts | ||
| function transformUse(data, plugin, transformLoader) { | ||
| if (data.resource == null) return []; | ||
| const id = normalizeAbsolutePath(data.resource + (data.resourceQuery || "")); | ||
| if (plugin.transformInclude && !plugin.transformInclude(id)) return []; | ||
| const { filter } = normalizeObjectHook("load", plugin.transform); | ||
| if (!filter(id)) return []; | ||
| return [{ | ||
| loader: transformLoader, | ||
| options: { plugin }, | ||
| ident: plugin.name | ||
| }]; | ||
| } | ||
| /** | ||
| * Normalizes a given path when it's absolute. Normalizing means returning a new path by converting | ||
| * the input path to the native os format. This is useful in cases where we want to normalize | ||
| * the `id` argument of a hook. Any absolute ids should be in the default format | ||
| * of the operating system. Any relative imports or node_module imports should remain | ||
| * untouched. | ||
| * | ||
| * @param path - Path to normalize. | ||
| * @returns a new normalized path. | ||
| */ | ||
| function normalizeAbsolutePath(path$1) { | ||
| if (isAbsolute(path$1)) return normalize(path$1); | ||
| else return path$1; | ||
| } | ||
| //#endregion | ||
| export { transformUse as n, normalizeAbsolutePath as t }; |
| import { LoaderContext } from "webpack"; | ||
| //#region src/webpack/loaders/load.d.ts | ||
| declare function load(this: LoaderContext<any>, source: string, map: any): Promise<void>; | ||
| //#endregion | ||
| export { load as default }; |
| import { n as normalizeObjectHook } from "../../context-BA9Bk3zk.mjs"; | ||
| import { t as normalizeAbsolutePath } from "../../webpack-like-BEGRU-K6.mjs"; | ||
| import { n as createBuildContext, r as createContext } from "../../context-DCMwCoy8.mjs"; | ||
| //#region src/webpack/loaders/load.ts | ||
| async function load(source, map) { | ||
| const callback = this.async(); | ||
| const { plugin } = this.query; | ||
| let id = this.resource; | ||
| if (!plugin?.load || !id) return callback(null, source, map); | ||
| if (id.startsWith(plugin.__virtualModulePrefix)) id = decodeURIComponent(id.slice(plugin.__virtualModulePrefix.length)); | ||
| const context = createContext(this); | ||
| const { handler } = normalizeObjectHook("load", plugin.load); | ||
| const res = await handler.call(Object.assign({}, createBuildContext({ | ||
| addWatchFile: (file) => { | ||
| this.addDependency(file); | ||
| }, | ||
| getWatchFiles: () => { | ||
| return this.getDependencies(); | ||
| } | ||
| }, this._compiler, this._compilation, this), context), normalizeAbsolutePath(id)); | ||
| if (res == null) callback(null, source, map); | ||
| else if (typeof res !== "string") callback(null, res.code, res.map ?? map); | ||
| else callback(null, res, map); | ||
| } | ||
| //#endregion | ||
| export { load as default }; |
| import { LoaderContext } from "webpack"; | ||
| //#region src/webpack/loaders/transform.d.ts | ||
| declare function transform(this: LoaderContext<any>, source: string, map: any): Promise<void>; | ||
| //#endregion | ||
| export { transform as default }; |
| import { n as normalizeObjectHook } from "../../context-BA9Bk3zk.mjs"; | ||
| import { n as createBuildContext, r as createContext } from "../../context-DCMwCoy8.mjs"; | ||
| //#region src/webpack/loaders/transform.ts | ||
| async function transform(source, map) { | ||
| const callback = this.async(); | ||
| const { plugin } = this.query; | ||
| if (!plugin?.transform) return callback(null, source, map); | ||
| const context = createContext(this); | ||
| const { handler, filter } = normalizeObjectHook("transform", plugin.transform); | ||
| if (!filter(this.resource, source)) return callback(null, source, map); | ||
| try { | ||
| const res = await handler.call(Object.assign({}, createBuildContext({ | ||
| addWatchFile: (file) => { | ||
| this.addDependency(file); | ||
| }, | ||
| getWatchFiles: () => { | ||
| return this.getDependencies(); | ||
| } | ||
| }, this._compiler, this._compilation, this), context), source, this.resource); | ||
| if (res == null) callback(null, source, map); | ||
| else if (typeof res !== "string") callback(null, res.code, map == null ? map : res.map || map); | ||
| else callback(null, res, map); | ||
| } catch (error) { | ||
| if (error instanceof Error) callback(error); | ||
| else callback(new Error(String(error))); | ||
| } | ||
| } | ||
| //#endregion | ||
| export { transform as default }; |
+39
-39
| { | ||
| "name": "unplugin", | ||
| "type": "module", | ||
| "version": "2.3.10", | ||
| "version": "3.0.0-beta.1", | ||
| "description": "Unified plugin system for build tools", | ||
@@ -14,12 +14,12 @@ "license": "MIT", | ||
| "exports": { | ||
| ".": { | ||
| "import": "./dist/index.js", | ||
| "require": "./dist/index.cjs" | ||
| }, | ||
| "./dist/webpack/loaders/*": "./dist/webpack/loaders/*.cjs", | ||
| "./dist/rspack/loaders/*": "./dist/rspack/loaders/*.cjs" | ||
| ".": "./dist/index.mjs", | ||
| "./rspack/loaders/load": "./dist/rspack/loaders/load.mjs", | ||
| "./rspack/loaders/transform": "./dist/rspack/loaders/transform.mjs", | ||
| "./webpack/loaders/load": "./dist/webpack/loaders/load.mjs", | ||
| "./webpack/loaders/transform": "./dist/webpack/loaders/transform.mjs", | ||
| "./package.json": "./package.json" | ||
| }, | ||
| "main": "dist/index.js", | ||
| "module": "dist/index.js", | ||
| "types": "dist/index.d.ts", | ||
| "main": "./dist/index.mjs", | ||
| "module": "./dist/index.mjs", | ||
| "types": "./dist/index.d.mts", | ||
| "files": [ | ||
@@ -29,4 +29,7 @@ "dist" | ||
| "engines": { | ||
| "node": ">=18.12.0" | ||
| "node": "^20.19.0 || >=22.12.0" | ||
| }, | ||
| "publishConfig": { | ||
| "tag": "beta" | ||
| }, | ||
| "dependencies": { | ||
@@ -39,34 +42,31 @@ "@jridgewell/remapping": "^2.3.5", | ||
| "devDependencies": { | ||
| "@antfu/eslint-config": "^5.2.1", | ||
| "@antfu/ni": "^25.0.0", | ||
| "@antfu/eslint-config": "^6.2.0", | ||
| "@antfu/ni": "^27.0.1", | ||
| "@farmfe/cli": "^1.0.5", | ||
| "@farmfe/core": "^1.7.11", | ||
| "@rspack/cli": "^1.5.0", | ||
| "@rspack/core": "^1.5.0", | ||
| "@types/fs-extra": "^11.0.4", | ||
| "@types/node": "^24.3.0", | ||
| "@rspack/cli": "^1.6.0", | ||
| "@rspack/core": "^1.6.0", | ||
| "@types/node": "^24.10.0", | ||
| "@types/picomatch": "^4.0.2", | ||
| "ansis": "^4.1.0", | ||
| "bumpp": "^10.2.3", | ||
| "esbuild": "^0.25.9", | ||
| "esbuild-plugin-copy": "^2.1.1", | ||
| "eslint": "^9.33.0", | ||
| "eslint-plugin-format": "^1.0.1", | ||
| "fast-glob": "^3.3.3", | ||
| "fs-extra": "^11.3.1", | ||
| "jiti": "^2.5.1", | ||
| "lint-staged": "^16.1.5", | ||
| "magic-string": "^0.30.17", | ||
| "rolldown": "^1.0.0-beta.33", | ||
| "rollup": "^4.46.4", | ||
| "ansis": "^4.2.0", | ||
| "bumpp": "^10.3.1", | ||
| "bun-types-no-globals": "^1.2.22", | ||
| "esbuild": "^0.25.12", | ||
| "eslint": "^9.39.0", | ||
| "eslint-plugin-format": "^1.0.2", | ||
| "jiti": "^2.6.1", | ||
| "lint-staged": "^16.2.6", | ||
| "magic-string": "^0.30.21", | ||
| "rolldown": "^1.0.0-beta.46", | ||
| "rollup": "^4.52.5", | ||
| "simple-git-hooks": "^2.13.1", | ||
| "tsdown": "^0.14.1", | ||
| "typescript": "~5.9.2", | ||
| "tsdown": "^0.15.12", | ||
| "typescript": "~5.9.3", | ||
| "unloader": "^0.5.0", | ||
| "unplugin-unused": "^0.5.2", | ||
| "vite": "^7.1.3", | ||
| "vitest": "^3.2.4", | ||
| "webpack": "^5.101.3", | ||
| "unplugin-unused": "^0.5.5", | ||
| "vite": "^7.1.12", | ||
| "vitest": "^4.0.6", | ||
| "webpack": "^5.102.1", | ||
| "webpack-cli": "^6.0.1", | ||
| "unplugin": "2.3.10" | ||
| "unplugin": "3.0.0-beta.1" | ||
| }, | ||
@@ -77,3 +77,3 @@ "resolutions": { | ||
| "simple-git-hooks": { | ||
| "pre-commit": "pnpm i --frozen-lockfile --ignore-scripts --offline && npx lint-staged" | ||
| "pre-commit": "pnpm i --frozen-lockfile --ignore-scripts --offline && pnpm exec lint-staged" | ||
| }, | ||
@@ -93,5 +93,5 @@ "lint-staged": { | ||
| "release": "bumpp", | ||
| "test": "nr test:build && vitest run --pool=forks", | ||
| "test": "nr test:build && vitest run", | ||
| "test:build": "jiti scripts/buildFixtures.ts" | ||
| } | ||
| } |
+1
-0
@@ -18,2 +18,3 @@ # Unplugin | ||
| - [Farm](https://www.farmfe.org/) | ||
| - [Bun](https://bun.com/) | ||
| - And every framework built on top of them. | ||
@@ -20,0 +21,0 @@ |
| import { parse } from "./context-D49cMElb.js"; | ||
| import { createRequire } from "node:module"; | ||
| import { resolve } from "node:path"; | ||
| import { Buffer } from "node:buffer"; | ||
| import process from "node:process"; | ||
| //#region src/webpack/context.ts | ||
| function contextOptionsFromCompilation(compilation) { | ||
| return { | ||
| addWatchFile(file) { | ||
| (compilation.fileDependencies ?? compilation.compilationDependencies).add(file); | ||
| }, | ||
| getWatchFiles() { | ||
| return Array.from(compilation.fileDependencies ?? compilation.compilationDependencies); | ||
| } | ||
| }; | ||
| } | ||
| const require = createRequire(import.meta.url); | ||
| function getSource(fileSource) { | ||
| const webpack = require("webpack"); | ||
| return new webpack.sources.RawSource(typeof fileSource === "string" ? fileSource : Buffer.from(fileSource.buffer)); | ||
| } | ||
| function createBuildContext(options, compiler, compilation, loaderContext) { | ||
| return { | ||
| parse, | ||
| addWatchFile(id) { | ||
| options.addWatchFile(resolve(process.cwd(), id)); | ||
| }, | ||
| emitFile(emittedFile) { | ||
| const outFileName = emittedFile.fileName || emittedFile.name; | ||
| if (emittedFile.source && outFileName) { | ||
| if (!compilation) throw new Error("unplugin/webpack: emitFile outside supported hooks (buildStart, buildEnd, load, transform, watchChange)"); | ||
| compilation.emitAsset(outFileName, getSource(emittedFile.source)); | ||
| } | ||
| }, | ||
| getWatchFiles() { | ||
| return options.getWatchFiles(); | ||
| }, | ||
| getNativeBuildContext() { | ||
| return { | ||
| framework: "webpack", | ||
| compiler, | ||
| compilation, | ||
| loaderContext | ||
| }; | ||
| } | ||
| }; | ||
| } | ||
| function createContext(loader) { | ||
| return { | ||
| error: (error) => loader.emitError(normalizeMessage(error)), | ||
| warn: (message) => loader.emitWarning(normalizeMessage(message)) | ||
| }; | ||
| } | ||
| function normalizeMessage(error) { | ||
| const err = new Error(typeof error === "string" ? error : error.message); | ||
| if (typeof error === "object") { | ||
| err.stack = error.stack; | ||
| err.cause = error.meta; | ||
| } | ||
| return err; | ||
| } | ||
| //#endregion | ||
| export { contextOptionsFromCompilation, createBuildContext, createContext, normalizeMessage }; |
| const require_context = require('./context-DwbtaXxf.cjs'); | ||
| const node_path = require_context.__toESM(require("node:path")); | ||
| const node_buffer = require_context.__toESM(require("node:buffer")); | ||
| const node_process = require_context.__toESM(require("node:process")); | ||
| const node_module = require_context.__toESM(require("node:module")); | ||
| //#region src/webpack/context.ts | ||
| function contextOptionsFromCompilation(compilation) { | ||
| return { | ||
| addWatchFile(file) { | ||
| (compilation.fileDependencies ?? compilation.compilationDependencies).add(file); | ||
| }, | ||
| getWatchFiles() { | ||
| return Array.from(compilation.fileDependencies ?? compilation.compilationDependencies); | ||
| } | ||
| }; | ||
| } | ||
| const require$1 = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href); | ||
| function getSource(fileSource) { | ||
| const webpack = require$1("webpack"); | ||
| return new webpack.sources.RawSource(typeof fileSource === "string" ? fileSource : node_buffer.Buffer.from(fileSource.buffer)); | ||
| } | ||
| function createBuildContext(options, compiler, compilation, loaderContext) { | ||
| return { | ||
| parse: require_context.parse, | ||
| addWatchFile(id) { | ||
| options.addWatchFile((0, node_path.resolve)(node_process.default.cwd(), id)); | ||
| }, | ||
| emitFile(emittedFile) { | ||
| const outFileName = emittedFile.fileName || emittedFile.name; | ||
| if (emittedFile.source && outFileName) { | ||
| if (!compilation) throw new Error("unplugin/webpack: emitFile outside supported hooks (buildStart, buildEnd, load, transform, watchChange)"); | ||
| compilation.emitAsset(outFileName, getSource(emittedFile.source)); | ||
| } | ||
| }, | ||
| getWatchFiles() { | ||
| return options.getWatchFiles(); | ||
| }, | ||
| getNativeBuildContext() { | ||
| return { | ||
| framework: "webpack", | ||
| compiler, | ||
| compilation, | ||
| loaderContext | ||
| }; | ||
| } | ||
| }; | ||
| } | ||
| function createContext(loader) { | ||
| return { | ||
| error: (error) => loader.emitError(normalizeMessage(error)), | ||
| warn: (message) => loader.emitWarning(normalizeMessage(message)) | ||
| }; | ||
| } | ||
| function normalizeMessage(error) { | ||
| const err = new Error(typeof error === "string" ? error : error.message); | ||
| if (typeof error === "object") { | ||
| err.stack = error.stack; | ||
| err.cause = error.meta; | ||
| } | ||
| return err; | ||
| } | ||
| //#endregion | ||
| Object.defineProperty(exports, 'contextOptionsFromCompilation', { | ||
| enumerable: true, | ||
| get: function () { | ||
| return contextOptionsFromCompilation; | ||
| } | ||
| }); | ||
| Object.defineProperty(exports, 'createBuildContext', { | ||
| enumerable: true, | ||
| get: function () { | ||
| return createBuildContext; | ||
| } | ||
| }); | ||
| Object.defineProperty(exports, 'createContext', { | ||
| enumerable: true, | ||
| get: function () { | ||
| return createContext; | ||
| } | ||
| }); | ||
| Object.defineProperty(exports, 'normalizeMessage', { | ||
| enumerable: true, | ||
| get: function () { | ||
| return normalizeMessage; | ||
| } | ||
| }); |
| import { parse } from "./context-D49cMElb.js"; | ||
| import { resolve } from "node:path"; | ||
| import { Buffer } from "node:buffer"; | ||
| //#region src/rspack/context.ts | ||
| function createBuildContext(compiler, compilation, loaderContext) { | ||
| return { | ||
| getNativeBuildContext() { | ||
| return { | ||
| framework: "rspack", | ||
| compiler, | ||
| compilation, | ||
| loaderContext | ||
| }; | ||
| }, | ||
| addWatchFile(file) { | ||
| const cwd = process.cwd(); | ||
| compilation.fileDependencies.add(resolve(cwd, file)); | ||
| }, | ||
| getWatchFiles() { | ||
| return Array.from(compilation.fileDependencies); | ||
| }, | ||
| parse, | ||
| emitFile(emittedFile) { | ||
| const outFileName = emittedFile.fileName || emittedFile.name; | ||
| if (emittedFile.source && outFileName) { | ||
| const { sources } = compilation.compiler.webpack; | ||
| compilation.emitAsset(outFileName, new sources.RawSource(typeof emittedFile.source === "string" ? emittedFile.source : Buffer.from(emittedFile.source))); | ||
| } | ||
| } | ||
| }; | ||
| } | ||
| function createContext(loader) { | ||
| return { | ||
| error: (error) => loader.emitError(normalizeMessage(error)), | ||
| warn: (message) => loader.emitWarning(normalizeMessage(message)) | ||
| }; | ||
| } | ||
| function normalizeMessage(error) { | ||
| const err = new Error(typeof error === "string" ? error : error.message); | ||
| if (typeof error === "object") { | ||
| err.stack = error.stack; | ||
| err.cause = error.meta; | ||
| } | ||
| return err; | ||
| } | ||
| //#endregion | ||
| export { createBuildContext, createContext, normalizeMessage }; |
| import { resolve } from "node:path"; | ||
| import picomatch from "picomatch"; | ||
| import { Parser } from "acorn"; | ||
| //#region src/utils/general.ts | ||
| function toArray(array) { | ||
| array = array || []; | ||
| if (Array.isArray(array)) return array; | ||
| return [array]; | ||
| } | ||
| //#endregion | ||
| //#region src/utils/filter.ts | ||
| const BACKSLASH_REGEX = /\\/g; | ||
| function normalize$1(path$1) { | ||
| return path$1.replace(BACKSLASH_REGEX, "/"); | ||
| } | ||
| const ABSOLUTE_PATH_REGEX = /^(?:\/|(?:[A-Z]:)?[/\\|])/i; | ||
| function isAbsolute$1(path$1) { | ||
| return ABSOLUTE_PATH_REGEX.test(path$1); | ||
| } | ||
| function getMatcherString(glob, cwd) { | ||
| if (glob.startsWith("**") || isAbsolute$1(glob)) return normalize$1(glob); | ||
| const resolved = resolve(cwd, glob); | ||
| return normalize$1(resolved); | ||
| } | ||
| function patternToIdFilter(pattern) { | ||
| if (pattern instanceof RegExp) return (id) => { | ||
| const normalizedId = normalize$1(id); | ||
| const result = pattern.test(normalizedId); | ||
| pattern.lastIndex = 0; | ||
| return result; | ||
| }; | ||
| const cwd = process.cwd(); | ||
| const glob = getMatcherString(pattern, cwd); | ||
| const matcher = picomatch(glob, { dot: true }); | ||
| return (id) => { | ||
| const normalizedId = normalize$1(id); | ||
| return matcher(normalizedId); | ||
| }; | ||
| } | ||
| function patternToCodeFilter(pattern) { | ||
| if (pattern instanceof RegExp) return (code) => { | ||
| const result = pattern.test(code); | ||
| pattern.lastIndex = 0; | ||
| return result; | ||
| }; | ||
| return (code) => code.includes(pattern); | ||
| } | ||
| function createFilter(exclude, include) { | ||
| if (!exclude && !include) return; | ||
| return (input) => { | ||
| if (exclude?.some((filter) => filter(input))) return false; | ||
| if (include?.some((filter) => filter(input))) return true; | ||
| return !(include && include.length > 0); | ||
| }; | ||
| } | ||
| function normalizeFilter(filter) { | ||
| if (typeof filter === "string" || filter instanceof RegExp) return { include: [filter] }; | ||
| if (Array.isArray(filter)) return { include: filter }; | ||
| return { | ||
| exclude: filter.exclude ? toArray(filter.exclude) : void 0, | ||
| include: filter.include ? toArray(filter.include) : void 0 | ||
| }; | ||
| } | ||
| function createIdFilter(filter) { | ||
| if (!filter) return; | ||
| const { exclude, include } = normalizeFilter(filter); | ||
| const excludeFilter = exclude?.map(patternToIdFilter); | ||
| const includeFilter = include?.map(patternToIdFilter); | ||
| return createFilter(excludeFilter, includeFilter); | ||
| } | ||
| function createCodeFilter(filter) { | ||
| if (!filter) return; | ||
| const { exclude, include } = normalizeFilter(filter); | ||
| const excludeFilter = exclude?.map(patternToCodeFilter); | ||
| const includeFilter = include?.map(patternToCodeFilter); | ||
| return createFilter(excludeFilter, includeFilter); | ||
| } | ||
| function createFilterForId(filter) { | ||
| const filterFunction = createIdFilter(filter); | ||
| return filterFunction ? (id) => !!filterFunction(id) : void 0; | ||
| } | ||
| function createFilterForTransform(idFilter, codeFilter) { | ||
| if (!idFilter && !codeFilter) return; | ||
| const idFilterFunction = createIdFilter(idFilter); | ||
| const codeFilterFunction = createCodeFilter(codeFilter); | ||
| return (id, code) => { | ||
| let fallback = true; | ||
| if (idFilterFunction) fallback &&= idFilterFunction(id); | ||
| if (!fallback) return false; | ||
| if (codeFilterFunction) fallback &&= codeFilterFunction(code); | ||
| return fallback; | ||
| }; | ||
| } | ||
| function normalizeObjectHook(name, hook) { | ||
| let handler; | ||
| let filter; | ||
| if (typeof hook === "function") handler = hook; | ||
| else { | ||
| handler = hook.handler; | ||
| const hookFilter = hook.filter; | ||
| if (name === "resolveId" || name === "load") filter = createFilterForId(hookFilter?.id); | ||
| else filter = createFilterForTransform(hookFilter?.id, hookFilter?.code); | ||
| } | ||
| return { | ||
| handler, | ||
| filter: filter || (() => true) | ||
| }; | ||
| } | ||
| //#endregion | ||
| //#region src/utils/context.ts | ||
| function parse(code, opts = {}) { | ||
| return Parser.parse(code, { | ||
| sourceType: "module", | ||
| ecmaVersion: "latest", | ||
| locations: true, | ||
| ...opts | ||
| }); | ||
| } | ||
| //#endregion | ||
| export { normalizeObjectHook, parse, toArray }; |
| //#region rolldown:runtime | ||
| var __create = Object.create; | ||
| var __defProp = Object.defineProperty; | ||
| var __getOwnPropDesc = Object.getOwnPropertyDescriptor; | ||
| var __getOwnPropNames = Object.getOwnPropertyNames; | ||
| var __getProtoOf = Object.getPrototypeOf; | ||
| var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
| var __copyProps = (to, from, except, desc) => { | ||
| if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) { | ||
| key = keys[i]; | ||
| if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { | ||
| get: ((k) => from[k]).bind(null, key), | ||
| enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable | ||
| }); | ||
| } | ||
| return to; | ||
| }; | ||
| var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { | ||
| value: mod, | ||
| enumerable: true | ||
| }) : target, mod)); | ||
| //#endregion | ||
| const node_path = __toESM(require("node:path")); | ||
| const picomatch = __toESM(require("picomatch")); | ||
| const acorn = __toESM(require("acorn")); | ||
| //#region src/utils/general.ts | ||
| function toArray(array) { | ||
| array = array || []; | ||
| if (Array.isArray(array)) return array; | ||
| return [array]; | ||
| } | ||
| //#endregion | ||
| //#region src/utils/filter.ts | ||
| const BACKSLASH_REGEX = /\\/g; | ||
| function normalize(path) { | ||
| return path.replace(BACKSLASH_REGEX, "/"); | ||
| } | ||
| const ABSOLUTE_PATH_REGEX = /^(?:\/|(?:[A-Z]:)?[/\\|])/i; | ||
| function isAbsolute(path) { | ||
| return ABSOLUTE_PATH_REGEX.test(path); | ||
| } | ||
| function getMatcherString(glob, cwd) { | ||
| if (glob.startsWith("**") || isAbsolute(glob)) return normalize(glob); | ||
| const resolved = (0, node_path.resolve)(cwd, glob); | ||
| return normalize(resolved); | ||
| } | ||
| function patternToIdFilter(pattern) { | ||
| if (pattern instanceof RegExp) return (id) => { | ||
| const normalizedId = normalize(id); | ||
| const result = pattern.test(normalizedId); | ||
| pattern.lastIndex = 0; | ||
| return result; | ||
| }; | ||
| const cwd = process.cwd(); | ||
| const glob = getMatcherString(pattern, cwd); | ||
| const matcher = (0, picomatch.default)(glob, { dot: true }); | ||
| return (id) => { | ||
| const normalizedId = normalize(id); | ||
| return matcher(normalizedId); | ||
| }; | ||
| } | ||
| function patternToCodeFilter(pattern) { | ||
| if (pattern instanceof RegExp) return (code) => { | ||
| const result = pattern.test(code); | ||
| pattern.lastIndex = 0; | ||
| return result; | ||
| }; | ||
| return (code) => code.includes(pattern); | ||
| } | ||
| function createFilter(exclude, include) { | ||
| if (!exclude && !include) return; | ||
| return (input) => { | ||
| if (exclude?.some((filter) => filter(input))) return false; | ||
| if (include?.some((filter) => filter(input))) return true; | ||
| return !(include && include.length > 0); | ||
| }; | ||
| } | ||
| function normalizeFilter(filter) { | ||
| if (typeof filter === "string" || filter instanceof RegExp) return { include: [filter] }; | ||
| if (Array.isArray(filter)) return { include: filter }; | ||
| return { | ||
| exclude: filter.exclude ? toArray(filter.exclude) : void 0, | ||
| include: filter.include ? toArray(filter.include) : void 0 | ||
| }; | ||
| } | ||
| function createIdFilter(filter) { | ||
| if (!filter) return; | ||
| const { exclude, include } = normalizeFilter(filter); | ||
| const excludeFilter = exclude?.map(patternToIdFilter); | ||
| const includeFilter = include?.map(patternToIdFilter); | ||
| return createFilter(excludeFilter, includeFilter); | ||
| } | ||
| function createCodeFilter(filter) { | ||
| if (!filter) return; | ||
| const { exclude, include } = normalizeFilter(filter); | ||
| const excludeFilter = exclude?.map(patternToCodeFilter); | ||
| const includeFilter = include?.map(patternToCodeFilter); | ||
| return createFilter(excludeFilter, includeFilter); | ||
| } | ||
| function createFilterForId(filter) { | ||
| const filterFunction = createIdFilter(filter); | ||
| return filterFunction ? (id) => !!filterFunction(id) : void 0; | ||
| } | ||
| function createFilterForTransform(idFilter, codeFilter) { | ||
| if (!idFilter && !codeFilter) return; | ||
| const idFilterFunction = createIdFilter(idFilter); | ||
| const codeFilterFunction = createCodeFilter(codeFilter); | ||
| return (id, code) => { | ||
| let fallback = true; | ||
| if (idFilterFunction) fallback &&= idFilterFunction(id); | ||
| if (!fallback) return false; | ||
| if (codeFilterFunction) fallback &&= codeFilterFunction(code); | ||
| return fallback; | ||
| }; | ||
| } | ||
| function normalizeObjectHook(name, hook) { | ||
| let handler; | ||
| let filter; | ||
| if (typeof hook === "function") handler = hook; | ||
| else { | ||
| handler = hook.handler; | ||
| const hookFilter = hook.filter; | ||
| if (name === "resolveId" || name === "load") filter = createFilterForId(hookFilter?.id); | ||
| else filter = createFilterForTransform(hookFilter?.id, hookFilter?.code); | ||
| } | ||
| return { | ||
| handler, | ||
| filter: filter || (() => true) | ||
| }; | ||
| } | ||
| //#endregion | ||
| //#region src/utils/context.ts | ||
| function parse(code, opts = {}) { | ||
| return acorn.Parser.parse(code, { | ||
| sourceType: "module", | ||
| ecmaVersion: "latest", | ||
| locations: true, | ||
| ...opts | ||
| }); | ||
| } | ||
| //#endregion | ||
| Object.defineProperty(exports, '__toESM', { | ||
| enumerable: true, | ||
| get: function () { | ||
| return __toESM; | ||
| } | ||
| }); | ||
| Object.defineProperty(exports, 'normalizeObjectHook', { | ||
| enumerable: true, | ||
| get: function () { | ||
| return normalizeObjectHook; | ||
| } | ||
| }); | ||
| Object.defineProperty(exports, 'parse', { | ||
| enumerable: true, | ||
| get: function () { | ||
| return parse; | ||
| } | ||
| }); | ||
| Object.defineProperty(exports, 'toArray', { | ||
| enumerable: true, | ||
| get: function () { | ||
| return toArray; | ||
| } | ||
| }); |
| const require_context = require('./context-DwbtaXxf.cjs'); | ||
| const node_path = require_context.__toESM(require("node:path")); | ||
| const node_buffer = require_context.__toESM(require("node:buffer")); | ||
| //#region src/rspack/context.ts | ||
| function createBuildContext(compiler, compilation, loaderContext) { | ||
| return { | ||
| getNativeBuildContext() { | ||
| return { | ||
| framework: "rspack", | ||
| compiler, | ||
| compilation, | ||
| loaderContext | ||
| }; | ||
| }, | ||
| addWatchFile(file) { | ||
| const cwd = process.cwd(); | ||
| compilation.fileDependencies.add((0, node_path.resolve)(cwd, file)); | ||
| }, | ||
| getWatchFiles() { | ||
| return Array.from(compilation.fileDependencies); | ||
| }, | ||
| parse: require_context.parse, | ||
| emitFile(emittedFile) { | ||
| const outFileName = emittedFile.fileName || emittedFile.name; | ||
| if (emittedFile.source && outFileName) { | ||
| const { sources } = compilation.compiler.webpack; | ||
| compilation.emitAsset(outFileName, new sources.RawSource(typeof emittedFile.source === "string" ? emittedFile.source : node_buffer.Buffer.from(emittedFile.source))); | ||
| } | ||
| } | ||
| }; | ||
| } | ||
| function createContext(loader) { | ||
| return { | ||
| error: (error) => loader.emitError(normalizeMessage(error)), | ||
| warn: (message) => loader.emitWarning(normalizeMessage(message)) | ||
| }; | ||
| } | ||
| function normalizeMessage(error) { | ||
| const err = new Error(typeof error === "string" ? error : error.message); | ||
| if (typeof error === "object") { | ||
| err.stack = error.stack; | ||
| err.cause = error.meta; | ||
| } | ||
| return err; | ||
| } | ||
| //#endregion | ||
| Object.defineProperty(exports, 'createBuildContext', { | ||
| enumerable: true, | ||
| get: function () { | ||
| return createBuildContext; | ||
| } | ||
| }); | ||
| Object.defineProperty(exports, 'createContext', { | ||
| enumerable: true, | ||
| get: function () { | ||
| return createContext; | ||
| } | ||
| }); | ||
| Object.defineProperty(exports, 'normalizeMessage', { | ||
| enumerable: true, | ||
| get: function () { | ||
| return normalizeMessage; | ||
| } | ||
| }); |
-1039
| const require_context = require('./context-DwbtaXxf.cjs'); | ||
| const require_webpack_like = require('./webpack-like-BAQNtVsj.cjs'); | ||
| const require_context$1 = require('./context-PvRDlMNZ.cjs'); | ||
| const require_utils = require('./utils-BeoYHuOg.cjs'); | ||
| const require_context$2 = require('./context-C4aYoZcz.cjs'); | ||
| const node_fs = require_context.__toESM(require("node:fs")); | ||
| const node_path = require_context.__toESM(require("node:path")); | ||
| const node_buffer = require_context.__toESM(require("node:buffer")); | ||
| const __jridgewell_remapping = require_context.__toESM(require("@jridgewell/remapping")); | ||
| const node_querystring = require_context.__toESM(require("node:querystring")); | ||
| const node_process = require_context.__toESM(require("node:process")); | ||
| const webpack_virtual_modules = require_context.__toESM(require("webpack-virtual-modules")); | ||
| //#region src/esbuild/utils.ts | ||
| const ExtToLoader = { | ||
| ".js": "js", | ||
| ".mjs": "js", | ||
| ".cjs": "js", | ||
| ".jsx": "jsx", | ||
| ".ts": "ts", | ||
| ".cts": "ts", | ||
| ".mts": "ts", | ||
| ".tsx": "tsx", | ||
| ".css": "css", | ||
| ".less": "css", | ||
| ".stylus": "css", | ||
| ".scss": "css", | ||
| ".sass": "css", | ||
| ".json": "json", | ||
| ".txt": "text" | ||
| }; | ||
| function guessLoader(code, id) { | ||
| return ExtToLoader[node_path.default.extname(id).toLowerCase()] || "js"; | ||
| } | ||
| function unwrapLoader(loader, code, id) { | ||
| if (typeof loader === "function") return loader(code, id); | ||
| return loader; | ||
| } | ||
| function fixSourceMap(map) { | ||
| if (!Object.prototype.hasOwnProperty.call(map, "toString")) Object.defineProperty(map, "toString", { | ||
| enumerable: false, | ||
| value: function toString() { | ||
| return JSON.stringify(this); | ||
| } | ||
| }); | ||
| if (!Object.prototype.hasOwnProperty.call(map, "toUrl")) Object.defineProperty(map, "toUrl", { | ||
| enumerable: false, | ||
| value: function toUrl() { | ||
| return `data:application/json;charset=utf-8;base64,${node_buffer.Buffer.from(this.toString()).toString("base64")}`; | ||
| } | ||
| }); | ||
| return map; | ||
| } | ||
| const nullSourceMap = { | ||
| names: [], | ||
| sources: [], | ||
| mappings: "", | ||
| version: 3 | ||
| }; | ||
| function combineSourcemaps(filename, sourcemapList) { | ||
| sourcemapList = sourcemapList.filter((m) => m.sources); | ||
| if (sourcemapList.length === 0 || sourcemapList.every((m) => m.sources.length === 0)) return { ...nullSourceMap }; | ||
| let map; | ||
| let mapIndex = 1; | ||
| const useArrayInterface = sourcemapList.slice(0, -1).find((m) => m.sources.length !== 1) === void 0; | ||
| if (useArrayInterface) map = (0, __jridgewell_remapping.default)(sourcemapList, () => null, true); | ||
| else map = (0, __jridgewell_remapping.default)(sourcemapList[0], (sourcefile) => { | ||
| if (sourcefile === filename && sourcemapList[mapIndex]) return sourcemapList[mapIndex++]; | ||
| else return { ...nullSourceMap }; | ||
| }, true); | ||
| if (!map.file) delete map.file; | ||
| return map; | ||
| } | ||
| function createBuildContext$2(build) { | ||
| const watchFiles = []; | ||
| const { initialOptions } = build; | ||
| return { | ||
| parse: require_context.parse, | ||
| addWatchFile() { | ||
| throw new Error("unplugin/esbuild: addWatchFile outside supported hooks (resolveId, load, transform)"); | ||
| }, | ||
| emitFile(emittedFile) { | ||
| const outFileName = emittedFile.fileName || emittedFile.name; | ||
| if (initialOptions.outdir && emittedFile.source && outFileName) { | ||
| const outPath = node_path.default.resolve(initialOptions.outdir, outFileName); | ||
| const outDir = node_path.default.dirname(outPath); | ||
| if (!node_fs.default.existsSync(outDir)) node_fs.default.mkdirSync(outDir, { recursive: true }); | ||
| node_fs.default.writeFileSync(outPath, emittedFile.source); | ||
| } | ||
| }, | ||
| getWatchFiles() { | ||
| return watchFiles; | ||
| }, | ||
| getNativeBuildContext() { | ||
| return { | ||
| framework: "esbuild", | ||
| build | ||
| }; | ||
| } | ||
| }; | ||
| } | ||
| function createPluginContext(context) { | ||
| const errors = []; | ||
| const warnings = []; | ||
| const pluginContext = { | ||
| error(message) { | ||
| errors.push(normalizeMessage$2(message)); | ||
| }, | ||
| warn(message) { | ||
| warnings.push(normalizeMessage$2(message)); | ||
| } | ||
| }; | ||
| const mixedContext = { | ||
| ...context, | ||
| ...pluginContext, | ||
| addWatchFile(id) { | ||
| context.getWatchFiles().push(id); | ||
| } | ||
| }; | ||
| return { | ||
| errors, | ||
| warnings, | ||
| mixedContext | ||
| }; | ||
| } | ||
| function normalizeMessage$2(message) { | ||
| if (typeof message === "string") message = { message }; | ||
| return { | ||
| id: message.id, | ||
| pluginName: message.plugin, | ||
| text: message.message, | ||
| location: message.loc ? { | ||
| file: message.loc.file, | ||
| line: message.loc.line, | ||
| column: message.loc.column | ||
| } : null, | ||
| detail: message.meta, | ||
| notes: [] | ||
| }; | ||
| } | ||
| function processCodeWithSourceMap(map, code) { | ||
| if (map) { | ||
| if (!map.sourcesContent || map.sourcesContent.length === 0) map.sourcesContent = [code]; | ||
| map = fixSourceMap(map); | ||
| code += `\n//# sourceMappingURL=${map.toUrl()}`; | ||
| } | ||
| return code; | ||
| } | ||
| //#endregion | ||
| //#region src/esbuild/index.ts | ||
| function getEsbuildPlugin(factory) { | ||
| return (userOptions) => { | ||
| const meta = { framework: "esbuild" }; | ||
| const plugins = require_context.toArray(factory(userOptions, meta)); | ||
| const setupPlugins = async (build) => { | ||
| const setup = buildSetup(); | ||
| const loaders = []; | ||
| for (const plugin of plugins) { | ||
| const loader = {}; | ||
| await setup(plugin)({ | ||
| ...build, | ||
| onLoad(_options, callback) { | ||
| loader.options = _options; | ||
| loader.onLoadCb = callback; | ||
| }, | ||
| onTransform(_options, callback) { | ||
| loader.options ||= _options; | ||
| loader.onTransformCb = callback; | ||
| } | ||
| }, build); | ||
| if (loader.onLoadCb || loader.onTransformCb) loaders.push(loader); | ||
| } | ||
| if (loaders.length) build.onLoad(loaders.length === 1 ? loaders[0].options : { filter: /.*/ }, async (args) => { | ||
| function checkFilter(options) { | ||
| return loaders.length === 1 || !options?.filter || options.filter.test(args.path); | ||
| } | ||
| let result; | ||
| for (const { options, onLoadCb } of loaders) { | ||
| if (!checkFilter(options)) continue; | ||
| if (onLoadCb) result = await onLoadCb(args); | ||
| if (result?.contents) break; | ||
| } | ||
| let fsContentsCache; | ||
| for (const { options, onTransformCb } of loaders) { | ||
| if (!checkFilter(options)) continue; | ||
| if (onTransformCb) { | ||
| const newArgs = { | ||
| ...result, | ||
| ...args, | ||
| async getContents() { | ||
| if (result?.contents) return result.contents; | ||
| if (fsContentsCache) return fsContentsCache; | ||
| return fsContentsCache = await node_fs.default.promises.readFile(args.path, "utf8"); | ||
| } | ||
| }; | ||
| const _result = await onTransformCb(newArgs); | ||
| if (_result?.contents) result = _result; | ||
| } | ||
| } | ||
| if (result?.contents) return result; | ||
| }); | ||
| }; | ||
| return { | ||
| name: (plugins.length === 1 ? plugins[0].name : meta.esbuildHostName) ?? `unplugin-host:${plugins.map((p) => p.name).join(":")}`, | ||
| setup: setupPlugins | ||
| }; | ||
| }; | ||
| } | ||
| function buildSetup() { | ||
| return (plugin) => { | ||
| return (build, rawBuild) => { | ||
| const context = createBuildContext$2(rawBuild); | ||
| const { onStart, onEnd, onResolve, onLoad, onTransform, initialOptions } = build; | ||
| const onResolveFilter = plugin.esbuild?.onResolveFilter ?? /.*/; | ||
| const onLoadFilter = plugin.esbuild?.onLoadFilter ?? /.*/; | ||
| const loader = plugin.esbuild?.loader ?? guessLoader; | ||
| plugin.esbuild?.config?.call(context, initialOptions); | ||
| if (plugin.buildStart) onStart(() => plugin.buildStart.call(context)); | ||
| if (plugin.buildEnd || plugin.writeBundle) onEnd(async () => { | ||
| if (plugin.buildEnd) await plugin.buildEnd.call(context); | ||
| if (plugin.writeBundle) await plugin.writeBundle(); | ||
| }); | ||
| if (plugin.resolveId) onResolve({ filter: onResolveFilter }, async (args) => { | ||
| const id = args.path; | ||
| if (initialOptions.external?.includes(id)) return; | ||
| const { handler, filter } = require_context.normalizeObjectHook("resolveId", plugin.resolveId); | ||
| if (!filter(id)) return; | ||
| const { errors, warnings, mixedContext } = createPluginContext(context); | ||
| const isEntry = args.kind === "entry-point"; | ||
| const result = await handler.call(mixedContext, id, isEntry ? void 0 : args.importer, { isEntry }); | ||
| if (typeof result === "string") return { | ||
| path: result, | ||
| namespace: plugin.name, | ||
| errors, | ||
| warnings, | ||
| watchFiles: mixedContext.getWatchFiles() | ||
| }; | ||
| else if (typeof result === "object" && result !== null) return { | ||
| path: result.id, | ||
| external: result.external, | ||
| namespace: plugin.name, | ||
| errors, | ||
| warnings, | ||
| watchFiles: mixedContext.getWatchFiles() | ||
| }; | ||
| }); | ||
| if (plugin.load) onLoad({ filter: onLoadFilter }, async (args) => { | ||
| const { handler, filter } = require_context.normalizeObjectHook("load", plugin.load); | ||
| const id = args.path + (args.suffix || ""); | ||
| if (plugin.loadInclude && !plugin.loadInclude(id)) return; | ||
| if (!filter(id)) return; | ||
| const { errors, warnings, mixedContext } = createPluginContext(context); | ||
| let code; | ||
| let map; | ||
| const result = await handler.call(mixedContext, id); | ||
| if (typeof result === "string") code = result; | ||
| else if (typeof result === "object" && result !== null) { | ||
| code = result.code; | ||
| map = result.map; | ||
| } | ||
| if (code === void 0) return null; | ||
| if (map) code = processCodeWithSourceMap(map, code); | ||
| const resolveDir = node_path.default.dirname(args.path); | ||
| return { | ||
| contents: code, | ||
| errors, | ||
| warnings, | ||
| watchFiles: mixedContext.getWatchFiles(), | ||
| loader: unwrapLoader(loader, code, args.path), | ||
| resolveDir | ||
| }; | ||
| }); | ||
| if (plugin.transform) onTransform({ filter: onLoadFilter }, async (args) => { | ||
| const { handler, filter } = require_context.normalizeObjectHook("transform", plugin.transform); | ||
| const id = args.path + (args.suffix || ""); | ||
| if (plugin.transformInclude && !plugin.transformInclude(id)) return; | ||
| let code = await args.getContents(); | ||
| if (!filter(id, code)) return; | ||
| const { mixedContext, errors, warnings } = createPluginContext(context); | ||
| const resolveDir = node_path.default.dirname(args.path); | ||
| let map; | ||
| const result = await handler.call(mixedContext, code, id); | ||
| if (typeof result === "string") code = result; | ||
| else if (typeof result === "object" && result !== null) { | ||
| code = result.code; | ||
| if (map && result.map) map = combineSourcemaps(args.path, [result.map === "string" ? JSON.parse(result.map) : result.map, map]); | ||
| else if (typeof result.map === "string") map = JSON.parse(result.map); | ||
| else map = result.map; | ||
| } | ||
| if (code) { | ||
| if (map) code = processCodeWithSourceMap(map, code); | ||
| return { | ||
| contents: code, | ||
| errors, | ||
| warnings, | ||
| watchFiles: mixedContext.getWatchFiles(), | ||
| loader: unwrapLoader(loader, code, args.path), | ||
| resolveDir | ||
| }; | ||
| } | ||
| }); | ||
| if (plugin.esbuild?.setup) return plugin.esbuild.setup(rawBuild); | ||
| }; | ||
| }; | ||
| } | ||
| //#endregion | ||
| //#region src/farm/context.ts | ||
| function createFarmContext(context, currentResolveId) { | ||
| return { | ||
| parse: require_context.parse, | ||
| addWatchFile(id) { | ||
| context.addWatchFile(id, currentResolveId || id); | ||
| }, | ||
| emitFile(emittedFile) { | ||
| const outFileName = emittedFile.fileName || emittedFile.name; | ||
| if (emittedFile.source && outFileName) context.emitFile({ | ||
| resolvedPath: outFileName, | ||
| name: outFileName, | ||
| content: [...node_buffer.Buffer.from(emittedFile.source)], | ||
| resourceType: (0, node_path.extname)(outFileName) | ||
| }); | ||
| }, | ||
| getWatchFiles() { | ||
| return context.getWatchFiles(); | ||
| }, | ||
| getNativeBuildContext() { | ||
| return { | ||
| framework: "farm", | ||
| context | ||
| }; | ||
| } | ||
| }; | ||
| } | ||
| function unpluginContext(context) { | ||
| return { | ||
| error: (error) => context.error(typeof error === "string" ? new Error(error) : error), | ||
| warn: (error) => context.warn(typeof error === "string" ? new Error(error) : error) | ||
| }; | ||
| } | ||
| //#endregion | ||
| //#region src/farm/utils.ts | ||
| function convertEnforceToPriority(value) { | ||
| const defaultPriority = 100; | ||
| const enforceToPriority = { | ||
| pre: 102, | ||
| post: 98 | ||
| }; | ||
| return enforceToPriority[value] !== void 0 ? enforceToPriority[value] : defaultPriority; | ||
| } | ||
| function convertWatchEventChange(value) { | ||
| const watchEventChange = { | ||
| Added: "create", | ||
| Updated: "update", | ||
| Removed: "delete" | ||
| }; | ||
| return watchEventChange[value]; | ||
| } | ||
| function isString(variable) { | ||
| return typeof variable === "string"; | ||
| } | ||
| function isObject(variable) { | ||
| return typeof variable === "object" && variable !== null; | ||
| } | ||
| function customParseQueryString(url) { | ||
| if (!url) return []; | ||
| const queryString = url.split("?")[1]; | ||
| const parsedParams = node_querystring.parse(queryString); | ||
| const paramsArray = []; | ||
| for (const key in parsedParams) paramsArray.push([key, parsedParams[key]]); | ||
| return paramsArray; | ||
| } | ||
| function encodeStr(str) { | ||
| const len = str.length; | ||
| if (len === 0) return str; | ||
| const firstNullIndex = str.indexOf("\0"); | ||
| if (firstNullIndex === -1) return str; | ||
| const result = Array.from({ length: len + countNulls(str, firstNullIndex) }); | ||
| let pos = 0; | ||
| for (let i = 0; i < firstNullIndex; i++) result[pos++] = str[i]; | ||
| for (let i = firstNullIndex; i < len; i++) { | ||
| const char = str[i]; | ||
| if (char === "\0") { | ||
| result[pos++] = "\\"; | ||
| result[pos++] = "0"; | ||
| } else result[pos++] = char; | ||
| } | ||
| return node_path.default.posix.normalize(result.join("")); | ||
| } | ||
| function decodeStr(str) { | ||
| const len = str.length; | ||
| if (len === 0) return str; | ||
| const firstIndex = str.indexOf("\\0"); | ||
| if (firstIndex === -1) return str; | ||
| const result = Array.from({ length: len - countBackslashZeros(str, firstIndex) }); | ||
| let pos = 0; | ||
| for (let i$1 = 0; i$1 < firstIndex; i$1++) result[pos++] = str[i$1]; | ||
| let i = firstIndex; | ||
| while (i < len) if (str[i] === "\\" && str[i + 1] === "0") { | ||
| result[pos++] = "\0"; | ||
| i += 2; | ||
| } else result[pos++] = str[i++]; | ||
| return node_path.default.posix.normalize(result.join("")); | ||
| } | ||
| function getContentValue(content) { | ||
| if (content === null || content === void 0) throw new Error("Content cannot be null or undefined"); | ||
| const strContent = typeof content === "string" ? content : content.code || ""; | ||
| return encodeStr(strContent); | ||
| } | ||
| function countNulls(str, startIndex) { | ||
| let count = 0; | ||
| const len = str.length; | ||
| for (let i = startIndex; i < len; i++) if (str[i] === "\0") count++; | ||
| return count; | ||
| } | ||
| function countBackslashZeros(str, startIndex) { | ||
| let count = 0; | ||
| const len = str.length; | ||
| for (let i = startIndex; i < len - 1; i++) if (str[i] === "\\" && str[i + 1] === "0") { | ||
| count++; | ||
| i++; | ||
| } | ||
| return count; | ||
| } | ||
| function removeQuery(pathe) { | ||
| const queryIndex = pathe.indexOf("?"); | ||
| if (queryIndex !== -1) return node_path.default.posix.normalize(pathe.slice(0, queryIndex)); | ||
| return node_path.default.posix.normalize(pathe); | ||
| } | ||
| function isStartsWithSlash(str) { | ||
| return str?.startsWith("/"); | ||
| } | ||
| function appendQuery(id, query) { | ||
| if (!query.length) return id; | ||
| return `${id}?${stringifyQuery(query)}`; | ||
| } | ||
| function stringifyQuery(query) { | ||
| if (!query.length) return ""; | ||
| let queryStr = ""; | ||
| for (const [key, value] of query) queryStr += `${key}${value ? `=${value}` : ""}&`; | ||
| return `${queryStr.slice(0, -1)}`; | ||
| } | ||
| const CSS_LANGS_RES = [ | ||
| [/\.(less)(?:$|\?)/, "less"], | ||
| [/\.(scss|sass)(?:$|\?)/, "sass"], | ||
| [/\.(styl|stylus)(?:$|\?)/, "stylus"], | ||
| [/\.(css)(?:$|\?)/, "css"] | ||
| ]; | ||
| const JS_LANGS_RES = [ | ||
| [/\.(js|mjs|cjs)(?:$|\?)/, "js"], | ||
| [/\.(jsx)(?:$|\?)/, "jsx"], | ||
| [/\.(ts|cts|mts)(?:$|\?)/, "ts"], | ||
| [/\.(tsx)(?:$|\?)/, "tsx"] | ||
| ]; | ||
| function getCssModuleType(id) { | ||
| for (const [reg, lang] of CSS_LANGS_RES) if (reg.test(id)) return lang; | ||
| return null; | ||
| } | ||
| function getJsModuleType(id) { | ||
| for (const [reg, lang] of JS_LANGS_RES) if (reg.test(id)) return lang; | ||
| return null; | ||
| } | ||
| function formatLoadModuleType(id) { | ||
| const cssModuleType = getCssModuleType(id); | ||
| if (cssModuleType) return cssModuleType; | ||
| const jsModuleType = getJsModuleType(id); | ||
| if (jsModuleType) return jsModuleType; | ||
| return "js"; | ||
| } | ||
| function formatTransformModuleType(id) { | ||
| return formatLoadModuleType(id); | ||
| } | ||
| //#endregion | ||
| //#region src/farm/index.ts | ||
| function getFarmPlugin(factory) { | ||
| return ((userOptions) => { | ||
| const meta = { framework: "farm" }; | ||
| const rawPlugins = require_context.toArray(factory(userOptions, meta)); | ||
| const plugins = rawPlugins.map((rawPlugin) => { | ||
| const plugin = toFarmPlugin(rawPlugin, userOptions); | ||
| if (rawPlugin.farm) Object.assign(plugin, rawPlugin.farm); | ||
| return plugin; | ||
| }); | ||
| return plugins.length === 1 ? plugins[0] : plugins; | ||
| }); | ||
| } | ||
| function toFarmPlugin(plugin, options) { | ||
| const farmPlugin = { | ||
| name: plugin.name, | ||
| priority: convertEnforceToPriority(plugin.enforce) | ||
| }; | ||
| if (plugin.farm) Object.keys(plugin.farm).forEach((key) => { | ||
| const value = plugin.farm[key]; | ||
| if (value) Reflect.set(farmPlugin, key, value); | ||
| }); | ||
| if (plugin.buildStart) { | ||
| const _buildStart = plugin.buildStart; | ||
| farmPlugin.buildStart = { async executor(_, context) { | ||
| await _buildStart.call(createFarmContext(context)); | ||
| } }; | ||
| } | ||
| if (plugin.resolveId) { | ||
| const _resolveId = plugin.resolveId; | ||
| let filters = []; | ||
| if (options) filters = options?.filters ?? []; | ||
| farmPlugin.resolve = { | ||
| filters: { | ||
| sources: filters.length ? filters : [".*"], | ||
| importers: [".*"] | ||
| }, | ||
| async executor(params, context) { | ||
| const resolvedIdPath = node_path.default.resolve(params.importer ?? ""); | ||
| const id = decodeStr(params.source); | ||
| const { handler, filter } = require_context.normalizeObjectHook("resolveId", _resolveId); | ||
| if (!filter(id)) return null; | ||
| let isEntry = false; | ||
| if (isObject(params.kind) && "entry" in params.kind) { | ||
| const kindWithEntry = params.kind; | ||
| isEntry = kindWithEntry.entry === "index"; | ||
| } | ||
| const farmContext = createFarmContext(context, resolvedIdPath); | ||
| const resolveIdResult = await handler.call(Object.assign(unpluginContext(context), farmContext), id, resolvedIdPath ?? null, { isEntry }); | ||
| if (isString(resolveIdResult)) return { | ||
| resolvedPath: removeQuery(encodeStr(resolveIdResult)), | ||
| query: customParseQueryString(resolveIdResult), | ||
| sideEffects: true, | ||
| external: false, | ||
| meta: {} | ||
| }; | ||
| if (isObject(resolveIdResult)) return { | ||
| resolvedPath: removeQuery(encodeStr(resolveIdResult?.id)), | ||
| query: customParseQueryString(resolveIdResult?.id), | ||
| sideEffects: false, | ||
| external: Boolean(resolveIdResult?.external), | ||
| meta: {} | ||
| }; | ||
| if (!isStartsWithSlash(params.source)) return null; | ||
| } | ||
| }; | ||
| } | ||
| if (plugin.load) { | ||
| const _load = plugin.load; | ||
| farmPlugin.load = { | ||
| filters: { resolvedPaths: [".*"] }, | ||
| async executor(params, context) { | ||
| const resolvedPath = decodeStr(params.resolvedPath); | ||
| const id = appendQuery(resolvedPath, params.query); | ||
| const loader = formatTransformModuleType(id); | ||
| if (plugin.loadInclude && !plugin.loadInclude?.(id)) return null; | ||
| const { handler, filter } = require_context.normalizeObjectHook("load", _load); | ||
| if (!filter(id)) return null; | ||
| const farmContext = createFarmContext(context, id); | ||
| const content = await handler.call(Object.assign(unpluginContext(context), farmContext), id); | ||
| const loadFarmResult = { | ||
| content: getContentValue(content), | ||
| moduleType: loader | ||
| }; | ||
| return loadFarmResult; | ||
| } | ||
| }; | ||
| } | ||
| if (plugin.transform) { | ||
| const _transform = plugin.transform; | ||
| farmPlugin.transform = { | ||
| filters: { | ||
| resolvedPaths: [".*"], | ||
| moduleTypes: [".*"] | ||
| }, | ||
| async executor(params, context) { | ||
| const resolvedPath = decodeStr(params.resolvedPath); | ||
| const id = appendQuery(resolvedPath, params.query); | ||
| const loader = formatTransformModuleType(id); | ||
| if (plugin.transformInclude && !plugin.transformInclude(id)) return null; | ||
| const { handler, filter } = require_context.normalizeObjectHook("transform", _transform); | ||
| if (!filter(id, params.content)) return null; | ||
| const farmContext = createFarmContext(context, id); | ||
| const resource = await handler.call(Object.assign(unpluginContext(context), farmContext), params.content, id); | ||
| if (resource && typeof resource !== "string") { | ||
| const transformFarmResult = { | ||
| content: getContentValue(resource), | ||
| moduleType: loader, | ||
| sourceMap: typeof resource.map === "object" && resource.map !== null ? JSON.stringify(resource.map) : void 0 | ||
| }; | ||
| return transformFarmResult; | ||
| } | ||
| } | ||
| }; | ||
| } | ||
| if (plugin.watchChange) { | ||
| const _watchChange = plugin.watchChange; | ||
| farmPlugin.updateModules = { async executor(param, context) { | ||
| const updatePathContent = param.paths[0]; | ||
| const ModifiedPath = updatePathContent[0]; | ||
| const eventChange = convertWatchEventChange(updatePathContent[1]); | ||
| await _watchChange.call(createFarmContext(context), ModifiedPath, { event: eventChange }); | ||
| } }; | ||
| } | ||
| if (plugin.buildEnd) { | ||
| const _buildEnd = plugin.buildEnd; | ||
| farmPlugin.buildEnd = { async executor(_, context) { | ||
| await _buildEnd.call(createFarmContext(context)); | ||
| } }; | ||
| } | ||
| if (plugin.writeBundle) { | ||
| const _writeBundle = plugin.writeBundle; | ||
| farmPlugin.finish = { async executor() { | ||
| await _writeBundle(); | ||
| } }; | ||
| } | ||
| return farmPlugin; | ||
| } | ||
| //#endregion | ||
| //#region src/rollup/index.ts | ||
| function getRollupPlugin(factory) { | ||
| return ((userOptions) => { | ||
| const meta = { framework: "rollup" }; | ||
| const rawPlugins = require_context.toArray(factory(userOptions, meta)); | ||
| const plugins = rawPlugins.map((plugin) => toRollupPlugin(plugin, "rollup")); | ||
| return plugins.length === 1 ? plugins[0] : plugins; | ||
| }); | ||
| } | ||
| function toRollupPlugin(plugin, key) { | ||
| const nativeFilter = key === "rolldown"; | ||
| if (plugin.resolveId && !nativeFilter && typeof plugin.resolveId === "object" && plugin.resolveId.filter) { | ||
| const resolveIdHook = plugin.resolveId; | ||
| const { handler, filter } = require_context.normalizeObjectHook("load", resolveIdHook); | ||
| replaceHookHandler("resolveId", resolveIdHook, function(...args) { | ||
| const [id] = args; | ||
| const supportFilter = supportNativeFilter(this, key); | ||
| if (!supportFilter && !filter(id)) return; | ||
| return handler.apply(this, args); | ||
| }); | ||
| } | ||
| if (plugin.load && (plugin.loadInclude || !nativeFilter && typeof plugin.load === "object" && plugin.load.filter)) { | ||
| const loadHook = plugin.load; | ||
| const { handler, filter } = require_context.normalizeObjectHook("load", loadHook); | ||
| replaceHookHandler("load", loadHook, function(...args) { | ||
| const [id] = args; | ||
| if (plugin.loadInclude && !plugin.loadInclude(id)) return; | ||
| const supportFilter = supportNativeFilter(this, key); | ||
| if (!supportFilter && !filter(id)) return; | ||
| return handler.apply(this, args); | ||
| }); | ||
| } | ||
| if (plugin.transform && (plugin.transformInclude || !nativeFilter && typeof plugin.transform === "object" && plugin.transform.filter)) { | ||
| const transformHook = plugin.transform; | ||
| const { handler, filter } = require_context.normalizeObjectHook("transform", transformHook); | ||
| replaceHookHandler("transform", transformHook, function(...args) { | ||
| const [code, id] = args; | ||
| if (plugin.transformInclude && !plugin.transformInclude(id)) return; | ||
| const supportFilter = supportNativeFilter(this, key); | ||
| if (!supportFilter && !filter(id, code)) return; | ||
| return handler.apply(this, args); | ||
| }); | ||
| } | ||
| if (plugin[key]) Object.assign(plugin, plugin[key]); | ||
| return plugin; | ||
| function replaceHookHandler(name, hook, handler) { | ||
| if (typeof hook === "function") plugin[name] = handler; | ||
| else hook.handler = handler; | ||
| } | ||
| } | ||
| function supportNativeFilter(context, framework) { | ||
| if (framework === "unloader") return false; | ||
| if (framework === "vite") return !!context?.meta?.viteVersion; | ||
| if (framework === "rolldown") return true; | ||
| const rollupVersion = context?.meta?.rollupVersion; | ||
| if (!rollupVersion) return false; | ||
| const [major, minor] = rollupVersion.split("."); | ||
| return Number(major) > 4 || Number(major) === 4 && Number(minor) >= 40; | ||
| } | ||
| //#endregion | ||
| //#region src/rolldown/index.ts | ||
| function getRolldownPlugin(factory) { | ||
| return ((userOptions) => { | ||
| const meta = { framework: "rolldown" }; | ||
| const rawPlugins = require_context.toArray(factory(userOptions, meta)); | ||
| const plugins = rawPlugins.map((rawPlugin) => { | ||
| const plugin = toRollupPlugin(rawPlugin, "rolldown"); | ||
| return plugin; | ||
| }); | ||
| return plugins.length === 1 ? plugins[0] : plugins; | ||
| }); | ||
| } | ||
| //#endregion | ||
| //#region src/rspack/index.ts | ||
| const TRANSFORM_LOADER$1 = (0, node_path.resolve)(__dirname, "rspack/loaders/transform"); | ||
| const LOAD_LOADER$1 = (0, node_path.resolve)(__dirname, "rspack/loaders/load"); | ||
| function getRspackPlugin(factory) { | ||
| return (userOptions) => { | ||
| return { apply(compiler) { | ||
| const VIRTUAL_MODULE_PREFIX = (0, node_path.resolve)(compiler.options.context ?? process.cwd(), "node_modules/.virtual", process.pid.toString()); | ||
| const meta = { | ||
| framework: "rspack", | ||
| rspack: { compiler } | ||
| }; | ||
| const rawPlugins = require_context.toArray(factory(userOptions, meta)); | ||
| for (const rawPlugin of rawPlugins) { | ||
| const plugin = Object.assign(rawPlugin, { | ||
| __unpluginMeta: meta, | ||
| __virtualModulePrefix: VIRTUAL_MODULE_PREFIX | ||
| }); | ||
| const externalModules = /* @__PURE__ */ new Set(); | ||
| if (plugin.resolveId) { | ||
| const createPlugin = (plugin$1) => { | ||
| if (compiler.rspack.experiments.VirtualModulesPlugin) return new compiler.rspack.experiments.VirtualModulesPlugin(); | ||
| return new require_utils.FakeVirtualModulesPlugin(plugin$1); | ||
| }; | ||
| const vfs = createPlugin(plugin); | ||
| vfs.apply(compiler); | ||
| const vfsModules = /* @__PURE__ */ new Map(); | ||
| plugin.__vfsModules = vfsModules; | ||
| plugin.__vfs = vfs; | ||
| compiler.hooks.compilation.tap(plugin.name, (compilation, { normalModuleFactory }) => { | ||
| normalModuleFactory.hooks.resolve.tapPromise(plugin.name, async (resolveData) => { | ||
| const id = require_webpack_like.normalizeAbsolutePath(resolveData.request); | ||
| const requestContext = resolveData.contextInfo; | ||
| let importer = requestContext.issuer !== "" ? requestContext.issuer : void 0; | ||
| const isEntry = requestContext.issuer === ""; | ||
| if (importer?.startsWith(plugin.__virtualModulePrefix)) importer = decodeURIComponent(importer.slice(plugin.__virtualModulePrefix.length)); | ||
| const context = require_context$1.createBuildContext(compiler, compilation); | ||
| let error; | ||
| const pluginContext = { | ||
| error(msg) { | ||
| if (error == null) error = require_context$1.normalizeMessage(msg); | ||
| else console.error(`unplugin/rspack: multiple errors returned from resolveId hook: ${msg}`); | ||
| }, | ||
| warn(msg) { | ||
| console.warn(`unplugin/rspack: warning from resolveId hook: ${msg}`); | ||
| } | ||
| }; | ||
| const { handler, filter } = require_context.normalizeObjectHook("resolveId", plugin.resolveId); | ||
| if (!filter(id)) return; | ||
| const resolveIdResult = await handler.call({ | ||
| ...context, | ||
| ...pluginContext | ||
| }, id, importer, { isEntry }); | ||
| if (error != null) throw error; | ||
| if (resolveIdResult == null) return; | ||
| let resolved = typeof resolveIdResult === "string" ? resolveIdResult : resolveIdResult.id; | ||
| const isExternal = typeof resolveIdResult === "string" ? false : resolveIdResult.external === true; | ||
| if (isExternal) externalModules.add(resolved); | ||
| let isVirtual = true; | ||
| try { | ||
| (compiler.inputFileSystem?.statSync ?? node_fs.default.statSync)(resolved); | ||
| isVirtual = false; | ||
| } catch { | ||
| isVirtual = !require_utils.isVirtualModuleId(resolved, plugin); | ||
| } | ||
| if (isVirtual) { | ||
| const encodedVirtualPath = require_utils.encodeVirtualModuleId(resolved, plugin); | ||
| if (!vfsModules.has(resolved)) { | ||
| const fsPromise = Promise.resolve(vfs.writeModule(encodedVirtualPath, "")); | ||
| vfsModules.set(resolved, fsPromise); | ||
| await fsPromise; | ||
| } else await vfsModules.get(resolved); | ||
| resolved = encodedVirtualPath; | ||
| } | ||
| resolveData.request = resolved; | ||
| }); | ||
| }); | ||
| } | ||
| if (plugin.load) compiler.options.module.rules.unshift({ | ||
| enforce: plugin.enforce, | ||
| include(id) { | ||
| if (require_utils.isVirtualModuleId(id, plugin)) id = require_utils.decodeVirtualModuleId(id, plugin); | ||
| if (plugin.loadInclude && !plugin.loadInclude(id)) return false; | ||
| const { filter } = require_context.normalizeObjectHook("load", plugin.load); | ||
| if (!filter(id)) return false; | ||
| return !externalModules.has(id); | ||
| }, | ||
| use: [{ | ||
| loader: LOAD_LOADER$1, | ||
| options: { plugin } | ||
| }], | ||
| type: "javascript/auto" | ||
| }); | ||
| if (plugin.transform) compiler.options.module.rules.unshift({ | ||
| enforce: plugin.enforce, | ||
| use(data) { | ||
| return require_webpack_like.transformUse(data, plugin, TRANSFORM_LOADER$1); | ||
| } | ||
| }); | ||
| if (plugin.rspack) plugin.rspack(compiler); | ||
| if (plugin.watchChange || plugin.buildStart) compiler.hooks.make.tapPromise(plugin.name, async (compilation) => { | ||
| const context = require_context$1.createBuildContext(compiler, compilation); | ||
| if (plugin.watchChange && (compiler.modifiedFiles || compiler.removedFiles)) { | ||
| const promises = []; | ||
| if (compiler.modifiedFiles) compiler.modifiedFiles.forEach((file) => promises.push(Promise.resolve(plugin.watchChange.call(context, file, { event: "update" })))); | ||
| if (compiler.removedFiles) compiler.removedFiles.forEach((file) => promises.push(Promise.resolve(plugin.watchChange.call(context, file, { event: "delete" })))); | ||
| await Promise.all(promises); | ||
| } | ||
| if (plugin.buildStart) return await plugin.buildStart.call(context); | ||
| }); | ||
| if (plugin.buildEnd) compiler.hooks.emit.tapPromise(plugin.name, async (compilation) => { | ||
| await plugin.buildEnd.call(require_context$1.createBuildContext(compiler, compilation)); | ||
| }); | ||
| if (plugin.writeBundle) compiler.hooks.afterEmit.tapPromise(plugin.name, async () => { | ||
| await plugin.writeBundle(); | ||
| }); | ||
| } | ||
| } }; | ||
| }; | ||
| } | ||
| //#endregion | ||
| //#region src/unloader/index.ts | ||
| function getUnloaderPlugin(factory) { | ||
| return ((userOptions) => { | ||
| const meta = { framework: "unloader" }; | ||
| const rawPlugins = require_context.toArray(factory(userOptions, meta)); | ||
| const plugins = rawPlugins.map((rawPlugin) => { | ||
| const plugin = toRollupPlugin(rawPlugin, "unloader"); | ||
| return plugin; | ||
| }); | ||
| return plugins.length === 1 ? plugins[0] : plugins; | ||
| }); | ||
| } | ||
| //#endregion | ||
| //#region src/vite/index.ts | ||
| function getVitePlugin(factory) { | ||
| return ((userOptions) => { | ||
| const meta = { framework: "vite" }; | ||
| const rawPlugins = require_context.toArray(factory(userOptions, meta)); | ||
| const plugins = rawPlugins.map((rawPlugin) => { | ||
| const plugin = toRollupPlugin(rawPlugin, "vite"); | ||
| return plugin; | ||
| }); | ||
| return plugins.length === 1 ? plugins[0] : plugins; | ||
| }); | ||
| } | ||
| //#endregion | ||
| //#region src/webpack/index.ts | ||
| const TRANSFORM_LOADER = (0, node_path.resolve)(__dirname, "webpack/loaders/transform"); | ||
| const LOAD_LOADER = (0, node_path.resolve)(__dirname, "webpack/loaders/load"); | ||
| function getWebpackPlugin(factory) { | ||
| return (userOptions) => { | ||
| return { apply(compiler) { | ||
| const VIRTUAL_MODULE_PREFIX = (0, node_path.resolve)(compiler.options.context ?? node_process.default.cwd(), "_virtual_"); | ||
| const meta = { | ||
| framework: "webpack", | ||
| webpack: { compiler } | ||
| }; | ||
| const rawPlugins = require_context.toArray(factory(userOptions, meta)); | ||
| for (const rawPlugin of rawPlugins) { | ||
| const plugin = Object.assign(rawPlugin, { | ||
| __unpluginMeta: meta, | ||
| __virtualModulePrefix: VIRTUAL_MODULE_PREFIX | ||
| }); | ||
| const externalModules = /* @__PURE__ */ new Set(); | ||
| if (plugin.resolveId) { | ||
| let vfs = compiler.options.plugins.find((i) => i instanceof webpack_virtual_modules.default); | ||
| if (!vfs) { | ||
| vfs = new webpack_virtual_modules.default(); | ||
| compiler.options.plugins.push(vfs); | ||
| } | ||
| const vfsModules = /* @__PURE__ */ new Set(); | ||
| plugin.__vfsModules = vfsModules; | ||
| plugin.__vfs = vfs; | ||
| const resolverPlugin = { apply(resolver) { | ||
| const target = resolver.ensureHook("resolve"); | ||
| resolver.getHook("resolve").tapAsync(plugin.name, async (request, resolveContext, callback) => { | ||
| if (!request.request) return callback(); | ||
| if (require_webpack_like.normalizeAbsolutePath(request.request).startsWith(plugin.__virtualModulePrefix)) return callback(); | ||
| const id = require_webpack_like.normalizeAbsolutePath(request.request); | ||
| const requestContext = request.context; | ||
| let importer = requestContext.issuer !== "" ? requestContext.issuer : void 0; | ||
| const isEntry = requestContext.issuer === ""; | ||
| if (importer?.startsWith(plugin.__virtualModulePrefix)) importer = decodeURIComponent(importer.slice(plugin.__virtualModulePrefix.length)); | ||
| const fileDependencies = /* @__PURE__ */ new Set(); | ||
| const context = require_context$2.createBuildContext({ | ||
| addWatchFile(file) { | ||
| fileDependencies.add(file); | ||
| resolveContext.fileDependencies?.add(file); | ||
| }, | ||
| getWatchFiles() { | ||
| return Array.from(fileDependencies); | ||
| } | ||
| }, compiler); | ||
| let error; | ||
| const pluginContext = { | ||
| error(msg) { | ||
| if (error == null) error = require_context$2.normalizeMessage(msg); | ||
| else console.error(`unplugin/webpack: multiple errors returned from resolveId hook: ${msg}`); | ||
| }, | ||
| warn(msg) { | ||
| console.warn(`unplugin/webpack: warning from resolveId hook: ${msg}`); | ||
| } | ||
| }; | ||
| const { handler, filter } = require_context.normalizeObjectHook("resolveId", plugin.resolveId); | ||
| if (!filter(id)) return callback(); | ||
| const resolveIdResult = await handler.call({ | ||
| ...context, | ||
| ...pluginContext | ||
| }, id, importer, { isEntry }); | ||
| if (error != null) return callback(error); | ||
| if (resolveIdResult == null) return callback(); | ||
| let resolved = typeof resolveIdResult === "string" ? resolveIdResult : resolveIdResult.id; | ||
| const isExternal = typeof resolveIdResult === "string" ? false : resolveIdResult.external === true; | ||
| if (isExternal) externalModules.add(resolved); | ||
| if (!node_fs.default.existsSync(resolved)) { | ||
| resolved = require_webpack_like.normalizeAbsolutePath(plugin.__virtualModulePrefix + encodeURIComponent(resolved)); | ||
| if (!vfsModules.has(resolved)) { | ||
| plugin.__vfs.writeModule(resolved, ""); | ||
| vfsModules.add(resolved); | ||
| } | ||
| } | ||
| const newRequest = { | ||
| ...request, | ||
| request: resolved | ||
| }; | ||
| resolver.doResolve(target, newRequest, null, resolveContext, callback); | ||
| }); | ||
| } }; | ||
| compiler.options.resolve.plugins = compiler.options.resolve.plugins || []; | ||
| compiler.options.resolve.plugins.push(resolverPlugin); | ||
| } | ||
| if (plugin.load) compiler.options.module.rules.unshift({ | ||
| include(id) { | ||
| return shouldLoad(id, plugin, externalModules); | ||
| }, | ||
| enforce: plugin.enforce, | ||
| use: [{ | ||
| loader: LOAD_LOADER, | ||
| options: { plugin } | ||
| }], | ||
| type: "javascript/auto" | ||
| }); | ||
| if (plugin.transform) compiler.options.module.rules.unshift({ | ||
| enforce: plugin.enforce, | ||
| use(data) { | ||
| return require_webpack_like.transformUse(data, plugin, TRANSFORM_LOADER); | ||
| } | ||
| }); | ||
| if (plugin.webpack) plugin.webpack(compiler); | ||
| if (plugin.watchChange || plugin.buildStart) compiler.hooks.make.tapPromise(plugin.name, async (compilation) => { | ||
| const context = require_context$2.createBuildContext(require_context$2.contextOptionsFromCompilation(compilation), compiler, compilation); | ||
| if (plugin.watchChange && (compiler.modifiedFiles || compiler.removedFiles)) { | ||
| const promises = []; | ||
| if (compiler.modifiedFiles) compiler.modifiedFiles.forEach((file) => promises.push(Promise.resolve(plugin.watchChange.call(context, file, { event: "update" })))); | ||
| if (compiler.removedFiles) compiler.removedFiles.forEach((file) => promises.push(Promise.resolve(plugin.watchChange.call(context, file, { event: "delete" })))); | ||
| await Promise.all(promises); | ||
| } | ||
| if (plugin.buildStart) return await plugin.buildStart.call(context); | ||
| }); | ||
| if (plugin.buildEnd) compiler.hooks.emit.tapPromise(plugin.name, async (compilation) => { | ||
| await plugin.buildEnd.call(require_context$2.createBuildContext(require_context$2.contextOptionsFromCompilation(compilation), compiler, compilation)); | ||
| }); | ||
| if (plugin.writeBundle) compiler.hooks.afterEmit.tapPromise(plugin.name, async () => { | ||
| await plugin.writeBundle(); | ||
| }); | ||
| } | ||
| } }; | ||
| }; | ||
| } | ||
| function shouldLoad(id, plugin, externalModules) { | ||
| if (id.startsWith(plugin.__virtualModulePrefix)) id = decodeURIComponent(id.slice(plugin.__virtualModulePrefix.length)); | ||
| if (plugin.loadInclude && !plugin.loadInclude(id)) return false; | ||
| const { filter } = require_context.normalizeObjectHook("load", plugin.load); | ||
| if (!filter(id)) return false; | ||
| return !externalModules.has(id); | ||
| } | ||
| //#endregion | ||
| //#region src/define.ts | ||
| function createUnplugin(factory) { | ||
| return { | ||
| get esbuild() { | ||
| return getEsbuildPlugin(factory); | ||
| }, | ||
| get rollup() { | ||
| return getRollupPlugin(factory); | ||
| }, | ||
| get vite() { | ||
| return getVitePlugin(factory); | ||
| }, | ||
| get rolldown() { | ||
| return getRolldownPlugin(factory); | ||
| }, | ||
| get webpack() { | ||
| return getWebpackPlugin(factory); | ||
| }, | ||
| get rspack() { | ||
| return getRspackPlugin(factory); | ||
| }, | ||
| get farm() { | ||
| return getFarmPlugin(factory); | ||
| }, | ||
| get unloader() { | ||
| return getUnloaderPlugin(factory); | ||
| }, | ||
| get raw() { | ||
| return factory; | ||
| } | ||
| }; | ||
| } | ||
| function createEsbuildPlugin(factory) { | ||
| return getEsbuildPlugin(factory); | ||
| } | ||
| function createRollupPlugin(factory) { | ||
| return getRollupPlugin(factory); | ||
| } | ||
| function createVitePlugin(factory) { | ||
| return getVitePlugin(factory); | ||
| } | ||
| function createRolldownPlugin(factory) { | ||
| return getRolldownPlugin(factory); | ||
| } | ||
| function createWebpackPlugin(factory) { | ||
| return getWebpackPlugin(factory); | ||
| } | ||
| function createRspackPlugin(factory) { | ||
| return getRspackPlugin(factory); | ||
| } | ||
| function createFarmPlugin(factory) { | ||
| return getFarmPlugin(factory); | ||
| } | ||
| function createUnloaderPlugin(factory) { | ||
| return getUnloaderPlugin(factory); | ||
| } | ||
| //#endregion | ||
| exports.createEsbuildPlugin = createEsbuildPlugin; | ||
| exports.createFarmPlugin = createFarmPlugin; | ||
| exports.createRolldownPlugin = createRolldownPlugin; | ||
| exports.createRollupPlugin = createRollupPlugin; | ||
| exports.createRspackPlugin = createRspackPlugin; | ||
| exports.createUnloaderPlugin = createUnloaderPlugin; | ||
| exports.createUnplugin = createUnplugin; | ||
| exports.createVitePlugin = createVitePlugin; | ||
| exports.createWebpackPlugin = createWebpackPlugin; |
-196
| import { CompilationContext, JsPlugin } from "@farmfe/core"; | ||
| import { Compilation, Compiler as RspackCompiler, LoaderContext, RspackPluginInstance } from "@rspack/core"; | ||
| import { BuildOptions, Loader, Plugin as EsbuildPlugin, PluginBuild } from "esbuild"; | ||
| import { Plugin as RolldownPlugin } from "rolldown"; | ||
| import { AstNode, EmittedAsset, Plugin as RollupPlugin, PluginContextMeta, SourceMapInput } from "rollup"; | ||
| import { Plugin as UnloaderPlugin } from "unloader"; | ||
| import { Plugin as VitePlugin } from "vite"; | ||
| import { Compilation as Compilation$1, Compiler as WebpackCompiler, LoaderContext as LoaderContext$1, WebpackPluginInstance } from "webpack"; | ||
| import VirtualModulesPlugin from "webpack-virtual-modules"; | ||
| //#region src/types.d.ts | ||
| type Thenable<T> = T | Promise<T>; | ||
| /** | ||
| * Null or whatever | ||
| */ | ||
| type Nullable<T> = T | null | undefined; | ||
| /** | ||
| * Array, or not yet | ||
| */ | ||
| type Arrayable<T> = T | Array<T>; | ||
| interface SourceMapCompact { | ||
| file?: string | undefined; | ||
| mappings: string; | ||
| names: string[]; | ||
| sourceRoot?: string | undefined; | ||
| sources: string[]; | ||
| sourcesContent?: (string | null)[] | undefined; | ||
| version: number; | ||
| } | ||
| type TransformResult = string | { | ||
| code: string; | ||
| map?: SourceMapInput | SourceMapCompact | null | undefined; | ||
| } | null | undefined | void; | ||
| interface ExternalIdResult { | ||
| id: string; | ||
| external?: boolean | undefined; | ||
| } | ||
| type NativeBuildContext = { | ||
| framework: "webpack"; | ||
| compiler: WebpackCompiler; | ||
| compilation?: Compilation$1 | undefined; | ||
| loaderContext?: LoaderContext$1<{ | ||
| unpluginName: string; | ||
| }> | undefined; | ||
| } | { | ||
| framework: "esbuild"; | ||
| build: PluginBuild; | ||
| } | { | ||
| framework: "rspack"; | ||
| compiler: RspackCompiler; | ||
| compilation: Compilation; | ||
| loaderContext?: LoaderContext | undefined; | ||
| } | { | ||
| framework: "farm"; | ||
| context: CompilationContext; | ||
| }; | ||
| interface UnpluginBuildContext { | ||
| addWatchFile: (id: string) => void; | ||
| emitFile: (emittedFile: EmittedAsset) => void; | ||
| getWatchFiles: () => string[]; | ||
| parse: (input: string, options?: any) => AstNode; | ||
| getNativeBuildContext?: (() => NativeBuildContext) | undefined; | ||
| } | ||
| type StringOrRegExp = string | RegExp; | ||
| type FilterPattern = Arrayable<StringOrRegExp>; | ||
| type StringFilter = FilterPattern | { | ||
| include?: FilterPattern | undefined; | ||
| exclude?: FilterPattern | undefined; | ||
| }; | ||
| interface HookFilter { | ||
| id?: StringFilter | undefined; | ||
| code?: StringFilter | undefined; | ||
| } | ||
| interface ObjectHook<T extends HookFnMap[keyof HookFnMap], F extends keyof HookFilter> { | ||
| filter?: Pick<HookFilter, F> | undefined; | ||
| handler: T; | ||
| } | ||
| type Hook<T extends HookFnMap[keyof HookFnMap], F extends keyof HookFilter> = T | ObjectHook<T, F>; | ||
| interface HookFnMap { | ||
| buildStart: (this: UnpluginBuildContext) => Thenable<void>; | ||
| buildEnd: (this: UnpluginBuildContext) => Thenable<void>; | ||
| transform: (this: UnpluginBuildContext & UnpluginContext, code: string, id: string) => Thenable<TransformResult>; | ||
| load: (this: UnpluginBuildContext & UnpluginContext, id: string) => Thenable<TransformResult>; | ||
| resolveId: (this: UnpluginBuildContext & UnpluginContext, id: string, importer: string | undefined, options: { | ||
| isEntry: boolean; | ||
| }) => Thenable<string | ExternalIdResult | null | undefined>; | ||
| writeBundle: (this: void) => Thenable<void>; | ||
| } | ||
| interface UnpluginOptions { | ||
| name: string; | ||
| enforce?: "post" | "pre" | undefined; | ||
| buildStart?: HookFnMap["buildStart"] | undefined; | ||
| buildEnd?: HookFnMap["buildEnd"] | undefined; | ||
| transform?: Hook<HookFnMap["transform"], "code" | "id"> | undefined; | ||
| load?: Hook<HookFnMap["load"], "id"> | undefined; | ||
| resolveId?: Hook<HookFnMap["resolveId"], "id"> | undefined; | ||
| writeBundle?: HookFnMap["writeBundle"] | undefined; | ||
| watchChange?: ((this: UnpluginBuildContext, id: string, change: { | ||
| event: "create" | "update" | "delete"; | ||
| }) => void) | undefined; | ||
| /** | ||
| * Custom predicate function to filter modules to be loaded. | ||
| * When omitted, all modules will be included (might have potential perf impact on Webpack). | ||
| * | ||
| * @deprecated Use `load.filter` instead. | ||
| */ | ||
| loadInclude?: ((id: string) => boolean | null | undefined) | undefined; | ||
| /** | ||
| * Custom predicate function to filter modules to be transformed. | ||
| * When omitted, all modules will be included (might have potential perf impact on Webpack). | ||
| * | ||
| * @deprecated Use `transform.filter` instead. | ||
| */ | ||
| transformInclude?: ((id: string) => boolean | null | undefined) | undefined; | ||
| rollup?: Partial<RollupPlugin> | undefined; | ||
| webpack?: ((compiler: WebpackCompiler) => void) | undefined; | ||
| rspack?: ((compiler: RspackCompiler) => void) | undefined; | ||
| vite?: Partial<VitePlugin> | undefined; | ||
| unloader?: Partial<UnloaderPlugin> | undefined; | ||
| rolldown?: Partial<RolldownPlugin> | undefined; | ||
| esbuild?: { | ||
| onResolveFilter?: RegExp | undefined; | ||
| onLoadFilter?: RegExp | undefined; | ||
| loader?: Loader | ((code: string, id: string) => Loader) | undefined; | ||
| setup?: ((build: PluginBuild) => void | Promise<void>) | undefined; | ||
| config?: ((options: BuildOptions) => void) | undefined; | ||
| } | undefined; | ||
| farm?: Partial<JsPlugin> | undefined; | ||
| } | ||
| interface ResolvedUnpluginOptions extends UnpluginOptions { | ||
| __vfs?: VirtualModulesPlugin | undefined; | ||
| __vfsModules?: Map<string, Promise<unknown>> | Set<string> | undefined; | ||
| __virtualModulePrefix: string; | ||
| } | ||
| type UnpluginFactory<UserOptions, Nested extends boolean = boolean> = (options: UserOptions, meta: UnpluginContextMeta) => Nested extends true ? Array<UnpluginOptions> : UnpluginOptions; | ||
| type UnpluginFactoryOutput<UserOptions, Return> = undefined extends UserOptions ? (options?: UserOptions | undefined) => Return : (options: UserOptions) => Return; | ||
| interface UnpluginInstance<UserOptions, Nested extends boolean = boolean> { | ||
| rollup: UnpluginFactoryOutput<UserOptions, Nested extends true ? Array<RollupPlugin> : RollupPlugin>; | ||
| vite: UnpluginFactoryOutput<UserOptions, Nested extends true ? Array<VitePlugin> : VitePlugin>; | ||
| rolldown: UnpluginFactoryOutput<UserOptions, Nested extends true ? Array<RolldownPlugin> : RolldownPlugin>; | ||
| webpack: UnpluginFactoryOutput<UserOptions, WebpackPluginInstance>; | ||
| rspack: UnpluginFactoryOutput<UserOptions, RspackPluginInstance>; | ||
| esbuild: UnpluginFactoryOutput<UserOptions, EsbuildPlugin>; | ||
| unloader: UnpluginFactoryOutput<UserOptions, Nested extends true ? Array<UnloaderPlugin> : UnloaderPlugin>; | ||
| farm: UnpluginFactoryOutput<UserOptions, JsPlugin>; | ||
| raw: UnpluginFactory<UserOptions, Nested>; | ||
| } | ||
| type UnpluginContextMeta = Partial<PluginContextMeta> & ({ | ||
| framework: "rollup" | "vite" | "rolldown" | "farm" | "unloader"; | ||
| } | { | ||
| framework: "webpack"; | ||
| webpack: { | ||
| compiler: WebpackCompiler; | ||
| }; | ||
| } | { | ||
| framework: "esbuild"; | ||
| /** Set the host plugin name of esbuild when returning multiple plugins */ | ||
| esbuildHostName?: string | undefined; | ||
| } | { | ||
| framework: "rspack"; | ||
| rspack: { | ||
| compiler: RspackCompiler; | ||
| }; | ||
| }); | ||
| interface UnpluginMessage { | ||
| name?: string | undefined; | ||
| id?: string | undefined; | ||
| message: string; | ||
| stack?: string | undefined; | ||
| code?: string | undefined; | ||
| plugin?: string | undefined; | ||
| pluginCode?: unknown | undefined; | ||
| loc?: { | ||
| column: number; | ||
| file?: string | undefined; | ||
| line: number; | ||
| } | undefined; | ||
| meta?: any; | ||
| } | ||
| interface UnpluginContext { | ||
| error: (message: string | UnpluginMessage) => void; | ||
| warn: (message: string | UnpluginMessage) => void; | ||
| } | ||
| //#endregion | ||
| //#region src/define.d.ts | ||
| declare function createUnplugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions, Nested>; | ||
| declare function createEsbuildPlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["esbuild"]; | ||
| declare function createRollupPlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["rollup"]; | ||
| declare function createVitePlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["vite"]; | ||
| declare function createRolldownPlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["rolldown"]; | ||
| declare function createWebpackPlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["webpack"]; | ||
| declare function createRspackPlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["rspack"]; | ||
| declare function createFarmPlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["farm"]; | ||
| declare function createUnloaderPlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["unloader"]; | ||
| //#endregion | ||
| export { Arrayable, type EsbuildPlugin, ExternalIdResult, FilterPattern, Hook, HookFilter, HookFnMap, NativeBuildContext, Nullable, ObjectHook, ResolvedUnpluginOptions, type RolldownPlugin, type RollupPlugin, type RspackCompiler, type RspackPluginInstance, SourceMapCompact, StringFilter, StringOrRegExp, Thenable, TransformResult, type UnloaderPlugin, UnpluginBuildContext, UnpluginContext, UnpluginContextMeta, UnpluginFactory, UnpluginFactoryOutput, UnpluginInstance, UnpluginMessage, UnpluginOptions, type VitePlugin, type WebpackCompiler, type WebpackPluginInstance, createEsbuildPlugin, createFarmPlugin, createRolldownPlugin, createRollupPlugin, createRspackPlugin, createUnloaderPlugin, createUnplugin, createVitePlugin, createWebpackPlugin }; |
-196
| import VirtualModulesPlugin from "webpack-virtual-modules"; | ||
| import { CompilationContext, JsPlugin } from "@farmfe/core"; | ||
| import { Compilation, Compiler as RspackCompiler, LoaderContext, RspackPluginInstance } from "@rspack/core"; | ||
| import { BuildOptions, Loader, Plugin as EsbuildPlugin, PluginBuild } from "esbuild"; | ||
| import { Plugin as RolldownPlugin } from "rolldown"; | ||
| import { AstNode, EmittedAsset, Plugin as RollupPlugin, PluginContextMeta, SourceMapInput } from "rollup"; | ||
| import { Plugin as UnloaderPlugin } from "unloader"; | ||
| import { Plugin as VitePlugin } from "vite"; | ||
| import { Compilation as Compilation$1, Compiler as WebpackCompiler, LoaderContext as LoaderContext$1, WebpackPluginInstance } from "webpack"; | ||
| //#region src/types.d.ts | ||
| type Thenable<T> = T | Promise<T>; | ||
| /** | ||
| * Null or whatever | ||
| */ | ||
| type Nullable<T> = T | null | undefined; | ||
| /** | ||
| * Array, or not yet | ||
| */ | ||
| type Arrayable<T> = T | Array<T>; | ||
| interface SourceMapCompact { | ||
| file?: string | undefined; | ||
| mappings: string; | ||
| names: string[]; | ||
| sourceRoot?: string | undefined; | ||
| sources: string[]; | ||
| sourcesContent?: (string | null)[] | undefined; | ||
| version: number; | ||
| } | ||
| type TransformResult = string | { | ||
| code: string; | ||
| map?: SourceMapInput | SourceMapCompact | null | undefined; | ||
| } | null | undefined | void; | ||
| interface ExternalIdResult { | ||
| id: string; | ||
| external?: boolean | undefined; | ||
| } | ||
| type NativeBuildContext = { | ||
| framework: "webpack"; | ||
| compiler: WebpackCompiler; | ||
| compilation?: Compilation$1 | undefined; | ||
| loaderContext?: LoaderContext$1<{ | ||
| unpluginName: string; | ||
| }> | undefined; | ||
| } | { | ||
| framework: "esbuild"; | ||
| build: PluginBuild; | ||
| } | { | ||
| framework: "rspack"; | ||
| compiler: RspackCompiler; | ||
| compilation: Compilation; | ||
| loaderContext?: LoaderContext | undefined; | ||
| } | { | ||
| framework: "farm"; | ||
| context: CompilationContext; | ||
| }; | ||
| interface UnpluginBuildContext { | ||
| addWatchFile: (id: string) => void; | ||
| emitFile: (emittedFile: EmittedAsset) => void; | ||
| getWatchFiles: () => string[]; | ||
| parse: (input: string, options?: any) => AstNode; | ||
| getNativeBuildContext?: (() => NativeBuildContext) | undefined; | ||
| } | ||
| type StringOrRegExp = string | RegExp; | ||
| type FilterPattern = Arrayable<StringOrRegExp>; | ||
| type StringFilter = FilterPattern | { | ||
| include?: FilterPattern | undefined; | ||
| exclude?: FilterPattern | undefined; | ||
| }; | ||
| interface HookFilter { | ||
| id?: StringFilter | undefined; | ||
| code?: StringFilter | undefined; | ||
| } | ||
| interface ObjectHook<T extends HookFnMap[keyof HookFnMap], F extends keyof HookFilter> { | ||
| filter?: Pick<HookFilter, F> | undefined; | ||
| handler: T; | ||
| } | ||
| type Hook<T extends HookFnMap[keyof HookFnMap], F extends keyof HookFilter> = T | ObjectHook<T, F>; | ||
| interface HookFnMap { | ||
| buildStart: (this: UnpluginBuildContext) => Thenable<void>; | ||
| buildEnd: (this: UnpluginBuildContext) => Thenable<void>; | ||
| transform: (this: UnpluginBuildContext & UnpluginContext, code: string, id: string) => Thenable<TransformResult>; | ||
| load: (this: UnpluginBuildContext & UnpluginContext, id: string) => Thenable<TransformResult>; | ||
| resolveId: (this: UnpluginBuildContext & UnpluginContext, id: string, importer: string | undefined, options: { | ||
| isEntry: boolean; | ||
| }) => Thenable<string | ExternalIdResult | null | undefined>; | ||
| writeBundle: (this: void) => Thenable<void>; | ||
| } | ||
| interface UnpluginOptions { | ||
| name: string; | ||
| enforce?: "post" | "pre" | undefined; | ||
| buildStart?: HookFnMap["buildStart"] | undefined; | ||
| buildEnd?: HookFnMap["buildEnd"] | undefined; | ||
| transform?: Hook<HookFnMap["transform"], "code" | "id"> | undefined; | ||
| load?: Hook<HookFnMap["load"], "id"> | undefined; | ||
| resolveId?: Hook<HookFnMap["resolveId"], "id"> | undefined; | ||
| writeBundle?: HookFnMap["writeBundle"] | undefined; | ||
| watchChange?: ((this: UnpluginBuildContext, id: string, change: { | ||
| event: "create" | "update" | "delete"; | ||
| }) => void) | undefined; | ||
| /** | ||
| * Custom predicate function to filter modules to be loaded. | ||
| * When omitted, all modules will be included (might have potential perf impact on Webpack). | ||
| * | ||
| * @deprecated Use `load.filter` instead. | ||
| */ | ||
| loadInclude?: ((id: string) => boolean | null | undefined) | undefined; | ||
| /** | ||
| * Custom predicate function to filter modules to be transformed. | ||
| * When omitted, all modules will be included (might have potential perf impact on Webpack). | ||
| * | ||
| * @deprecated Use `transform.filter` instead. | ||
| */ | ||
| transformInclude?: ((id: string) => boolean | null | undefined) | undefined; | ||
| rollup?: Partial<RollupPlugin> | undefined; | ||
| webpack?: ((compiler: WebpackCompiler) => void) | undefined; | ||
| rspack?: ((compiler: RspackCompiler) => void) | undefined; | ||
| vite?: Partial<VitePlugin> | undefined; | ||
| unloader?: Partial<UnloaderPlugin> | undefined; | ||
| rolldown?: Partial<RolldownPlugin> | undefined; | ||
| esbuild?: { | ||
| onResolveFilter?: RegExp | undefined; | ||
| onLoadFilter?: RegExp | undefined; | ||
| loader?: Loader | ((code: string, id: string) => Loader) | undefined; | ||
| setup?: ((build: PluginBuild) => void | Promise<void>) | undefined; | ||
| config?: ((options: BuildOptions) => void) | undefined; | ||
| } | undefined; | ||
| farm?: Partial<JsPlugin> | undefined; | ||
| } | ||
| interface ResolvedUnpluginOptions extends UnpluginOptions { | ||
| __vfs?: VirtualModulesPlugin | undefined; | ||
| __vfsModules?: Map<string, Promise<unknown>> | Set<string> | undefined; | ||
| __virtualModulePrefix: string; | ||
| } | ||
| type UnpluginFactory<UserOptions, Nested extends boolean = boolean> = (options: UserOptions, meta: UnpluginContextMeta) => Nested extends true ? Array<UnpluginOptions> : UnpluginOptions; | ||
| type UnpluginFactoryOutput<UserOptions, Return> = undefined extends UserOptions ? (options?: UserOptions | undefined) => Return : (options: UserOptions) => Return; | ||
| interface UnpluginInstance<UserOptions, Nested extends boolean = boolean> { | ||
| rollup: UnpluginFactoryOutput<UserOptions, Nested extends true ? Array<RollupPlugin> : RollupPlugin>; | ||
| vite: UnpluginFactoryOutput<UserOptions, Nested extends true ? Array<VitePlugin> : VitePlugin>; | ||
| rolldown: UnpluginFactoryOutput<UserOptions, Nested extends true ? Array<RolldownPlugin> : RolldownPlugin>; | ||
| webpack: UnpluginFactoryOutput<UserOptions, WebpackPluginInstance>; | ||
| rspack: UnpluginFactoryOutput<UserOptions, RspackPluginInstance>; | ||
| esbuild: UnpluginFactoryOutput<UserOptions, EsbuildPlugin>; | ||
| unloader: UnpluginFactoryOutput<UserOptions, Nested extends true ? Array<UnloaderPlugin> : UnloaderPlugin>; | ||
| farm: UnpluginFactoryOutput<UserOptions, JsPlugin>; | ||
| raw: UnpluginFactory<UserOptions, Nested>; | ||
| } | ||
| type UnpluginContextMeta = Partial<PluginContextMeta> & ({ | ||
| framework: "rollup" | "vite" | "rolldown" | "farm" | "unloader"; | ||
| } | { | ||
| framework: "webpack"; | ||
| webpack: { | ||
| compiler: WebpackCompiler; | ||
| }; | ||
| } | { | ||
| framework: "esbuild"; | ||
| /** Set the host plugin name of esbuild when returning multiple plugins */ | ||
| esbuildHostName?: string | undefined; | ||
| } | { | ||
| framework: "rspack"; | ||
| rspack: { | ||
| compiler: RspackCompiler; | ||
| }; | ||
| }); | ||
| interface UnpluginMessage { | ||
| name?: string | undefined; | ||
| id?: string | undefined; | ||
| message: string; | ||
| stack?: string | undefined; | ||
| code?: string | undefined; | ||
| plugin?: string | undefined; | ||
| pluginCode?: unknown | undefined; | ||
| loc?: { | ||
| column: number; | ||
| file?: string | undefined; | ||
| line: number; | ||
| } | undefined; | ||
| meta?: any; | ||
| } | ||
| interface UnpluginContext { | ||
| error: (message: string | UnpluginMessage) => void; | ||
| warn: (message: string | UnpluginMessage) => void; | ||
| } | ||
| //#endregion | ||
| //#region src/define.d.ts | ||
| declare function createUnplugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions, Nested>; | ||
| declare function createEsbuildPlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["esbuild"]; | ||
| declare function createRollupPlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["rollup"]; | ||
| declare function createVitePlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["vite"]; | ||
| declare function createRolldownPlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["rolldown"]; | ||
| declare function createWebpackPlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["webpack"]; | ||
| declare function createRspackPlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["rspack"]; | ||
| declare function createFarmPlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["farm"]; | ||
| declare function createUnloaderPlugin<UserOptions, Nested extends boolean = boolean>(factory: UnpluginFactory<UserOptions, Nested>): UnpluginInstance<UserOptions>["unloader"]; | ||
| //#endregion | ||
| export { Arrayable, type EsbuildPlugin, ExternalIdResult, FilterPattern, Hook, HookFilter, HookFnMap, NativeBuildContext, Nullable, ObjectHook, ResolvedUnpluginOptions, type RolldownPlugin, type RollupPlugin, type RspackCompiler, type RspackPluginInstance, SourceMapCompact, StringFilter, StringOrRegExp, Thenable, TransformResult, type UnloaderPlugin, UnpluginBuildContext, UnpluginContext, UnpluginContextMeta, UnpluginFactory, UnpluginFactoryOutput, UnpluginInstance, UnpluginMessage, UnpluginOptions, type VitePlugin, type WebpackCompiler, type WebpackPluginInstance, createEsbuildPlugin, createFarmPlugin, createRolldownPlugin, createRollupPlugin, createRspackPlugin, createUnloaderPlugin, createUnplugin, createVitePlugin, createWebpackPlugin }; |
-1038
| import { normalizeObjectHook, parse, toArray } from "./context-D49cMElb.js"; | ||
| import { normalizeAbsolutePath, transformUse } from "./webpack-like-CSbnjTNU.js"; | ||
| import { createBuildContext as createBuildContext$1, normalizeMessage as normalizeMessage$1 } from "./context-D_KPTgTH.js"; | ||
| import { FakeVirtualModulesPlugin, decodeVirtualModuleId, encodeVirtualModuleId, isVirtualModuleId } from "./utils-C8vphsat.js"; | ||
| import { contextOptionsFromCompilation, createBuildContext, normalizeMessage } from "./context-BZKy5Nsn.js"; | ||
| import fs from "node:fs"; | ||
| import path, { extname, resolve } from "node:path"; | ||
| import { Buffer } from "node:buffer"; | ||
| import remapping from "@jridgewell/remapping"; | ||
| import * as querystring from "node:querystring"; | ||
| import { fileURLToPath } from "node:url"; | ||
| import process$1 from "node:process"; | ||
| import VirtualModulesPlugin from "webpack-virtual-modules"; | ||
| //#region src/esbuild/utils.ts | ||
| const ExtToLoader = { | ||
| ".js": "js", | ||
| ".mjs": "js", | ||
| ".cjs": "js", | ||
| ".jsx": "jsx", | ||
| ".ts": "ts", | ||
| ".cts": "ts", | ||
| ".mts": "ts", | ||
| ".tsx": "tsx", | ||
| ".css": "css", | ||
| ".less": "css", | ||
| ".stylus": "css", | ||
| ".scss": "css", | ||
| ".sass": "css", | ||
| ".json": "json", | ||
| ".txt": "text" | ||
| }; | ||
| function guessLoader(code, id) { | ||
| return ExtToLoader[path.extname(id).toLowerCase()] || "js"; | ||
| } | ||
| function unwrapLoader(loader, code, id) { | ||
| if (typeof loader === "function") return loader(code, id); | ||
| return loader; | ||
| } | ||
| function fixSourceMap(map) { | ||
| if (!Object.prototype.hasOwnProperty.call(map, "toString")) Object.defineProperty(map, "toString", { | ||
| enumerable: false, | ||
| value: function toString() { | ||
| return JSON.stringify(this); | ||
| } | ||
| }); | ||
| if (!Object.prototype.hasOwnProperty.call(map, "toUrl")) Object.defineProperty(map, "toUrl", { | ||
| enumerable: false, | ||
| value: function toUrl() { | ||
| return `data:application/json;charset=utf-8;base64,${Buffer.from(this.toString()).toString("base64")}`; | ||
| } | ||
| }); | ||
| return map; | ||
| } | ||
| const nullSourceMap = { | ||
| names: [], | ||
| sources: [], | ||
| mappings: "", | ||
| version: 3 | ||
| }; | ||
| function combineSourcemaps(filename, sourcemapList) { | ||
| sourcemapList = sourcemapList.filter((m) => m.sources); | ||
| if (sourcemapList.length === 0 || sourcemapList.every((m) => m.sources.length === 0)) return { ...nullSourceMap }; | ||
| let map; | ||
| let mapIndex = 1; | ||
| const useArrayInterface = sourcemapList.slice(0, -1).find((m) => m.sources.length !== 1) === void 0; | ||
| if (useArrayInterface) map = remapping(sourcemapList, () => null, true); | ||
| else map = remapping(sourcemapList[0], (sourcefile) => { | ||
| if (sourcefile === filename && sourcemapList[mapIndex]) return sourcemapList[mapIndex++]; | ||
| else return { ...nullSourceMap }; | ||
| }, true); | ||
| if (!map.file) delete map.file; | ||
| return map; | ||
| } | ||
| function createBuildContext$2(build) { | ||
| const watchFiles = []; | ||
| const { initialOptions } = build; | ||
| return { | ||
| parse, | ||
| addWatchFile() { | ||
| throw new Error("unplugin/esbuild: addWatchFile outside supported hooks (resolveId, load, transform)"); | ||
| }, | ||
| emitFile(emittedFile) { | ||
| const outFileName = emittedFile.fileName || emittedFile.name; | ||
| if (initialOptions.outdir && emittedFile.source && outFileName) { | ||
| const outPath = path.resolve(initialOptions.outdir, outFileName); | ||
| const outDir = path.dirname(outPath); | ||
| if (!fs.existsSync(outDir)) fs.mkdirSync(outDir, { recursive: true }); | ||
| fs.writeFileSync(outPath, emittedFile.source); | ||
| } | ||
| }, | ||
| getWatchFiles() { | ||
| return watchFiles; | ||
| }, | ||
| getNativeBuildContext() { | ||
| return { | ||
| framework: "esbuild", | ||
| build | ||
| }; | ||
| } | ||
| }; | ||
| } | ||
| function createPluginContext(context) { | ||
| const errors = []; | ||
| const warnings = []; | ||
| const pluginContext = { | ||
| error(message) { | ||
| errors.push(normalizeMessage$2(message)); | ||
| }, | ||
| warn(message) { | ||
| warnings.push(normalizeMessage$2(message)); | ||
| } | ||
| }; | ||
| const mixedContext = { | ||
| ...context, | ||
| ...pluginContext, | ||
| addWatchFile(id) { | ||
| context.getWatchFiles().push(id); | ||
| } | ||
| }; | ||
| return { | ||
| errors, | ||
| warnings, | ||
| mixedContext | ||
| }; | ||
| } | ||
| function normalizeMessage$2(message) { | ||
| if (typeof message === "string") message = { message }; | ||
| return { | ||
| id: message.id, | ||
| pluginName: message.plugin, | ||
| text: message.message, | ||
| location: message.loc ? { | ||
| file: message.loc.file, | ||
| line: message.loc.line, | ||
| column: message.loc.column | ||
| } : null, | ||
| detail: message.meta, | ||
| notes: [] | ||
| }; | ||
| } | ||
| function processCodeWithSourceMap(map, code) { | ||
| if (map) { | ||
| if (!map.sourcesContent || map.sourcesContent.length === 0) map.sourcesContent = [code]; | ||
| map = fixSourceMap(map); | ||
| code += `\n//# sourceMappingURL=${map.toUrl()}`; | ||
| } | ||
| return code; | ||
| } | ||
| //#endregion | ||
| //#region src/esbuild/index.ts | ||
| function getEsbuildPlugin(factory) { | ||
| return (userOptions) => { | ||
| const meta = { framework: "esbuild" }; | ||
| const plugins = toArray(factory(userOptions, meta)); | ||
| const setupPlugins = async (build) => { | ||
| const setup = buildSetup(); | ||
| const loaders = []; | ||
| for (const plugin of plugins) { | ||
| const loader = {}; | ||
| await setup(plugin)({ | ||
| ...build, | ||
| onLoad(_options, callback) { | ||
| loader.options = _options; | ||
| loader.onLoadCb = callback; | ||
| }, | ||
| onTransform(_options, callback) { | ||
| loader.options ||= _options; | ||
| loader.onTransformCb = callback; | ||
| } | ||
| }, build); | ||
| if (loader.onLoadCb || loader.onTransformCb) loaders.push(loader); | ||
| } | ||
| if (loaders.length) build.onLoad(loaders.length === 1 ? loaders[0].options : { filter: /.*/ }, async (args) => { | ||
| function checkFilter(options) { | ||
| return loaders.length === 1 || !options?.filter || options.filter.test(args.path); | ||
| } | ||
| let result; | ||
| for (const { options, onLoadCb } of loaders) { | ||
| if (!checkFilter(options)) continue; | ||
| if (onLoadCb) result = await onLoadCb(args); | ||
| if (result?.contents) break; | ||
| } | ||
| let fsContentsCache; | ||
| for (const { options, onTransformCb } of loaders) { | ||
| if (!checkFilter(options)) continue; | ||
| if (onTransformCb) { | ||
| const newArgs = { | ||
| ...result, | ||
| ...args, | ||
| async getContents() { | ||
| if (result?.contents) return result.contents; | ||
| if (fsContentsCache) return fsContentsCache; | ||
| return fsContentsCache = await fs.promises.readFile(args.path, "utf8"); | ||
| } | ||
| }; | ||
| const _result = await onTransformCb(newArgs); | ||
| if (_result?.contents) result = _result; | ||
| } | ||
| } | ||
| if (result?.contents) return result; | ||
| }); | ||
| }; | ||
| return { | ||
| name: (plugins.length === 1 ? plugins[0].name : meta.esbuildHostName) ?? `unplugin-host:${plugins.map((p) => p.name).join(":")}`, | ||
| setup: setupPlugins | ||
| }; | ||
| }; | ||
| } | ||
| function buildSetup() { | ||
| return (plugin) => { | ||
| return (build, rawBuild) => { | ||
| const context = createBuildContext$2(rawBuild); | ||
| const { onStart, onEnd, onResolve, onLoad, onTransform, initialOptions } = build; | ||
| const onResolveFilter = plugin.esbuild?.onResolveFilter ?? /.*/; | ||
| const onLoadFilter = plugin.esbuild?.onLoadFilter ?? /.*/; | ||
| const loader = plugin.esbuild?.loader ?? guessLoader; | ||
| plugin.esbuild?.config?.call(context, initialOptions); | ||
| if (plugin.buildStart) onStart(() => plugin.buildStart.call(context)); | ||
| if (plugin.buildEnd || plugin.writeBundle) onEnd(async () => { | ||
| if (plugin.buildEnd) await plugin.buildEnd.call(context); | ||
| if (plugin.writeBundle) await plugin.writeBundle(); | ||
| }); | ||
| if (plugin.resolveId) onResolve({ filter: onResolveFilter }, async (args) => { | ||
| const id = args.path; | ||
| if (initialOptions.external?.includes(id)) return; | ||
| const { handler, filter } = normalizeObjectHook("resolveId", plugin.resolveId); | ||
| if (!filter(id)) return; | ||
| const { errors, warnings, mixedContext } = createPluginContext(context); | ||
| const isEntry = args.kind === "entry-point"; | ||
| const result = await handler.call(mixedContext, id, isEntry ? void 0 : args.importer, { isEntry }); | ||
| if (typeof result === "string") return { | ||
| path: result, | ||
| namespace: plugin.name, | ||
| errors, | ||
| warnings, | ||
| watchFiles: mixedContext.getWatchFiles() | ||
| }; | ||
| else if (typeof result === "object" && result !== null) return { | ||
| path: result.id, | ||
| external: result.external, | ||
| namespace: plugin.name, | ||
| errors, | ||
| warnings, | ||
| watchFiles: mixedContext.getWatchFiles() | ||
| }; | ||
| }); | ||
| if (plugin.load) onLoad({ filter: onLoadFilter }, async (args) => { | ||
| const { handler, filter } = normalizeObjectHook("load", plugin.load); | ||
| const id = args.path + (args.suffix || ""); | ||
| if (plugin.loadInclude && !plugin.loadInclude(id)) return; | ||
| if (!filter(id)) return; | ||
| const { errors, warnings, mixedContext } = createPluginContext(context); | ||
| let code; | ||
| let map; | ||
| const result = await handler.call(mixedContext, id); | ||
| if (typeof result === "string") code = result; | ||
| else if (typeof result === "object" && result !== null) { | ||
| code = result.code; | ||
| map = result.map; | ||
| } | ||
| if (code === void 0) return null; | ||
| if (map) code = processCodeWithSourceMap(map, code); | ||
| const resolveDir = path.dirname(args.path); | ||
| return { | ||
| contents: code, | ||
| errors, | ||
| warnings, | ||
| watchFiles: mixedContext.getWatchFiles(), | ||
| loader: unwrapLoader(loader, code, args.path), | ||
| resolveDir | ||
| }; | ||
| }); | ||
| if (plugin.transform) onTransform({ filter: onLoadFilter }, async (args) => { | ||
| const { handler, filter } = normalizeObjectHook("transform", plugin.transform); | ||
| const id = args.path + (args.suffix || ""); | ||
| if (plugin.transformInclude && !plugin.transformInclude(id)) return; | ||
| let code = await args.getContents(); | ||
| if (!filter(id, code)) return; | ||
| const { mixedContext, errors, warnings } = createPluginContext(context); | ||
| const resolveDir = path.dirname(args.path); | ||
| let map; | ||
| const result = await handler.call(mixedContext, code, id); | ||
| if (typeof result === "string") code = result; | ||
| else if (typeof result === "object" && result !== null) { | ||
| code = result.code; | ||
| if (map && result.map) map = combineSourcemaps(args.path, [result.map === "string" ? JSON.parse(result.map) : result.map, map]); | ||
| else if (typeof result.map === "string") map = JSON.parse(result.map); | ||
| else map = result.map; | ||
| } | ||
| if (code) { | ||
| if (map) code = processCodeWithSourceMap(map, code); | ||
| return { | ||
| contents: code, | ||
| errors, | ||
| warnings, | ||
| watchFiles: mixedContext.getWatchFiles(), | ||
| loader: unwrapLoader(loader, code, args.path), | ||
| resolveDir | ||
| }; | ||
| } | ||
| }); | ||
| if (plugin.esbuild?.setup) return plugin.esbuild.setup(rawBuild); | ||
| }; | ||
| }; | ||
| } | ||
| //#endregion | ||
| //#region src/farm/context.ts | ||
| function createFarmContext(context, currentResolveId) { | ||
| return { | ||
| parse, | ||
| addWatchFile(id) { | ||
| context.addWatchFile(id, currentResolveId || id); | ||
| }, | ||
| emitFile(emittedFile) { | ||
| const outFileName = emittedFile.fileName || emittedFile.name; | ||
| if (emittedFile.source && outFileName) context.emitFile({ | ||
| resolvedPath: outFileName, | ||
| name: outFileName, | ||
| content: [...Buffer.from(emittedFile.source)], | ||
| resourceType: extname(outFileName) | ||
| }); | ||
| }, | ||
| getWatchFiles() { | ||
| return context.getWatchFiles(); | ||
| }, | ||
| getNativeBuildContext() { | ||
| return { | ||
| framework: "farm", | ||
| context | ||
| }; | ||
| } | ||
| }; | ||
| } | ||
| function unpluginContext(context) { | ||
| return { | ||
| error: (error) => context.error(typeof error === "string" ? new Error(error) : error), | ||
| warn: (error) => context.warn(typeof error === "string" ? new Error(error) : error) | ||
| }; | ||
| } | ||
| //#endregion | ||
| //#region src/farm/utils.ts | ||
| function convertEnforceToPriority(value) { | ||
| const defaultPriority = 100; | ||
| const enforceToPriority = { | ||
| pre: 102, | ||
| post: 98 | ||
| }; | ||
| return enforceToPriority[value] !== void 0 ? enforceToPriority[value] : defaultPriority; | ||
| } | ||
| function convertWatchEventChange(value) { | ||
| const watchEventChange = { | ||
| Added: "create", | ||
| Updated: "update", | ||
| Removed: "delete" | ||
| }; | ||
| return watchEventChange[value]; | ||
| } | ||
| function isString(variable) { | ||
| return typeof variable === "string"; | ||
| } | ||
| function isObject(variable) { | ||
| return typeof variable === "object" && variable !== null; | ||
| } | ||
| function customParseQueryString(url) { | ||
| if (!url) return []; | ||
| const queryString = url.split("?")[1]; | ||
| const parsedParams = querystring.parse(queryString); | ||
| const paramsArray = []; | ||
| for (const key in parsedParams) paramsArray.push([key, parsedParams[key]]); | ||
| return paramsArray; | ||
| } | ||
| function encodeStr(str) { | ||
| const len = str.length; | ||
| if (len === 0) return str; | ||
| const firstNullIndex = str.indexOf("\0"); | ||
| if (firstNullIndex === -1) return str; | ||
| const result = Array.from({ length: len + countNulls(str, firstNullIndex) }); | ||
| let pos = 0; | ||
| for (let i = 0; i < firstNullIndex; i++) result[pos++] = str[i]; | ||
| for (let i = firstNullIndex; i < len; i++) { | ||
| const char = str[i]; | ||
| if (char === "\0") { | ||
| result[pos++] = "\\"; | ||
| result[pos++] = "0"; | ||
| } else result[pos++] = char; | ||
| } | ||
| return path.posix.normalize(result.join("")); | ||
| } | ||
| function decodeStr(str) { | ||
| const len = str.length; | ||
| if (len === 0) return str; | ||
| const firstIndex = str.indexOf("\\0"); | ||
| if (firstIndex === -1) return str; | ||
| const result = Array.from({ length: len - countBackslashZeros(str, firstIndex) }); | ||
| let pos = 0; | ||
| for (let i$1 = 0; i$1 < firstIndex; i$1++) result[pos++] = str[i$1]; | ||
| let i = firstIndex; | ||
| while (i < len) if (str[i] === "\\" && str[i + 1] === "0") { | ||
| result[pos++] = "\0"; | ||
| i += 2; | ||
| } else result[pos++] = str[i++]; | ||
| return path.posix.normalize(result.join("")); | ||
| } | ||
| function getContentValue(content) { | ||
| if (content === null || content === void 0) throw new Error("Content cannot be null or undefined"); | ||
| const strContent = typeof content === "string" ? content : content.code || ""; | ||
| return encodeStr(strContent); | ||
| } | ||
| function countNulls(str, startIndex) { | ||
| let count = 0; | ||
| const len = str.length; | ||
| for (let i = startIndex; i < len; i++) if (str[i] === "\0") count++; | ||
| return count; | ||
| } | ||
| function countBackslashZeros(str, startIndex) { | ||
| let count = 0; | ||
| const len = str.length; | ||
| for (let i = startIndex; i < len - 1; i++) if (str[i] === "\\" && str[i + 1] === "0") { | ||
| count++; | ||
| i++; | ||
| } | ||
| return count; | ||
| } | ||
| function removeQuery(pathe) { | ||
| const queryIndex = pathe.indexOf("?"); | ||
| if (queryIndex !== -1) return path.posix.normalize(pathe.slice(0, queryIndex)); | ||
| return path.posix.normalize(pathe); | ||
| } | ||
| function isStartsWithSlash(str) { | ||
| return str?.startsWith("/"); | ||
| } | ||
| function appendQuery(id, query) { | ||
| if (!query.length) return id; | ||
| return `${id}?${stringifyQuery(query)}`; | ||
| } | ||
| function stringifyQuery(query) { | ||
| if (!query.length) return ""; | ||
| let queryStr = ""; | ||
| for (const [key, value] of query) queryStr += `${key}${value ? `=${value}` : ""}&`; | ||
| return `${queryStr.slice(0, -1)}`; | ||
| } | ||
| const CSS_LANGS_RES = [ | ||
| [/\.(less)(?:$|\?)/, "less"], | ||
| [/\.(scss|sass)(?:$|\?)/, "sass"], | ||
| [/\.(styl|stylus)(?:$|\?)/, "stylus"], | ||
| [/\.(css)(?:$|\?)/, "css"] | ||
| ]; | ||
| const JS_LANGS_RES = [ | ||
| [/\.(js|mjs|cjs)(?:$|\?)/, "js"], | ||
| [/\.(jsx)(?:$|\?)/, "jsx"], | ||
| [/\.(ts|cts|mts)(?:$|\?)/, "ts"], | ||
| [/\.(tsx)(?:$|\?)/, "tsx"] | ||
| ]; | ||
| function getCssModuleType(id) { | ||
| for (const [reg, lang] of CSS_LANGS_RES) if (reg.test(id)) return lang; | ||
| return null; | ||
| } | ||
| function getJsModuleType(id) { | ||
| for (const [reg, lang] of JS_LANGS_RES) if (reg.test(id)) return lang; | ||
| return null; | ||
| } | ||
| function formatLoadModuleType(id) { | ||
| const cssModuleType = getCssModuleType(id); | ||
| if (cssModuleType) return cssModuleType; | ||
| const jsModuleType = getJsModuleType(id); | ||
| if (jsModuleType) return jsModuleType; | ||
| return "js"; | ||
| } | ||
| function formatTransformModuleType(id) { | ||
| return formatLoadModuleType(id); | ||
| } | ||
| //#endregion | ||
| //#region src/farm/index.ts | ||
| function getFarmPlugin(factory) { | ||
| return ((userOptions) => { | ||
| const meta = { framework: "farm" }; | ||
| const rawPlugins = toArray(factory(userOptions, meta)); | ||
| const plugins = rawPlugins.map((rawPlugin) => { | ||
| const plugin = toFarmPlugin(rawPlugin, userOptions); | ||
| if (rawPlugin.farm) Object.assign(plugin, rawPlugin.farm); | ||
| return plugin; | ||
| }); | ||
| return plugins.length === 1 ? plugins[0] : plugins; | ||
| }); | ||
| } | ||
| function toFarmPlugin(plugin, options) { | ||
| const farmPlugin = { | ||
| name: plugin.name, | ||
| priority: convertEnforceToPriority(plugin.enforce) | ||
| }; | ||
| if (plugin.farm) Object.keys(plugin.farm).forEach((key) => { | ||
| const value = plugin.farm[key]; | ||
| if (value) Reflect.set(farmPlugin, key, value); | ||
| }); | ||
| if (plugin.buildStart) { | ||
| const _buildStart = plugin.buildStart; | ||
| farmPlugin.buildStart = { async executor(_, context) { | ||
| await _buildStart.call(createFarmContext(context)); | ||
| } }; | ||
| } | ||
| if (plugin.resolveId) { | ||
| const _resolveId = plugin.resolveId; | ||
| let filters = []; | ||
| if (options) filters = options?.filters ?? []; | ||
| farmPlugin.resolve = { | ||
| filters: { | ||
| sources: filters.length ? filters : [".*"], | ||
| importers: [".*"] | ||
| }, | ||
| async executor(params, context) { | ||
| const resolvedIdPath = path.resolve(params.importer ?? ""); | ||
| const id = decodeStr(params.source); | ||
| const { handler, filter } = normalizeObjectHook("resolveId", _resolveId); | ||
| if (!filter(id)) return null; | ||
| let isEntry = false; | ||
| if (isObject(params.kind) && "entry" in params.kind) { | ||
| const kindWithEntry = params.kind; | ||
| isEntry = kindWithEntry.entry === "index"; | ||
| } | ||
| const farmContext = createFarmContext(context, resolvedIdPath); | ||
| const resolveIdResult = await handler.call(Object.assign(unpluginContext(context), farmContext), id, resolvedIdPath ?? null, { isEntry }); | ||
| if (isString(resolveIdResult)) return { | ||
| resolvedPath: removeQuery(encodeStr(resolveIdResult)), | ||
| query: customParseQueryString(resolveIdResult), | ||
| sideEffects: true, | ||
| external: false, | ||
| meta: {} | ||
| }; | ||
| if (isObject(resolveIdResult)) return { | ||
| resolvedPath: removeQuery(encodeStr(resolveIdResult?.id)), | ||
| query: customParseQueryString(resolveIdResult?.id), | ||
| sideEffects: false, | ||
| external: Boolean(resolveIdResult?.external), | ||
| meta: {} | ||
| }; | ||
| if (!isStartsWithSlash(params.source)) return null; | ||
| } | ||
| }; | ||
| } | ||
| if (plugin.load) { | ||
| const _load = plugin.load; | ||
| farmPlugin.load = { | ||
| filters: { resolvedPaths: [".*"] }, | ||
| async executor(params, context) { | ||
| const resolvedPath = decodeStr(params.resolvedPath); | ||
| const id = appendQuery(resolvedPath, params.query); | ||
| const loader = formatTransformModuleType(id); | ||
| if (plugin.loadInclude && !plugin.loadInclude?.(id)) return null; | ||
| const { handler, filter } = normalizeObjectHook("load", _load); | ||
| if (!filter(id)) return null; | ||
| const farmContext = createFarmContext(context, id); | ||
| const content = await handler.call(Object.assign(unpluginContext(context), farmContext), id); | ||
| const loadFarmResult = { | ||
| content: getContentValue(content), | ||
| moduleType: loader | ||
| }; | ||
| return loadFarmResult; | ||
| } | ||
| }; | ||
| } | ||
| if (plugin.transform) { | ||
| const _transform = plugin.transform; | ||
| farmPlugin.transform = { | ||
| filters: { | ||
| resolvedPaths: [".*"], | ||
| moduleTypes: [".*"] | ||
| }, | ||
| async executor(params, context) { | ||
| const resolvedPath = decodeStr(params.resolvedPath); | ||
| const id = appendQuery(resolvedPath, params.query); | ||
| const loader = formatTransformModuleType(id); | ||
| if (plugin.transformInclude && !plugin.transformInclude(id)) return null; | ||
| const { handler, filter } = normalizeObjectHook("transform", _transform); | ||
| if (!filter(id, params.content)) return null; | ||
| const farmContext = createFarmContext(context, id); | ||
| const resource = await handler.call(Object.assign(unpluginContext(context), farmContext), params.content, id); | ||
| if (resource && typeof resource !== "string") { | ||
| const transformFarmResult = { | ||
| content: getContentValue(resource), | ||
| moduleType: loader, | ||
| sourceMap: typeof resource.map === "object" && resource.map !== null ? JSON.stringify(resource.map) : void 0 | ||
| }; | ||
| return transformFarmResult; | ||
| } | ||
| } | ||
| }; | ||
| } | ||
| if (plugin.watchChange) { | ||
| const _watchChange = plugin.watchChange; | ||
| farmPlugin.updateModules = { async executor(param, context) { | ||
| const updatePathContent = param.paths[0]; | ||
| const ModifiedPath = updatePathContent[0]; | ||
| const eventChange = convertWatchEventChange(updatePathContent[1]); | ||
| await _watchChange.call(createFarmContext(context), ModifiedPath, { event: eventChange }); | ||
| } }; | ||
| } | ||
| if (plugin.buildEnd) { | ||
| const _buildEnd = plugin.buildEnd; | ||
| farmPlugin.buildEnd = { async executor(_, context) { | ||
| await _buildEnd.call(createFarmContext(context)); | ||
| } }; | ||
| } | ||
| if (plugin.writeBundle) { | ||
| const _writeBundle = plugin.writeBundle; | ||
| farmPlugin.finish = { async executor() { | ||
| await _writeBundle(); | ||
| } }; | ||
| } | ||
| return farmPlugin; | ||
| } | ||
| //#endregion | ||
| //#region src/rollup/index.ts | ||
| function getRollupPlugin(factory) { | ||
| return ((userOptions) => { | ||
| const meta = { framework: "rollup" }; | ||
| const rawPlugins = toArray(factory(userOptions, meta)); | ||
| const plugins = rawPlugins.map((plugin) => toRollupPlugin(plugin, "rollup")); | ||
| return plugins.length === 1 ? plugins[0] : plugins; | ||
| }); | ||
| } | ||
| function toRollupPlugin(plugin, key) { | ||
| const nativeFilter = key === "rolldown"; | ||
| if (plugin.resolveId && !nativeFilter && typeof plugin.resolveId === "object" && plugin.resolveId.filter) { | ||
| const resolveIdHook = plugin.resolveId; | ||
| const { handler, filter } = normalizeObjectHook("load", resolveIdHook); | ||
| replaceHookHandler("resolveId", resolveIdHook, function(...args) { | ||
| const [id] = args; | ||
| const supportFilter = supportNativeFilter(this, key); | ||
| if (!supportFilter && !filter(id)) return; | ||
| return handler.apply(this, args); | ||
| }); | ||
| } | ||
| if (plugin.load && (plugin.loadInclude || !nativeFilter && typeof plugin.load === "object" && plugin.load.filter)) { | ||
| const loadHook = plugin.load; | ||
| const { handler, filter } = normalizeObjectHook("load", loadHook); | ||
| replaceHookHandler("load", loadHook, function(...args) { | ||
| const [id] = args; | ||
| if (plugin.loadInclude && !plugin.loadInclude(id)) return; | ||
| const supportFilter = supportNativeFilter(this, key); | ||
| if (!supportFilter && !filter(id)) return; | ||
| return handler.apply(this, args); | ||
| }); | ||
| } | ||
| if (plugin.transform && (plugin.transformInclude || !nativeFilter && typeof plugin.transform === "object" && plugin.transform.filter)) { | ||
| const transformHook = plugin.transform; | ||
| const { handler, filter } = normalizeObjectHook("transform", transformHook); | ||
| replaceHookHandler("transform", transformHook, function(...args) { | ||
| const [code, id] = args; | ||
| if (plugin.transformInclude && !plugin.transformInclude(id)) return; | ||
| const supportFilter = supportNativeFilter(this, key); | ||
| if (!supportFilter && !filter(id, code)) return; | ||
| return handler.apply(this, args); | ||
| }); | ||
| } | ||
| if (plugin[key]) Object.assign(plugin, plugin[key]); | ||
| return plugin; | ||
| function replaceHookHandler(name, hook, handler) { | ||
| if (typeof hook === "function") plugin[name] = handler; | ||
| else hook.handler = handler; | ||
| } | ||
| } | ||
| function supportNativeFilter(context, framework) { | ||
| if (framework === "unloader") return false; | ||
| if (framework === "vite") return !!context?.meta?.viteVersion; | ||
| if (framework === "rolldown") return true; | ||
| const rollupVersion = context?.meta?.rollupVersion; | ||
| if (!rollupVersion) return false; | ||
| const [major, minor] = rollupVersion.split("."); | ||
| return Number(major) > 4 || Number(major) === 4 && Number(minor) >= 40; | ||
| } | ||
| //#endregion | ||
| //#region src/rolldown/index.ts | ||
| function getRolldownPlugin(factory) { | ||
| return ((userOptions) => { | ||
| const meta = { framework: "rolldown" }; | ||
| const rawPlugins = toArray(factory(userOptions, meta)); | ||
| const plugins = rawPlugins.map((rawPlugin) => { | ||
| const plugin = toRollupPlugin(rawPlugin, "rolldown"); | ||
| return plugin; | ||
| }); | ||
| return plugins.length === 1 ? plugins[0] : plugins; | ||
| }); | ||
| } | ||
| //#endregion | ||
| //#region node_modules/.pnpm/tsdown@0.14.1_publint@0.3.5_typescript@5.9.2_unplugin-unused@0.5.2_vue-tsc@3.0.6_typescript@5.9.2_/node_modules/tsdown/esm-shims.js | ||
| const getFilename = () => fileURLToPath(import.meta.url); | ||
| const getDirname = () => path.dirname(getFilename()); | ||
| const __dirname = /* @__PURE__ */ getDirname(); | ||
| //#endregion | ||
| //#region src/rspack/index.ts | ||
| const TRANSFORM_LOADER$1 = resolve(__dirname, "rspack/loaders/transform"); | ||
| const LOAD_LOADER$1 = resolve(__dirname, "rspack/loaders/load"); | ||
| function getRspackPlugin(factory) { | ||
| return (userOptions) => { | ||
| return { apply(compiler) { | ||
| const VIRTUAL_MODULE_PREFIX = resolve(compiler.options.context ?? process.cwd(), "node_modules/.virtual", process.pid.toString()); | ||
| const meta = { | ||
| framework: "rspack", | ||
| rspack: { compiler } | ||
| }; | ||
| const rawPlugins = toArray(factory(userOptions, meta)); | ||
| for (const rawPlugin of rawPlugins) { | ||
| const plugin = Object.assign(rawPlugin, { | ||
| __unpluginMeta: meta, | ||
| __virtualModulePrefix: VIRTUAL_MODULE_PREFIX | ||
| }); | ||
| const externalModules = /* @__PURE__ */ new Set(); | ||
| if (plugin.resolveId) { | ||
| const createPlugin = (plugin$1) => { | ||
| if (compiler.rspack.experiments.VirtualModulesPlugin) return new compiler.rspack.experiments.VirtualModulesPlugin(); | ||
| return new FakeVirtualModulesPlugin(plugin$1); | ||
| }; | ||
| const vfs = createPlugin(plugin); | ||
| vfs.apply(compiler); | ||
| const vfsModules = /* @__PURE__ */ new Map(); | ||
| plugin.__vfsModules = vfsModules; | ||
| plugin.__vfs = vfs; | ||
| compiler.hooks.compilation.tap(plugin.name, (compilation, { normalModuleFactory }) => { | ||
| normalModuleFactory.hooks.resolve.tapPromise(plugin.name, async (resolveData) => { | ||
| const id = normalizeAbsolutePath(resolveData.request); | ||
| const requestContext = resolveData.contextInfo; | ||
| let importer = requestContext.issuer !== "" ? requestContext.issuer : void 0; | ||
| const isEntry = requestContext.issuer === ""; | ||
| if (importer?.startsWith(plugin.__virtualModulePrefix)) importer = decodeURIComponent(importer.slice(plugin.__virtualModulePrefix.length)); | ||
| const context = createBuildContext$1(compiler, compilation); | ||
| let error; | ||
| const pluginContext = { | ||
| error(msg) { | ||
| if (error == null) error = normalizeMessage$1(msg); | ||
| else console.error(`unplugin/rspack: multiple errors returned from resolveId hook: ${msg}`); | ||
| }, | ||
| warn(msg) { | ||
| console.warn(`unplugin/rspack: warning from resolveId hook: ${msg}`); | ||
| } | ||
| }; | ||
| const { handler, filter } = normalizeObjectHook("resolveId", plugin.resolveId); | ||
| if (!filter(id)) return; | ||
| const resolveIdResult = await handler.call({ | ||
| ...context, | ||
| ...pluginContext | ||
| }, id, importer, { isEntry }); | ||
| if (error != null) throw error; | ||
| if (resolveIdResult == null) return; | ||
| let resolved = typeof resolveIdResult === "string" ? resolveIdResult : resolveIdResult.id; | ||
| const isExternal = typeof resolveIdResult === "string" ? false : resolveIdResult.external === true; | ||
| if (isExternal) externalModules.add(resolved); | ||
| let isVirtual = true; | ||
| try { | ||
| (compiler.inputFileSystem?.statSync ?? fs.statSync)(resolved); | ||
| isVirtual = false; | ||
| } catch { | ||
| isVirtual = !isVirtualModuleId(resolved, plugin); | ||
| } | ||
| if (isVirtual) { | ||
| const encodedVirtualPath = encodeVirtualModuleId(resolved, plugin); | ||
| if (!vfsModules.has(resolved)) { | ||
| const fsPromise = Promise.resolve(vfs.writeModule(encodedVirtualPath, "")); | ||
| vfsModules.set(resolved, fsPromise); | ||
| await fsPromise; | ||
| } else await vfsModules.get(resolved); | ||
| resolved = encodedVirtualPath; | ||
| } | ||
| resolveData.request = resolved; | ||
| }); | ||
| }); | ||
| } | ||
| if (plugin.load) compiler.options.module.rules.unshift({ | ||
| enforce: plugin.enforce, | ||
| include(id) { | ||
| if (isVirtualModuleId(id, plugin)) id = decodeVirtualModuleId(id, plugin); | ||
| if (plugin.loadInclude && !plugin.loadInclude(id)) return false; | ||
| const { filter } = normalizeObjectHook("load", plugin.load); | ||
| if (!filter(id)) return false; | ||
| return !externalModules.has(id); | ||
| }, | ||
| use: [{ | ||
| loader: LOAD_LOADER$1, | ||
| options: { plugin } | ||
| }], | ||
| type: "javascript/auto" | ||
| }); | ||
| if (plugin.transform) compiler.options.module.rules.unshift({ | ||
| enforce: plugin.enforce, | ||
| use(data) { | ||
| return transformUse(data, plugin, TRANSFORM_LOADER$1); | ||
| } | ||
| }); | ||
| if (plugin.rspack) plugin.rspack(compiler); | ||
| if (plugin.watchChange || plugin.buildStart) compiler.hooks.make.tapPromise(plugin.name, async (compilation) => { | ||
| const context = createBuildContext$1(compiler, compilation); | ||
| if (plugin.watchChange && (compiler.modifiedFiles || compiler.removedFiles)) { | ||
| const promises = []; | ||
| if (compiler.modifiedFiles) compiler.modifiedFiles.forEach((file) => promises.push(Promise.resolve(plugin.watchChange.call(context, file, { event: "update" })))); | ||
| if (compiler.removedFiles) compiler.removedFiles.forEach((file) => promises.push(Promise.resolve(plugin.watchChange.call(context, file, { event: "delete" })))); | ||
| await Promise.all(promises); | ||
| } | ||
| if (plugin.buildStart) return await plugin.buildStart.call(context); | ||
| }); | ||
| if (plugin.buildEnd) compiler.hooks.emit.tapPromise(plugin.name, async (compilation) => { | ||
| await plugin.buildEnd.call(createBuildContext$1(compiler, compilation)); | ||
| }); | ||
| if (plugin.writeBundle) compiler.hooks.afterEmit.tapPromise(plugin.name, async () => { | ||
| await plugin.writeBundle(); | ||
| }); | ||
| } | ||
| } }; | ||
| }; | ||
| } | ||
| //#endregion | ||
| //#region src/unloader/index.ts | ||
| function getUnloaderPlugin(factory) { | ||
| return ((userOptions) => { | ||
| const meta = { framework: "unloader" }; | ||
| const rawPlugins = toArray(factory(userOptions, meta)); | ||
| const plugins = rawPlugins.map((rawPlugin) => { | ||
| const plugin = toRollupPlugin(rawPlugin, "unloader"); | ||
| return plugin; | ||
| }); | ||
| return plugins.length === 1 ? plugins[0] : plugins; | ||
| }); | ||
| } | ||
| //#endregion | ||
| //#region src/vite/index.ts | ||
| function getVitePlugin(factory) { | ||
| return ((userOptions) => { | ||
| const meta = { framework: "vite" }; | ||
| const rawPlugins = toArray(factory(userOptions, meta)); | ||
| const plugins = rawPlugins.map((rawPlugin) => { | ||
| const plugin = toRollupPlugin(rawPlugin, "vite"); | ||
| return plugin; | ||
| }); | ||
| return plugins.length === 1 ? plugins[0] : plugins; | ||
| }); | ||
| } | ||
| //#endregion | ||
| //#region src/webpack/index.ts | ||
| const TRANSFORM_LOADER = resolve(__dirname, "webpack/loaders/transform"); | ||
| const LOAD_LOADER = resolve(__dirname, "webpack/loaders/load"); | ||
| function getWebpackPlugin(factory) { | ||
| return (userOptions) => { | ||
| return { apply(compiler) { | ||
| const VIRTUAL_MODULE_PREFIX = resolve(compiler.options.context ?? process$1.cwd(), "_virtual_"); | ||
| const meta = { | ||
| framework: "webpack", | ||
| webpack: { compiler } | ||
| }; | ||
| const rawPlugins = toArray(factory(userOptions, meta)); | ||
| for (const rawPlugin of rawPlugins) { | ||
| const plugin = Object.assign(rawPlugin, { | ||
| __unpluginMeta: meta, | ||
| __virtualModulePrefix: VIRTUAL_MODULE_PREFIX | ||
| }); | ||
| const externalModules = /* @__PURE__ */ new Set(); | ||
| if (plugin.resolveId) { | ||
| let vfs = compiler.options.plugins.find((i) => i instanceof VirtualModulesPlugin); | ||
| if (!vfs) { | ||
| vfs = new VirtualModulesPlugin(); | ||
| compiler.options.plugins.push(vfs); | ||
| } | ||
| const vfsModules = /* @__PURE__ */ new Set(); | ||
| plugin.__vfsModules = vfsModules; | ||
| plugin.__vfs = vfs; | ||
| const resolverPlugin = { apply(resolver) { | ||
| const target = resolver.ensureHook("resolve"); | ||
| resolver.getHook("resolve").tapAsync(plugin.name, async (request, resolveContext, callback) => { | ||
| if (!request.request) return callback(); | ||
| if (normalizeAbsolutePath(request.request).startsWith(plugin.__virtualModulePrefix)) return callback(); | ||
| const id = normalizeAbsolutePath(request.request); | ||
| const requestContext = request.context; | ||
| let importer = requestContext.issuer !== "" ? requestContext.issuer : void 0; | ||
| const isEntry = requestContext.issuer === ""; | ||
| if (importer?.startsWith(plugin.__virtualModulePrefix)) importer = decodeURIComponent(importer.slice(plugin.__virtualModulePrefix.length)); | ||
| const fileDependencies = /* @__PURE__ */ new Set(); | ||
| const context = createBuildContext({ | ||
| addWatchFile(file) { | ||
| fileDependencies.add(file); | ||
| resolveContext.fileDependencies?.add(file); | ||
| }, | ||
| getWatchFiles() { | ||
| return Array.from(fileDependencies); | ||
| } | ||
| }, compiler); | ||
| let error; | ||
| const pluginContext = { | ||
| error(msg) { | ||
| if (error == null) error = normalizeMessage(msg); | ||
| else console.error(`unplugin/webpack: multiple errors returned from resolveId hook: ${msg}`); | ||
| }, | ||
| warn(msg) { | ||
| console.warn(`unplugin/webpack: warning from resolveId hook: ${msg}`); | ||
| } | ||
| }; | ||
| const { handler, filter } = normalizeObjectHook("resolveId", plugin.resolveId); | ||
| if (!filter(id)) return callback(); | ||
| const resolveIdResult = await handler.call({ | ||
| ...context, | ||
| ...pluginContext | ||
| }, id, importer, { isEntry }); | ||
| if (error != null) return callback(error); | ||
| if (resolveIdResult == null) return callback(); | ||
| let resolved = typeof resolveIdResult === "string" ? resolveIdResult : resolveIdResult.id; | ||
| const isExternal = typeof resolveIdResult === "string" ? false : resolveIdResult.external === true; | ||
| if (isExternal) externalModules.add(resolved); | ||
| if (!fs.existsSync(resolved)) { | ||
| resolved = normalizeAbsolutePath(plugin.__virtualModulePrefix + encodeURIComponent(resolved)); | ||
| if (!vfsModules.has(resolved)) { | ||
| plugin.__vfs.writeModule(resolved, ""); | ||
| vfsModules.add(resolved); | ||
| } | ||
| } | ||
| const newRequest = { | ||
| ...request, | ||
| request: resolved | ||
| }; | ||
| resolver.doResolve(target, newRequest, null, resolveContext, callback); | ||
| }); | ||
| } }; | ||
| compiler.options.resolve.plugins = compiler.options.resolve.plugins || []; | ||
| compiler.options.resolve.plugins.push(resolverPlugin); | ||
| } | ||
| if (plugin.load) compiler.options.module.rules.unshift({ | ||
| include(id) { | ||
| return shouldLoad(id, plugin, externalModules); | ||
| }, | ||
| enforce: plugin.enforce, | ||
| use: [{ | ||
| loader: LOAD_LOADER, | ||
| options: { plugin } | ||
| }], | ||
| type: "javascript/auto" | ||
| }); | ||
| if (plugin.transform) compiler.options.module.rules.unshift({ | ||
| enforce: plugin.enforce, | ||
| use(data) { | ||
| return transformUse(data, plugin, TRANSFORM_LOADER); | ||
| } | ||
| }); | ||
| if (plugin.webpack) plugin.webpack(compiler); | ||
| if (plugin.watchChange || plugin.buildStart) compiler.hooks.make.tapPromise(plugin.name, async (compilation) => { | ||
| const context = createBuildContext(contextOptionsFromCompilation(compilation), compiler, compilation); | ||
| if (plugin.watchChange && (compiler.modifiedFiles || compiler.removedFiles)) { | ||
| const promises = []; | ||
| if (compiler.modifiedFiles) compiler.modifiedFiles.forEach((file) => promises.push(Promise.resolve(plugin.watchChange.call(context, file, { event: "update" })))); | ||
| if (compiler.removedFiles) compiler.removedFiles.forEach((file) => promises.push(Promise.resolve(plugin.watchChange.call(context, file, { event: "delete" })))); | ||
| await Promise.all(promises); | ||
| } | ||
| if (plugin.buildStart) return await plugin.buildStart.call(context); | ||
| }); | ||
| if (plugin.buildEnd) compiler.hooks.emit.tapPromise(plugin.name, async (compilation) => { | ||
| await plugin.buildEnd.call(createBuildContext(contextOptionsFromCompilation(compilation), compiler, compilation)); | ||
| }); | ||
| if (plugin.writeBundle) compiler.hooks.afterEmit.tapPromise(plugin.name, async () => { | ||
| await plugin.writeBundle(); | ||
| }); | ||
| } | ||
| } }; | ||
| }; | ||
| } | ||
| function shouldLoad(id, plugin, externalModules) { | ||
| if (id.startsWith(plugin.__virtualModulePrefix)) id = decodeURIComponent(id.slice(plugin.__virtualModulePrefix.length)); | ||
| if (plugin.loadInclude && !plugin.loadInclude(id)) return false; | ||
| const { filter } = normalizeObjectHook("load", plugin.load); | ||
| if (!filter(id)) return false; | ||
| return !externalModules.has(id); | ||
| } | ||
| //#endregion | ||
| //#region src/define.ts | ||
| function createUnplugin(factory) { | ||
| return { | ||
| get esbuild() { | ||
| return getEsbuildPlugin(factory); | ||
| }, | ||
| get rollup() { | ||
| return getRollupPlugin(factory); | ||
| }, | ||
| get vite() { | ||
| return getVitePlugin(factory); | ||
| }, | ||
| get rolldown() { | ||
| return getRolldownPlugin(factory); | ||
| }, | ||
| get webpack() { | ||
| return getWebpackPlugin(factory); | ||
| }, | ||
| get rspack() { | ||
| return getRspackPlugin(factory); | ||
| }, | ||
| get farm() { | ||
| return getFarmPlugin(factory); | ||
| }, | ||
| get unloader() { | ||
| return getUnloaderPlugin(factory); | ||
| }, | ||
| get raw() { | ||
| return factory; | ||
| } | ||
| }; | ||
| } | ||
| function createEsbuildPlugin(factory) { | ||
| return getEsbuildPlugin(factory); | ||
| } | ||
| function createRollupPlugin(factory) { | ||
| return getRollupPlugin(factory); | ||
| } | ||
| function createVitePlugin(factory) { | ||
| return getVitePlugin(factory); | ||
| } | ||
| function createRolldownPlugin(factory) { | ||
| return getRolldownPlugin(factory); | ||
| } | ||
| function createWebpackPlugin(factory) { | ||
| return getWebpackPlugin(factory); | ||
| } | ||
| function createRspackPlugin(factory) { | ||
| return getRspackPlugin(factory); | ||
| } | ||
| function createFarmPlugin(factory) { | ||
| return getFarmPlugin(factory); | ||
| } | ||
| function createUnloaderPlugin(factory) { | ||
| return getUnloaderPlugin(factory); | ||
| } | ||
| //#endregion | ||
| export { createEsbuildPlugin, createFarmPlugin, createRolldownPlugin, createRollupPlugin, createRspackPlugin, createUnloaderPlugin, createUnplugin, createVitePlugin, createWebpackPlugin }; |
| const require_context = require('../../context-DwbtaXxf.cjs'); | ||
| const require_webpack_like = require('../../webpack-like-BAQNtVsj.cjs'); | ||
| const require_context$1 = require('../../context-PvRDlMNZ.cjs'); | ||
| const require_utils = require('../../utils-BeoYHuOg.cjs'); | ||
| //#region src/rspack/loaders/load.ts | ||
| async function load(source, map) { | ||
| const callback = this.async(); | ||
| const { plugin } = this.query; | ||
| let id = this.resource; | ||
| if (!plugin?.load || !id) return callback(null, source, map); | ||
| if (require_utils.isVirtualModuleId(id, plugin)) id = require_utils.decodeVirtualModuleId(id, plugin); | ||
| const context = require_context$1.createContext(this); | ||
| const { handler } = require_context.normalizeObjectHook("load", plugin.load); | ||
| try { | ||
| const res = await handler.call(Object.assign({}, this._compilation && require_context$1.createBuildContext(this._compiler, this._compilation, this), context), require_webpack_like.normalizeAbsolutePath(id)); | ||
| if (res == null) callback(null, source, map); | ||
| else if (typeof res !== "string") callback(null, res.code, res.map ?? map); | ||
| else callback(null, res, map); | ||
| } catch (error) { | ||
| if (error instanceof Error) callback(error); | ||
| else callback(new Error(String(error))); | ||
| } | ||
| } | ||
| //#endregion | ||
| module.exports = load; |
| import { LoaderContext } from "@rspack/core"; | ||
| //#region src/rspack/loaders/load.d.ts | ||
| declare function load(this: LoaderContext, source: string, map: any): Promise<void>; | ||
| export = load; |
| import { LoaderContext } from "@rspack/core"; | ||
| //#region src/rspack/loaders/load.d.ts | ||
| declare function load(this: LoaderContext, source: string, map: any): Promise<void>; | ||
| //#endregion | ||
| export { load as default }; |
| import { normalizeObjectHook } from "../../context-D49cMElb.js"; | ||
| import { normalizeAbsolutePath } from "../../webpack-like-CSbnjTNU.js"; | ||
| import { createBuildContext, createContext } from "../../context-D_KPTgTH.js"; | ||
| import { decodeVirtualModuleId, isVirtualModuleId } from "../../utils-C8vphsat.js"; | ||
| //#region src/rspack/loaders/load.ts | ||
| async function load(source, map) { | ||
| const callback = this.async(); | ||
| const { plugin } = this.query; | ||
| let id = this.resource; | ||
| if (!plugin?.load || !id) return callback(null, source, map); | ||
| if (isVirtualModuleId(id, plugin)) id = decodeVirtualModuleId(id, plugin); | ||
| const context = createContext(this); | ||
| const { handler } = normalizeObjectHook("load", plugin.load); | ||
| try { | ||
| const res = await handler.call(Object.assign({}, this._compilation && createBuildContext(this._compiler, this._compilation, this), context), normalizeAbsolutePath(id)); | ||
| if (res == null) callback(null, source, map); | ||
| else if (typeof res !== "string") callback(null, res.code, res.map ?? map); | ||
| else callback(null, res, map); | ||
| } catch (error) { | ||
| if (error instanceof Error) callback(error); | ||
| else callback(new Error(String(error))); | ||
| } | ||
| } | ||
| //#endregion | ||
| export { load as default }; |
| const require_context = require('../../context-DwbtaXxf.cjs'); | ||
| const require_context$1 = require('../../context-PvRDlMNZ.cjs'); | ||
| //#region src/rspack/loaders/transform.ts | ||
| async function transform(source, map) { | ||
| const callback = this.async(); | ||
| const { plugin } = this.query; | ||
| if (!plugin?.transform) return callback(null, source, map); | ||
| const id = this.resource; | ||
| const context = require_context$1.createContext(this); | ||
| const { handler, filter } = require_context.normalizeObjectHook("transform", plugin.transform); | ||
| if (!filter(this.resource, source)) return callback(null, source, map); | ||
| try { | ||
| const res = await handler.call(Object.assign({}, this._compilation && require_context$1.createBuildContext(this._compiler, this._compilation, this), context), source, id); | ||
| if (res == null) callback(null, source, map); | ||
| else if (typeof res !== "string") callback(null, res.code, map == null ? map : res.map || map); | ||
| else callback(null, res, map); | ||
| } catch (error) { | ||
| if (error instanceof Error) callback(error); | ||
| else callback(new Error(String(error))); | ||
| } | ||
| } | ||
| //#endregion | ||
| module.exports = transform; |
| import { LoaderContext } from "@rspack/core"; | ||
| //#region src/rspack/loaders/transform.d.ts | ||
| declare function transform(this: LoaderContext, source: string, map: any): Promise<void>; | ||
| export = transform; |
| import { LoaderContext } from "@rspack/core"; | ||
| //#region src/rspack/loaders/transform.d.ts | ||
| declare function transform(this: LoaderContext, source: string, map: any): Promise<void>; | ||
| //#endregion | ||
| export { transform as default }; |
| import { normalizeObjectHook } from "../../context-D49cMElb.js"; | ||
| import { createBuildContext, createContext } from "../../context-D_KPTgTH.js"; | ||
| //#region src/rspack/loaders/transform.ts | ||
| async function transform(source, map) { | ||
| const callback = this.async(); | ||
| const { plugin } = this.query; | ||
| if (!plugin?.transform) return callback(null, source, map); | ||
| const id = this.resource; | ||
| const context = createContext(this); | ||
| const { handler, filter } = normalizeObjectHook("transform", plugin.transform); | ||
| if (!filter(this.resource, source)) return callback(null, source, map); | ||
| try { | ||
| const res = await handler.call(Object.assign({}, this._compilation && createBuildContext(this._compiler, this._compilation, this), context), source, id); | ||
| if (res == null) callback(null, source, map); | ||
| else if (typeof res !== "string") callback(null, res.code, map == null ? map : res.map || map); | ||
| else callback(null, res, map); | ||
| } catch (error) { | ||
| if (error instanceof Error) callback(error); | ||
| else callback(new Error(String(error))); | ||
| } | ||
| } | ||
| //#endregion | ||
| export { transform as default }; |
| const require_context = require('./context-DwbtaXxf.cjs'); | ||
| const node_fs = require_context.__toESM(require("node:fs")); | ||
| const node_path = require_context.__toESM(require("node:path")); | ||
| //#region src/rspack/utils.ts | ||
| function encodeVirtualModuleId(id, plugin) { | ||
| return (0, node_path.resolve)(plugin.__virtualModulePrefix, encodeURIComponent(id)); | ||
| } | ||
| function decodeVirtualModuleId(encoded, _plugin) { | ||
| return decodeURIComponent((0, node_path.basename)(encoded)); | ||
| } | ||
| function isVirtualModuleId(encoded, plugin) { | ||
| return (0, node_path.dirname)(encoded) === plugin.__virtualModulePrefix; | ||
| } | ||
| var FakeVirtualModulesPlugin = class FakeVirtualModulesPlugin { | ||
| name = "FakeVirtualModulesPlugin"; | ||
| static counters = /* @__PURE__ */ new Map(); | ||
| static initCleanup = false; | ||
| constructor(plugin) { | ||
| this.plugin = plugin; | ||
| if (!FakeVirtualModulesPlugin.initCleanup) { | ||
| FakeVirtualModulesPlugin.initCleanup = true; | ||
| process.once("exit", () => { | ||
| FakeVirtualModulesPlugin.counters.forEach((_, dir) => { | ||
| node_fs.default.rmSync(dir, { | ||
| recursive: true, | ||
| force: true | ||
| }); | ||
| }); | ||
| }); | ||
| } | ||
| } | ||
| apply(compiler) { | ||
| const dir = this.plugin.__virtualModulePrefix; | ||
| if (!node_fs.default.existsSync(dir)) node_fs.default.mkdirSync(dir, { recursive: true }); | ||
| const counter = FakeVirtualModulesPlugin.counters.get(dir) ?? 0; | ||
| FakeVirtualModulesPlugin.counters.set(dir, counter + 1); | ||
| compiler.hooks.shutdown.tap(this.name, () => { | ||
| const counter$1 = (FakeVirtualModulesPlugin.counters.get(dir) ?? 1) - 1; | ||
| if (counter$1 === 0) { | ||
| FakeVirtualModulesPlugin.counters.delete(dir); | ||
| node_fs.default.rmSync(dir, { | ||
| recursive: true, | ||
| force: true | ||
| }); | ||
| } else FakeVirtualModulesPlugin.counters.set(dir, counter$1); | ||
| }); | ||
| } | ||
| async writeModule(file) { | ||
| return node_fs.default.promises.writeFile(file, ""); | ||
| } | ||
| }; | ||
| //#endregion | ||
| Object.defineProperty(exports, 'FakeVirtualModulesPlugin', { | ||
| enumerable: true, | ||
| get: function () { | ||
| return FakeVirtualModulesPlugin; | ||
| } | ||
| }); | ||
| Object.defineProperty(exports, 'decodeVirtualModuleId', { | ||
| enumerable: true, | ||
| get: function () { | ||
| return decodeVirtualModuleId; | ||
| } | ||
| }); | ||
| Object.defineProperty(exports, 'encodeVirtualModuleId', { | ||
| enumerable: true, | ||
| get: function () { | ||
| return encodeVirtualModuleId; | ||
| } | ||
| }); | ||
| Object.defineProperty(exports, 'isVirtualModuleId', { | ||
| enumerable: true, | ||
| get: function () { | ||
| return isVirtualModuleId; | ||
| } | ||
| }); |
| import fs from "node:fs"; | ||
| import { basename, dirname, resolve } from "node:path"; | ||
| //#region src/rspack/utils.ts | ||
| function encodeVirtualModuleId(id, plugin) { | ||
| return resolve(plugin.__virtualModulePrefix, encodeURIComponent(id)); | ||
| } | ||
| function decodeVirtualModuleId(encoded, _plugin) { | ||
| return decodeURIComponent(basename(encoded)); | ||
| } | ||
| function isVirtualModuleId(encoded, plugin) { | ||
| return dirname(encoded) === plugin.__virtualModulePrefix; | ||
| } | ||
| var FakeVirtualModulesPlugin = class FakeVirtualModulesPlugin { | ||
| name = "FakeVirtualModulesPlugin"; | ||
| static counters = /* @__PURE__ */ new Map(); | ||
| static initCleanup = false; | ||
| constructor(plugin) { | ||
| this.plugin = plugin; | ||
| if (!FakeVirtualModulesPlugin.initCleanup) { | ||
| FakeVirtualModulesPlugin.initCleanup = true; | ||
| process.once("exit", () => { | ||
| FakeVirtualModulesPlugin.counters.forEach((_, dir) => { | ||
| fs.rmSync(dir, { | ||
| recursive: true, | ||
| force: true | ||
| }); | ||
| }); | ||
| }); | ||
| } | ||
| } | ||
| apply(compiler) { | ||
| const dir = this.plugin.__virtualModulePrefix; | ||
| if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); | ||
| const counter = FakeVirtualModulesPlugin.counters.get(dir) ?? 0; | ||
| FakeVirtualModulesPlugin.counters.set(dir, counter + 1); | ||
| compiler.hooks.shutdown.tap(this.name, () => { | ||
| const counter$1 = (FakeVirtualModulesPlugin.counters.get(dir) ?? 1) - 1; | ||
| if (counter$1 === 0) { | ||
| FakeVirtualModulesPlugin.counters.delete(dir); | ||
| fs.rmSync(dir, { | ||
| recursive: true, | ||
| force: true | ||
| }); | ||
| } else FakeVirtualModulesPlugin.counters.set(dir, counter$1); | ||
| }); | ||
| } | ||
| async writeModule(file) { | ||
| return fs.promises.writeFile(file, ""); | ||
| } | ||
| }; | ||
| //#endregion | ||
| export { FakeVirtualModulesPlugin, decodeVirtualModuleId, encodeVirtualModuleId, isVirtualModuleId }; |
| const require_context = require('./context-DwbtaXxf.cjs'); | ||
| const node_path = require_context.__toESM(require("node:path")); | ||
| //#region src/utils/webpack-like.ts | ||
| function transformUse(data, plugin, transformLoader) { | ||
| if (data.resource == null) return []; | ||
| const id = normalizeAbsolutePath(data.resource + (data.resourceQuery || "")); | ||
| if (plugin.transformInclude && !plugin.transformInclude(id)) return []; | ||
| const { filter } = require_context.normalizeObjectHook("load", plugin.transform); | ||
| if (!filter(id)) return []; | ||
| return [{ | ||
| loader: transformLoader, | ||
| options: { plugin }, | ||
| ident: plugin.name | ||
| }]; | ||
| } | ||
| /** | ||
| * Normalizes a given path when it's absolute. Normalizing means returning a new path by converting | ||
| * the input path to the native os format. This is useful in cases where we want to normalize | ||
| * the `id` argument of a hook. Any absolute ids should be in the default format | ||
| * of the operating system. Any relative imports or node_module imports should remain | ||
| * untouched. | ||
| * | ||
| * @param path - Path to normalize. | ||
| * @returns a new normalized path. | ||
| */ | ||
| function normalizeAbsolutePath(path) { | ||
| if ((0, node_path.isAbsolute)(path)) return (0, node_path.normalize)(path); | ||
| else return path; | ||
| } | ||
| //#endregion | ||
| Object.defineProperty(exports, 'normalizeAbsolutePath', { | ||
| enumerable: true, | ||
| get: function () { | ||
| return normalizeAbsolutePath; | ||
| } | ||
| }); | ||
| Object.defineProperty(exports, 'transformUse', { | ||
| enumerable: true, | ||
| get: function () { | ||
| return transformUse; | ||
| } | ||
| }); |
| import { normalizeObjectHook } from "./context-D49cMElb.js"; | ||
| import { isAbsolute, normalize } from "node:path"; | ||
| //#region src/utils/webpack-like.ts | ||
| function transformUse(data, plugin, transformLoader) { | ||
| if (data.resource == null) return []; | ||
| const id = normalizeAbsolutePath(data.resource + (data.resourceQuery || "")); | ||
| if (plugin.transformInclude && !plugin.transformInclude(id)) return []; | ||
| const { filter } = normalizeObjectHook("load", plugin.transform); | ||
| if (!filter(id)) return []; | ||
| return [{ | ||
| loader: transformLoader, | ||
| options: { plugin }, | ||
| ident: plugin.name | ||
| }]; | ||
| } | ||
| /** | ||
| * Normalizes a given path when it's absolute. Normalizing means returning a new path by converting | ||
| * the input path to the native os format. This is useful in cases where we want to normalize | ||
| * the `id` argument of a hook. Any absolute ids should be in the default format | ||
| * of the operating system. Any relative imports or node_module imports should remain | ||
| * untouched. | ||
| * | ||
| * @param path - Path to normalize. | ||
| * @returns a new normalized path. | ||
| */ | ||
| function normalizeAbsolutePath(path$1) { | ||
| if (isAbsolute(path$1)) return normalize(path$1); | ||
| else return path$1; | ||
| } | ||
| //#endregion | ||
| export { normalizeAbsolutePath, transformUse }; |
| const require_context = require('../../context-DwbtaXxf.cjs'); | ||
| const require_webpack_like = require('../../webpack-like-BAQNtVsj.cjs'); | ||
| const require_context$1 = require('../../context-C4aYoZcz.cjs'); | ||
| //#region src/webpack/loaders/load.ts | ||
| async function load(source, map) { | ||
| const callback = this.async(); | ||
| const { plugin } = this.query; | ||
| let id = this.resource; | ||
| if (!plugin?.load || !id) return callback(null, source, map); | ||
| if (id.startsWith(plugin.__virtualModulePrefix)) id = decodeURIComponent(id.slice(plugin.__virtualModulePrefix.length)); | ||
| const context = require_context$1.createContext(this); | ||
| const { handler } = require_context.normalizeObjectHook("load", plugin.load); | ||
| const res = await handler.call(Object.assign({}, require_context$1.createBuildContext({ | ||
| addWatchFile: (file) => { | ||
| this.addDependency(file); | ||
| }, | ||
| getWatchFiles: () => { | ||
| return this.getDependencies(); | ||
| } | ||
| }, this._compiler, this._compilation, this), context), require_webpack_like.normalizeAbsolutePath(id)); | ||
| if (res == null) callback(null, source, map); | ||
| else if (typeof res !== "string") callback(null, res.code, res.map ?? map); | ||
| else callback(null, res, map); | ||
| } | ||
| //#endregion | ||
| module.exports = load; |
| import { LoaderContext } from "webpack"; | ||
| //#region src/webpack/loaders/load.d.ts | ||
| declare function load(this: LoaderContext<any>, source: string, map: any): Promise<void>; | ||
| export = load; |
| import { LoaderContext } from "webpack"; | ||
| //#region src/webpack/loaders/load.d.ts | ||
| declare function load(this: LoaderContext<any>, source: string, map: any): Promise<void>; | ||
| //#endregion | ||
| export { load as default }; |
| import { normalizeObjectHook } from "../../context-D49cMElb.js"; | ||
| import { normalizeAbsolutePath } from "../../webpack-like-CSbnjTNU.js"; | ||
| import { createBuildContext, createContext } from "../../context-BZKy5Nsn.js"; | ||
| //#region src/webpack/loaders/load.ts | ||
| async function load(source, map) { | ||
| const callback = this.async(); | ||
| const { plugin } = this.query; | ||
| let id = this.resource; | ||
| if (!plugin?.load || !id) return callback(null, source, map); | ||
| if (id.startsWith(plugin.__virtualModulePrefix)) id = decodeURIComponent(id.slice(plugin.__virtualModulePrefix.length)); | ||
| const context = createContext(this); | ||
| const { handler } = normalizeObjectHook("load", plugin.load); | ||
| const res = await handler.call(Object.assign({}, createBuildContext({ | ||
| addWatchFile: (file) => { | ||
| this.addDependency(file); | ||
| }, | ||
| getWatchFiles: () => { | ||
| return this.getDependencies(); | ||
| } | ||
| }, this._compiler, this._compilation, this), context), normalizeAbsolutePath(id)); | ||
| if (res == null) callback(null, source, map); | ||
| else if (typeof res !== "string") callback(null, res.code, res.map ?? map); | ||
| else callback(null, res, map); | ||
| } | ||
| //#endregion | ||
| export { load as default }; |
| const require_context = require('../../context-DwbtaXxf.cjs'); | ||
| const require_context$1 = require('../../context-C4aYoZcz.cjs'); | ||
| //#region src/webpack/loaders/transform.ts | ||
| async function transform(source, map) { | ||
| const callback = this.async(); | ||
| const { plugin } = this.query; | ||
| if (!plugin?.transform) return callback(null, source, map); | ||
| const context = require_context$1.createContext(this); | ||
| const { handler, filter } = require_context.normalizeObjectHook("transform", plugin.transform); | ||
| if (!filter(this.resource, source)) return callback(null, source, map); | ||
| try { | ||
| const res = await handler.call(Object.assign({}, require_context$1.createBuildContext({ | ||
| addWatchFile: (file) => { | ||
| this.addDependency(file); | ||
| }, | ||
| getWatchFiles: () => { | ||
| return this.getDependencies(); | ||
| } | ||
| }, this._compiler, this._compilation, this), context), source, this.resource); | ||
| if (res == null) callback(null, source, map); | ||
| else if (typeof res !== "string") callback(null, res.code, map == null ? map : res.map || map); | ||
| else callback(null, res, map); | ||
| } catch (error) { | ||
| if (error instanceof Error) callback(error); | ||
| else callback(new Error(String(error))); | ||
| } | ||
| } | ||
| //#endregion | ||
| module.exports = transform; |
| import { LoaderContext } from "webpack"; | ||
| //#region src/webpack/loaders/transform.d.ts | ||
| declare function transform(this: LoaderContext<any>, source: string, map: any): Promise<void>; | ||
| export = transform; |
| import { LoaderContext } from "webpack"; | ||
| //#region src/webpack/loaders/transform.d.ts | ||
| declare function transform(this: LoaderContext<any>, source: string, map: any): Promise<void>; | ||
| //#endregion | ||
| export { transform as default }; |
| import { normalizeObjectHook } from "../../context-D49cMElb.js"; | ||
| import { createBuildContext, createContext } from "../../context-BZKy5Nsn.js"; | ||
| //#region src/webpack/loaders/transform.ts | ||
| async function transform(source, map) { | ||
| const callback = this.async(); | ||
| const { plugin } = this.query; | ||
| if (!plugin?.transform) return callback(null, source, map); | ||
| const context = createContext(this); | ||
| const { handler, filter } = normalizeObjectHook("transform", plugin.transform); | ||
| if (!filter(this.resource, source)) return callback(null, source, map); | ||
| try { | ||
| const res = await handler.call(Object.assign({}, createBuildContext({ | ||
| addWatchFile: (file) => { | ||
| this.addDependency(file); | ||
| }, | ||
| getWatchFiles: () => { | ||
| return this.getDependencies(); | ||
| } | ||
| }, this._compiler, this._compilation, this), context), source, this.resource); | ||
| if (res == null) callback(null, source, map); | ||
| else if (typeof res !== "string") callback(null, res.code, map == null ? map : res.map || map); | ||
| else callback(null, res, map); | ||
| } catch (error) { | ||
| if (error instanceof Error) callback(error); | ||
| else callback(new Error(String(error))); | ||
| } | ||
| } | ||
| //#endregion | ||
| export { transform as default }; |
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
29
-9.37%37
2.78%74091
-44.55%18
-45.45%1600
-49.87%1
Infinity%1
Infinity%