added fonts

This commit is contained in:
guus committed 2025-07-02 11:28:41 +02:00
1 parent 4134e3a234
commit 142d2986b6
9079 files changed
+1498421 -2

No files matched your search

@@ -0,0 +1,34 @@
import type { LoaderContext } from 'next/dist/compiled/webpack/webpack';
export interface CssImport {
icss?: boolean;
importName: string;
url: string;
type?: 'url' | string;
index?: number;
}
export interface CssExport {
name: string;
value: string;
}
export interface ApiParam {
url?: string;
importName?: string;
layer?: string;
supports?: string;
media?: string;
dedupe?: boolean;
index?: number;
}
export interface ApiReplacement {
replacementName: string;
localName?: string;
importName: string;
needQuotes?: boolean;
hash?: string;
}
export declare function getImportCode(imports: CssImport[], options: any): string;
export declare function getModuleCode(result: {
map: any;
css: any;
}, api: ApiParam[], replacements: ApiReplacement[], options: any, loaderContext: LoaderContext<any>): string;
export declare function getExportCode(exports: CssExport[], replacements: ApiReplacement[], options: any): string;
@@ -0,0 +1,156 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
getExportCode: null,
getImportCode: null,
getModuleCode: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
getExportCode: function() {
return getExportCode;
},
getImportCode: function() {
return getImportCode;
},
getModuleCode: function() {
return getModuleCode;
}
});
const _camelcase = /*#__PURE__*/ _interop_require_default(require("../../css-loader/src/camelcase"));
const _utils = require("../../css-loader/src/utils");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function getImportCode(imports, options) {
let code = '';
for (const item of imports){
const { importName, url, icss } = item;
if (options.esModule) {
if (icss && options.modules.namedExport) {
code += `import ${options.modules.exportOnlyLocals ? '' : `${importName}, `}* as ${importName}_NAMED___ from ${url};\n`;
} else {
code += `import ${importName} from ${url};\n`;
}
} else {
code += `var ${importName} = require(${url});\n`;
}
}
return code ? `// Imports\n${code}` : '';
}
function getModuleCode(result, api, replacements, options, loaderContext) {
if (options.modules.exportOnlyLocals === true) {
return '';
}
const sourceMapValue = options.sourceMap ? `,${(0, _utils.normalizeSourceMapForRuntime)(result.map, loaderContext)}` : '';
let code = JSON.stringify(result.css);
let beforeCode = `var ___CSS_LOADER_EXPORT___ = ___CSS_LOADER_API_IMPORT___(${options.sourceMap});\n`;
for (const item of api){
const { url, media, dedupe } = item;
beforeCode += url ? `___CSS_LOADER_EXPORT___.push([module.id, ${JSON.stringify(`@import url(${url});`)}${media ? `, ${JSON.stringify(media)}` : ''}]);\n` : `___CSS_LOADER_EXPORT___.i(${item.importName}${media ? `, ${JSON.stringify(media)}` : dedupe ? ', ""' : ''}${dedupe ? ', true' : ''});\n`;
}
for (const item of replacements){
const { replacementName, importName, localName } = item;
if (localName) {
code = code.replace(new RegExp(replacementName, 'g'), ()=>options.modules.namedExport ? `" + ${importName}_NAMED___[${JSON.stringify((0, _camelcase.default)(localName))}] + "` : `" + ${importName}.locals[${JSON.stringify(localName)}] + "`);
} else {
const { hash, needQuotes } = item;
const getUrlOptions = [
...hash ? [
`hash: ${JSON.stringify(hash)}`
] : [],
...needQuotes ? 'needQuotes: true' : []
];
const preparedOptions = getUrlOptions.length > 0 ? `, { ${getUrlOptions.join(', ')} }` : '';
beforeCode += `var ${replacementName} = ___CSS_LOADER_GET_URL_IMPORT___(${importName}${preparedOptions});\n`;
code = code.replace(new RegExp(replacementName, 'g'), ()=>`" + ${replacementName} + "`);
}
}
return `${beforeCode}// Module\n___CSS_LOADER_EXPORT___.push([module.id, ${code}, ""${sourceMapValue}]);\n`;
}
function getExportCode(exports1, replacements, options) {
let code = '// Exports\n';
let localsCode = '';
const addExportToLocalsCode = (name, value)=>{
if (options.modules.namedExport) {
localsCode += `export const ${(0, _camelcase.default)(name)} = ${JSON.stringify(value)};\n`;
} else {
if (localsCode) {
localsCode += `,\n`;
}
localsCode += `\t${JSON.stringify(name)}: ${JSON.stringify(value)}`;
}
};
for (const { name, value } of exports1){
switch(options.modules.exportLocalsConvention){
case 'camelCase':
{
addExportToLocalsCode(name, value);
const modifiedName = (0, _camelcase.default)(name);
if (modifiedName !== name) {
addExportToLocalsCode(modifiedName, value);
}
break;
}
case 'camelCaseOnly':
{
addExportToLocalsCode((0, _camelcase.default)(name), value);
break;
}
case 'dashes':
{
addExportToLocalsCode(name, value);
const modifiedName = (0, _utils.dashesCamelCase)(name);
if (modifiedName !== name) {
addExportToLocalsCode(modifiedName, value);
}
break;
}
case 'dashesOnly':
{
addExportToLocalsCode((0, _utils.dashesCamelCase)(name), value);
break;
}
case 'asIs':
default:
addExportToLocalsCode(name, value);
break;
}
}
for (const item of replacements){
const { replacementName, localName } = item;
if (localName) {
const { importName } = item;
localsCode = localsCode.replace(new RegExp(replacementName, 'g'), ()=>{
if (options.modules.namedExport) {
return `" + ${importName}_NAMED___[${JSON.stringify((0, _camelcase.default)(localName))}] + "`;
} else if (options.modules.exportOnlyLocals) {
return `" + ${importName}[${JSON.stringify(localName)}] + "`;
}
return `" + ${importName}.locals[${JSON.stringify(localName)}] + "`;
});
} else {
localsCode = localsCode.replace(new RegExp(replacementName, 'g'), ()=>`" + ${replacementName} + "`);
}
}
if (options.modules.exportOnlyLocals) {
code += options.modules.namedExport ? localsCode : `${options.esModule ? 'export default' : 'module.exports ='} {\n${localsCode}\n};\n`;
return code;
}
if (localsCode) {
code += options.modules.namedExport ? localsCode : `___CSS_LOADER_EXPORT___.locals = {\n${localsCode}\n};\n`;
}
code += `${options.esModule ? 'export default' : 'module.exports ='} ___CSS_LOADER_EXPORT___;\n`;
return code;
}
//# sourceMappingURL=codegen.js.map
@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../src/build/webpack/loaders/lightningcss-loader/src/codegen.ts"],"sourcesContent":["import type { LoaderContext } from 'next/dist/compiled/webpack/webpack'\nimport camelCase from '../../css-loader/src/camelcase'\nimport {\n dashesCamelCase,\n normalizeSourceMapForRuntime,\n} from '../../css-loader/src/utils'\n\nexport interface CssImport {\n icss?: boolean\n importName: string\n url: string\n type?: 'url' | string\n index?: number\n}\n\nexport interface CssExport {\n name: string\n value: string\n}\n\nexport interface ApiParam {\n url?: string\n importName?: string\n\n layer?: string\n supports?: string\n media?: string\n\n dedupe?: boolean\n index?: number\n}\n\nexport interface ApiReplacement {\n replacementName: string\n localName?: string\n importName: string\n needQuotes?: boolean\n hash?: string\n}\n\nexport function getImportCode(imports: CssImport[], options: any) {\n let code = ''\n\n for (const item of imports) {\n const { importName, url, icss } = item\n\n if (options.esModule) {\n if (icss && options.modules.namedExport) {\n code += `import ${\n options.modules.exportOnlyLocals ? '' : `${importName}, `\n }* as ${importName}_NAMED___ from ${url};\\n`\n } else {\n code += `import ${importName} from ${url};\\n`\n }\n } else {\n code += `var ${importName} = require(${url});\\n`\n }\n }\n\n return code ? `// Imports\\n${code}` : ''\n}\n\nexport function getModuleCode(\n result: { map: any; css: any },\n api: ApiParam[],\n replacements: ApiReplacement[],\n options: any,\n loaderContext: LoaderContext<any>\n) {\n if (options.modules.exportOnlyLocals === true) {\n return ''\n }\n\n const sourceMapValue = options.sourceMap\n ? `,${normalizeSourceMapForRuntime(result.map, loaderContext)}`\n : ''\n\n let code = JSON.stringify(result.css)\n let beforeCode = `var ___CSS_LOADER_EXPORT___ = ___CSS_LOADER_API_IMPORT___(${options.sourceMap});\\n`\n\n for (const item of api) {\n const { url, media, dedupe } = item\n\n beforeCode += url\n ? `___CSS_LOADER_EXPORT___.push([module.id, ${JSON.stringify(\n `@import url(${url});`\n )}${media ? `, ${JSON.stringify(media)}` : ''}]);\\n`\n : `___CSS_LOADER_EXPORT___.i(${item.importName}${\n media ? `, ${JSON.stringify(media)}` : dedupe ? ', \"\"' : ''\n }${dedupe ? ', true' : ''});\\n`\n }\n\n for (const item of replacements) {\n const { replacementName, importName, localName } = item\n\n if (localName) {\n code = code.replace(new RegExp(replacementName, 'g'), () =>\n options.modules.namedExport\n ? `\" + ${importName}_NAMED___[${JSON.stringify(\n camelCase(localName)\n )}] + \"`\n : `\" + ${importName}.locals[${JSON.stringify(localName)}] + \"`\n )\n } else {\n const { hash, needQuotes } = item\n const getUrlOptions = [\n ...(hash ? [`hash: ${JSON.stringify(hash)}`] : []),\n ...(needQuotes ? 'needQuotes: true' : []),\n ]\n const preparedOptions =\n getUrlOptions.length > 0 ? `, { ${getUrlOptions.join(', ')} }` : ''\n\n beforeCode += `var ${replacementName} = ___CSS_LOADER_GET_URL_IMPORT___(${importName}${preparedOptions});\\n`\n code = code.replace(\n new RegExp(replacementName, 'g'),\n () => `\" + ${replacementName} + \"`\n )\n }\n }\n\n return `${beforeCode}// Module\\n___CSS_LOADER_EXPORT___.push([module.id, ${code}, \"\"${sourceMapValue}]);\\n`\n}\n\nexport function getExportCode(\n exports: CssExport[],\n replacements: ApiReplacement[],\n options: any\n) {\n let code = '// Exports\\n'\n let localsCode = ''\n\n const addExportToLocalsCode = (name: string, value: any) => {\n if (options.modules.namedExport) {\n localsCode += `export const ${camelCase(name)} = ${JSON.stringify(\n value\n )};\\n`\n } else {\n if (localsCode) {\n localsCode += `,\\n`\n }\n\n localsCode += `\\t${JSON.stringify(name)}: ${JSON.stringify(value)}`\n }\n }\n\n for (const { name, value } of exports) {\n switch (options.modules.exportLocalsConvention) {\n case 'camelCase': {\n addExportToLocalsCode(name, value)\n\n const modifiedName = camelCase(name)\n\n if (modifiedName !== name) {\n addExportToLocalsCode(modifiedName, value)\n }\n break\n }\n case 'camelCaseOnly': {\n addExportToLocalsCode(camelCase(name), value)\n break\n }\n case 'dashes': {\n addExportToLocalsCode(name, value)\n\n const modifiedName = dashesCamelCase(name)\n\n if (modifiedName !== name) {\n addExportToLocalsCode(modifiedName, value)\n }\n break\n }\n case 'dashesOnly': {\n addExportToLocalsCode(dashesCamelCase(name), value)\n break\n }\n case 'asIs':\n default:\n Line truncated
@@ -0,0 +1,3 @@
import { LightningCssLoader } from './loader';
export { LightningCssMinifyPlugin } from './minify';
export default LightningCssLoader;
@@ -0,0 +1,27 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
LightningCssMinifyPlugin: null,
default: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
LightningCssMinifyPlugin: function() {
return _minify.LightningCssMinifyPlugin;
},
default: function() {
return _default;
}
});
const _loader = require("./loader");
const _minify = require("./minify");
const _default = _loader.LightningCssLoader;
//# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../src/build/webpack/loaders/lightningcss-loader/src/index.ts"],"sourcesContent":["import { LightningCssLoader } from './loader'\n\nexport { LightningCssMinifyPlugin } from './minify'\nexport default LightningCssLoader\n"],"names":["LightningCssMinifyPlugin","LightningCssLoader"],"mappings":";;;;;;;;;;;;;;;IAESA,wBAAwB;eAAxBA,gCAAwB;;IACjC,OAAiC;eAAjC;;;wBAHmC;wBAEM;MACzC,WAAeC,0BAAkB"}
@@ -0,0 +1,4 @@
export declare enum ECacheKey {
loader = "loader",
minify = "minify"
}
@@ -0,0 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "ECacheKey", {
enumerable: true,
get: function() {
return ECacheKey;
}
});
var ECacheKey = /*#__PURE__*/ function(ECacheKey) {
ECacheKey["loader"] = "loader";
ECacheKey["minify"] = "minify";
return ECacheKey;
}({});
//# sourceMappingURL=interface.js.map
@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../src/build/webpack/loaders/lightningcss-loader/src/interface.ts"],"sourcesContent":["export enum ECacheKey {\n loader = 'loader',\n minify = 'minify',\n}\n"],"names":["ECacheKey"],"mappings":";;;;+BAAYA;;;eAAAA;;;AAAL,IAAA,AAAKA,mCAAAA;;;WAAAA"}
@@ -0,0 +1,3 @@
import type { LoaderContext } from 'webpack';
export declare function LightningCssLoader(this: LoaderContext<any>, source: string, prevMap?: Record<string, any>): Promise<void>;
export declare const raw = true;
@@ -0,0 +1,424 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
LightningCssLoader: null,
raw: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
LightningCssLoader: function() {
return LightningCssLoader;
},
raw: function() {
return raw;
}
});
const _utils = require("./utils");
const _codegen = require("./codegen");
const _utils1 = require("../../css-loader/src/utils");
const _stringifyrequest = require("../../../stringify-request");
const _interface = require("./interface");
const encoder = new TextEncoder();
function createUrlAndImportVisitor(visitorOptions, apis, imports, replacements, replacedUrls, replacedImportUrls) {
const importUrlToNameMap = new Map();
let hasUrlImportHelper = false;
const urlToNameMap = new Map();
const urlToReplacementMap = new Map();
let urlIndex = -1;
let importUrlIndex = -1;
function handleUrl(u) {
let url = u.url;
const needKeep = visitorOptions.urlFilter(url);
if (!needKeep) {
return u;
}
if ((0, _utils1.isDataUrl)(url)) {
return u;
}
urlIndex++;
replacedUrls.set(urlIndex, url);
url = `__NEXT_LIGHTNINGCSS_LOADER_URL_REPLACE_${urlIndex}__`;
const [, query, hashOrQuery] = url.split(/(\?)?#/, 3);
const queryParts = url.split('!');
let prefix;
if (queryParts.length > 1) {
url = queryParts.pop();
prefix = queryParts.join('!');
}
let hash = query ? '?' : '';
hash += hashOrQuery ? `#${hashOrQuery}` : '';
if (!hasUrlImportHelper) {
imports.push({
type: 'get_url_import',
importName: '___CSS_LOADER_GET_URL_IMPORT___',
url: JSON.stringify(require.resolve('../../css-loader/src/runtime/getUrl.js')),
index: -1
});
hasUrlImportHelper = true;
}
const newUrl = prefix ? `${prefix}!${url}` : url;
let importName = urlToNameMap.get(newUrl);
if (!importName) {
importName = `___CSS_LOADER_URL_IMPORT_${urlToNameMap.size}___`;
urlToNameMap.set(newUrl, importName);
imports.push({
type: 'url',
importName,
url: JSON.stringify(newUrl),
index: urlIndex
});
}
// This should be true for string-urls in image-set
const needQuotes = false;
const replacementKey = JSON.stringify({
newUrl,
hash,
needQuotes
});
let replacementName = urlToReplacementMap.get(replacementKey);
if (!replacementName) {
replacementName = `___CSS_LOADER_URL_REPLACEMENT_${urlToReplacementMap.size}___`;
urlToReplacementMap.set(replacementKey, replacementName);
replacements.push({
replacementName,
importName,
hash,
needQuotes
});
}
return {
loc: u.loc,
url: replacementName
};
}
return {
Rule: {
import (node) {
if (visitorOptions.importFilter) {
const needKeep = visitorOptions.importFilter(node.value.url, node.value.media);
if (!needKeep) {
return node;
}
}
let url = node.value.url;
importUrlIndex++;
replacedImportUrls.set(importUrlIndex, url);
url = `__NEXT_LIGHTNINGCSS_LOADER_IMPORT_URL_REPLACE_${importUrlIndex}__`;
// TODO: Use identical logic as valueParser.stringify()
const media = node.value.media.mediaQueries.length ? JSON.stringify(node.value.media.mediaQueries) : undefined;
const isRequestable = (0, _utils1.isUrlRequestable)(url);
let prefix;
if (isRequestable) {
const queryParts = url.split('!');
if (queryParts.length > 1) {
url = queryParts.pop();
prefix = queryParts.join('!');
}
}
if (!isRequestable) {
apis.push({
url,
media
});
// Bug of lightningcss
return {
type: 'ignored',
value: ''
};
}
const newUrl = prefix ? `${prefix}!${url}` : url;
let importName = importUrlToNameMap.get(newUrl);
if (!importName) {
importName = `___CSS_LOADER_AT_RULE_IMPORT_${importUrlToNameMap.size}___`;
importUrlToNameMap.set(newUrl, importName);
const importUrl = visitorOptions.urlHandler(newUrl);
imports.push({
type: 'rule_import',
importName,
url: importUrl
});
}
apis.push({
importName,
media
});
// Bug of lightningcss
return {
type: 'ignored',
value: ''
};
}
},
Url (node) {
return handleUrl(node);
}
};
}
function createIcssVisitor({ apis, imports, replacements, replacedUrls, urlHandler }) {
let index = -1;
let replacementIndex = -1;
return {
Declaration: {
composes (node) {
if (node.property === 'unparsed') {
return;
}
const specifier = node.value.from;
if ((specifier == null ? void 0 : specifier.type) !== 'file') {
return;
}
let url = specifier.value;
if (!url) {
return;
}
index++;
replacedUrls.set(index, url);
url = `__NEXT_LIGHTNINGCSS_LOADER_ICSS_URL_REPLACE_${index}__`;
const importName = `___CSS_LOADER_ICSS_IMPORT_${imports.length}___`;
imports.push({
type: 'icss_import',
importName,
icss: true,
url: urlHandler(url),
index
});
apis.push({
importName,
dedupe: true,
index
});
const newNames = [];
for (const localName of node.value.names){
replacementIndex++;
const replacementName = `___CSS_LOADER_ICSS_IMPORT_${index}_REPLACEMENT_${replacementIndex}___`;
replacements.push({
replacementName,
importName,
localName
});
newNames.push(replacementName);
}
return {
property: 'composes',
value: {
loc: node.value.loc,
names: newNames,
from: specifier
}
};
}
}
};
}
const LOADER_NAME = `lightningcss-loader`;
async function LightningCssLoader(source, prevMap) {
var _options_modules;
const done = this.async();
const options = this.getOptions();
const { implementation, targets: userTargets, ...opts } = options;
options.modules ??= {};
if (implementation && typeof implementation.transformCss !== 'function') {
done(Object.defineProperty(new TypeError(`[${LOADER_NAME}]: options.implementation.transformCss must be an 'lightningcss' transform function. Received ${typeof implementation.transformCss}`), "__NEXT_ERROR_CODE", {
value: "E560",
enumerable: false,
configurable: true
}));
return;
}
if (options.postcss) {
var _postcssWithPlugins_plugins;
const { postcssWithPlugins } = await options.postcss();
if ((postcssWithPlugins == null ? void 0 : (_postcssWithPlugins_plugins = postcssWithPlugins.plugins) == null ? void 0 : _postcssWithPlugins_plugins.length) > 0) {
throw Object.defineProperty(new Error(`[${LOADER_NAME}]: experimental.useLightningcss does not work with postcss plugins. Please remove 'useLightningcss: true' from your configuration.`), "__NEXT_ERROR_CODE", {
value: "E519",
enumerable: false,
configurable: true
});
}
}
const exports1 = [];
const imports = [];
const icssImports = [];
const apis = [];
const replacements = [];
if (((_options_modules = options.modules) == null ? void 0 : _options_modules.exportOnlyLocals) !== true) {
imports.unshift({
type: 'api_import',
importName: '___CSS_LOADER_API_IMPORT___',
url: (0, _stringifyrequest.stringifyRequest)(this, require.resolve('../../css-loader/src/runtime/api'))
});
}
const { loadBindings } = require('next/dist/build/swc');
const transform = (implementation == null ? void 0 : implementation.transformCss) ?? (await loadBindings()).css.lightning.transform;
const replacedUrls = new Map();
const icssReplacedUrls = new Map();
const replacedImportUrls = new Map();
const urlImportVisitor = createUrlAndImportVisitor({
urlHandler: (url)=>(0, _stringifyrequest.stringifyRequest)(this, (0, _utils1.getPreRequester)(this)(options.importLoaders ?? 0) + url),
urlFilter: (0, _utils1.getFilter)(options.url, this.resourcePath),
importFilter: (0, _utils1.getFilter)(options.import, this.resourcePath),
context: this.context
}, apis, imports, replacements, replacedUrls, replacedImportUrls);
const icssVisitor = createIcssVisitor({
apis,
imports: icssImports,
replacements,
replacedUrls: icssReplacedUrls,
urlHandler: (url)=>(0, _stringifyrequest.stringifyRequest)(this, (0, _utils1.getPreRequester)(this)(options.importLoaders) + url)
});
// This works by returned visitors are not conflicting.
// naive workaround for composeVisitors, as we do not directly depends on lightningcss's npm pkg
// but next-swc provides bindings
const visitor = {
...urlImportVisitor,
...icssVisitor
};
try {
const { code, map, exports: moduleExports } = transform({
...opts,
visitor,
cssModules: options.modules ? {
pattern: process.env.__NEXT_TEST_MODE ? '[name]__[local]' : '[name]__[hash]__[local]'
} : undefined,
filename: this.resourcePath,
code: encoder.encode(source),
sourceMap: this.sourceMap,
targets: (0, _utils.getTargets)({
targets: userTargets,
key: _interface.ECacheKey.loader
}),
inputSourceMap: this.sourceMap && prevMap ? JSON.stringify(prevMap) : undefined,
include: 1
});
let cssCodeAsString = code.toString();
if (moduleExports) {
for(const name in moduleExports){
if (Object.prototype.hasOwnProperty.call(moduleExports, name)) {
const v = moduleExports[name];
let value = v.name;
for (const compose of v.composes){
value += ` ${compose.name}`;
}
exports1.push({
name,
value
});
}
}
}
if (replacedUrls.size !== 0) {
const urlResolver = this.getResolve({
conditionNames: [
'asset'
],
mainFields: [
'asset'
],
mainFiles: [],
extensions: []
});
for (const [index, url] of replacedUrls.entries()){
const [pathname] = url.split(/(\?)?#/, 3);
const request = (0, _utils1.requestify)(pathname, this.rootContext);
const resolvedUrl = await (0, _utils1.resolveRequests)(urlResolver, this.context, [
...new Set([
request,
url
])
]);
for (const importItem of imports){
importItem.url = importItem.url.replace(`__NEXT_LIGHTNINGCSS_LOADER_URL_REPLACE_${index}__`, resolvedUrl ?? url);
}
}
}
if (replacedImportUrls.size !== 0) {
const importResolver = this.getResolve({
conditionNames: [
'style'
],
extensions: [
'.css'
],
mainFields: [
'css',
'style',
'main',
'...'
],
mainFiles: [
'index',
'...'
],
restrictions: [
/\.css$/i
]
});
for (const [index, url] of replacedImportUrls.entries()){
const [pathname] = url.split(/(\?)?#/, 3);
const request = (0, _utils1.requestify)(pathname, this.rootContext);
const resolvedUrl = await (0, _utils1.resolveRequests)(importResolver, this.context, [
...new Set([
request,
url
])
]);
for (const importItem of imports){
importItem.url = importItem.url.replace(`__NEXT_LIGHTNINGCSS_LOADER_IMPORT_URL_REPLACE_${index}__`, resolvedUrl ?? url);
}
}
}
if (icssReplacedUrls.size !== 0) {
const icssResolver = this.getResolve({
conditionNames: [
'style'
],
extensions: [],
mainFields: [
'css',
'style',
'main',
'...'
],
mainFiles: [
'index',
'...'
]
});
for (const [index, url] of icssReplacedUrls.entries()){
const [pathname] = url.split(/(\?)?#/, 3);
const request = (0, _utils1.requestify)(pathname, this.rootContext);
const resolvedUrl = await (0, _utils1.resolveRequests)(icssResolver, this.context, [
...new Set([
url,
request
])
]);
for (const importItem of icssImports){
importItem.url = importItem.url.replace(`__NEXT_LIGHTNINGCSS_LOADER_ICSS_URL_REPLACE_${index}__`, resolvedUrl ?? url);
}
}
}
imports.push(...icssImports);
const importCode = (0, _codegen.getImportCode)(imports, options);
const moduleCode = (0, _codegen.getModuleCode)({
css: cssCodeAsString,
map
}, apis, replacements, options, this);
const exportCode = (0, _codegen.getExportCode)(exports1, replacements, options);
const esCode = `${importCode}${moduleCode}${exportCode}`;
done(null, esCode, map && JSON.parse(map.toString()));
} catch (error) {
console.error('lightningcss-loader error', error);
done(error);
}
}
const raw = true;
//# sourceMappingURL=loader.js.map
@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../src/build/webpack/loaders/lightningcss-loader/src/loader.ts"],"sourcesContent":["import type { LoaderContext } from 'webpack'\nimport { getTargets } from './utils'\nimport {\n getImportCode,\n type ApiParam,\n type ApiReplacement,\n type CssExport,\n type CssImport,\n getModuleCode,\n getExportCode,\n} from './codegen'\nimport {\n getFilter,\n getPreRequester,\n isDataUrl,\n isUrlRequestable,\n requestify,\n resolveRequests,\n} from '../../css-loader/src/utils'\nimport { stringifyRequest } from '../../../stringify-request'\nimport { ECacheKey } from './interface'\n\nconst encoder = new TextEncoder()\n\nfunction createUrlAndImportVisitor(\n visitorOptions: any,\n apis: ApiParam[],\n imports: CssImport[],\n replacements: ApiReplacement[],\n replacedUrls: Map<number, string>,\n replacedImportUrls: Map<number, string>\n) {\n const importUrlToNameMap = new Map<string, string>()\n\n let hasUrlImportHelper = false\n const urlToNameMap = new Map()\n const urlToReplacementMap = new Map()\n let urlIndex = -1\n let importUrlIndex = -1\n\n function handleUrl(u: { url: string; loc: unknown }): unknown {\n let url = u.url\n const needKeep = visitorOptions.urlFilter(url)\n\n if (!needKeep) {\n return u\n }\n\n if (isDataUrl(url)) {\n return u\n }\n\n urlIndex++\n\n replacedUrls.set(urlIndex, url)\n url = `__NEXT_LIGHTNINGCSS_LOADER_URL_REPLACE_${urlIndex}__`\n\n const [, query, hashOrQuery] = url.split(/(\\?)?#/, 3)\n\n const queryParts = url.split('!')\n let prefix: string | undefined\n\n if (queryParts.length > 1) {\n url = queryParts.pop()!\n prefix = queryParts.join('!')\n }\n\n let hash = query ? '?' : ''\n hash += hashOrQuery ? `#${hashOrQuery}` : ''\n\n if (!hasUrlImportHelper) {\n imports.push({\n type: 'get_url_import',\n importName: '___CSS_LOADER_GET_URL_IMPORT___',\n url: JSON.stringify(\n require.resolve('../../css-loader/src/runtime/getUrl.js')\n ),\n index: -1,\n })\n\n hasUrlImportHelper = true\n }\n\n const newUrl = prefix ? `${prefix}!${url}` : url\n let importName = urlToNameMap.get(newUrl)\n\n if (!importName) {\n importName = `___CSS_LOADER_URL_IMPORT_${urlToNameMap.size}___`\n urlToNameMap.set(newUrl, importName)\n\n imports.push({\n type: 'url',\n importName,\n url: JSON.stringify(newUrl),\n index: urlIndex,\n })\n }\n // This should be true for string-urls in image-set\n const needQuotes = false\n\n const replacementKey = JSON.stringify({ newUrl, hash, needQuotes })\n let replacementName = urlToReplacementMap.get(replacementKey)\n\n if (!replacementName) {\n replacementName = `___CSS_LOADER_URL_REPLACEMENT_${urlToReplacementMap.size}___`\n urlToReplacementMap.set(replacementKey, replacementName)\n\n replacements.push({\n replacementName,\n importName,\n hash,\n needQuotes,\n })\n }\n\n return {\n loc: u.loc,\n url: replacementName,\n }\n }\n\n return {\n Rule: {\n import(node: any) {\n if (visitorOptions.importFilter) {\n const needKeep = visitorOptions.importFilter(\n node.value.url,\n node.value.media\n )\n\n if (!needKeep) {\n return node\n }\n }\n let url = node.value.url\n\n importUrlIndex++\n\n replacedImportUrls.set(importUrlIndex, url)\n url = `__NEXT_LIGHTNINGCSS_LOADER_IMPORT_URL_REPLACE_${importUrlIndex}__`\n\n // TODO: Use identical logic as valueParser.stringify()\n const media = node.value.media.mediaQueries.length\n ? JSON.stringify(node.value.media.mediaQueries)\n : undefined\n const isRequestable = isUrlRequestable(url)\n let prefix: string | undefined\n if (isRequestable) {\n const queryParts = url.split('!')\n if (queryParts.length > 1) {\n url = queryParts.pop()!\n prefix = queryParts.join('!')\n }\n }\n if (!isRequestable) {\n apis.push({ url, media })\n // Bug of lightningcss\n return { type: 'ignored', value: '' }\n }\n const newUrl = prefix ? `${prefix}!${url}` : url\n let importName = importUrlToNameMap.get(newUrl)\n if (!importName) {\n importName = `___CSS_LOADER_AT_RULE_IMPORT_${importUrlToNameMap.size}___`\n importUrlToNameMap.set(newUrl, importName)\n\n const importUrl = visitorOptions.urlHandler(newUrl)\n imports.push({\n type: 'rule_import',\n importName,\n url: importUrl,\n })\n }\n apis.push({ importName, media })\n // Bug of lightningcss\n return { type: 'ignored', value: '' }\n },\n },\n Url(node: any) {\n return handlLine truncated
@@ -0,0 +1,8 @@
import type { Compiler } from 'webpack';
export declare class LightningCssMinifyPlugin {
private readonly options;
private transform;
constructor(opts?: any);
apply(compiler: Compiler): void;
private transformAssets;
}
@@ -0,0 +1,94 @@
// @ts-ignore
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "LightningCssMinifyPlugin", {
enumerable: true,
get: function() {
return LightningCssMinifyPlugin;
}
});
const _webpack = require("next/dist/compiled/webpack/webpack");
const _webpacksources3 = require("next/dist/compiled/webpack-sources3");
const _interface = require("./interface");
const _utils = require("./utils");
const _buffer = require("buffer");
const PLUGIN_NAME = 'lightning-css-minify';
const CSS_FILE_REG = /\.css(?:\?.*)?$/i;
class LightningCssMinifyPlugin {
constructor(opts = {}){
const { implementation, ...otherOpts } = opts;
if (implementation && typeof implementation.transformCss !== 'function') {
throw Object.defineProperty(new TypeError(`[LightningCssMinifyPlugin]: implementation.transformCss must be an 'lightningcss' transform function. Received ${typeof implementation.transformCss}`), "__NEXT_ERROR_CODE", {
value: "E561",
enumerable: false,
configurable: true
});
}
this.transform = implementation == null ? void 0 : implementation.transformCss;
this.options = otherOpts;
}
apply(compiler) {
const meta = JSON.stringify({
name: '@next/lightningcss-loader',
version: '0.0.0',
options: this.options
});
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation)=>{
compilation.hooks.chunkHash.tap(PLUGIN_NAME, (_, hash)=>hash.update(meta));
compilation.hooks.processAssets.tapPromise({
name: PLUGIN_NAME,
stage: _webpack.webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE,
additionalAssets: true
}, async ()=>await this.transformAssets(compilation));
compilation.hooks.statsPrinter.tap(PLUGIN_NAME, (statsPrinter)=>{
statsPrinter.hooks.print.for('asset.info.minimized')// @ts-ignore
.tap(PLUGIN_NAME, (minimized, { green, formatFlag })=>{
// @ts-ignore
return minimized ? green(formatFlag('minimized')) : undefined;
});
});
});
}
async transformAssets(compilation) {
const { options: { devtool } } = compilation.compiler;
if (!this.transform) {
const { loadBindings } = require('next/dist/build/swc');
this.transform = (await loadBindings()).css.lightning.transform;
}
const sourcemap = this.options.sourceMap === undefined ? devtool && devtool.includes('source-map') : this.options.sourceMap;
const { include, exclude, test: testRegExp, targets: userTargets, ...transformOptions } = this.options;
const assets = compilation.getAssets().filter((asset)=>// Filter out already minimized
!asset.info.minimized && // Filter out by file type
(testRegExp || CSS_FILE_REG).test(asset.name) && _webpack.ModuleFilenameHelpers.matchObject({
include,
exclude
}, asset.name));
await Promise.all(assets.map(async (asset)=>{
const { source, map } = asset.source.sourceAndMap();
const sourceAsString = source.toString();
const code = typeof source === 'string' ? _buffer.Buffer.from(source) : source;
const targets = (0, _utils.getTargets)({
targets: userTargets,
key: _interface.ECacheKey.minify
});
const result = await this.transform({
filename: asset.name,
code,
minify: true,
sourceMap: sourcemap,
targets,
...transformOptions
});
const codeString = result.code.toString();
compilation.updateAsset(asset.name, // @ts-ignore
sourcemap ? new _webpacksources3.SourceMapSource(codeString, asset.name, JSON.parse(result.map.toString()), sourceAsString, map, true) : new _webpacksources3.RawSource(codeString), {
...asset.info,
minimized: true
});
}));
}
}
//# sourceMappingURL=minify.js.map
@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../src/build/webpack/loaders/lightningcss-loader/src/minify.ts"],"sourcesContent":["// @ts-ignore\nimport { ModuleFilenameHelpers } from 'next/dist/compiled/webpack/webpack'\nimport { webpack } from 'next/dist/compiled/webpack/webpack'\n// @ts-ignore\nimport { RawSource, SourceMapSource } from 'next/dist/compiled/webpack-sources3'\nimport { ECacheKey } from './interface'\nimport type { Compilation, Compiler } from 'webpack'\nimport { getTargets } from './utils'\nimport { Buffer } from 'buffer'\n\nconst PLUGIN_NAME = 'lightning-css-minify'\nconst CSS_FILE_REG = /\\.css(?:\\?.*)?$/i\n\nexport class LightningCssMinifyPlugin {\n private readonly options: any\n private transform: any | undefined\n\n constructor(opts: any = {}) {\n const { implementation, ...otherOpts } = opts\n if (implementation && typeof implementation.transformCss !== 'function') {\n throw new TypeError(\n `[LightningCssMinifyPlugin]: implementation.transformCss must be an 'lightningcss' transform function. Received ${typeof implementation.transformCss}`\n )\n }\n\n this.transform = implementation?.transformCss\n this.options = otherOpts\n }\n\n apply(compiler: Compiler) {\n const meta = JSON.stringify({\n name: '@next/lightningcss-loader',\n version: '0.0.0',\n options: this.options,\n })\n\n compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {\n compilation.hooks.chunkHash.tap(PLUGIN_NAME, (_, hash) =>\n hash.update(meta)\n )\n\n compilation.hooks.processAssets.tapPromise(\n {\n name: PLUGIN_NAME,\n stage: webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE,\n additionalAssets: true,\n },\n async () => await this.transformAssets(compilation)\n )\n\n compilation.hooks.statsPrinter.tap(PLUGIN_NAME, (statsPrinter) => {\n statsPrinter.hooks.print\n .for('asset.info.minimized')\n // @ts-ignore\n .tap(PLUGIN_NAME, (minimized, { green, formatFlag }) => {\n // @ts-ignore\n return minimized ? green(formatFlag('minimized')) : undefined\n })\n })\n })\n }\n\n private async transformAssets(compilation: Compilation): Promise<void> {\n const {\n options: { devtool },\n } = compilation.compiler\n\n if (!this.transform) {\n const { loadBindings } = require('next/dist/build/swc')\n this.transform = (await loadBindings()).css.lightning.transform\n }\n\n const sourcemap =\n this.options.sourceMap === undefined\n ? ((devtool && (devtool as string).includes('source-map')) as boolean)\n : this.options.sourceMap\n\n const {\n include,\n exclude,\n test: testRegExp,\n targets: userTargets,\n ...transformOptions\n } = this.options\n\n const assets = compilation.getAssets().filter(\n (asset) =>\n // Filter out already minimized\n !asset.info.minimized &&\n // Filter out by file type\n (testRegExp || CSS_FILE_REG).test(asset.name) &&\n ModuleFilenameHelpers.matchObject({ include, exclude }, asset.name)\n )\n\n await Promise.all(\n assets.map(async (asset) => {\n const { source, map } = asset.source.sourceAndMap()\n const sourceAsString = source.toString()\n const code = typeof source === 'string' ? Buffer.from(source) : source\n const targets = getTargets({\n targets: userTargets,\n key: ECacheKey.minify,\n })\n\n const result = await this.transform!({\n filename: asset.name,\n code,\n minify: true,\n sourceMap: sourcemap,\n targets,\n ...transformOptions,\n })\n const codeString = result.code.toString()\n\n compilation.updateAsset(\n asset.name,\n // @ts-ignore\n sourcemap\n ? new SourceMapSource(\n codeString,\n asset.name,\n JSON.parse(result.map!.toString()),\n sourceAsString,\n map as any,\n true\n )\n : new RawSource(codeString),\n {\n ...asset.info,\n minimized: true,\n }\n )\n })\n )\n }\n}\n"],"names":["LightningCssMinifyPlugin","PLUGIN_NAME","CSS_FILE_REG","constructor","opts","implementation","otherOpts","transformCss","TypeError","transform","options","apply","compiler","meta","JSON","stringify","name","version","hooks","compilation","tap","chunkHash","_","hash","update","processAssets","tapPromise","stage","webpack","Compilation","PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE","additionalAssets","transformAssets","statsPrinter","print","for","minimized","green","formatFlag","undefined","devtool","loadBindings","require","css","lightning","sourcemap","sourceMap","includes","include","exclude","test","testRegExp","targets","userTargetLine truncated
@@ -0,0 +1,4 @@
export declare const getTargets: (opts: {
targets?: string[];
key: any;
}) => any;
@@ -0,0 +1,58 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getTargets", {
enumerable: true,
get: function() {
return getTargets;
}
});
let targetsCache = {};
/**
* Convert a version number to a single 24-bit number
*
* https://github.com/lumeland/lume/blob/4cc75599006df423a14befc06d3ed8493c645b09/plugins/lightningcss.ts#L160
*/ function version(major, minor = 0, patch = 0) {
return major << 16 | minor << 8 | patch;
}
function parseVersion(v) {
return v.split('.').reduce((acc, val)=>{
if (!acc) {
return null;
}
const parsed = parseInt(val, 10);
if (isNaN(parsed)) {
return null;
}
acc.push(parsed);
return acc;
}, []);
}
function browserslistToTargets(targets) {
return targets.reduce((acc, value)=>{
const [name, v] = value.split(' ');
const parsedVersion = parseVersion(v);
if (!parsedVersion) {
return acc;
}
const versionDigit = version(parsedVersion[0], parsedVersion[1], parsedVersion[2]);
if (name === 'and_qq' || name === 'and_uc' || name === 'baidu' || name === 'bb' || name === 'kaios' || name === 'op_mini') {
return acc;
}
if (acc[name] == null || versionDigit < acc[name]) {
acc[name] = versionDigit;
}
return acc;
}, {});
}
const getTargets = (opts)=>{
const cache = targetsCache[opts.key];
if (cache) {
return cache;
}
const result = browserslistToTargets(opts.targets ?? []);
return targetsCache[opts.key] = result;
};
//# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../src/build/webpack/loaders/lightningcss-loader/src/utils.ts"],"sourcesContent":["let targetsCache: Record<string, any> = {}\n\n/**\n * Convert a version number to a single 24-bit number\n *\n * https://github.com/lumeland/lume/blob/4cc75599006df423a14befc06d3ed8493c645b09/plugins/lightningcss.ts#L160\n */\nfunction version(major: number, minor = 0, patch = 0): number {\n return (major << 16) | (minor << 8) | patch\n}\n\nfunction parseVersion(v: string) {\n return v.split('.').reduce(\n (acc, val) => {\n if (!acc) {\n return null\n }\n\n const parsed = parseInt(val, 10)\n if (isNaN(parsed)) {\n return null\n }\n acc.push(parsed)\n return acc\n },\n [] as Array<number> | null\n )\n}\n\nfunction browserslistToTargets(targets: Array<string>) {\n return targets.reduce(\n (acc, value) => {\n const [name, v] = value.split(' ')\n const parsedVersion = parseVersion(v)\n\n if (!parsedVersion) {\n return acc\n }\n const versionDigit = version(\n parsedVersion[0],\n parsedVersion[1],\n parsedVersion[2]\n )\n\n if (\n name === 'and_qq' ||\n name === 'and_uc' ||\n name === 'baidu' ||\n name === 'bb' ||\n name === 'kaios' ||\n name === 'op_mini'\n ) {\n return acc\n }\n\n if (acc[name] == null || versionDigit < acc[name]) {\n acc[name] = versionDigit\n }\n\n return acc\n },\n {} as Record<string, number>\n )\n}\n\nexport const getTargets = (opts: { targets?: string[]; key: any }) => {\n const cache = targetsCache[opts.key]\n if (cache) {\n return cache\n }\n\n const result = browserslistToTargets(opts.targets ?? [])\n return (targetsCache[opts.key] = result)\n}\n"],"names":["getTargets","targetsCache","version","major","minor","patch","parseVersion","v","split","reduce","acc","val","parsed","parseInt","isNaN","push","browserslistToTargets","targets","value","name","parsedVersion","versionDigit","opts","cache","key","result"],"mappings":";;;;+BAiEaA;;;eAAAA;;;AAjEb,IAAIC,eAAoC,CAAC;AAEzC;;;;CAIC,GACD,SAASC,QAAQC,KAAa,EAAEC,QAAQ,CAAC,EAAEC,QAAQ,CAAC;IAClD,OAAO,AAACF,SAAS,KAAOC,SAAS,IAAKC;AACxC;AAEA,SAASC,aAAaC,CAAS;IAC7B,OAAOA,EAAEC,KAAK,CAAC,KAAKC,MAAM,CACxB,CAACC,KAAKC;QACJ,IAAI,CAACD,KAAK;YACR,OAAO;QACT;QAEA,MAAME,SAASC,SAASF,KAAK;QAC7B,IAAIG,MAAMF,SAAS;YACjB,OAAO;QACT;QACAF,IAAIK,IAAI,CAACH;QACT,OAAOF;IACT,GACA,EAAE;AAEN;AAEA,SAASM,sBAAsBC,OAAsB;IACnD,OAAOA,QAAQR,MAAM,CACnB,CAACC,KAAKQ;QACJ,MAAM,CAACC,MAAMZ,EAAE,GAAGW,MAAMV,KAAK,CAAC;QAC9B,MAAMY,gBAAgBd,aAAaC;QAEnC,IAAI,CAACa,eAAe;YAClB,OAAOV;QACT;QACA,MAAMW,eAAenB,QACnBkB,aAAa,CAAC,EAAE,EAChBA,aAAa,CAAC,EAAE,EAChBA,aAAa,CAAC,EAAE;QAGlB,IACED,SAAS,YACTA,SAAS,YACTA,SAAS,WACTA,SAAS,QACTA,SAAS,WACTA,SAAS,WACT;YACA,OAAOT;QACT;QAEA,IAAIA,GAAG,CAACS,KAAK,IAAI,QAAQE,eAAeX,GAAG,CAACS,KAAK,EAAE;YACjDT,GAAG,CAACS,KAAK,GAAGE;QACd;QAEA,OAAOX;IACT,GACA,CAAC;AAEL;AAEO,MAAMV,aAAa,CAACsB;IACzB,MAAMC,QAAQtB,YAAY,CAACqB,KAAKE,GAAG,CAAC;IACpC,IAAID,OAAO;QACT,OAAOA;IACT;IAEA,MAAME,SAAST,sBAAsBM,KAAKL,OAAO,IAAI,EAAE;IACvD,OAAQhB,YAAY,CAACqB,KAAKE,GAAG,CAAC,GAAGC;AACnC"}