routie dev init since i didn't adhere to any proper guidance up until now

This commit is contained in:
2026-04-29 22:27:29 -06:00
commit e1dabb71e2
15301 changed files with 3562618 additions and 0 deletions
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021-PRESENT Nuxt Contrib
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+35
View File
@@ -0,0 +1,35 @@
# Unplugin
[![npm version][npm-version-src]][npm-version-href]
[![npm downloads][npm-downloads-src]][npm-downloads-href]
[![License][license-src]][license-href]
Unified plugin system for build tools.
Currently supports:
- [Vite](https://vite.dev/)
- [Rollup](https://rollupjs.org/)
- [Webpack](https://webpack.js.org/)
- [esbuild](https://esbuild.github.io/)
- [Rspack](https://www.rspack.dev/)
- [Rolldown](https://rolldown.rs/)
- [Farm](https://www.farmfe.org/)
- And every framework built on top of them.
## Documentations
Learn more on the [Documentation](https://unplugin.unjs.io/)
## License
[MIT](./LICENSE) License © 2021-PRESENT Nuxt Contrib
<!-- Badges -->
[npm-version-src]: https://img.shields.io/npm/v/unplugin?style=flat&colorA=18181B&colorB=F0DB4F
[npm-version-href]: https://npmjs.com/package/unplugin
[npm-downloads-src]: https://img.shields.io/npm/dm/unplugin?style=flat&colorA=18181B&colorB=F0DB4F
[npm-downloads-href]: https://npmjs.com/package/unplugin
[license-src]: https://img.shields.io/github/license/unjs/unplugin.svg?style=flat&colorA=18181B&colorB=F0DB4F
[license-href]: https://github.com/unjs/unplugin/blob/main/LICENSE
+65
View File
@@ -0,0 +1,65 @@
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 };
+124
View File
@@ -0,0 +1,124 @@
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 };
+49
View File
@@ -0,0 +1,49 @@
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 as createBuildContext$1, createContext as createContext$1, normalizeMessage as normalizeMessage$1 };
+88
View File
@@ -0,0 +1,88 @@
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$1', {
enumerable: true,
get: function () {
return createBuildContext;
}
});
Object.defineProperty(exports, 'createContext$1', {
enumerable: true,
get: function () {
return createContext;
}
});
Object.defineProperty(exports, 'normalizeMessage$1', {
enumerable: true,
get: function () {
return normalizeMessage;
}
});
+170
View File
@@ -0,0 +1,170 @@
//#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;
}
});
+66
View File
@@ -0,0 +1,66 @@
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;
}
});
+1879
View File
File diff suppressed because it is too large Load Diff
+204
View File
@@ -0,0 +1,204 @@
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;
mappings: string;
names: string[];
sourceRoot?: string;
sources: string[];
// In magic-string v0.27.0, `sourcesContent` becomes nullable, while rollup haven't catch up yet
sourcesContent?: (string | null)[];
version: number;
}
type TransformResult = string | {
code: string;
map?: SourceMapInput | SourceMapCompact | null;
} | null | undefined | void;
interface ExternalIdResult {
id: string;
external?: boolean;
}
type NativeBuildContext = {
framework: "webpack";
compiler: WebpackCompiler;
compilation?: Compilation$1;
loaderContext?: LoaderContext$1<{
unpluginName: string;
}>;
} | {
framework: "esbuild";
build: PluginBuild;
} | {
framework: "rspack";
compiler: RspackCompiler;
compilation: Compilation;
loaderContext?: LoaderContext;
} | {
framework: "farm";
context: CompilationContext;
};
interface UnpluginBuildContext {
addWatchFile: (id: string) => void;
emitFile: (emittedFile: EmittedAsset) => void;
getWatchFiles: () => string[];
parse: (input: string, options?: any) => AstNode;
getNativeBuildContext?: () => NativeBuildContext;
}
type StringOrRegExp = string | RegExp;
type FilterPattern = Arrayable<StringOrRegExp>;
type StringFilter = FilterPattern | {
include?: FilterPattern;
exclude?: FilterPattern;
};
interface HookFilter {
id?: StringFilter;
code?: StringFilter;
}
interface ObjectHook<T extends HookFnMap[keyof HookFnMap], F extends keyof HookFilter> {
filter?: Pick<HookFilter, F>;
handler: T;
}
type Hook<T extends HookFnMap[keyof HookFnMap], F extends keyof HookFilter> = T | ObjectHook<T, F>;
interface HookFnMap {
// Build Hooks
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>;
// Output Generation Hooks
writeBundle: (this: void) => Thenable<void>;
}
interface UnpluginOptions {
name: string;
enforce?: "post" | "pre" | undefined;
buildStart?: HookFnMap["buildStart"];
buildEnd?: HookFnMap["buildEnd"];
transform?: Hook<HookFnMap["transform"], "code" | "id">;
load?: Hook<HookFnMap["load"], "id">;
resolveId?: Hook<HookFnMap["resolveId"], "id">;
writeBundle?: HookFnMap["writeBundle"];
watchChange?: (this: UnpluginBuildContext, id: string, change: {
event: "create" | "update" | "delete";
}) => void;
/**
* 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;
/**
* 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;
// framework specify extends
rollup?: Partial<RollupPlugin>;
webpack?: (compiler: WebpackCompiler) => void;
rspack?: (compiler: RspackCompiler) => void;
vite?: Partial<VitePlugin>;
unloader?: Partial<UnloaderPlugin>;
rolldown?: Partial<RolldownPlugin>;
esbuild?: {
// using regexp in esbuild improves performance
onResolveFilter?: RegExp;
onLoadFilter?: RegExp;
loader?: Loader | ((code: string, id: string) => Loader);
setup?: (build: PluginBuild) => void | Promise<void>;
config?: (options: BuildOptions) => void;
};
farm?: Partial<JsPlugin>;
}
interface ResolvedUnpluginOptions extends UnpluginOptions {
// injected internal objects
__vfs?: VirtualModulesPlugin;
__vfsModules?: Map<string, Promise<string>> | Set<string>;
__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) => 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;
} | {
framework: "rspack";
rspack: {
compiler: RspackCompiler;
};
});
interface UnpluginMessage {
name?: string;
id?: string;
message: string;
stack?: string;
code?: string;
plugin?: string;
pluginCode?: unknown;
loc?: {
column: number;
file?: string;
line: number;
};
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, EsbuildPlugin, ExternalIdResult, FilterPattern, Hook, HookFilter, HookFnMap, NativeBuildContext, Nullable, ObjectHook, ResolvedUnpluginOptions, RolldownPlugin, RollupPlugin, RspackCompiler, RspackPluginInstance, SourceMapCompact, StringFilter, StringOrRegExp, Thenable, TransformResult, UnloaderPlugin, UnpluginBuildContext, UnpluginContext, UnpluginContextMeta, UnpluginFactory, UnpluginFactoryOutput, UnpluginInstance, UnpluginMessage, UnpluginOptions, VitePlugin, WebpackCompiler, WebpackPluginInstance, createEsbuildPlugin, createFarmPlugin, createRolldownPlugin, createRollupPlugin, createRspackPlugin, createUnloaderPlugin, createUnplugin, createVitePlugin, createWebpackPlugin };
+204
View File
@@ -0,0 +1,204 @@
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;
mappings: string;
names: string[];
sourceRoot?: string;
sources: string[];
// In magic-string v0.27.0, `sourcesContent` becomes nullable, while rollup haven't catch up yet
sourcesContent?: (string | null)[];
version: number;
}
type TransformResult = string | {
code: string;
map?: SourceMapInput | SourceMapCompact | null;
} | null | undefined | void;
interface ExternalIdResult {
id: string;
external?: boolean;
}
type NativeBuildContext = {
framework: "webpack";
compiler: WebpackCompiler;
compilation?: Compilation$1;
loaderContext?: LoaderContext$1<{
unpluginName: string;
}>;
} | {
framework: "esbuild";
build: PluginBuild;
} | {
framework: "rspack";
compiler: RspackCompiler;
compilation: Compilation;
loaderContext?: LoaderContext;
} | {
framework: "farm";
context: CompilationContext;
};
interface UnpluginBuildContext {
addWatchFile: (id: string) => void;
emitFile: (emittedFile: EmittedAsset) => void;
getWatchFiles: () => string[];
parse: (input: string, options?: any) => AstNode;
getNativeBuildContext?: () => NativeBuildContext;
}
type StringOrRegExp = string | RegExp;
type FilterPattern = Arrayable<StringOrRegExp>;
type StringFilter = FilterPattern | {
include?: FilterPattern;
exclude?: FilterPattern;
};
interface HookFilter {
id?: StringFilter;
code?: StringFilter;
}
interface ObjectHook<T extends HookFnMap[keyof HookFnMap], F extends keyof HookFilter> {
filter?: Pick<HookFilter, F>;
handler: T;
}
type Hook<T extends HookFnMap[keyof HookFnMap], F extends keyof HookFilter> = T | ObjectHook<T, F>;
interface HookFnMap {
// Build Hooks
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>;
// Output Generation Hooks
writeBundle: (this: void) => Thenable<void>;
}
interface UnpluginOptions {
name: string;
enforce?: "post" | "pre" | undefined;
buildStart?: HookFnMap["buildStart"];
buildEnd?: HookFnMap["buildEnd"];
transform?: Hook<HookFnMap["transform"], "code" | "id">;
load?: Hook<HookFnMap["load"], "id">;
resolveId?: Hook<HookFnMap["resolveId"], "id">;
writeBundle?: HookFnMap["writeBundle"];
watchChange?: (this: UnpluginBuildContext, id: string, change: {
event: "create" | "update" | "delete";
}) => void;
/**
* 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;
/**
* 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;
// framework specify extends
rollup?: Partial<RollupPlugin>;
webpack?: (compiler: WebpackCompiler) => void;
rspack?: (compiler: RspackCompiler) => void;
vite?: Partial<VitePlugin>;
unloader?: Partial<UnloaderPlugin>;
rolldown?: Partial<RolldownPlugin>;
esbuild?: {
// using regexp in esbuild improves performance
onResolveFilter?: RegExp;
onLoadFilter?: RegExp;
loader?: Loader | ((code: string, id: string) => Loader);
setup?: (build: PluginBuild) => void | Promise<void>;
config?: (options: BuildOptions) => void;
};
farm?: Partial<JsPlugin>;
}
interface ResolvedUnpluginOptions extends UnpluginOptions {
// injected internal objects
__vfs?: VirtualModulesPlugin;
__vfsModules?: Map<string, Promise<string>> | Set<string>;
__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) => 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;
} | {
framework: "rspack";
rspack: {
compiler: RspackCompiler;
};
});
interface UnpluginMessage {
name?: string;
id?: string;
message: string;
stack?: string;
code?: string;
plugin?: string;
pluginCode?: unknown;
loc?: {
column: number;
file?: string;
line: number;
};
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, EsbuildPlugin, ExternalIdResult, FilterPattern, Hook, HookFilter, HookFnMap, NativeBuildContext, Nullable, ObjectHook, ResolvedUnpluginOptions, RolldownPlugin, RollupPlugin, RspackCompiler, RspackPluginInstance, SourceMapCompact, StringFilter, StringOrRegExp, Thenable, TransformResult, UnloaderPlugin, UnpluginBuildContext, UnpluginContext, UnpluginContextMeta, UnpluginFactory, UnpluginFactoryOutput, UnpluginInstance, UnpluginMessage, UnpluginOptions, VitePlugin, WebpackCompiler, WebpackPluginInstance, createEsbuildPlugin, createFarmPlugin, createRolldownPlugin, createRollupPlugin, createRspackPlugin, createUnloaderPlugin, createUnplugin, createVitePlugin, createWebpackPlugin };
+1878
View File
File diff suppressed because it is too large Load Diff
+22
View File
@@ -0,0 +1,22 @@
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-D30tqOw3.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);
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);
}
//#endregion
module.exports = load;
+7
View File
@@ -0,0 +1,7 @@
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 };
+7
View File
@@ -0,0 +1,7 @@
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 };
+22
View File
@@ -0,0 +1,22 @@
import { normalizeObjectHook } from "../../context-D49cMElb.js";
import { normalizeAbsolutePath } from "../../webpack-like-CSbnjTNU.js";
import { createBuildContext$1 as createBuildContext, createContext$1 as createContext } from "../../context-DY6ggBKV.js";
import { decodeVirtualModuleId, isVirtualModuleId } from "../../utils-Cbrj-Du4.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);
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);
}
//#endregion
export { load as default };
+25
View File
@@ -0,0 +1,25 @@
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;
+7
View File
@@ -0,0 +1,7 @@
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 };
+7
View File
@@ -0,0 +1,7 @@
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 };
+25
View File
@@ -0,0 +1,25 @@
import { normalizeObjectHook } from "../../context-D49cMElb.js";
import { createBuildContext$1 as createBuildContext, createContext$1 as createContext } from "../../context-DY6ggBKV.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 };
+39
View File
@@ -0,0 +1,39 @@
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 counter = 0;
constructor(plugin) {
this.plugin = plugin;
}
apply(compiler) {
FakeVirtualModulesPlugin.counter++;
const dir = this.plugin.__virtualModulePrefix;
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
compiler.hooks.shutdown.tap(this.name, () => {
if (--FakeVirtualModulesPlugin.counter === 0) fs.rmSync(dir, {
recursive: true,
force: true
});
});
}
async writeModule(file) {
const path$1 = encodeVirtualModuleId(file, this.plugin);
await fs.promises.writeFile(path$1, "");
return path$1;
}
};
//#endregion
export { FakeVirtualModulesPlugin, decodeVirtualModuleId, encodeVirtualModuleId, isVirtualModuleId };
+63
View File
@@ -0,0 +1,63 @@
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 counter = 0;
constructor(plugin) {
this.plugin = plugin;
}
apply(compiler) {
FakeVirtualModulesPlugin.counter++;
const dir = this.plugin.__virtualModulePrefix;
if (!node_fs.default.existsSync(dir)) node_fs.default.mkdirSync(dir, { recursive: true });
compiler.hooks.shutdown.tap(this.name, () => {
if (--FakeVirtualModulesPlugin.counter === 0) node_fs.default.rmSync(dir, {
recursive: true,
force: true
});
});
}
async writeModule(file) {
const path = encodeVirtualModuleId(file, this.plugin);
await node_fs.default.promises.writeFile(path, "");
return path;
}
};
//#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;
}
});
+44
View File
@@ -0,0 +1,44 @@
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;
}
});
+33
View File
@@ -0,0 +1,33 @@
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 };
+28
View File
@@ -0,0 +1,28 @@
const require_context = require('../../context-DwbtaXxf.cjs');
const require_webpack_like = require('../../webpack-like-BAQNtVsj.cjs');
const require_context$1 = require('../../context-Df-kn6rn.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$1(this);
const { handler } = require_context.normalizeObjectHook("load", plugin.load);
const res = await handler.call(Object.assign({}, require_context$1.createBuildContext$1({
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;
+7
View File
@@ -0,0 +1,7 @@
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 };
+7
View File
@@ -0,0 +1,7 @@
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 };
+28
View File
@@ -0,0 +1,28 @@
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 };
+31
View File
@@ -0,0 +1,31 @@
const require_context = require('../../context-DwbtaXxf.cjs');
const require_context$1 = require('../../context-Df-kn6rn.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$1(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$1({
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;
+7
View File
@@ -0,0 +1,7 @@
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 };
+7
View File
@@ -0,0 +1,7 @@
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 };
+31
View File
@@ -0,0 +1,31 @@
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 };
+94
View File
@@ -0,0 +1,94 @@
{
"name": "unplugin",
"type": "module",
"version": "2.3.5",
"packageManager": "pnpm@10.11.0",
"description": "Unified plugin system for build tools",
"license": "MIT",
"homepage": "https://unplugin.unjs.io",
"repository": {
"type": "git",
"url": "git+https://github.com/unjs/unplugin.git"
},
"sideEffects": false,
"exports": {
".": {
"import": "./dist/index.js",
"require": "./dist/index.cjs"
},
"./dist/webpack/loaders/*": "./dist/webpack/loaders/*.cjs",
"./dist/rspack/loaders/*": "./dist/rspack/loaders/*.cjs"
},
"main": "dist/index.js",
"module": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"dist"
],
"engines": {
"node": ">=18.12.0"
},
"scripts": {
"build": "tsdown",
"dev": "tsdown --watch src",
"lint": "eslint --cache .",
"lint:fix": "nr lint --fix",
"typecheck": "tsc --noEmit",
"docs:dev": "pnpm -C docs run dev",
"docs:build": "pnpm -C docs run build",
"docs:gen-files": "pnpm -C docs run gen-files",
"prepublishOnly": "nr build",
"release": "bumpp --all && npm publish",
"test": "nr test:build && vitest run --pool=forks",
"test:build": "jiti scripts/buildFixtures.ts"
},
"dependencies": {
"acorn": "^8.14.1",
"picomatch": "^4.0.2",
"webpack-virtual-modules": "^0.6.2"
},
"devDependencies": {
"@ampproject/remapping": "^2.3.0",
"@antfu/eslint-config": "^4.13.2",
"@antfu/ni": "^25.0.0",
"@farmfe/cli": "^1.0.4",
"@farmfe/core": "^1.7.5",
"@rspack/cli": "^1.3.12",
"@rspack/core": "^1.3.12",
"@types/fs-extra": "^11.0.4",
"@types/node": "^22.15.21",
"@types/picomatch": "^4.0.0",
"ansis": "^4.0.0",
"bumpp": "^10.1.1",
"esbuild": "^0.25.5",
"esbuild-plugin-copy": "^2.1.1",
"eslint": "^9.27.0",
"eslint-plugin-format": "^1.0.1",
"fast-glob": "^3.3.3",
"fs-extra": "^11.3.0",
"jiti": "^2.4.2",
"lint-staged": "^16.0.0",
"magic-string": "^0.30.17",
"rolldown": "^1.0.0-beta.9",
"rollup": "^4.41.1",
"simple-git-hooks": "^2.13.0",
"tsdown": "^0.12.3",
"typescript": "~5.8.3",
"unloader": "^0.4.5",
"unplugin": "workspace:*",
"unplugin-unused": "^0.5.0",
"vite": "^6.3.5",
"vitest": "^3.1.4",
"webpack": "^5.99.9",
"webpack-cli": "^6.0.1"
},
"resolutions": {
"esbuild": "^0.25.5"
},
"simple-git-hooks": {
"pre-commit": "pnpm i --frozen-lockfile --ignore-scripts --offline && npx lint-staged"
},
"lint-staged": {
"*": "eslint --fix"
}
}