create project

This commit is contained in:
ismailsosic
2022-12-27 12:05:56 +01:00
parent 2a33a2d3de
commit cd2143287c
16035 changed files with 2489703 additions and 0 deletions

View File

@@ -0,0 +1,22 @@
export default class CssSyntaxError extends Error {
constructor(error){
super(error);
const { reason , line , column } = error;
this.name = "CssSyntaxError";
// Based on https://github.com/postcss/postcss/blob/master/lib/css-syntax-error.es6#L132
// We don't need `plugin` and `file` properties.
this.message = `${this.name}\n\n`;
if (typeof line !== "undefined") {
this.message += `(${line}:${column}) `;
}
this.message += `${reason}`;
const code = error.showSourceCode();
if (code) {
this.message += `\n\n${code}\n`;
}
// We don't need stack https://github.com/postcss/postcss/blob/master/docs/guidelines/runner.md#31-dont-show-js-stack-for-csssyntaxerror
this.stack = false;
}
};
//# sourceMappingURL=CssSyntaxError.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../build/webpack/loaders/css-loader/src/CssSyntaxError.js"],"names":["CssSyntaxError","Error","constructor","error","reason","line","column","name","message","code","showSourceCode","stack"],"mappings":"AAAA,eAAe,MAAMA,cAAc,SAASC,KAAK;IAC/CC,YAAYC,KAAK,CAAE;QACjB,KAAK,CAACA,KAAK,CAAC;QAEZ,MAAM,EAAEC,MAAM,CAAA,EAAEC,IAAI,CAAA,EAAEC,MAAM,CAAA,EAAE,GAAGH,KAAK;QAEtC,IAAI,CAACI,IAAI,GAAG,gBAAgB;QAE5B,wFAAwF;QACxF,gDAAgD;QAChD,IAAI,CAACC,OAAO,GAAG,CAAC,EAAE,IAAI,CAACD,IAAI,CAAC,IAAI,CAAC;QAEjC,IAAI,OAAOF,IAAI,KAAK,WAAW,EAAE;YAC/B,IAAI,CAACG,OAAO,IAAI,CAAC,CAAC,EAAEH,IAAI,CAAC,CAAC,EAAEC,MAAM,CAAC,EAAE,CAAC;SACvC;QAED,IAAI,CAACE,OAAO,IAAI,CAAC,EAAEJ,MAAM,CAAC,CAAC;QAE3B,MAAMK,IAAI,GAAGN,KAAK,CAACO,cAAc,EAAE;QAEnC,IAAID,IAAI,EAAE;YACR,IAAI,CAACD,OAAO,IAAI,CAAC,IAAI,EAAEC,IAAI,CAAC,EAAE,CAAC;SAChC;QAED,wIAAwI;QACxI,IAAI,CAACE,KAAK,GAAG,KAAK;KACnB;CACF,CAAA"}

View File

@@ -0,0 +1,79 @@
/*
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
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.
*/ const preserveCamelCase = (string, locale)=>{
let isLastCharLower = false;
let isLastCharUpper = false;
let isLastLastCharUpper = false;
for(let i = 0; i < string.length; i++){
const character = string[i];
if (isLastCharLower && /[\p{Lu}]/u.test(character)) {
string = string.slice(0, i) + "-" + string.slice(i);
isLastCharLower = false;
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper = true;
i++;
} else if (isLastCharUpper && isLastLastCharUpper && /[\p{Ll}]/u.test(character)) {
string = string.slice(0, i - 1) + "-" + string.slice(i - 1);
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper = false;
isLastCharLower = true;
} else {
isLastCharLower = character.toLocaleLowerCase(locale) === character && character.toLocaleUpperCase(locale) !== character;
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper = character.toLocaleUpperCase(locale) === character && character.toLocaleLowerCase(locale) !== character;
}
}
return string;
};
const preserveConsecutiveUppercase = (input)=>{
return input.replace(/^[\p{Lu}](?![\p{Lu}])/gu, (m1)=>m1.toLowerCase());
};
const postProcess = (input, options)=>{
return input.replace(/[_.\- ]+([\p{Alpha}\p{N}_]|$)/gu, (_, p1)=>p1.toLocaleUpperCase(options.locale)).replace(/\d+([\p{Alpha}\p{N}_]|$)/gu, (m)=>m.toLocaleUpperCase(options.locale));
};
const camelCase = (input, options)=>{
if (!(typeof input === "string" || Array.isArray(input))) {
throw new TypeError("Expected the input to be `string | string[]`");
}
options = {
pascalCase: false,
preserveConsecutiveUppercase: false,
...options
};
if (Array.isArray(input)) {
input = input.map((x)=>x.trim()).filter((x)=>x.length).join("-");
} else {
input = input.trim();
}
if (input.length === 0) {
return "";
}
if (input.length === 1) {
return options.pascalCase ? input.toLocaleUpperCase(options.locale) : input.toLocaleLowerCase(options.locale);
}
const hasUpperCase = input !== input.toLocaleLowerCase(options.locale);
if (hasUpperCase) {
input = preserveCamelCase(input, options.locale);
}
input = input.replace(/^[_.\- ]+/, "");
if (options.preserveConsecutiveUppercase) {
input = preserveConsecutiveUppercase(input);
} else {
input = input.toLocaleLowerCase();
}
if (options.pascalCase) {
input = input.charAt(0).toLocaleUpperCase(options.locale) + input.slice(1);
}
return postProcess(input, options);
};
export default camelCase;
//# sourceMappingURL=camelcase.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../build/webpack/loaders/css-loader/src/camelcase.js"],"names":["preserveCamelCase","string","locale","isLastCharLower","isLastCharUpper","isLastLastCharUpper","i","length","character","test","slice","toLocaleLowerCase","toLocaleUpperCase","preserveConsecutiveUppercase","input","replace","m1","toLowerCase","postProcess","options","_","p1","m","camelCase","Array","isArray","TypeError","pascalCase","map","x","trim","filter","join","hasUpperCase","charAt"],"mappings":"AA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;QACtB,OAAOY,OAAO,CAACQ,UAAU,GACrBb,KAAK,CAACF,iBAAiB,CAACO,OAAO,CAACjB,MAAM,CAAC,GACvCY,KAAK,CAACH,iBAAiB,CAACQ,OAAO,CAACjB,MAAM,CAAC,CAAA;KAC5C;IAED,MAAM+B,YAAY,GAAGnB,KAAK,KAAKA,KAAK,CAACH,iBAAiB,CAACQ,OAAO,CAACjB,MAAM,CAAC;IAEtE,IAAI+B,YAAY,EAAE;QAChBnB,KAAK,GAAGd,iBAAiB,CAACc,KAAK,EAAEK,OAAO,CAACjB,MAAM,CAAC;KACjD;IAEDY,KAAK,GAAGA,KAAK,CAACC,OAAO,cAAc,EAAE,CAAC;IAEtC,IAAII,OAAO,CAACN,4BAA4B,EAAE;QACxCC,KAAK,GAAGD,4BAA4B,CAACC,KAAK,CAAC;KAC5C,MAAM;QACLA,KAAK,GAAGA,KAAK,CAACH,iBAAiB,EAAE;KAClC;IAED,IAAIQ,OAAO,CAACQ,UAAU,EAAE;QACtBb,KAAK,GAAGA,KAAK,CAACoB,MAAM,CAAC,CAAC,CAAC,CAACtB,iBAAiB,CAACO,OAAO,CAACjB,MAAM,CAAC,GAAGY,KAAK,CAACJ,KAAK,CAAC,CAAC,CAAC;KAC3E;IAED,OAAOQ,WAAW,CAACJ,KAAK,EAAEK,OAAO,CAAC,CAAA;CACnC;AAED,eAAeI,SAAS,CAAA"}

View File

@@ -0,0 +1,247 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/ import CssSyntaxError from "./CssSyntaxError";
import Warning from "../../postcss-loader/src/Warning";
import { stringifyRequest } from "../../../stringify-request";
const moduleRegExp = /\.module\.\w+$/i;
function getModulesOptions(rawOptions, loaderContext) {
const { resourcePath } = loaderContext;
if (typeof rawOptions.modules === "undefined") {
const isModules = moduleRegExp.test(resourcePath);
if (!isModules) {
return false;
}
} else if (typeof rawOptions.modules === "boolean" && rawOptions.modules === false) {
return false;
}
let modulesOptions = {
compileType: rawOptions.icss ? "icss" : "module",
auto: true,
mode: "local",
exportGlobals: false,
localIdentName: "[hash:base64]",
localIdentContext: loaderContext.rootContext,
localIdentHashPrefix: "",
// eslint-disable-next-line no-undefined
localIdentRegExp: undefined,
namedExport: false,
exportLocalsConvention: "asIs",
exportOnlyLocals: false
};
if (typeof rawOptions.modules === "boolean" || typeof rawOptions.modules === "string") {
modulesOptions.mode = typeof rawOptions.modules === "string" ? rawOptions.modules : "local";
} else {
if (rawOptions.modules) {
if (typeof rawOptions.modules.auto === "boolean") {
const isModules = rawOptions.modules.auto && moduleRegExp.test(resourcePath);
if (!isModules) {
return false;
}
} else if (rawOptions.modules.auto instanceof RegExp) {
const isModules = rawOptions.modules.auto.test(resourcePath);
if (!isModules) {
return false;
}
} else if (typeof rawOptions.modules.auto === "function") {
const isModule = rawOptions.modules.auto(resourcePath);
if (!isModule) {
return false;
}
}
if (rawOptions.modules.namedExport === true && typeof rawOptions.modules.exportLocalsConvention === "undefined") {
modulesOptions.exportLocalsConvention = "camelCaseOnly";
}
}
modulesOptions = {
...modulesOptions,
...rawOptions.modules || {}
};
}
if (typeof modulesOptions.mode === "function") {
modulesOptions.mode = modulesOptions.mode(loaderContext.resourcePath);
}
if (modulesOptions.namedExport === true) {
if (rawOptions.esModule === false) {
throw new Error('The "modules.namedExport" option requires the "esModules" option to be enabled');
}
if (modulesOptions.exportLocalsConvention !== "camelCaseOnly") {
throw new Error('The "modules.namedExport" option requires the "modules.exportLocalsConvention" option to be "camelCaseOnly"');
}
}
return modulesOptions;
}
function normalizeOptions(rawOptions, loaderContext) {
if (rawOptions.icss) {
loaderContext.emitWarning(new Error('The "icss" option is deprecated, use "modules.compileType: "icss"" instead'));
}
const modulesOptions = getModulesOptions(rawOptions, loaderContext);
return {
url: typeof rawOptions.url === "undefined" ? true : rawOptions.url,
import: typeof rawOptions.import === "undefined" ? true : rawOptions.import,
modules: modulesOptions,
// TODO remove in the next major release
icss: typeof rawOptions.icss === "undefined" ? false : rawOptions.icss,
sourceMap: typeof rawOptions.sourceMap === "boolean" ? rawOptions.sourceMap : loaderContext.sourceMap,
importLoaders: typeof rawOptions.importLoaders === "string" ? parseInt(rawOptions.importLoaders, 10) : rawOptions.importLoaders,
esModule: typeof rawOptions.esModule === "undefined" ? true : rawOptions.esModule,
fontLoader: rawOptions.fontLoader
};
}
export default async function loader(content, map, meta) {
const rawOptions = this.getOptions();
const plugins = [];
const callback = this.async();
const loaderSpan = this.currentTraceSpan.traceChild("css-loader");
loaderSpan.traceAsyncFn(async ()=>{
let options;
try {
options = normalizeOptions(rawOptions, this);
} catch (error) {
throw error;
}
const { postcss } = await rawOptions.postcss();
const { shouldUseModulesPlugins , shouldUseImportPlugin , shouldUseURLPlugin , shouldUseIcssPlugin , getPreRequester , getExportCode , getFilter , getImportCode , getModuleCode , getModulesPlugins , normalizeSourceMap , sort , } = require("./utils");
const { icssParser , importParser , urlParser } = require("./plugins");
const replacements = [];
// if it's a font loader next-font-loader will have exports that should be exported as is
const exports = options.fontLoader ? meta.exports : [];
if (shouldUseModulesPlugins(options)) {
plugins.push(...getModulesPlugins(options, this, meta));
}
const importPluginImports = [];
const importPluginApi = [];
if (shouldUseImportPlugin(options)) {
const resolver = this.getResolve({
conditionNames: [
"style"
],
extensions: [
".css"
],
mainFields: [
"css",
"style",
"main",
"..."
],
mainFiles: [
"index",
"..."
],
restrictions: [
/\.css$/i
]
});
plugins.push(importParser({
imports: importPluginImports,
api: importPluginApi,
context: this.context,
rootContext: this.rootContext,
filter: getFilter(options.import, this.resourcePath),
resolver,
urlHandler: (url)=>stringifyRequest(this, getPreRequester(this)(options.importLoaders) + url)
}));
}
const urlPluginImports = [];
if (shouldUseURLPlugin(options)) {
const urlResolver = this.getResolve({
conditionNames: [
"asset"
],
mainFields: [
"asset"
],
mainFiles: [],
extensions: []
});
plugins.push(urlParser({
imports: urlPluginImports,
replacements,
context: this.context,
rootContext: this.rootContext,
filter: getFilter(options.url, this.resourcePath),
resolver: urlResolver,
urlHandler: (url)=>stringifyRequest(this, url)
}));
}
const icssPluginImports = [];
const icssPluginApi = [];
if (shouldUseIcssPlugin(options)) {
const icssResolver = this.getResolve({
conditionNames: [
"style"
],
extensions: [],
mainFields: [
"css",
"style",
"main",
"..."
],
mainFiles: [
"index",
"..."
]
});
plugins.push(icssParser({
imports: icssPluginImports,
api: icssPluginApi,
replacements,
exports,
context: this.context,
rootContext: this.rootContext,
resolver: icssResolver,
urlHandler: (url)=>stringifyRequest(this, getPreRequester(this)(options.importLoaders) + url)
}));
}
// Reuse CSS AST (PostCSS AST e.g 'postcss-loader') to avoid reparsing
if (meta) {
const { ast } = meta;
if (ast && ast.type === "postcss") {
// eslint-disable-next-line no-param-reassign
content = ast.root;
loaderSpan.setAttribute("astUsed", "true");
}
}
const { resourcePath } = this;
let result;
try {
result = await postcss(plugins).process(content, {
from: resourcePath,
to: resourcePath,
map: options.sourceMap ? {
prev: map ? normalizeSourceMap(map, resourcePath) : null,
inline: false,
annotation: false
} : false
});
} catch (error1) {
if (error1.file) {
this.addDependency(error1.file);
}
throw error1.name === "CssSyntaxError" ? new CssSyntaxError(error1) : error1;
}
for (const warning of result.warnings()){
this.emitWarning(new Warning(warning));
}
const imports = [].concat(icssPluginImports.sort(sort)).concat(importPluginImports.sort(sort)).concat(urlPluginImports.sort(sort));
const api = [].concat(importPluginApi.sort(sort)).concat(icssPluginApi.sort(sort));
if (options.modules.exportOnlyLocals !== true) {
imports.unshift({
importName: "___CSS_LOADER_API_IMPORT___",
url: stringifyRequest(this, require.resolve("./runtime/api"))
});
}
const importCode = getImportCode(imports, options);
const moduleCode = getModuleCode(result, api, replacements, options, this);
const exportCode = getExportCode(exports, replacements, options);
return `${importCode}${moduleCode}${exportCode}`;
}).then((code)=>{
callback(null, code);
}, (err)=>{
callback(err);
});
};
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,6 @@
import importParser from "./postcss-import-parser";
import icssParser from "./postcss-icss-parser";
import urlParser from "./postcss-url-parser";
export { importParser, icssParser, urlParser };
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../../build/webpack/loaders/css-loader/src/plugins/index.js"],"names":["importParser","icssParser","urlParser"],"mappings":"AAAA,OAAOA,YAAY,MAAM,yBAAyB,CAAA;AAClD,OAAOC,UAAU,MAAM,uBAAuB,CAAA;AAC9C,OAAOC,SAAS,MAAM,sBAAsB,CAAA;AAE5C,SAASF,YAAY,EAAEC,UAAU,EAAEC,SAAS,GAAE"}

View File

@@ -0,0 +1,97 @@
import { extractICSS, replaceValueSymbols, replaceSymbols } from "next/dist/compiled/icss-utils";
import { normalizeUrl, resolveRequests, requestify } from "../utils";
const plugin = (options = {})=>{
return {
postcssPlugin: "postcss-icss-parser",
async OnceExit (root) {
const importReplacements = Object.create(null);
const { icssImports , icssExports } = extractICSS(root);
const imports = new Map();
const tasks = [];
// eslint-disable-next-line guard-for-in
for(const url in icssImports){
const tokens = icssImports[url];
if (Object.keys(tokens).length === 0) {
continue;
}
let normalizedUrl = url;
let prefix = "";
const queryParts = normalizedUrl.split("!");
if (queryParts.length > 1) {
normalizedUrl = queryParts.pop();
prefix = queryParts.join("!");
}
const request = requestify(normalizeUrl(normalizedUrl, true), options.rootContext);
const doResolve = async ()=>{
const { resolver , context } = options;
const resolvedUrl = await resolveRequests(resolver, context, [
...new Set([
normalizedUrl,
request
]),
]);
if (!resolvedUrl) {
return;
}
// eslint-disable-next-line consistent-return
return {
url: resolvedUrl,
prefix,
tokens
};
};
tasks.push(doResolve());
}
const results = await Promise.all(tasks);
for(let index = 0; index <= results.length - 1; index++){
const item = results[index];
if (!item) {
continue;
}
const newUrl = item.prefix ? `${item.prefix}!${item.url}` : item.url;
const importKey = newUrl;
let importName = imports.get(importKey);
if (!importName) {
importName = `___CSS_LOADER_ICSS_IMPORT_${imports.size}___`;
imports.set(importKey, importName);
options.imports.push({
type: "icss_import",
importName,
url: options.urlHandler(newUrl),
icss: true,
index
});
options.api.push({
importName,
dedupe: true,
index
});
}
for (const [replacementIndex, token] of Object.keys(item.tokens).entries()){
const replacementName = `___CSS_LOADER_ICSS_IMPORT_${index}_REPLACEMENT_${replacementIndex}___`;
const localName = item.tokens[token];
importReplacements[token] = replacementName;
options.replacements.push({
replacementName,
importName,
localName
});
}
}
if (Object.keys(importReplacements).length > 0) {
replaceSymbols(root, importReplacements);
}
for (const name of Object.keys(icssExports)){
const value = replaceValueSymbols(icssExports[name], importReplacements);
options.exports.push({
name,
value
});
}
}
};
};
plugin.postcss = true;
export default plugin;
//# sourceMappingURL=postcss-icss-parser.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../../build/webpack/loaders/css-loader/src/plugins/postcss-icss-parser.js"],"names":["extractICSS","replaceValueSymbols","replaceSymbols","normalizeUrl","resolveRequests","requestify","plugin","options","postcssPlugin","OnceExit","root","importReplacements","Object","create","icssImports","icssExports","imports","Map","tasks","url","tokens","keys","length","normalizedUrl","prefix","queryParts","split","pop","join","request","rootContext","doResolve","resolver","context","resolvedUrl","Set","push","results","Promise","all","index","item","newUrl","importKey","importName","get","size","set","type","urlHandler","icss","api","dedupe","replacementIndex","token","entries","replacementName","localName","replacements","name","value","exports","postcss"],"mappings":"AAAA,SACEA,WAAW,EACXC,mBAAmB,EACnBC,cAAc,QACT,+BAA+B,CAAA;AAEtC,SAASC,YAAY,EAAEC,eAAe,EAAEC,UAAU,QAAQ,UAAU,CAAA;AAEpE,MAAMC,MAAM,GAAG,CAACC,OAAO,GAAG,EAAE,GAAK;IAC/B,OAAO;QACLC,aAAa,EAAE,qBAAqB;QACpC,MAAMC,QAAQ,EAACC,IAAI,EAAE;YACnB,MAAMC,kBAAkB,GAAGC,MAAM,CAACC,MAAM,CAAC,IAAI,CAAC;YAC9C,MAAM,EAAEC,WAAW,CAAA,EAAEC,WAAW,CAAA,EAAE,GAAGf,WAAW,CAACU,IAAI,CAAC;YACtD,MAAMM,OAAO,GAAG,IAAIC,GAAG,EAAE;Y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AAI,CAACrB,MAAM,CAACkC,KAAK,CAAC;oBAEpC3C,kBAAkB,CAAC2C,KAAK,CAAC,GAAGE,eAAe;oBAE3CjD,OAAO,CAACmD,YAAY,CAACtB,IAAI,CAAC;wBAAEoB,eAAe;wBAAEZ,UAAU;wBAAEa,SAAS;qBAAE,CAAC;iBACtE;aACF;YAED,IAAI7C,MAAM,CAACS,IAAI,CAACV,kBAAkB,CAAC,CAACW,MAAM,GAAG,CAAC,EAAE;gBAC9CpB,cAAc,CAACQ,IAAI,EAAEC,kBAAkB,CAAC;aACzC;YAED,KAAK,MAAMgD,IAAI,IAAI/C,MAAM,CAACS,IAAI,CAACN,WAAW,CAAC,CAAE;gBAC3C,MAAM6C,KAAK,GAAG3D,mBAAmB,CAACc,WAAW,CAAC4C,IAAI,CAAC,EAAEhD,kBAAkB,CAAC;gBAExEJ,OAAO,CAACsD,OAAO,CAACzB,IAAI,CAAC;oBAAEuB,IAAI;oBAAEC,KAAK;iBAAE,CAAC;aACtC;SACF;KACF,CAAA;CACF;AAEDtD,MAAM,CAACwD,OAAO,GAAG,IAAI;AAErB,eAAexD,MAAM,CAAA"}

View File

@@ -0,0 +1,191 @@
import valueParser from "next/dist/compiled/postcss-value-parser";
import { normalizeUrl, resolveRequests, isUrlRequestable, requestify, WEBPACK_IGNORE_COMMENT_REGEXP } from "../utils";
function parseNode(atRule, key) {
// Convert only top-level @import
if (atRule.parent.type !== "root") {
return;
}
if (atRule.raws && atRule.raws.afterName && atRule.raws.afterName.trim().length > 0) {
const lastCommentIndex = atRule.raws.afterName.lastIndexOf("/*");
const matched = atRule.raws.afterName.slice(lastCommentIndex).match(WEBPACK_IGNORE_COMMENT_REGEXP);
if (matched && matched[2] === "true") {
return;
}
}
const prevNode = atRule.prev();
if (prevNode && prevNode.type === "comment") {
const matched = prevNode.text.match(WEBPACK_IGNORE_COMMENT_REGEXP);
if (matched && matched[2] === "true") {
return;
}
}
// Nodes do not exists - `@import url('http://') :root {}`
if (atRule.nodes) {
const error = new Error("It looks like you didn't end your @import statement correctly. Child nodes are attached to it.");
error.node = atRule;
throw error;
}
const { nodes: paramsNodes } = valueParser(atRule[key]);
// No nodes - `@import ;`
// Invalid type - `@import foo-bar;`
if (paramsNodes.length === 0 || paramsNodes[0].type !== "string" && paramsNodes[0].type !== "function") {
const error = new Error(`Unable to find uri in "${atRule.toString()}"`);
error.node = atRule;
throw error;
}
let isStringValue;
let url;
if (paramsNodes[0].type === "string") {
isStringValue = true;
url = paramsNodes[0].value;
} else {
// Invalid function - `@import nourl(test.css);`
if (paramsNodes[0].value.toLowerCase() !== "url") {
const error = new Error(`Unable to find uri in "${atRule.toString()}"`);
error.node = atRule;
throw error;
}
isStringValue = paramsNodes[0].nodes.length !== 0 && paramsNodes[0].nodes[0].type === "string";
url = isStringValue ? paramsNodes[0].nodes[0].value : valueParser.stringify(paramsNodes[0].nodes);
}
url = normalizeUrl(url, isStringValue);
const isRequestable = isUrlRequestable(url);
let prefix;
if (isRequestable) {
const queryParts = url.split("!");
if (queryParts.length > 1) {
url = queryParts.pop();
prefix = queryParts.join("!");
}
}
// Empty url - `@import "";` or `@import url();`
if (url.trim().length === 0) {
const error = new Error(`Unable to find uri in "${atRule.toString()}"`);
error.node = atRule;
throw error;
}
const mediaNodes = paramsNodes.slice(1);
let media;
if (mediaNodes.length > 0) {
media = valueParser.stringify(mediaNodes).trim().toLowerCase();
}
// eslint-disable-next-line consistent-return
return {
atRule,
prefix,
url,
media,
isRequestable
};
}
const plugin = (options = {})=>{
return {
postcssPlugin: "postcss-import-parser",
prepare (result) {
const parsedAtRules = [];
return {
AtRule: {
import (atRule) {
let parsedAtRule;
try {
parsedAtRule = parseNode(atRule, "params", result);
} catch (error) {
result.warn(error.message, {
node: error.node
});
}
if (!parsedAtRule) {
return;
}
parsedAtRules.push(parsedAtRule);
}
},
async OnceExit () {
if (parsedAtRules.length === 0) {
return;
}
const resolvedAtRules = await Promise.all(parsedAtRules.map(async (parsedAtRule)=>{
const { atRule , isRequestable , prefix , url , media } = parsedAtRule;
if (options.filter) {
const needKeep = await options.filter(url, media);
if (!needKeep) {
return;
}
}
if (isRequestable) {
const request = requestify(url, options.rootContext);
const { resolver , context } = options;
const resolvedUrl = await resolveRequests(resolver, context, [
...new Set([
request,
url
]),
]);
if (!resolvedUrl) {
return;
}
if (resolvedUrl === options.resourcePath) {
atRule.remove();
return;
}
atRule.remove();
// eslint-disable-next-line consistent-return
return {
url: resolvedUrl,
media,
prefix,
isRequestable
};
}
atRule.remove();
// eslint-disable-next-line consistent-return
return {
url,
media,
prefix,
isRequestable
};
}));
const urlToNameMap = new Map();
for(let index = 0; index <= resolvedAtRules.length - 1; index++){
const resolvedAtRule = resolvedAtRules[index];
if (!resolvedAtRule) {
continue;
}
const { url , isRequestable , media } = resolvedAtRule;
if (!isRequestable) {
options.api.push({
url,
media,
index
});
continue;
}
const { prefix } = resolvedAtRule;
const newUrl = prefix ? `${prefix}!${url}` : url;
let importName = urlToNameMap.get(newUrl);
if (!importName) {
importName = `___CSS_LOADER_AT_RULE_IMPORT_${urlToNameMap.size}___`;
urlToNameMap.set(newUrl, importName);
options.imports.push({
type: "rule_import",
importName,
url: options.urlHandler(newUrl),
index
});
}
options.api.push({
importName,
media,
index
});
}
}
};
}
};
};
plugin.postcss = true;
export default plugin;
//# sourceMappingURL=postcss-import-parser.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,312 @@
import valueParser from "next/dist/compiled/postcss-value-parser";
import { resolveRequests, normalizeUrl, requestify, isUrlRequestable, isDataUrl, WEBPACK_IGNORE_COMMENT_REGEXP } from "../utils";
const isUrlFunc = /url/i;
const isImageSetFunc = /^(?:-webkit-)?image-set$/i;
const needParseDeclaration = /(?:url|(?:-webkit-)?image-set)\(/i;
function getNodeFromUrlFunc(node) {
return node.nodes && node.nodes[0];
}
function getWebpackIgnoreCommentValue(index, nodes, inBetween) {
if (index === 0 && typeof inBetween !== "undefined") {
return inBetween;
}
let prevValueNode = nodes[index - 1];
if (!prevValueNode) {
// eslint-disable-next-line consistent-return
return;
}
if (prevValueNode.type === "space") {
if (!nodes[index - 2]) {
// eslint-disable-next-line consistent-return
return;
}
prevValueNode = nodes[index - 2];
}
if (prevValueNode.type !== "comment") {
// eslint-disable-next-line consistent-return
return;
}
const matched = prevValueNode.value.match(WEBPACK_IGNORE_COMMENT_REGEXP);
return matched && matched[2] === "true";
}
function shouldHandleURL(url, declaration, result, isSupportDataURLInNewURL) {
if (url.length === 0) {
result.warn(`Unable to find uri in '${declaration.toString()}'`, {
node: declaration
});
return false;
}
if (isDataUrl(url) && isSupportDataURLInNewURL) {
try {
decodeURIComponent(url);
} catch (ignoreError) {
return false;
}
return true;
}
if (!isUrlRequestable(url)) {
return false;
}
return true;
}
function parseDeclaration(declaration, key, result, isSupportDataURLInNewURL) {
if (!needParseDeclaration.test(declaration[key])) {
return;
}
const parsed = valueParser(declaration.raws && declaration.raws.value && declaration.raws.value.raw ? declaration.raws.value.raw : declaration[key]);
let inBetween;
if (declaration.raws && declaration.raws.between) {
const lastCommentIndex = declaration.raws.between.lastIndexOf("/*");
const matched = declaration.raws.between.slice(lastCommentIndex).match(WEBPACK_IGNORE_COMMENT_REGEXP);
if (matched) {
inBetween = matched[2] === "true";
}
}
let isIgnoreOnDeclaration = false;
const prevNode = declaration.prev();
if (prevNode && prevNode.type === "comment") {
const matched = prevNode.text.match(WEBPACK_IGNORE_COMMENT_REGEXP);
if (matched) {
isIgnoreOnDeclaration = matched[2] === "true";
}
}
let needIgnore;
const parsedURLs = [];
parsed.walk((valueNode, index, valueNodes)=>{
if (valueNode.type !== "function") {
return;
}
if (isUrlFunc.test(valueNode.value)) {
needIgnore = getWebpackIgnoreCommentValue(index, valueNodes, inBetween);
if (isIgnoreOnDeclaration && typeof needIgnore === "undefined" || needIgnore) {
if (needIgnore) {
// eslint-disable-next-line no-undefined
needIgnore = undefined;
}
return;
}
const { nodes } = valueNode;
const isStringValue = nodes.length !== 0 && nodes[0].type === "string";
let url = isStringValue ? nodes[0].value : valueParser.stringify(nodes);
url = normalizeUrl(url, isStringValue);
// Do not traverse inside `url`
if (!shouldHandleURL(url, declaration, result, isSupportDataURLInNewURL)) {
// eslint-disable-next-line consistent-return
return false;
}
const queryParts = url.split("!");
let prefix;
if (queryParts.length > 1) {
url = queryParts.pop();
prefix = queryParts.join("!");
}
parsedURLs.push({
declaration,
parsed,
node: getNodeFromUrlFunc(valueNode),
prefix,
url,
needQuotes: false
});
// eslint-disable-next-line consistent-return
return false;
} else if (isImageSetFunc.test(valueNode.value)) {
for (const [innerIndex, nNode] of valueNode.nodes.entries()){
const { type , value } = nNode;
if (type === "function" && isUrlFunc.test(value)) {
needIgnore = getWebpackIgnoreCommentValue(innerIndex, valueNode.nodes);
if (isIgnoreOnDeclaration && typeof needIgnore === "undefined" || needIgnore) {
if (needIgnore) {
// eslint-disable-next-line no-undefined
needIgnore = undefined;
}
continue;
}
const { nodes } = nNode;
const isStringValue = nodes.length !== 0 && nodes[0].type === "string";
let url = isStringValue ? nodes[0].value : valueParser.stringify(nodes);
url = normalizeUrl(url, isStringValue);
// Do not traverse inside `url`
if (!shouldHandleURL(url, declaration, result, isSupportDataURLInNewURL)) {
// eslint-disable-next-line consistent-return
return false;
}
const queryParts = url.split("!");
let prefix;
if (queryParts.length > 1) {
url = queryParts.pop();
prefix = queryParts.join("!");
}
parsedURLs.push({
declaration,
parsed,
node: getNodeFromUrlFunc(nNode),
prefix,
url,
needQuotes: false
});
} else if (type === "string") {
needIgnore = getWebpackIgnoreCommentValue(innerIndex, valueNode.nodes);
if (isIgnoreOnDeclaration && typeof needIgnore === "undefined" || needIgnore) {
if (needIgnore) {
// eslint-disable-next-line no-undefined
needIgnore = undefined;
}
continue;
}
let url = normalizeUrl(value, true);
// Do not traverse inside `url`
if (!shouldHandleURL(url, declaration, result, isSupportDataURLInNewURL)) {
// eslint-disable-next-line consistent-return
return false;
}
const queryParts = url.split("!");
let prefix;
if (queryParts.length > 1) {
url = queryParts.pop();
prefix = queryParts.join("!");
}
parsedURLs.push({
declaration,
parsed,
node: nNode,
prefix,
url,
needQuotes: true
});
}
}
// Do not traverse inside `image-set`
// eslint-disable-next-line consistent-return
return false;
}
});
// eslint-disable-next-line consistent-return
return parsedURLs;
}
const plugin = (options = {})=>{
return {
postcssPlugin: "postcss-url-parser",
prepare (result) {
const parsedDeclarations = [];
return {
Declaration (declaration) {
const { isSupportDataURLInNewURL } = options;
const parsedURL = parseDeclaration(declaration, "value", result, isSupportDataURLInNewURL);
if (!parsedURL) {
return;
}
parsedDeclarations.push(...parsedURL);
},
async OnceExit () {
if (parsedDeclarations.length === 0) {
return;
}
const resolvedDeclarations = await Promise.all(parsedDeclarations.map(async (parsedDeclaration)=>{
const { url } = parsedDeclaration;
if (options.filter) {
const needKeep = await options.filter(url);
if (!needKeep) {
// eslint-disable-next-line consistent-return
return;
}
}
if (isDataUrl(url)) {
// eslint-disable-next-line consistent-return
return parsedDeclaration;
}
const splittedUrl = url.split(/(\?)?#/);
const [pathname, query, hashOrQuery] = splittedUrl;
let hash = query ? "?" : "";
hash += hashOrQuery ? `#${hashOrQuery}` : "";
const { needToResolveURL , rootContext } = options;
const request = requestify(pathname, rootContext, needToResolveURL);
if (!needToResolveURL) {
// eslint-disable-next-line consistent-return
return {
...parsedDeclaration,
url: request,
hash
};
}
const { resolver , context } = options;
const resolvedUrl = await resolveRequests(resolver, context, [
...new Set([
request,
url
]),
]);
if (!resolvedUrl) {
// eslint-disable-next-line consistent-return
return;
}
// eslint-disable-next-line consistent-return
return {
...parsedDeclaration,
url: resolvedUrl,
hash
};
}));
const urlToNameMap = new Map();
const urlToReplacementMap = new Map();
let hasUrlImportHelper = false;
for(let index = 0; index <= resolvedDeclarations.length - 1; index++){
const item = resolvedDeclarations[index];
if (!item) {
continue;
}
if (!hasUrlImportHelper) {
options.imports.push({
type: "get_url_import",
importName: "___CSS_LOADER_GET_URL_IMPORT___",
url: options.urlHandler(require.resolve("../runtime/getUrl.js")),
index: -1
});
hasUrlImportHelper = true;
}
const { url , prefix } = item;
const newUrl = prefix ? `${prefix}!${url}` : url;
let importName = urlToNameMap.get(newUrl);
if (!importName) {
importName = `___CSS_LOADER_URL_IMPORT_${urlToNameMap.size}___`;
urlToNameMap.set(newUrl, importName);
options.imports.push({
type: "url",
importName,
url: options.needToResolveURL ? options.urlHandler(newUrl) : JSON.stringify(newUrl),
index
});
}
const { hash , needQuotes } = item;
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);
options.replacements.push({
replacementName,
importName,
hash,
needQuotes
});
}
// eslint-disable-next-line no-param-reassign
item.node.type = "word";
// eslint-disable-next-line no-param-reassign
item.node.value = replacementName;
// eslint-disable-next-line no-param-reassign
item.declaration.value = item.parsed.toString();
}
}
};
}
};
};
plugin.postcss = true;
export default plugin;
//# sourceMappingURL=postcss-url-parser.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,87 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/ // css base code, injected by the css-loader
// eslint-disable-next-line func-names
module.exports = function(useSourceMap) {
var list = [] // return the list of modules as css string
;
list.toString = function toString() {
return this.map(function(item) {
var content = cssWithMappingToString(item, useSourceMap);
if (item[2]) {
return "@media ".concat(item[2], " {").concat(content, "}");
}
return content;
}).join("");
} // import a list of modules into the list
;
// eslint-disable-next-line func-names
list.i = function(modules, mediaQuery, dedupe) {
if (typeof modules === "string") {
// eslint-disable-next-line no-param-reassign
modules = [
[
null,
modules,
""
]
];
}
var alreadyImportedModules = {};
if (dedupe) {
for(var i = 0; i < this.length; i++){
// eslint-disable-next-line prefer-destructuring
var id = this[i][0];
if (id != null) {
alreadyImportedModules[id] = true;
}
}
}
for(var _i = 0; _i < modules.length; _i++){
var item = [].concat(modules[_i]);
if (dedupe && alreadyImportedModules[item[0]]) {
continue;
}
if (mediaQuery) {
if (!item[2]) {
item[2] = mediaQuery;
} else {
item[2] = "".concat(mediaQuery, " and ").concat(item[2]);
}
}
list.push(item);
}
};
return list;
};
function cssWithMappingToString(item, useSourceMap) {
var content = item[1] || "" // eslint-disable-next-line prefer-destructuring
;
var cssMapping = item[3];
if (!cssMapping) {
return content;
}
if (useSourceMap && typeof btoa === "function") {
var sourceMapping = toComment(cssMapping);
var sourceURLs = cssMapping.sources.map(function(source) {
return "/*# sourceURL=".concat(cssMapping.sourceRoot || "").concat(source, " */");
});
return [
content
].concat(sourceURLs).concat([
sourceMapping
]).join("\n");
}
return [
content
].join("\n");
} // Adapted from convert-source-map (MIT)
function toComment(sourceMap) {
// eslint-disable-next-line no-undef
var base64 = btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap))));
var data = "sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(base64);
return "/*# ".concat(data, " */");
}
//# sourceMappingURL=api.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../../build/webpack/loaders/css-loader/src/runtime/api.js"],"names":["module","exports","useSourceMap","list","toString","map","item","content","cssWithMappingToString","concat","join","i","modules","mediaQuery","dedupe","alreadyImportedModules","length","id","_i","push","cssMapping","btoa","sourceMapping","toComment","sourceURLs","sources","source","sourceRoot","sourceMap","base64","unescape","encodeURIComponent","JSON","stringify","data"],"mappings":"AAAA;;;EAGE,CACF,4CAA4C;AAC5C,sCAAsC;AACtCA,MAAM,CAACC,OAAO,GAAG,SAAUC,YAAY,EAAE;IACvC,IAAIC,IAAI,GAAG,EAAE,CAAC,2CAA2C;IAA5C;IAEbA,IAAI,CAACC,QAAQ,GAAG,SAASA,QAAQ,GAAG;QAClC,OAAO,IAAI,CAACC,GAAG,CAAC,SAAUC,IAAI,EAAE;YAC9B,IAAIC,OAAO,GAAGC,sBAAsB,CAACF,IAAI,EAAEJ,YAAY,CAAC;YAExD,IAAII,IAAI,CAAC,CAAC,CAAC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M,IAAI,GACN,8DAA8D,CAACzB,MAAM,CACnEoB,MAAM,CACP;IACH,OAAO,MAAM,CAACpB,MAAM,CAACyB,IAAI,EAAE,KAAK,CAAC,CAAA;CAClC"}

View File

@@ -0,0 +1,25 @@
module.exports = function(url, options) {
if (!options) {
// eslint-disable-next-line no-param-reassign
options = {};
} // eslint-disable-next-line no-underscore-dangle, no-param-reassign
url = url && url.__esModule ? url.default : url;
if (typeof url !== "string") {
return url;
} // If url is already wrapped in quotes, remove them
if (/^['"].*['"]$/.test(url)) {
// eslint-disable-next-line no-param-reassign
url = url.slice(1, -1);
}
if (options.hash) {
// eslint-disable-next-line no-param-reassign
url += options.hash;
} // Should url be wrapped?
// See https://drafts.csswg.org/css-values-3/#urls
if (/["'() \t\n]/.test(url) || options.needQuotes) {
return '"'.concat(url.replace(/"/g, '\\"').replace(/\n/g, "\\n"), '"');
}
return url;
};
//# sourceMappingURL=getUrl.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../../build/webpack/loaders/css-loader/src/runtime/getUrl.js"],"names":["module","exports","url","options","__esModule","default","test","slice","hash","needQuotes","concat","replace"],"mappings":"AAAAA,MAAM,CAACC,OAAO,GAAG,SAAUC,GAAG,EAAEC,OAAO,EAAE;IACvC,IAAI,CAACA,OAAO,EAAE;QACZ,6CAA6C;QAC7CA,OAAO,GAAG,EAAE;KACb,CAAC,mEAAmE;IAErED,GAAG,GAAGA,GAAG,IAAIA,GAAG,CAACE,UAAU,GAAGF,GAAG,CAACG,OAAO,GAAGH,GAAG;IAE/C,IAAI,OAAOA,GAAG,KAAK,QAAQ,EAAE;QAC3B,OAAOA,GAAG,CAAA;KACX,CAAC,mDAAmD;IAErD,IAAI,eAAeI,IAAI,CAACJ,GAAG,CAAC,EAAE;QAC5B,6CAA6C;QAC7CA,GAAG,GAAGA,GAAG,CAACK,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;KACvB;IAED,IAAIJ,OAAO,CAACK,IAAI,EAAE;QAChB,6CAA6C;QAC7CN,GAAG,IAAIC,OAAO,CAACK,IAAI;KACpB,CAAC,yBAAyB;IAC3B,kDAAkD;IAElD,IAAI,cAAcF,IAAI,CAACJ,GAAG,CAAC,IAAIC,OAAO,CAACM,UAAU,EAAE;QACjD,OAAO,GAAG,CAACC,MAAM,CAACR,GAAG,CAACS,OAAO,OAAO,KAAK,CAAC,CAACA,OAAO,QAAQ,KAAK,CAAC,EAAE,GAAG,CAAC,CAAA;KACvE;IAED,OAAOT,GAAG,CAAA;CACX"}

View File

@@ -0,0 +1,364 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/ import { fileURLToPath } from "url";
import path from "path";
import { urlToRequest } from "next/dist/compiled/loader-utils3";
import modulesValues from "next/dist/compiled/postcss-modules-values";
import localByDefault from "next/dist/compiled/postcss-modules-local-by-default";
import extractImports from "next/dist/compiled/postcss-modules-extract-imports";
import modulesScope from "next/dist/compiled/postcss-modules-scope";
import camelCase from "./camelcase";
const whitespace = "[\\x20\\t\\r\\n\\f]";
const unescapeRegExp = new RegExp(`\\\\([\\da-f]{1,6}${whitespace}?|(${whitespace})|.)`, "ig");
const matchNativeWin32Path = /^[A-Z]:[/\\]|^\\\\/i;
function unescape(str) {
return str.replace(unescapeRegExp, (_, escaped, escapedWhitespace)=>{
const high = `0x${escaped}` - 0x10000;
/* eslint-disable line-comment-position */ // NaN means non-codepoint
// Workaround erroneous numeric interpretation of +"0x"
// eslint-disable-next-line no-self-compare
return high !== high || escapedWhitespace ? escaped : high < 0 ? String.fromCharCode(high + 0x10000) : // eslint-disable-next-line no-bitwise
String.fromCharCode(high >> 10 | 0xd800, high & 0x3ff | 0xdc00);
/* eslint-enable line-comment-position */ });
}
function normalizePath(file) {
return path.sep === "\\" ? file.replace(/\\/g, "/") : file;
}
function fixedEncodeURIComponent(str) {
return str.replace(/[!'()*]/g, (c)=>`%${c.charCodeAt(0).toString(16)}`);
}
function normalizeUrl(url, isStringValue) {
let normalizedUrl = url;
if (isStringValue && /\\(\n|\r\n|\r|\f)/.test(normalizedUrl)) {
normalizedUrl = normalizedUrl.replace(/\\(\n|\r\n|\r|\f)/g, "");
}
if (matchNativeWin32Path.test(url)) {
try {
normalizedUrl = decodeURIComponent(normalizedUrl);
} catch (error) {
// Ignores invalid and broken URLs and try to resolve them as is
}
return normalizedUrl;
}
normalizedUrl = unescape(normalizedUrl);
if (isDataUrl(url)) {
return fixedEncodeURIComponent(normalizedUrl);
}
try {
normalizedUrl = decodeURI(normalizedUrl);
} catch (error) {
// Ignores invalid and broken URLs and try to resolve them as is
}
return normalizedUrl;
}
function requestify(url, rootContext) {
if (/^file:/i.test(url)) {
return fileURLToPath(url);
}
if (/^[a-z][a-z0-9+.-]*:/i.test(url)) {
return url;
}
return url.charAt(0) === "/" ? urlToRequest(url, rootContext) : urlToRequest(url);
}
function getFilter(filter, resourcePath) {
return (...args)=>{
if (typeof filter === "function") {
return filter(...args, resourcePath);
}
return true;
};
}
function shouldUseImportPlugin(options) {
if (options.modules.exportOnlyLocals) {
return false;
}
if (typeof options.import === "boolean") {
return options.import;
}
return true;
}
function shouldUseURLPlugin(options) {
if (options.modules.exportOnlyLocals) {
return false;
}
if (typeof options.url === "boolean") {
return options.url;
}
return true;
}
function shouldUseModulesPlugins(options) {
return options.modules.compileType === "module";
}
function shouldUseIcssPlugin(options) {
return options.icss === true || Boolean(options.modules);
}
function getModulesPlugins(options, loaderContext, meta) {
const { mode , getLocalIdent , localIdentName , localIdentContext , localIdentHashPrefix , localIdentRegExp , } = options.modules;
let plugins = [];
try {
plugins = [
modulesValues,
localByDefault({
mode
}),
extractImports(),
modulesScope({
generateScopedName (exportName) {
return getLocalIdent(loaderContext, localIdentName, exportName, {
context: localIdentContext,
hashPrefix: localIdentHashPrefix,
regExp: localIdentRegExp
}, meta);
},
exportGlobals: options.modules.exportGlobals
}),
];
} catch (error) {
loaderContext.emitError(error);
}
return plugins;
}
const IS_NATIVE_WIN32_PATH = /^[a-z]:[/\\]|^\\\\/i;
const ABSOLUTE_SCHEME = /^[a-z0-9+\-.]+:/i;
function getURLType(source) {
if (source[0] === "/") {
if (source[1] === "/") {
return "scheme-relative";
}
return "path-absolute";
}
if (IS_NATIVE_WIN32_PATH.test(source)) {
return "path-absolute";
}
return ABSOLUTE_SCHEME.test(source) ? "absolute" : "path-relative";
}
function normalizeSourceMap(map, resourcePath) {
let newMap = map;
// Some loader emit source map as string
// Strip any JSON XSSI avoidance prefix from the string (as documented in the source maps specification), and then parse the string as JSON.
if (typeof newMap === "string") {
newMap = JSON.parse(newMap);
}
delete newMap.file;
const { sourceRoot } = newMap;
delete newMap.sourceRoot;
if (newMap.sources) {
// Source maps should use forward slash because it is URLs (https://github.com/mozilla/source-map/issues/91)
// We should normalize path because previous loaders like `sass-loader` using backslash when generate source map
newMap.sources = newMap.sources.map((source)=>{
// Non-standard syntax from `postcss`
if (source.indexOf("<") === 0) {
return source;
}
const sourceType = getURLType(source);
// Do no touch `scheme-relative` and `absolute` URLs
if (sourceType === "path-relative" || sourceType === "path-absolute") {
const absoluteSource = sourceType === "path-relative" && sourceRoot ? path.resolve(sourceRoot, normalizePath(source)) : normalizePath(source);
return path.relative(path.dirname(resourcePath), absoluteSource);
}
return source;
});
}
return newMap;
}
function getPreRequester({ loaders , loaderIndex }) {
const cache = Object.create(null);
return (number)=>{
if (cache[number]) {
return cache[number];
}
if (number === false) {
cache[number] = "";
} else {
const loadersRequest = loaders.slice(loaderIndex, loaderIndex + 1 + (typeof number !== "number" ? 0 : number)).map((x)=>x.request).join("!");
cache[number] = `-!${loadersRequest}!`;
}
return cache[number];
};
}
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 normalizeSourceMapForRuntime(map, loaderContext) {
const resultMap = map ? map.toJSON() : null;
if (resultMap) {
delete resultMap.file;
resultMap.sourceRoot = "";
resultMap.sources = resultMap.sources.map((source)=>{
// Non-standard syntax from `postcss`
if (source.indexOf("<") === 0) {
return source;
}
const sourceType = getURLType(source);
if (sourceType !== "path-relative") {
return source;
}
const resourceDirname = path.dirname(loaderContext.resourcePath);
const absoluteSource = path.resolve(resourceDirname, source);
const contextifyPath = normalizePath(path.relative(loaderContext.rootContext, absoluteSource));
return `webpack://${contextifyPath}`;
});
}
return JSON.stringify(resultMap);
}
function getModuleCode(result, api, replacements, options, loaderContext) {
if (options.modules.exportOnlyLocals === true) {
return "";
}
const sourceMapValue = options.sourceMap ? `,${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 item1 of replacements){
const { replacementName , importName , localName } = item1;
if (localName) {
code = code.replace(new RegExp(replacementName, "g"), ()=>options.modules.namedExport ? `" + ${importName}_NAMED___[${JSON.stringify(camelCase(localName))}] + "` : `" + ${importName}.locals[${JSON.stringify(localName)}] + "`);
} else {
const { hash , needQuotes } = item1;
const getUrlOptions = [].concat(hash ? [
`hash: ${JSON.stringify(hash)}`
] : []).concat(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 dashesCamelCase(str) {
return str.replace(/-+(\w)/g, (match, firstLetter)=>firstLetter.toUpperCase());
}
function getExportCode(exports, replacements, options) {
let code = "// Exports\n";
let localsCode = "";
const addExportToLocalsCode = (name, value)=>{
if (options.modules.namedExport) {
localsCode += `export const ${camelCase(name)} = ${JSON.stringify(value)};\n`;
} else {
if (localsCode) {
localsCode += `,\n`;
}
localsCode += `\t${JSON.stringify(name)}: ${JSON.stringify(value)}`;
}
};
for (const { name: name1 , value: value1 } of exports){
switch(options.modules.exportLocalsConvention){
case "camelCase":
{
addExportToLocalsCode(name1, value1);
const modifiedName = camelCase(name1);
if (modifiedName !== name1) {
addExportToLocalsCode(modifiedName, value1);
}
break;
}
case "camelCaseOnly":
{
addExportToLocalsCode(camelCase(name1), value1);
break;
}
case "dashes":
{
addExportToLocalsCode(name1, value1);
const modifiedName = dashesCamelCase(name1);
if (modifiedName !== name1) {
addExportToLocalsCode(modifiedName, value1);
}
break;
}
case "dashesOnly":
{
addExportToLocalsCode(dashesCamelCase(name1), value1);
break;
}
case "asIs":
default:
addExportToLocalsCode(name1, value1);
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(camelCase(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;
}
async function resolveRequests(resolve, context, possibleRequests) {
return resolve(context, possibleRequests[0]).then((result)=>{
return result;
}).catch((error)=>{
const [, ...tailPossibleRequests] = possibleRequests;
if (tailPossibleRequests.length === 0) {
throw error;
}
return resolveRequests(resolve, context, tailPossibleRequests);
});
}
function isUrlRequestable(url) {
// Protocol-relative URLs
if (/^\/\//.test(url)) {
return false;
}
// `file:` protocol
if (/^file:/i.test(url)) {
return true;
}
// Absolute URLs
if (/^[a-z][a-z0-9+.-]*:/i.test(url)) {
return true;
}
// `#` URLs
if (/^#/.test(url)) {
return false;
}
return true;
}
function sort(a, b) {
return a.index - b.index;
}
function isDataUrl(url) {
if (/^data:/i.test(url)) {
return true;
}
return false;
}
export { isDataUrl, shouldUseModulesPlugins, shouldUseImportPlugin, shouldUseURLPlugin, shouldUseIcssPlugin, normalizeUrl, requestify, getFilter, getModulesPlugins, normalizeSourceMap, getPreRequester, getImportCode, getModuleCode, getExportCode, resolveRequests, isUrlRequestable, sort, };
//# sourceMappingURL=utils.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,17 @@
import chalk from "next/dist/compiled/chalk";
import path from "path";
const ErrorLoader = function() {
var ref, ref1, ref2;
// @ts-ignore exists
const options = this.getOptions() || {};
const { reason ="An unknown error has occurred" } = options;
// @ts-expect-error
const resource = ((ref = this._module) == null ? void 0 : (ref1 = ref.issuer) == null ? void 0 : ref1.resource) ?? null;
const context = this.rootContext ?? ((ref2 = this._compiler) == null ? void 0 : ref2.context);
const issuer = resource ? context ? path.relative(context, resource) : resource : null;
const err = new Error(reason + (issuer ? `\nLocation: ${chalk.cyan(issuer)}` : ""));
this.emitError(err);
};
export default ErrorLoader;
//# sourceMappingURL=error-loader.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/webpack/loaders/error-loader.ts"],"names":["chalk","path","ErrorLoader","options","getOptions","reason","resource","_module","issuer","context","rootContext","_compiler","relative","err","Error","cyan","emitError"],"mappings":"AAAA,OAAOA,KAAK,MAAM,0BAA0B,CAAA;AAC5C,OAAOC,IAAI,MAAM,MAAM,CAAA;AAGvB,MAAMC,WAAW,GAAqC,WAAY;QAO/C,GAAY,QACO,IAAc;IAPlD,oBAAoB;IACpB,MAAMC,OAAO,GAAG,IAAI,CAACC,UAAU,EAAE,IAAK,EAAE,AAAQ;IAEhD,MAAM,EAAEC,MAAM,EAAG,+BAA+B,CAAA,EAAE,GAAGF,OAAO;IAE5D,mBAAmB;IACnB,MAAMG,QAAQ,GAAG,CAAA,CAAA,GAAY,GAAZ,IAAI,CAACC,OAAO,SAAQ,GAApB,KAAA,CAAoB,GAApB,QAAA,GAAY,CAAEC,MAAM,SAAA,GAApB,KAAA,CAAoB,QAAEF,QAAQ,AAAV,CAAA,IAAc,IAAI;IACvD,MAAMG,OAAO,GAAG,IAAI,CAACC,WAAW,IAAI,CAAA,CAAA,IAAc,GAAd,IAAI,CAACC,SAAS,SAAS,GAAvB,KAAA,CAAuB,GAAvB,IAAc,CAAEF,OAAO,CAAA;IAE3D,MAAMD,MAAM,GAAGF,QAAQ,GACnBG,OAAO,GACLR,IAAI,CAACW,QAAQ,CAACH,OAAO,EAAEH,QAAQ,CAAC,GAChCA,QAAQ,GACV,IAAI;IAER,MAAMO,GAAG,GAAG,IAAIC,KAAK,CACnBT,MAAM,GAAG,CAACG,MAAM,GAAG,CAAC,YAAY,EAAER,KAAK,CAACe,IAAI,CAACP,MAAM,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAC7D;IACD,IAAI,CAACQ,SAAS,CAACH,GAAG,CAAC;CACpB;AAED,eAAeX,WAAW,CAAA"}

View File

@@ -0,0 +1,8 @@
/**
* A getter for module build info that casts to the type it should have.
* We also expose here types to make easier to use it.
*/ export function getModuleBuildInfo(webpackModule) {
return webpackModule.buildInfo;
}
//# sourceMappingURL=get-module-build-info.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/webpack/loaders/get-module-build-info.ts"],"names":["getModuleBuildInfo","webpackModule","buildInfo"],"mappings":"AAMA;;;GAGG,CACH,OAAO,SAASA,kBAAkB,CAACC,aAA6B,EAAE;IAChE,OAAOA,aAAa,CAACC,SAAS,CAY7B;CACF"}

View File

@@ -0,0 +1,191 @@
import chalk from "next/dist/compiled/chalk";
import { NODE_RESOLVE_OPTIONS } from "../../webpack-config";
import { getModuleBuildInfo } from "./get-module-build-info";
import { sep } from "path";
import { verifyRootLayout } from "../../../lib/verifyRootLayout";
import * as Log from "../../../build/output/log";
import { APP_DIR_ALIAS } from "../../../lib/constants";
const FILE_TYPES = {
layout: "layout",
template: "template",
error: "error",
loading: "loading",
head: "head",
"not-found": "not-found"
};
const GLOBAL_ERROR_FILE_TYPE = "global-error";
const PAGE_SEGMENT = "page$";
async function createTreeCodeFromPath({ pagePath , resolve , resolveParallelSegments }) {
const splittedPath = pagePath.split(/[\\/]/);
const appDirPrefix = splittedPath[0];
const pages = [];
let rootLayout;
let globalError;
async function createSubtreePropsFromSegmentPath(segments) {
const segmentPath = segments.join("/");
// Existing tree are the children of the current segment
const props = {};
// We need to resolve all parallel routes in this level.
const parallelSegments = [];
if (segments.length === 0) {
parallelSegments.push([
"children",
""
]);
} else {
parallelSegments.push(...resolveParallelSegments(segmentPath));
}
for (const [parallelKey, parallelSegment] of parallelSegments){
if (parallelSegment === PAGE_SEGMENT) {
const matchedPagePath = `${appDirPrefix}${segmentPath}/page`;
const resolvedPagePath = await resolve(matchedPagePath);
if (resolvedPagePath) pages.push(resolvedPagePath);
// Use '' for segment as it's the page. There can't be a segment called '' so this is the safest way to add it.
props[parallelKey] = `['', {}, {
page: [() => import(/* webpackMode: "eager" */ ${JSON.stringify(resolvedPagePath)}), ${JSON.stringify(resolvedPagePath)}]}]`;
continue;
}
const parallelSegmentPath = segmentPath + "/" + parallelSegment;
const subtree = await createSubtreePropsFromSegmentPath([
...segments,
parallelSegment,
]);
// `page` is not included here as it's added above.
const filePaths = await Promise.all(Object.values(FILE_TYPES).map(async (file)=>{
return [
file,
await resolve(`${appDirPrefix}${parallelSegmentPath}/${file}`),
];
}));
if (!rootLayout) {
var ref;
rootLayout = (ref = filePaths.find(([type, path])=>type === "layout" && !!path)) == null ? void 0 : ref[1];
}
if (!globalError) {
globalError = await resolve(`${appDirPrefix}${parallelSegmentPath}/${GLOBAL_ERROR_FILE_TYPE}`);
}
props[parallelKey] = `[
'${parallelSegment}',
${subtree},
{
${filePaths.filter(([, filePath])=>filePath !== undefined).map(([file, filePath])=>{
if (filePath === undefined) {
return "";
}
return `'${file}': [() => import(/* webpackMode: "eager" */ ${JSON.stringify(filePath)}), ${JSON.stringify(filePath)}],`;
}).join("\n")}
}
]`;
}
return `{
${Object.entries(props).map(([key, value])=>`${key}: ${value}`).join(",\n")}
}`;
}
const tree = await createSubtreePropsFromSegmentPath([]);
return [
`const tree = ${tree}.children;`,
pages,
rootLayout,
globalError
];
}
function createAbsolutePath(appDir, pathToTurnAbsolute) {
return pathToTurnAbsolute// Replace all POSIX path separators with the current OS path separator
.replace(/\//g, sep).replace(/^private-next-app-dir/, appDir);
}
const nextAppLoader = async function nextAppLoader() {
const { name , appDir , appPaths , pagePath , pageExtensions , rootDir , tsconfigPath , isDev , } = this.getOptions() || {};
const buildInfo = getModuleBuildInfo(this._module);
buildInfo.route = {
page: name.replace(/^app/, ""),
absolutePagePath: createAbsolutePath(appDir, pagePath)
};
const extensions = pageExtensions.map((extension)=>`.${extension}`);
const resolveOptions = {
...NODE_RESOLVE_OPTIONS,
extensions
};
const resolve = this.getResolve(resolveOptions);
const normalizedAppPaths = typeof appPaths === "string" ? [
appPaths
] : appPaths || [];
const resolveParallelSegments = (pathname)=>{
const matched = {};
for (const path of normalizedAppPaths){
if (path.startsWith(pathname + "/")) {
const rest = path.slice(pathname.length + 1).split("/");
let matchedSegment = rest[0];
// It is the actual page, mark it sepcially.
if (rest.length === 1 && matchedSegment === "page") {
matchedSegment = PAGE_SEGMENT;
}
const matchedKey = matchedSegment.startsWith("@") ? matchedSegment.slice(1) : "children";
matched[matchedKey] = matchedSegment;
}
}
return Object.entries(matched);
};
const resolver = async (pathname)=>{
try {
const resolved = await resolve(this.rootContext, pathname);
this.addDependency(resolved);
return resolved;
} catch (err) {
const absolutePath = createAbsolutePath(appDir, pathname);
for (const ext of extensions){
const absolutePathWithExtension = `${absolutePath}${ext}`;
this.addMissingDependency(absolutePathWithExtension);
}
if (err.message.includes("Can't resolve")) {
return undefined;
}
throw err;
}
};
const [treeCode, pages, rootLayout, globalError] = await createTreeCodeFromPath({
pagePath,
resolve: resolver,
resolveParallelSegments
});
if (!rootLayout) {
const errorMessage = `${chalk.bold(pagePath.replace(`${APP_DIR_ALIAS}/`, ""))} doesn't have a root layout. To fix this error, make sure every page has a root layout.`;
if (!isDev) {
// If we're building and missing a root layout, exit the build
Log.error(errorMessage);
process.exit(1);
} else {
// In dev we'll try to create a root layout
const createdRootLayout = await verifyRootLayout({
appDir: appDir,
dir: rootDir,
tsconfigPath: tsconfigPath,
pagePath,
pageExtensions
});
if (!createdRootLayout) {
throw new Error(errorMessage);
}
}
}
const result = `
export ${treeCode}
export const pages = ${JSON.stringify(pages)}
export { default as AppRouter } from 'next/dist/client/components/app-router'
export { default as LayoutRouter } from 'next/dist/client/components/layout-router'
export { default as RenderFromTemplateContext } from 'next/dist/client/components/render-from-template-context'
export { default as GlobalError } from ${JSON.stringify(globalError || "next/dist/client/components/error-boundary")}
export { staticGenerationAsyncStorage } from 'next/dist/client/components/static-generation-async-storage'
export { requestAsyncStorage } from 'next/dist/client/components/request-async-storage'
export * as serverHooks from 'next/dist/client/components/hooks-server-context'
export { renderToReadableStream } from 'next/dist/compiled/react-server-dom-webpack/server.browser'
export const __next_app_webpack_require__ = __webpack_require__
`;
return result;
};
export default nextAppLoader;
//# sourceMappingURL=next-app-loader.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,27 @@
import { stringifyRequest } from "../stringify-request";
// this parameter: https://www.typescriptlang.org/docs/handbook/functions.html#this-parameters
function nextClientPagesLoader() {
const pagesLoaderSpan = this.currentTraceSpan.traceChild("next-client-pages-loader");
return pagesLoaderSpan.traceFn(()=>{
const { absolutePagePath , page } = this.getOptions();
pagesLoaderSpan.setAttribute("absolutePagePath", absolutePagePath);
const stringifiedPageRequest = stringifyRequest(this, absolutePagePath);
const stringifiedPage = JSON.stringify(page);
return `
(window.__NEXT_P = window.__NEXT_P || []).push([
${stringifiedPage},
function () {
return require(${stringifiedPageRequest});
}
]);
if(module.hot) {
module.hot.dispose(function () {
window.__NEXT_P.push([${stringifiedPage}])
});
}
`;
});
}
export default nextClientPagesLoader;
//# sourceMappingURL=next-client-pages-loader.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/webpack/loaders/next-client-pages-loader.ts"],"names":["stringifyRequest","nextClientPagesLoader","pagesLoaderSpan","currentTraceSpan","traceChild","traceFn","absolutePagePath","page","getOptions","setAttribute","stringifiedPageRequest","stringifiedPage","JSON","stringify"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,sBAAsB,CAAA;AAOvD,8FAA8F;AAC9F,SAASC,qBAAqB,GAAY;IACxC,MAAMC,eAAe,GAAG,IAAI,CAACC,gBAAgB,CAACC,UAAU,CACtD,0BAA0B,CAC3B;IAED,OAAOF,eAAe,CAACG,OAAO,CAAC,IAAM;QACnC,MAAM,EAAEC,gBAAgB,CAAA,EAAEC,IAAI,CAAA,EAAE,GAC9B,IAAI,CAACC,UAAU,EAAE,AAA4B;QAE/CN,eAAe,CAACO,YAAY,CAAC,kBAAkB,EAAEH,gBAAgB,CAAC;QAElE,MAAMI,sBAAsB,GAAGV,gBAAgB,CAAC,IAAI,EAAEM,gBAAgB,CAAC;QACvE,MAAMK,eAAe,GAAGC,IAAI,CAACC,SAAS,CAACN,IAAI,CAAC;QAE5C,OAAO,CAAC;;MAEN,EAAEI,eAAe,CAAC;;uBAED,EAAED,sBAAsB,CAAC;;;;;8BAKlB,EAAEC,eAAe,CAAC;;;EAG9C,CAAC,CAAA;KACA,CAAC,CAAA;CACH;AAED,eAAeV,qBAAqB,CAAA"}

View File

@@ -0,0 +1,33 @@
import { getModuleBuildInfo } from "./get-module-build-info";
import { stringifyRequest } from "../stringify-request";
export default function middlewareLoader() {
const { absolutePagePath , page , rootDir } = this.getOptions();
const stringifiedPagePath = stringifyRequest(this, absolutePagePath);
const buildInfo = getModuleBuildInfo(this._module);
buildInfo.nextEdgeApiFunction = {
page: page || "/"
};
buildInfo.rootDir = rootDir;
return `
import { adapter, enhanceGlobals } from 'next/dist/esm/server/web/adapter'
enhanceGlobals()
var mod = require(${stringifiedPagePath})
var handler = mod.middleware || mod.default;
if (typeof handler !== 'function') {
throw new Error('The Edge Function "pages${page}" must export a \`default\` function');
}
export default function (opts) {
return adapter({
...opts,
page: ${JSON.stringify(page)},
handler,
})
}
`;
};
//# sourceMappingURL=next-edge-function-loader.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/webpack/loaders/next-edge-function-loader.ts"],"names":["getModuleBuildInfo","stringifyRequest","middlewareLoader","absolutePagePath","page","rootDir","getOptions","stringifiedPagePath","buildInfo","_module","nextEdgeApiFunction","JSON","stringify"],"mappings":"AAAA,SAASA,kBAAkB,QAAQ,yBAAyB,CAAA;AAC5D,SAASC,gBAAgB,QAAQ,sBAAsB,CAAA;AAQvD,eAAe,SAASC,gBAAgB,GAAY;IAClD,MAAM,EAAEC,gBAAgB,CAAA,EAAEC,IAAI,CAAA,EAAEC,OAAO,CAAA,EAAE,GACvC,IAAI,CAACC,UAAU,EAAE;IACnB,MAAMC,mBAAmB,GAAGN,gBAAgB,CAAC,IAAI,EAAEE,gBAAgB,CAAC;IACpE,MAAMK,SAAS,GAAGR,kBAAkB,CAAC,IAAI,CAACS,OAAO,CAAC;IAClDD,SAAS,CAACE,mBAAmB,GAAG;QAC9BN,IAAI,EAAEA,IAAI,IAAI,GAAG;KAClB;IACDI,SAAS,CAACH,OAAO,GAAGA,OAAO;IAE3B,OAAO,CAAC;;;;;0BAKgB,EAAEE,mBAAmB,CAAC;;;;mDAIG,EAAEH,IAAI,CAAC;;;;;;oBAMtC,EAAEO,IAAI,CAACC,SAAS,CAACR,IAAI,CAAC,CAAC;;;;IAIvC,CAAC,CAAA;CACJ,CAAA"}

View File

@@ -0,0 +1,97 @@
import { getModuleBuildInfo } from "../get-module-build-info";
import { stringifyRequest } from "../../stringify-request";
/*
For pages SSR'd at the edge, we bundle them with the ESM version of Next in order to
benefit from the better tree-shaking and thus, smaller bundle sizes.
The absolute paths for _app, _error and _document, used in this loader, link to the regular CJS modules.
They are generated in `createPagesMapping` where we don't have access to `isEdgeRuntime`,
so we have to do it here. It's not that bad because it keeps all references to ESM modules magic in this place.
*/ function swapDistFolderWithEsmDistFolder(path) {
return path.replace("next/dist/pages", "next/dist/esm/pages");
}
export default async function edgeSSRLoader() {
const { dev , page , buildId , absolutePagePath , absoluteAppPath , absoluteDocumentPath , absolute500Path , absoluteErrorPath , isServerComponent , stringifiedConfig , appDirLoader: appDirLoaderBase64 , pagesType , sriEnabled , hasFontLoaders , } = this.getOptions();
const appDirLoader = Buffer.from(appDirLoaderBase64 || "", "base64").toString();
const isAppDir = pagesType === "app";
const buildInfo = getModuleBuildInfo(this._module);
buildInfo.nextEdgeSSR = {
isServerComponent: isServerComponent === "true",
page: page,
isAppDir
};
buildInfo.route = {
page,
absolutePagePath
};
const stringifiedPagePath = stringifyRequest(this, absolutePagePath);
const stringifiedAppPath = stringifyRequest(this, swapDistFolderWithEsmDistFolder(absoluteAppPath));
const stringifiedErrorPath = stringifyRequest(this, swapDistFolderWithEsmDistFolder(absoluteErrorPath));
const stringifiedDocumentPath = stringifyRequest(this, swapDistFolderWithEsmDistFolder(absoluteDocumentPath));
const stringified500Path = absolute500Path ? stringifyRequest(this, absolute500Path) : null;
const pageModPath = `${appDirLoader}${stringifiedPagePath.substring(1, stringifiedPagePath.length - 1)}${isAppDir ? "?__edge_ssr_entry__" : ""}`;
const transformed = `
import { adapter, enhanceGlobals } from 'next/dist/esm/server/web/adapter'
import { getRender } from 'next/dist/esm/build/webpack/loaders/next-edge-ssr-loader/render'
enhanceGlobals()
const pageType = ${JSON.stringify(pagesType)}
${isAppDir ? `
import { renderToHTMLOrFlight as appRenderToHTML } from 'next/dist/esm/server/app-render'
import * as pageMod from ${JSON.stringify(pageModPath)}
const Document = null
const pagesRenderToHTML = null
const appMod = null
const errorMod = null
const error500Mod = null
` : `
import Document from ${stringifiedDocumentPath}
import { renderToHTML as pagesRenderToHTML } from 'next/dist/esm/server/render'
import * as pageMod from ${stringifiedPagePath}
import * as appMod from ${stringifiedAppPath}
import * as errorMod from ${stringifiedErrorPath}
${stringified500Path ? `import * as error500Mod from ${stringified500Path}` : `const error500Mod = null`}
const appRenderToHTML = null
`}
const buildManifest = self.__BUILD_MANIFEST
const reactLoadableManifest = self.__REACT_LOADABLE_MANIFEST
const rscManifest = self.__RSC_MANIFEST
const rscCssManifest = self.__RSC_CSS_MANIFEST
const subresourceIntegrityManifest = ${sriEnabled ? "self.__SUBRESOURCE_INTEGRITY_MANIFEST" : "undefined"}
const fontLoaderManifest = ${hasFontLoaders ? "self.__FONT_LOADER_MANIFEST" : "undefined"}
const render = getRender({
pageType,
dev: ${dev},
page: ${JSON.stringify(page)},
appMod,
pageMod,
errorMod,
error500Mod,
Document,
buildManifest,
appRenderToHTML,
pagesRenderToHTML,
reactLoadableManifest,
serverComponentManifest: ${isServerComponent} ? rscManifest : null,
serverCSSManifest: ${isServerComponent} ? rscCssManifest : null,
subresourceIntegrityManifest,
config: ${stringifiedConfig},
buildId: ${JSON.stringify(buildId)},
fontLoaderManifest,
})
export const ComponentMod = pageMod
export default function(opts) {
return adapter({
...opts,
handler: render
})
}`;
return transformed;
};
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../build/webpack/loaders/next-edge-ssr-loader/index.ts"],"names":["getModuleBuildInfo","stringifyRequest","swapDistFolderWithEsmDistFolder","path","replace","edgeSSRLoader","dev","page","buildId","absolutePagePath","absoluteAppPath","absoluteDocumentPath","absolute500Path","absoluteErrorPath","isServerComponent","stringifiedConfig","appDirLoader","appDirLoaderBase64","pagesType","sriEnabled","hasFontLoaders","getOptions","Buffer","from","toString","isAppDir","buildInfo","_module","nextEdgeSSR","route","stringifiedPagePath","stringifiedAppPath","stringifiedErrorPath","stringifiedDocumentPath","stringified500Path","pageModPath","substring","length","transformed","JSON","stringify"],"mappings":"AAAA,SAASA,kBAAkB,QAAQ,0BAA0B,CAAA;AAC7D,SAASC,gBAAgB,QAAQ,yBAAyB,CAAA;AAmB1D;;;;;;;EAOE,CACF,SAASC,+BAA+B,CAACC,IAAY,EAAE;IACrD,OAAOA,IAAI,CAACC,OAAO,CAAC,iBAAiB,EAAE,qBAAqB,CAAC,CAAA;CAC9D;AAED,eAAe,eAAeC,aAAa,GAAY;IACrD,MAAM,EACJC,GAAG,CAAA,EACHC,IAAI,CAAA,EACJC,OAAO,CAAA,EACPC,gBAAgB,CAAA,EAChBC,eAAe,CAAA,EACfC,oBAAoB,CAAA,EACpBC,eAAe,CAAA,EACfC,iBAAiB,CAAA,EACjBC,iBAAiB,CAAA,EACjBC,iBAAiB,CAAA,EACjBC,YAAY,EAAEC,kBAAkB,CAAA,EAChCC,SAAS,CAAA,EACTC,UAAU,CAAA,EACVC,cAAc,CAAA,IACf,GAAG,IAAI,CAACC,UAAU,EAAE;IAErB,MAAML,YAAY,GAAGM,MAAM,CAACC,IAAI,CAC9BN,kBAAkB,IAAI,EAAE,EACxB,QAAQ,CACT,CAACO,QAAQ,EAAE;IACZ,MAAMC,QAAQ,GAAGP,SAAS,KAAK,KAAK;IAEpC,MAAMQ,SAAS,GAAG1B,kBAAkB,CAAC,IAAI,CAAC2B,OAAO,CAAC;IAClDD,SAA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,wBAAwB,CAAC,CAC/B;;IAEH,CAAC,CACA;;;;;;yCAMoC,EACnCf,UAAU,GAAG,uCAAuC,GAAG,WAAW,CACnE;+BAC0B,EACzBC,cAAc,GAAG,6BAA6B,GAAG,WAAW,CAC7D;;;;WAIM,EAAEd,GAAG,CAAC;YACL,EAAEiC,IAAI,CAACC,SAAS,CAACjC,IAAI,CAAC,CAAC;;;;;;;;;;+BAUJ,EAAEO,iBAAiB,CAAC;yBAC1B,EAAEA,iBAAiB,CAAC;;cAE/B,EAAEC,iBAAiB,CAAC;eACnB,EAAEwB,IAAI,CAACC,SAAS,CAAChC,OAAO,CAAC,CAAC;;;;;;;;;;;KAWpC,CAAC;IAEJ,OAAO8B,WAAW,CAAA;CACnB,CAAA"}

View File

@@ -0,0 +1,84 @@
import WebServer from "../../../../server/web-server";
import { WebNextRequest, WebNextResponse } from "../../../../server/base-http/web";
import { SERVER_RUNTIME } from "../../../../lib/constants";
export function getRender({ dev , page , appMod , pageMod , errorMod , error500Mod , pagesType , Document , buildManifest , reactLoadableManifest , appRenderToHTML , pagesRenderToHTML , serverComponentManifest , subresourceIntegrityManifest , serverCSSManifest , config , buildId , fontLoaderManifest }) {
const isAppPath = pagesType === "app";
const baseLoadComponentResult = {
dev,
buildManifest,
reactLoadableManifest,
subresourceIntegrityManifest,
fontLoaderManifest,
Document,
App: appMod == null ? void 0 : appMod.default
};
const server = new WebServer({
dev,
conf: config,
minimalMode: true,
webServerConfig: {
page,
pagesType,
extendRenderOpts: {
buildId,
runtime: SERVER_RUNTIME.experimentalEdge,
supportsDynamicHTML: true,
disableOptimizedLoading: true,
serverComponentManifest,
serverCSSManifest
},
appRenderToHTML,
pagesRenderToHTML,
loadComponent: async (pathname)=>{
if (isAppPath) return null;
if (pathname === page) {
return {
...baseLoadComponentResult,
Component: pageMod.default,
pageConfig: pageMod.config || {},
getStaticProps: pageMod.getStaticProps,
getServerSideProps: pageMod.getServerSideProps,
getStaticPaths: pageMod.getStaticPaths,
ComponentMod: pageMod,
pathname
};
}
// If there is a custom 500 page, we need to handle it separately.
if (pathname === "/500" && error500Mod) {
return {
...baseLoadComponentResult,
Component: error500Mod.default,
pageConfig: error500Mod.config || {},
getStaticProps: error500Mod.getStaticProps,
getServerSideProps: error500Mod.getServerSideProps,
getStaticPaths: error500Mod.getStaticPaths,
ComponentMod: error500Mod,
pathname
};
}
if (pathname === "/_error") {
return {
...baseLoadComponentResult,
Component: errorMod.default,
pageConfig: errorMod.config || {},
getStaticProps: errorMod.getStaticProps,
getServerSideProps: errorMod.getServerSideProps,
getStaticPaths: errorMod.getStaticPaths,
ComponentMod: errorMod,
pathname
};
}
return null;
}
}
});
const requestHandler = server.getRequestHandler();
return async function render(request) {
const extendedReq = new WebNextRequest(request);
const extendedRes = new WebNextResponse();
requestHandler(extendedReq, extendedRes);
return await extendedRes.toResponse();
};
}
//# sourceMappingURL=render.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../build/webpack/loaders/next-edge-ssr-loader/render.ts"],"names":["WebServer","WebNextRequest","WebNextResponse","SERVER_RUNTIME","getRender","dev","page","appMod","pageMod","errorMod","error500Mod","pagesType","Document","buildManifest","reactLoadableManifest","appRenderToHTML","pagesRenderToHTML","serverComponentManifest","subresourceIntegrityManifest","serverCSSManifest","config","buildId","fontLoaderManifest","isAppPath","baseLoadComponentResult","App","default","server","conf","minimalMode","webServerConfig","extendRenderOpts","runtime","experimentalEdge","supportsDynamicHTML","disableOptimizedLoading","loadComponent","pathname","Component","pageConfig","getStaticProps","getServerSideProps","getStaticPaths","ComponentMod","requestHandler","getRequestHandler","render","request","extendedReq","extendedRes","toResponse"],"mappings":"AAOA,OAAOA,SAAS,MAAM,+BAA+B,CAAA;AACrD,SACEC,cAAc,EACdC,eAAe,QACV,kCAAkC,CAAA;AACzC,SAASC,cAAc,QAAQ,2BAA2B,CAAA;AAE1D,OAAO,SAASC,SAAS,CAAC,EACxBC,GAAG,CAAA,EACHC,IAAI,CAAA,EACJC,MAAM,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QACxC,OAAO,MAAMA,WAAW,CAACC,UAAU,EAAE,CAAA;KACtC,CAAA;CACF"}

View File

@@ -0,0 +1,26 @@
import { RSC_MODULE_TYPES } from "../../../shared/lib/constants";
import { getModuleBuildInfo } from "./get-module-build-info";
import { regexCSS } from "./utils";
export default async function transformSource() {
let { modules , server } = this.getOptions();
const isServer = server === "true";
if (!Array.isArray(modules)) {
modules = modules ? [
modules
] : [];
}
const requests = modules;
const code = requests// Filter out css files on the server
.filter((request)=>isServer ? !regexCSS.test(request) : true).map((request)=>regexCSS.test(request) ? `(() => import(/* webpackMode: "lazy" */ ${JSON.stringify(request)}))` : `import(/* webpackMode: "eager" */ ${JSON.stringify(request)})`).join(";\n");
const buildInfo = getModuleBuildInfo(this._module);
const resolve = this.getResolve();
// Resolve to absolute resource url for flight manifest to collect and use to determine client components
const resolvedRequests = await Promise.all(requests.map(async (r)=>await resolve(this.rootContext, r)));
buildInfo.rsc = {
type: RSC_MODULE_TYPES.client,
requests: resolvedRequests
};
return code;
};
//# sourceMappingURL=next-flight-client-entry-loader.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/webpack/loaders/next-flight-client-entry-loader.ts"],"names":["RSC_MODULE_TYPES","getModuleBuildInfo","regexCSS","transformSource","modules","server","getOptions","isServer","Array","isArray","requests","code","filter","request","test","map","JSON","stringify","join","buildInfo","_module","resolve","getResolve","resolvedRequests","Promise","all","r","rootContext","rsc","type","client"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,+BAA+B,CAAA;AAChE,SAASC,kBAAkB,QAAQ,yBAAyB,CAAA;AAC5D,SAASC,QAAQ,QAAQ,SAAS,CAAA;AAWlC,eAAe,eAAeC,eAAe,GAA6B;IACxE,IAAI,EAAEC,OAAO,CAAA,EAAEC,MAAM,CAAA,EAAE,GACrB,IAAI,CAACC,UAAU,EAAE;IACnB,MAAMC,QAAQ,GAAGF,MAAM,KAAK,MAAM;IAElC,IAAI,CAACG,KAAK,CAACC,OAAO,CAACL,OAAO,CAAC,EAAE;QAC3BA,OAAO,GAAGA,OAAO,GAAG;YAACA,OAAO;SAAC,GAAG,EAAE;KACnC;IAED,MAAMM,QAAQ,GAAGN,OAAO,AAAY;IACpC,MAAMO,IAAI,GAAGD,QAAQ,AACnB,qCAAqC;KACpCE,MAAM,CAAC,CAACC,OAAO,GAAMN,QAAQ,GAAG,CAACL,QAAQ,CAACY,IAAI,CAACD,OAAO,CAAC,GAAG,IAAI,AAAC,CAAC,CAChEE,GAAG,CAAC,CAACF,OAAO,GACXX,QAAQ,CAACY,IAAI,CAACD,OAAO,CAAC,GAClB,CAAC,wCAAwC,EAAEG,IAAI,CAACC,SAAS,CAACJ,OAAO,CAAC,CAAC,EAAE,CAAC,GACtE,CAAC,kCAAkC,EAAEG,IAAI,CAACC,SAAS,CAACJ,OAAO,CAAC,CAAC,CAAC,CAAC,CACpE,CACAK,IAAI,CAAC,KAAK,CAAC;IAEd,MAAMC,SAAS,GAAGlB,kBAAkB,CAAC,IAAI,CAACmB,OAAO,CAAC;IAClD,MAAMC,OAAO,GAAG,IAAI,CAACC,UAAU,EAAE;IAEjC,yGAAyG;IACzG,MAAMC,gBAAgB,GAAG,MAAMC,OAAO,CAACC,GAAG,CACxCf,QAAQ,CAACK,GAAG,CAAC,OAAOW,CAAC,GAAK,MAAML,OAAO,CAAC,IAAI,CAACM,WAAW,EAAED,CAAC,CAAC,CAAC,CAC9D;IAEDP,SAAS,CAACS,GAAG,GAAG;QACdC,IAAI,EAAE7B,gBAAgB,CAAC8B,MAAM;QAC7BpB,QAAQ,EAAEa,gBAAgB;KAC3B;IAED,OAAOZ,IAAI,CAAA;CACZ,CAAA"}

View File

@@ -0,0 +1,27 @@
/**
* For server-side CSS imports, we need to ignore the actual module content but
* still trigger the hot-reloading diff mechanism. So here we put the content
* inside a comment.
*/ import crypto from "crypto";
export function pitch() {
if (process.env.NODE_ENV !== "production") {
const content = this.fs.readFileSync(this.resourcePath);
this.data.__checksum = crypto.createHash("sha256").update(typeof content === "string" ? Buffer.from(content) : content).digest().toString("hex");
}
}
const NextServerCSSLoader = function(content) {
this.cacheable && this.cacheable();
// Only add the checksum during development.
if (process.env.NODE_ENV !== "production") {
const isCSSModule = this.resourcePath.match(/\.module\.(css|sass|scss)$/);
const checksum = crypto.createHash("sha256").update(this.data.__checksum + (typeof content === "string" ? Buffer.from(content) : content)).digest().toString("hex").substring(0, 12);
if (isCSSModule) {
return content + "\nmodule.exports.__checksum = " + JSON.stringify(checksum);
}
return `export default ${JSON.stringify(checksum)}`;
}
return content;
};
export default NextServerCSSLoader;
//# sourceMappingURL=next-flight-css-dev-loader.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/webpack/loaders/next-flight-css-dev-loader.ts"],"names":["crypto","pitch","process","env","NODE_ENV","content","fs","readFileSync","resourcePath","data","__checksum","createHash","update","Buffer","from","digest","toString","NextServerCSSLoader","cacheable","isCSSModule","match","checksum","substring","JSON","stringify"],"mappings":"AAAA;;;;GAIG,CAEH,OAAOA,MAAM,MAAM,QAAQ,CAAA;AAE3B,OAAO,SAASC,KAAK,GAAY;IAC/B,IAAIC,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,EAAE;QACzC,MAAMC,OAAO,GAAG,IAAI,CAACC,EAAE,CAACC,YAAY,CAAC,IAAI,CAACC,YAAY,CAAC;QACvD,IAAI,CAACC,IAAI,CAACC,UAAU,GAAGV,MAAM,CAC1BW,UAAU,CAAC,QAAQ,CAAC,CACpBC,MAAM,CAAC,OAAOP,OAAO,KAAK,QAAQ,GAAGQ,MAAM,CAACC,IAAI,CAACT,OAAO,CAAC,GAAGA,OAAO,CAAC,CACpEU,MAAM,EAAE,CACRC,QAAQ,CAAC,KAAK,CAAC;KACnB;CACF;AAED,MAAMC,mBAAmB,GAAG,SAAqBZ,OAAe,EAAE;IAChE,IAAI,CAACa,SAAS,IAAI,IAAI,CAACA,SAAS,EAAE;IAElC,4CAA4C;IAC5C,IAAIhB,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,EAAE;QACzC,MAAMe,WAAW,GAAG,IAAI,CAACX,YAAY,CAACY,KAAK,8BAA8B;QACzE,MAAMC,QAAQ,GAAGrB,MAAM,CACpBW,UAAU,CAAC,QAAQ,CAAC,CACpBC,MAAM,CACL,IAAI,CAACH,IAAI,CAACC,UAAU,GAClB,CAAC,OAAOL,OAAO,KAAK,QAAQ,GAAGQ,MAAM,CAACC,IAAI,CAACT,OAAO,CAAC,GAAGA,OAAO,CAAC,CACjE,CACAU,MAAM,EAAE,CACRC,QAAQ,CAAC,KAAK,CAAC,CACfM,SAAS,CAAC,CAAC,EAAE,EAAE,CAAC;QAEnB,IAAIH,WAAW,EAAE;YACf,OACEd,OAAO,GAAG,gCAAgC,GAAGkB,IAAI,CAACC,SAAS,CAACH,QAAQ,CAAC,CACtE;SACF;QAED,OAAO,CAAC,eAAe,EAAEE,IAAI,CAACC,SAAS,CAACH,QAAQ,CAAC,CAAC,CAAC,CAAA;KACpD;IAED,OAAOhB,OAAO,CAAA;CACf;AAED,eAAeY,mBAAmB,CAAA"}

View File

@@ -0,0 +1,29 @@
import { RSC_MODULE_TYPES } from "../../../../shared/lib/constants";
import { warnOnce } from "../../../../shared/lib/utils/warn-once";
import { getRSCModuleType } from "../../../analysis/get-page-static-info";
import { getModuleBuildInfo } from "../get-module-build-info";
const noopHeadPath = require.resolve("next/dist/client/components/noop-head");
export default async function transformSource(source, sourceMap) {
var ref;
// Avoid buffer to be consumed
if (typeof source !== "string") {
throw new Error("Expected source to have been transformed to a string.");
}
const callback = this.async();
const buildInfo = getModuleBuildInfo(this._module);
const rscType = getRSCModuleType(source);
// Assign the RSC meta information to buildInfo.
// Exclude next internal files which are not marked as client files
buildInfo.rsc = {
type: rscType
};
if (((ref = buildInfo.rsc) == null ? void 0 : ref.type) === RSC_MODULE_TYPES.client) {
return callback(null, source, sourceMap);
}
if (noopHeadPath === this.resourcePath) {
warnOnce(`Warning: You're using \`next/head\` inside app directory, please migrate to \`head.js\`. Checkout https://beta.nextjs.org/docs/api-reference/file-conventions/head for details.`);
}
return callback(null, source, sourceMap);
};
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../build/webpack/loaders/next-flight-loader/index.ts"],"names":["RSC_MODULE_TYPES","warnOnce","getRSCModuleType","getModuleBuildInfo","noopHeadPath","require","resolve","transformSource","source","sourceMap","buildInfo","Error","callback","async","_module","rscType","rsc","type","client","resourcePath"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,kCAAkC,CAAA;AACnE,SAASC,QAAQ,QAAQ,wCAAwC,CAAA;AACjE,SAASC,gBAAgB,QAAQ,wCAAwC,CAAA;AACzE,SAASC,kBAAkB,QAAQ,0BAA0B,CAAA;AAE7D,MAAMC,YAAY,GAAGC,OAAO,CAACC,OAAO,CAAC,uCAAuC,CAAC;AAE7E,eAAe,eAAeC,eAAe,CAE3CC,MAAc,EACdC,SAAc,EACd;QAcIC,GAAa;IAbjB,8BAA8B;IAC9B,IAAI,OAAOF,MAAM,KAAK,QAAQ,EAAE;QAC9B,MAAM,IAAIG,KAAK,CAAC,uDAAuD,CAAC,CAAA;KACzE;IAED,MAAMC,QAAQ,GAAG,IAAI,CAACC,KAAK,EAAE;IAC7B,MAAMH,SAAS,GAAGP,kBAAkB,CAAC,IAAI,CAACW,OAAO,CAAC;IAClD,MAAMC,OAAO,GAAGb,gBAAgB,CAACM,MAAM,CAAC;IAExC,gDAAgD;IAChD,mEAAmE;IACnEE,SAAS,CAACM,GAAG,GAAG;QAAEC,IAAI,EAAEF,OAAO;KAAE;IAEjC,IAAIL,CAAAA,CAAAA,GAAa,GAAbA,SAAS,CAACM,GAAG,SAAM,GAAnBN,KAAAA,CAAmB,GAAnBA,GAAa,CAAEO,IAAI,CAAA,KAAKjB,gBAAgB,CAACkB,MAAM,EAAE;QACnD,OAAON,QAAQ,CAAC,IAAI,EAAEJ,MAAM,EAAEC,SAAS,CAAC,CAAA;KACzC;IAED,IAAIL,YAAY,KAAK,IAAI,CAACe,YAAY,EAAE;QACtClB,QAAQ,CACN,CAAC,+KAA+K,CAAC,CAClL;KACF;IACD,OAAOW,QAAQ,CAAC,IAAI,EAAEJ,MAAM,EAAEC,SAAS,CAAC,CAAA;CACzC,CAAA"}

View File

@@ -0,0 +1,94 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/ // Modified from https://github.com/facebook/react/blob/main/packages/react-server-dom-webpack/src/ReactFlightWebpackNodeRegister.js
const MODULE_REFERENCE = Symbol.for("react.module.reference");
const PROMISE_PROTOTYPE = Promise.prototype;
const proxyHandlers = {
get: function(target, name, _receiver) {
switch(name){
// These names are read by the Flight runtime if you end up using the exports object.
case "$$typeof":
// These names are a little too common. We should probably have a way to
// have the Flight runtime extract the inner target instead.
return target.$$typeof;
case "filepath":
return target.filepath;
case "name":
return target.name;
case "async":
return target.async;
// We need to special case this because createElement reads it if we pass this
// reference.
case "defaultProps":
return undefined;
case "__esModule":
// Something is conditionally checking which export to use. We'll pretend to be
// an ESM compat module but then we'll check again on the client.
target.default = {
$$typeof: MODULE_REFERENCE,
filepath: target.filepath,
// This a placeholder value that tells the client to conditionally use the
// whole object or just the default export.
name: "",
async: target.async
};
return true;
case "then":
if (!target.async) {
// If this module is expected to return a Promise (such as an AsyncModule) then
// we should resolve that with a client reference that unwraps the Promise on
// the client.
const then = function then(resolve, _reject) {
const moduleReference = {
$$typeof: MODULE_REFERENCE,
filepath: target.filepath,
name: "*",
async: true
};
return Promise.resolve(resolve(new Proxy(moduleReference, proxyHandlers)));
};
// If this is not used as a Promise but is treated as a reference to a `.then`
// export then we should treat it as a reference to that name.
then.$$typeof = MODULE_REFERENCE;
then.filepath = target.filepath;
// then.name is conveniently already "then" which is the export name we need.
// This will break if it's minified though.
return then;
}
break;
default:
break;
}
let cachedReference = target[name];
if (!cachedReference) {
cachedReference = target[name] = {
$$typeof: MODULE_REFERENCE,
filepath: target.filepath,
name: name,
async: target.async
};
}
return cachedReference;
},
getPrototypeOf (_target) {
// Pretend to be a Promise in case anyone asks.
return PROMISE_PROTOTYPE;
},
set: function() {
throw new Error("Cannot assign to a client module from a server module.");
}
};
export function createProxy(moduleId) {
const moduleReference = {
$$typeof: MODULE_REFERENCE,
filepath: moduleId,
name: "*",
async: false
};
return new Proxy(moduleReference, proxyHandlers);
}
//# sourceMappingURL=module-proxy.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../build/webpack/loaders/next-flight-loader/module-proxy.ts"],"names":["MODULE_REFERENCE","Symbol","for","PROMISE_PROTOTYPE","Promise","prototype","proxyHandlers","get","target","name","_receiver","$$typeof","filepath","async","undefined","default","then","resolve","_reject","moduleReference","Proxy","cachedReference","getPrototypeOf","_target","set","Error","createProxy","moduleId"],"mappings":"AAAA;;;;;GAKG,CAEH,oIAAoI;AAEpI,MAAMA,gBAAgB,GAAGC,MAAM,CAACC,GAAG,CAAC,wBAAwB,CAAC;AAC7D,MAAMC,iBAAiB,GAAGC,OAAO,CAACC,SAAS;AAE3C,MAAMC,aAAa,GAAyB;IAC1CC,GAAG,EAAE,SAAUC,MAAW,EAAEC,IAAY,EAAEC,SAAc,EAAE;QACxD,OAAQD,IAAI;YACV,qFAAqF;YACrF,KAAK,UAAU;gBACb,wEAAwE;gBACxE,4DAA4D;gBAC5D,OAAOD,MAAM,CAACG,QAAQ,CAAA;YACxB,KAAK,UAAU;gBACb,OAAOH,MAAM,CAACI,QAAQ,CAAA;YACxB,KAAK,MAAM;gBACT,OAAOJ,MAAM,CAACC,IAAI,CAAA;YACpB,KAAK,OAAO;gBACV,OAAOD,MAAM,CAACK,KAAK,CAAA;YACrB,8EAA8E;YAC9E,aAAa;YACb,KAAK,cAAc;gBACjB,OAAOC,SAAS,CAAA;YAClB,KAAK,YAAY;gBACf,+EAA+E;gBAC/E,iEAAiE;gBACjEN,MAAM,CAACO,OAAO,GAAG;oBACfJ,QAAQ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AE;QAC9B,+CAA+C;QAC/C,OAAOpB,iBAAiB,CAAA;KACzB;IACDqB,GAAG,EAAE,WAAY;QACf,MAAM,IAAIC,KAAK,CAAC,wDAAwD,CAAC,CAAA;KAC1E;CACF;AAED,OAAO,SAASC,WAAW,CAACC,QAAgB,EAAE;IAC5C,MAAMR,eAAe,GAAG;QACtBR,QAAQ,EAAEX,gBAAgB;QAC1BY,QAAQ,EAAEe,QAAQ;QAClBlB,IAAI,EAAE,GAAG;QACTI,KAAK,EAAE,KAAK;KACb;IACD,OAAO,IAAIO,KAAK,CAACD,eAAe,EAAEb,aAAa,CAAC,CAAA;CACjD"}

View File

@@ -0,0 +1,91 @@
import { promises as fs } from "fs";
import path from "path";
import chalk from "next/dist/compiled/chalk";
import loaderUtils from "next/dist/compiled/loader-utils3";
import postcssNextFontPlugin from "./postcss-next-font";
import { promisify } from "util";
import { CONFIG_FILES } from "../../../../shared/lib/constants";
export default async function nextFontLoader() {
const fontLoaderSpan = this.currentTraceSpan.traceChild("next-font-loader");
return fontLoaderSpan.traceAsyncFn(async ()=>{
const callback = this.async();
// next-swc next_font_loaders turns each font loader call into JSON
const { path: relativeFilePathFromRoot , import: functionName , arguments: data , variableName , } = JSON.parse(this.resourceQuery.slice(1));
// Throw error if @next/font is used in _document.js
if (/pages[\\/]_document\./.test(relativeFilePathFromRoot)) {
const err = new Error(`${chalk.bold("Cannot")} be used within ${chalk.cyan("pages/_document.js")}.`);
err.name = "NextFontError";
callback(err);
return;
}
const { isDev , isServer , assetPrefix , fontLoaderOptions , postcss: getPostcss , } = this.getOptions();
const nextConfigPaths = CONFIG_FILES.map((config)=>path.join(this.rootContext, config));
// Add next.config.js as a dependency, loaders must rerun in case options changed
await Promise.all(nextConfigPaths.map(async (configPath)=>{
const hasConfig = await fs.access(configPath).then(()=>true, ()=>false);
if (hasConfig) {
this.addDependency(configPath);
} else {
this.addMissingDependency(configPath);
}
}));
const emitFontFile = (content, ext, preload)=>{
const opts = {
context: this.rootContext,
content
};
const interpolatedName = loaderUtils.interpolateName(this, // Font files ending with .p.(woff|woff2|eot|ttf|otf) are preloaded
`static/media/[hash]${preload ? ".p" : ""}.${ext}`, opts);
const outputPath = `${assetPrefix}/_next/${interpolatedName}`;
if (!isServer) {
this.emitFile(interpolatedName, content, null);
}
return outputPath;
};
try {
const fontLoader = require(path.join(this.resourcePath, "../loader.js")).default;
let { css , fallbackFonts , adjustFontFallback , weight , style , variable } = await fontLoader({
functionName,
variableName,
data,
config: fontLoaderOptions,
emitFontFile,
resolve: (src)=>promisify(this.resolve)(path.dirname(path.join(this.rootContext, relativeFilePathFromRoot)), src.startsWith(".") ? src : `./${src}`),
isDev,
isServer,
loaderContext: this
});
const { postcss } = await getPostcss();
// Exports will be exported as is from css-loader instead of a CSS module export
const exports = [];
const fontFamilyHash = loaderUtils.getHashDigest(Buffer.from(css), "md5", "hex", 6);
// Add CSS classes, exports and make the font-family localy scoped by turning it unguessable
const result = await postcss(postcssNextFontPlugin({
exports,
fontFamilyHash,
fallbackFonts,
weight,
style,
adjustFontFallback,
variable
})).process(css, {
from: undefined
});
// Reuse ast in css-loader
const ast = {
type: "postcss",
version: result.processor.version,
root: result.root
};
callback(null, result.css, null, {
exports,
ast,
fontFamilyHash
});
} catch (err) {
callback(err);
}
});
};
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../build/webpack/loaders/next-font-loader/index.ts"],"names":["promises","fs","path","chalk","loaderUtils","postcssNextFontPlugin","promisify","CONFIG_FILES","nextFontLoader","fontLoaderSpan","currentTraceSpan","traceChild","traceAsyncFn","callback","async","relativeFilePathFromRoot","import","functionName","arguments","data","variableName","JSON","parse","resourceQuery","slice","test","err","Error","bold","cyan","name","isDev","isServer","assetPrefix","fontLoaderOptions","postcss","getPostcss","getOptions","nextConfigPaths","map","config","join","rootContext","Promise","all","configPath","hasConfig","access","then","addDependency","addMissingDependency","emitFontFile","content","ext","preload","opts","context","interpolatedName","interpolateName","outputPath","emitFile","fontLoader","require","resourcePath","default","css","fallbackFonts","adjustFontFallback","weight","style","variable","resolve","src","dirname","startsWith","loaderContext","exports","fontFamilyHash","getHashDigest","Buffer","from","result","process","undefined","ast","type","version","processor","root"],"mappings":"AAEA,SAASA,QAAQ,IAAIC,EAAE,QAAQ,IAAI,CAAA;AACnC,OAAOC,IAAI,MAAM,MAAM,CAAA;AACvB,OAAOC,KAAK,MAAM,0BAA0B,CAAA;AAC5C,OAAOC,WAAW,MAAM,kCAAkC,CAAA;AAC1D,OAAOC,qBAAqB,MAAM,qBAAqB,CAAA;AACvD,SAASC,SAAS,QAAQ,MAAM,CAAA;AAChC,SAASC,YAAY,QAAQ,kCAAkC,CAAA;AAE/D,eAAe,eAAeC,cAAc,GAAY;IACtD,MAAMC,cAAc,GAAG,IAAI,CAACC,gBAAgB,CAACC,UAAU,CAAC,kBAAkB,CAAC;IAC3E,OAAOF,cAAc,CAACG,YAAY,CAAC,UAAY;QAC7C,MAAMC,QAAQ,GAAG,IAAI,CAACC,KAAK,EAAE;QAE7B,mEAAmE;QACnE,MAAM,EACJZ,IAAI,EAAEa,wBAAwB,CAAA,EAC9BC,MAAM,EAAEC,YAAY,CAAA,EACpBC,SAAS,EAAEC,IAAI,CAAA,EACfC,YAAY,CAAA,IACb,GAAGC,IAAI,CAACC,KAAK,CAAC,IAAI,CAACC,aAAa,CAACC,KAAK,CAAC,CAAC,CAAC,CAAC;QAE3C,oDAAoD;QACpD,IAAI,wBAAwBC,IAAI,CAACV,wBAAwB,CAAC,EAAE;YAC1D,MAAMW,GAAG,GAAG,IAAIC,KAAK,CACnB,CAAC,EAAExB,KAAK,CAACyB,IAAI,CAAC,QAAQ,CAAC,CAAC,gBAAgB,EAAEzB,KAAK,CAAC0B,IAAI,CAClD,oBAAoB,CACrB,CAAC,CAAC,CAAC,CACL;YACDH,GAAG,CAACI,IAAI,GAAG,eAAe;YAC1BjB,QAAQ,CAACa,GAAG,CAAC;YACb,OAAM;SACP;QAED,MAAM,EAC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CAAC;YAEF,0BAA0B;YAC1B,MAAMC,GAAG,GAAG;gBACVC,IAAI,EAAE,SAAS;gBACfC,OAAO,EAAEL,MAAM,CAACM,SAAS,CAACD,OAAO;gBACjCE,IAAI,EAAEP,MAAM,CAACO,IAAI;aAClB;YACD3E,QAAQ,CAAC,IAAI,EAAEoE,MAAM,CAAChB,GAAG,EAAE,IAAI,EAAE;gBAC/BW,OAAO;gBACPQ,GAAG;gBACHP,cAAc;aACf,CAAC;SACH,CAAC,OAAOnD,GAAG,EAAO;YACjBb,QAAQ,CAACa,GAAG,CAAC;SACd;KACF,CAAC,CAAA;CACH,CAAA"}

View File

@@ -0,0 +1,134 @@
import postcss from "postcss";
const postcssNextFontPlugin = ({ exports , fontFamilyHash , fallbackFonts =[] , adjustFontFallback , variable , weight , style })=>{
return {
postcssPlugin: "postcss-next-font",
Once (root) {
let fontFamily;
const normalizeFamily = (family)=>{
return family.replace(/['"]/g, "");
};
const formatFamily = (family)=>{
// Turn the font family unguessable to make it localy scoped
return `'__${family.replace(/ /g, "_")}_${fontFamilyHash}'`;
};
// Hash font-family names
for (const node of root.nodes){
if (node.type === "atrule" && node.name === "font-face") {
const familyNode = node.nodes.find((decl)=>decl.prop === "font-family");
if (!familyNode) {
continue;
}
if (!fontFamily) {
fontFamily = normalizeFamily(familyNode.value);
}
familyNode.value = formatFamily(fontFamily);
}
}
if (!fontFamily) {
throw new Error("Font loaders must return one or more @font-face's");
}
// Add fallback font with override values
let adjustFontFallbackFamily;
if (adjustFontFallback) {
adjustFontFallbackFamily = formatFamily(`${fontFamily} Fallback`);
const fallbackFontFace = postcss.atRule({
name: "font-face"
});
const { fallbackFont , ascentOverride , descentOverride , lineGapOverride , sizeAdjust , } = adjustFontFallback;
fallbackFontFace.nodes = [
new postcss.Declaration({
prop: "font-family",
value: adjustFontFallbackFamily
}),
new postcss.Declaration({
prop: "src",
value: `local("${fallbackFont}")`
}),
...ascentOverride ? [
new postcss.Declaration({
prop: "ascent-override",
value: ascentOverride
}),
] : [],
...descentOverride ? [
new postcss.Declaration({
prop: "descent-override",
value: descentOverride
}),
] : [],
...lineGapOverride ? [
new postcss.Declaration({
prop: "line-gap-override",
value: lineGapOverride
}),
] : [],
...sizeAdjust ? [
new postcss.Declaration({
prop: "size-adjust",
value: sizeAdjust
}),
] : [],
];
root.nodes.push(fallbackFontFace);
}
// Variable fonts can define ranges of values
const isRange = (value)=>value.trim().includes(" ");
const formattedFontFamilies = [
formatFamily(fontFamily),
...adjustFontFallbackFamily ? [
adjustFontFallbackFamily
] : [],
...fallbackFonts,
].join(", ");
// Add class with family, weight and style
const classRule = new postcss.Rule({
selector: ".className"
});
classRule.nodes = [
new postcss.Declaration({
prop: "font-family",
value: formattedFontFamilies
}),
...weight && !isRange(weight) ? [
new postcss.Declaration({
prop: "font-weight",
value: weight
}),
] : [],
...style && !isRange(style) ? [
new postcss.Declaration({
prop: "font-style",
value: style
}),
] : [],
];
root.nodes.push(classRule);
// Add class that defines a variable with the font family
if (variable) {
const varialbeRule = new postcss.Rule({
selector: ".variable"
});
varialbeRule.nodes = [
new postcss.Declaration({
prop: variable,
value: formattedFontFamilies
}),
];
root.nodes.push(varialbeRule);
}
// Export @font-face values as is
exports.push({
name: "style",
value: {
fontFamily: formattedFontFamilies,
fontWeight: !Number.isNaN(Number(weight)) ? Number(weight) : undefined,
fontStyle: style && !isRange(style) ? style : undefined
}
});
}
};
};
postcssNextFontPlugin.postcss = true;
export default postcssNextFontPlugin;
//# sourceMappingURL=postcss-next-font.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../build/webpack/loaders/next-font-loader/postcss-next-font.ts"],"names":["postcss","postcssNextFontPlugin","exports","fontFamilyHash","fallbackFonts","adjustFontFallback","variable","weight","style","postcssPlugin","Once","root","fontFamily","normalizeFamily","family","replace","formatFamily","node","nodes","type","name","familyNode","find","decl","prop","value","Error","adjustFontFallbackFamily","fallbackFontFace","atRule","fallbackFont","ascentOverride","descentOverride","lineGapOverride","sizeAdjust","Declaration","push","isRange","trim","includes","formattedFontFamilies","join","classRule","Rule","selector","varialbeRule","fontWeight","Number","isNaN","undefined","fontStyle"],"mappings":"AACA,OAAOA,OAAO,MAAuB,SAAS,CAAA;AAE9C,MAAMC,qBAAqB,GAAG,CAAC,EAC7BC,OAAO,CAAA,EACPC,cAAc,CAAA,EACdC,aAAa,EAAG,EAAE,CAAA,EAClBC,kBAAkB,CAAA,EAClBC,QAAQ,CAAA,EACRC,MAAM,CAAA,EACNC,KAAK,CAAA,EASN,GAAK;IACJ,OAAO;QACLC,aAAa,EAAE,mBAAmB;QAClCC,IAAI,EAACC,IAAS,EAAE;YACd,IAAIC,UAAU,AAAoB;YAElC,MAAMC,eAAe,GAAG,CAACC,MAAc,GAAK;gBAC1C,OAAOA,MAAM,CAACC,OAAO,UAAU,EAAE,CAAC,CAAA;aACnC;YAED,MAAMC,YAAY,GAAG,CAACF,MAAc,GAAK;gBACvC,4DAA4D;gBAC5D,OAAO,CAAC,GAAG,EAAEA,MAAM,CAACC,OAAO,OAAO,GAAG,CAAC,CAAC,CAAC,EAAEZ,cAAc,CAAC,CAAC,CAAC,CAAA;aAC5D;YAED,yBAAyB;YACzB,KAAK,MAAMc,IAAI,IAAIN,IAAI,CAACO,KAAK,CAAE;gBAC7B,IAAID,IAAI,CAACE,IAAI,KAAK,QAAQ,IAAIF,IAAI,CAACG,IAAI,KAAK,WAAW,EAAE;oBACvD,MAAMC,UAAU,GAAGJ,IAAI,CAACC,KAAK,CAACI,IAAI,CAChC,CAACC,IAAiB,GAAKA,IAAI,CAACC,IAAI,KAAK,aAAa,CACnD;oBACD,IAAI,CAACH,UAAU,EAAE;wBACf,SAAQ;qBACT;oBAED,IAAI,CAACT,UAAU,EAAE;wBACfA,UAAU,GAAGC,eAAe,CAACQ,UAAU,CAACI,KAAK,CAAC;qBAC/C;oBAEDJ,UAAU,CAACI,KAAK,GAAGT,YAAY,CAACJ,UAAU,CAAC;iBAC5C;aACF;YAED,IAAI,CAACA,U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AC;oBAAEC,QAAQ,EAAE,WAAW;iBAAE,CAAC;gBAChEC,YAAY,CAAC3B,KAAK,GAAG;oBACnB,IAAIlB,OAAO,CAACmC,WAAW,CAAC;wBACtBX,IAAI,EAAElB,QAAQ;wBACdmB,KAAK,EAAEe,qBAAqB;qBAC7B,CAAC;iBACH;gBACD7B,IAAI,CAACO,KAAK,CAACkB,IAAI,CAACS,YAAY,CAAC;aAC9B;YAED,iCAAiC;YACjC3C,OAAO,CAACkC,IAAI,CAAC;gBACXhB,IAAI,EAAE,OAAO;gBACbK,KAAK,EAAE;oBACLb,UAAU,EAAE4B,qBAAqB;oBACjCM,UAAU,EAAE,CAACC,MAAM,CAACC,KAAK,CAACD,MAAM,CAACxC,MAAM,CAAC,CAAC,GACrCwC,MAAM,CAACxC,MAAM,CAAC,GACd0C,SAAS;oBACbC,SAAS,EAAE1C,KAAK,IAAI,CAAC6B,OAAO,CAAC7B,KAAK,CAAC,GAAGA,KAAK,GAAGyC,SAAS;iBACxD;aACF,CAAC;SACH;KACF,CAAA;CACF;AAEDhD,qBAAqB,CAACD,OAAO,GAAG,IAAI;AAEpC,eAAeC,qBAAqB,CAAA"}

View File

@@ -0,0 +1,93 @@
import isAnimated from "next/dist/compiled/is-animated";
import loaderUtils from "next/dist/compiled/loader-utils3";
import { optimizeImage, getImageSize } from "../../../server/image-optimizer";
const BLUR_IMG_SIZE = 8;
const BLUR_QUALITY = 70;
const VALID_BLUR_EXT = [
"jpeg",
"png",
"webp",
"avif"
] // should match next/client/image.tsx
;
function nextImageLoader(content) {
const imageLoaderSpan = this.currentTraceSpan.traceChild("next-image-loader");
return imageLoaderSpan.traceAsyncFn(async ()=>{
const options = this.getOptions();
const { isServer , isDev , assetPrefix , basePath } = options;
const context = this.rootContext;
const opts = {
context,
content
};
const interpolatedName = loaderUtils.interpolateName(this, "/static/media/[name].[hash:8].[ext]", opts);
const outputPath = assetPrefix + "/_next" + interpolatedName;
let extension = loaderUtils.interpolateName(this, "[ext]", opts);
if (extension === "jpg") {
extension = "jpeg";
}
const imageSizeSpan = imageLoaderSpan.traceChild("image-size-calculation");
const imageSize = await imageSizeSpan.traceAsyncFn(()=>getImageSize(content, extension).catch((err)=>err));
if (imageSize instanceof Error) {
const err = imageSize;
err.name = "InvalidImageFormatError";
throw err;
}
let blurDataURL;
let blurWidth;
let blurHeight;
if (VALID_BLUR_EXT.includes(extension)) {
// Shrink the image's largest dimension
if (imageSize.width >= imageSize.height) {
blurWidth = BLUR_IMG_SIZE;
blurHeight = Math.max(Math.round(imageSize.height / imageSize.width * BLUR_IMG_SIZE), 1);
} else {
blurWidth = Math.max(Math.round(imageSize.width / imageSize.height * BLUR_IMG_SIZE), 1);
blurHeight = BLUR_IMG_SIZE;
}
if (isDev) {
// During `next dev`, we don't want to generate blur placeholders with webpack
// because it can delay starting the dev server. Instead, we inline a
// special url to lazily generate the blur placeholder at request time.
const prefix = "http://localhost";
const url = new URL(`${basePath || ""}/_next/image`, prefix);
url.searchParams.set("url", outputPath);
url.searchParams.set("w", String(blurWidth));
url.searchParams.set("q", String(BLUR_QUALITY));
blurDataURL = url.href.slice(prefix.length);
} else {
const resizeImageSpan = imageLoaderSpan.traceChild("image-resize");
const resizedImage = await resizeImageSpan.traceAsyncFn(()=>{
if (isAnimated(content)) {
return content;
}
return optimizeImage({
buffer: content,
width: blurWidth,
height: blurHeight,
contentType: `image/${extension}`,
quality: BLUR_QUALITY
});
});
const blurDataURLSpan = imageLoaderSpan.traceChild("image-base64-tostring");
blurDataURL = blurDataURLSpan.traceFn(()=>`data:image/${extension};base64,${resizedImage.toString("base64")}`);
}
}
const stringifiedData = imageLoaderSpan.traceChild("image-data-stringify").traceFn(()=>JSON.stringify({
src: outputPath,
height: imageSize.height,
width: imageSize.width,
blurDataURL,
blurWidth,
blurHeight
}));
if (isServer) {
this.emitFile(`../${isDev ? "" : "../"}${interpolatedName}`, content, null);
}
return `export default ${stringifiedData};`;
});
}
export const raw = true;
export default nextImageLoader;
//# sourceMappingURL=next-image-loader.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/webpack/loaders/next-image-loader.ts"],"names":["isAnimated","loaderUtils","optimizeImage","getImageSize","BLUR_IMG_SIZE","BLUR_QUALITY","VALID_BLUR_EXT","nextImageLoader","content","imageLoaderSpan","currentTraceSpan","traceChild","traceAsyncFn","options","getOptions","isServer","isDev","assetPrefix","basePath","context","rootContext","opts","interpolatedName","interpolateName","outputPath","extension","imageSizeSpan","imageSize","catch","err","Error","name","blurDataURL","blurWidth","blurHeight","includes","width","height","Math","max","round","prefix","url","URL","searchParams","set","String","href","slice","length","resizeImageSpan","resizedImage","buffer","contentType","quality","blurDataURLSpan","traceFn","toString","stringifiedData","JSON","stringify","src","emitFile","raw"],"mappings":"AAAA,OAAOA,UAAU,MAAM,gCAAgC,CAAA;AACvD,OAAOC,WAAW,MAAM,kCAAkC,CAAA;AAC1D,SAASC,aAAa,EAAEC,YAAY,QAAQ,iCAAiC,CAAA;AAE7E,MAAMC,aAAa,GAAG,CAAC;AACvB,MAAMC,YAAY,GAAG,EAAE;AACvB,MAAMC,cAAc,GAAG;IAAC,MAAM;IAAE,KAAK;IAAE,MAAM;IAAE,MAAM;CAAC,CAAC,qCAAqC;AAAtC;AAStD,SAASC,eAAe,CAAYC,OAAe,EAAE;IACnD,MAAMC,eAAe,GAAG,IAAI,CAACC,gBAAgB,CAACC,UAAU,CAAC,mBAAmB,CAAC;IAC7E,OAAOF,eAAe,CAACG,YAAY,CAAC,UAAY;QAC9C,MAAMC,OAAO,GAAY,IAAI,CAACC,UAAU,EAAE;QAC1C,MAAM,EAAEC,QAAQ,CAAA,EAAEC,KAAK,CAAA,EAAEC,WAAW,CAAA,EAAEC,QAAQ,CAAA,EAAE,GAAGL,OAAO;QAC1D,MAAMM,OAAO,GAAG,IAAI,CAACC,WAAW;QAChC,MAAMC,IAAI,GAAG;YAAEF,OAAO;YAAEX,OAAO;SAAE;QACjC,MAAMc,gBAAgB,GAAGrB,WAAW,CA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,CAAC,CAAC,CAAC,CACtE;aACF;SACF;QAED,MAAMC,eAAe,GAAGjD,eAAe,CACpCE,UAAU,CAAC,sBAAsB,CAAC,CAClC6C,OAAO,CAAC,IACPG,IAAI,CAACC,SAAS,CAAC;gBACbC,GAAG,EAAErC,UAAU;gBACfa,MAAM,EAAEV,SAAS,CAACU,MAAM;gBACxBD,KAAK,EAAET,SAAS,CAACS,KAAK;gBACtBJ,WAAW;gBACXC,SAAS;gBACTC,UAAU;aACX,CAAC,CACH;QAEH,IAAInB,QAAQ,EAAE;YACZ,IAAI,CAAC+C,QAAQ,CACX,CAAC,GAAG,EAAE9C,KAAK,GAAG,EAAE,GAAG,KAAK,CAAC,EAAEM,gBAAgB,CAAC,CAAC,EAC7Cd,OAAO,EACP,IAAI,CACL;SACF;QAED,OAAO,CAAC,eAAe,EAAEkD,eAAe,CAAC,CAAC,CAAC,CAAA;KAC5C,CAAC,CAAA;CACH;AACD,OAAO,MAAMK,GAAG,GAAG,IAAI,CAAA;AACvB,eAAexD,eAAe,CAAA"}

View File

@@ -0,0 +1,19 @@
import loaderUtils from "next/dist/compiled/loader-utils3";
import { getModuleBuildInfo } from "./get-module-build-info";
export default function MiddlewareAssetLoader(source) {
const name = loaderUtils.interpolateName(this, "[name].[hash].[ext]", {
context: this.rootContext,
content: source
});
const filePath = `edge-chunks/asset_${name}`;
const buildInfo = getModuleBuildInfo(this._module);
buildInfo.nextAssetMiddlewareBinding = {
filePath: `server/${filePath}`,
name
};
this.emitFile(filePath, source);
return `module.exports = ${JSON.stringify(`blob:${name}`)}`;
};
export const raw = true;
//# sourceMappingURL=next-middleware-asset-loader.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/webpack/loaders/next-middleware-asset-loader.ts"],"names":["loaderUtils","getModuleBuildInfo","MiddlewareAssetLoader","source","name","interpolateName","context","rootContext","content","filePath","buildInfo","_module","nextAssetMiddlewareBinding","emitFile","JSON","stringify","raw"],"mappings":"AAAA,OAAOA,WAAW,MAAM,kCAAkC,CAAA;AAC1D,SAASC,kBAAkB,QAAQ,yBAAyB,CAAA;AAE5D,eAAe,SAASC,qBAAqB,CAAYC,MAAc,EAAE;IACvE,MAAMC,IAAI,GAAGJ,WAAW,CAACK,eAAe,CAAC,IAAI,EAAE,qBAAqB,EAAE;QACpEC,OAAO,EAAE,IAAI,CAACC,WAAW;QACzBC,OAAO,EAAEL,MAAM;KAChB,CAAC;IACF,MAAMM,QAAQ,GAAG,CAAC,kBAAkB,EAAEL,IAAI,CAAC,CAAC;IAC5C,MAAMM,SAAS,GAAGT,kBAAkB,CAAC,IAAI,CAACU,OAAO,CAAC;IAClDD,SAAS,CAACE,0BAA0B,GAAG;QACrCH,QAAQ,EAAE,CAAC,OAAO,EAAEA,QAAQ,CAAC,CAAC;QAC9BL,IAAI;KACL;IACD,IAAI,CAACS,QAAQ,CAACJ,QAAQ,EAAEN,MAAM,CAAC;IAC/B,OAAO,CAAC,iBAAiB,EAAEW,IAAI,CAACC,SAAS,CAAC,CAAC,KAAK,EAAEX,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;CAC5D,CAAA;AAED,OAAO,MAAMY,GAAG,GAAG,IAAI,CAAA"}

View File

@@ -0,0 +1,44 @@
import { getModuleBuildInfo } from "./get-module-build-info";
import { stringifyRequest } from "../stringify-request";
import { MIDDLEWARE_LOCATION_REGEXP } from "../../../lib/constants";
// matchers can have special characters that break the loader params
// parsing so we base64 encode/decode the string
export function encodeMatchers(matchers) {
return Buffer.from(JSON.stringify(matchers)).toString("base64");
}
export function decodeMatchers(encodedMatchers) {
return JSON.parse(Buffer.from(encodedMatchers, "base64").toString());
}
export default function middlewareLoader() {
const { absolutePagePath , page , rootDir , matchers: encodedMatchers , } = this.getOptions();
const matchers = encodedMatchers ? decodeMatchers(encodedMatchers) : undefined;
const stringifiedPagePath = stringifyRequest(this, absolutePagePath);
const buildInfo = getModuleBuildInfo(this._module);
buildInfo.nextEdgeMiddleware = {
matchers,
page: page.replace(new RegExp(`/${MIDDLEWARE_LOCATION_REGEXP}$`), "") || "/"
};
buildInfo.rootDir = rootDir;
return `
import { adapter, enhanceGlobals } from 'next/dist/esm/server/web/adapter'
enhanceGlobals()
var mod = require(${stringifiedPagePath})
var handler = mod.middleware || mod.default;
if (typeof handler !== 'function') {
throw new Error('The Middleware "pages${page}" must export a \`middleware\` or a \`default\` function');
}
export default function (opts) {
return adapter({
...opts,
page: ${JSON.stringify(page)},
handler,
})
}
`;
};
//# sourceMappingURL=next-middleware-loader.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/webpack/loaders/next-middleware-loader.ts"],"names":["getModuleBuildInfo","stringifyRequest","MIDDLEWARE_LOCATION_REGEXP","encodeMatchers","matchers","Buffer","from","JSON","stringify","toString","decodeMatchers","encodedMatchers","parse","middlewareLoader","absolutePagePath","page","rootDir","getOptions","undefined","stringifiedPagePath","buildInfo","_module","nextEdgeMiddleware","replace","RegExp"],"mappings":"AACA,SAASA,kBAAkB,QAAQ,yBAAyB,CAAA;AAC5D,SAASC,gBAAgB,QAAQ,sBAAsB,CAAA;AACvD,SAASC,0BAA0B,QAAQ,wBAAwB,CAAA;AASnE,oEAAoE;AACpE,gDAAgD;AAChD,OAAO,SAASC,cAAc,CAACC,QAA6B,EAAE;IAC5D,OAAOC,MAAM,CAACC,IAAI,CAACC,IAAI,CAACC,SAAS,CAACJ,QAAQ,CAAC,CAAC,CAACK,QAAQ,CAAC,QAAQ,CAAC,CAAA;CAChE;AAED,OAAO,SAASC,cAAc,CAACC,eAAuB,EAAE;IACtD,OAAOJ,IAAI,CAACK,KAAK,CACfP,MAAM,CAACC,IAAI,CAACK,eAAe,EAAE,QAAQ,CAAC,CAACF,QAAQ,EAAE,CAClD,CAAuB;CACzB;AAED,eAAe,SAASI,gBAAgB,GAAY;IAClD,MAAM,EACJC,gBAAgB,CAAA,EAChBC,IAAI,CAAA,EACJC,OAAO,CAAA,EACPZ,QAAQ,EAAEO,eAAe,CAAA,IAC1B,GAA4B,IAAI,CAACM,UAAU,EAAE;IAC9C,MAAMb,QAAQ,GAAGO,eAAe,GAAGD,cAAc,CAACC,eAAe,CAAC,GAAGO,SAAS;IAC9E,MAAMC,mBAAmB,GAAGlB,gBAAgB,CAAC,IAAI,EAAEa,gBAAgB,CAAC;IACpE,MAAMM,SAAS,GAAGpB,kBAAkB,CAAC,IAAI,CAACqB,OAAO,CAAC;IAClDD,SAAS,CAACE,kBAAkB,GAAG;QAC7BlB,QAAQ;QACRW,IAAI,EACFA,IAAI,CAACQ,OAAO,CAAC,IAAIC,MAAM,CAAC,CAAC,CAAC,EAAEtB,0BAA0B,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,GAAG;KACzE;IACDkB,SAAS,CAACJ,OAAO,GAAGA,OAAO;IAE3B,OAAO,CAAC;;;;;0BAKgB,EAAEG,mBAAmB,CAAC;;;;gDAIA,EAAEJ,IAAI,CAAC;;;;;;oBAMnC,EAAER,IAAI,CAACC,SAAS,CAACO,IAAI,CAAC,CAAC;;;;IAIvC,CAAC,CAAA;CACJ,CAAA"}

View File

@@ -0,0 +1,19 @@
import { getModuleBuildInfo } from "./get-module-build-info";
import crypto from "crypto";
function sha1(source) {
return crypto.createHash("sha1").update(source).digest("hex");
}
export default function MiddlewareWasmLoader(source) {
const name = `wasm_${sha1(source)}`;
const filePath = `edge-chunks/${name}.wasm`;
const buildInfo = getModuleBuildInfo(this._module);
buildInfo.nextWasmMiddlewareBinding = {
filePath: `server/${filePath}`,
name
};
this.emitFile(`/${filePath}`, source, null);
return `module.exports = ${name};`;
};
export const raw = true;
//# sourceMappingURL=next-middleware-wasm-loader.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/webpack/loaders/next-middleware-wasm-loader.ts"],"names":["getModuleBuildInfo","crypto","sha1","source","createHash","update","digest","MiddlewareWasmLoader","name","filePath","buildInfo","_module","nextWasmMiddlewareBinding","emitFile","raw"],"mappings":"AAAA,SAASA,kBAAkB,QAAQ,yBAAyB,CAAA;AAC5D,OAAOC,MAAM,MAAM,QAAQ,CAAA;AAE3B,SAASC,IAAI,CAACC,MAAuB,EAAE;IACrC,OAAOF,MAAM,CAACG,UAAU,CAAC,MAAM,CAAC,CAACC,MAAM,CAACF,MAAM,CAAC,CAACG,MAAM,CAAC,KAAK,CAAC,CAAA;CAC9D;AAED,eAAe,SAASC,oBAAoB,CAAYJ,MAAc,EAAE;IACtE,MAAMK,IAAI,GAAG,CAAC,KAAK,EAAEN,IAAI,CAACC,MAAM,CAAC,CAAC,CAAC;IACnC,MAAMM,QAAQ,GAAG,CAAC,YAAY,EAAED,IAAI,CAAC,KAAK,CAAC;IAC3C,MAAME,SAAS,GAAGV,kBAAkB,CAAC,IAAI,CAACW,OAAO,CAAC;IAClDD,SAAS,CAACE,yBAAyB,GAAG;QAAEH,QAAQ,EAAE,CAAC,OAAO,EAAEA,QAAQ,CAAC,CAAC;QAAED,IAAI;KAAE;IAC9E,IAAI,CAACK,QAAQ,CAAC,CAAC,CAAC,EAAEJ,QAAQ,CAAC,CAAC,EAAEN,MAAM,EAAE,IAAI,CAAC;IAC3C,OAAO,CAAC,iBAAiB,EAAEK,IAAI,CAAC,CAAC,CAAC,CAAA;CACnC,CAAA;AAED,OAAO,MAAMM,GAAG,GAAG,IAAI,CAAA"}

View File

@@ -0,0 +1,42 @@
import { parse as parseUrl } from "url";
import { IncomingMessage, ServerResponse } from "http";
import { apiResolver } from "../../../../server/api-utils/node";
import { getUtils, vercelHeader } from "./utils";
import { DecodeError } from "../../../../shared/lib/utils";
import { NodeNextResponse, NodeNextRequest } from "../../../../server/base-http/node";
export function getApiHandler(ctx) {
const { pageModule , encodedPreviewProps , pageIsDynamic } = ctx;
const { handleRewrites , handleBasePath , dynamicRouteMatcher , normalizeDynamicRouteParams , } = getUtils(ctx);
return async (rawReq, rawRes)=>{
const req = rawReq instanceof IncomingMessage ? new NodeNextRequest(rawReq) : rawReq;
const res = rawRes instanceof ServerResponse ? new NodeNextResponse(rawRes) : rawRes;
try {
// We need to trust the dynamic route params from the proxy
// to ensure we are using the correct values
const trustQuery = req.headers[vercelHeader];
const parsedUrl = parseUrl(req.url, true);
handleRewrites(req, parsedUrl);
if (parsedUrl.query.nextInternalLocale) {
delete parsedUrl.query.nextInternalLocale;
}
handleBasePath(req, parsedUrl);
let params = {};
if (pageIsDynamic) {
const result = normalizeDynamicRouteParams(trustQuery ? parsedUrl.query : dynamicRouteMatcher(parsedUrl.pathname));
params = result.params;
}
await apiResolver(req.originalRequest, res.originalResponse, Object.assign({}, parsedUrl.query, params), await pageModule, encodedPreviewProps, true);
} catch (err) {
console.error(err);
if (err instanceof DecodeError) {
res.statusCode = 400;
res.body("Bad Request").send();
} else {
// Throw the error to crash the serverless function
throw err;
}
}
};
}
//# sourceMappingURL=api-handler.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../build/webpack/loaders/next-serverless-loader/api-handler.ts"],"names":["parse","parseUrl","IncomingMessage","ServerResponse","apiResolver","getUtils","vercelHeader","DecodeError","NodeNextResponse","NodeNextRequest","getApiHandler","ctx","pageModule","encodedPreviewProps","pageIsDynamic","handleRewrites","handleBasePath","dynamicRouteMatcher","normalizeDynamicRouteParams","rawReq","rawRes","req","res","trustQuery","headers","parsedUrl","url","query","nextInternalLocale","params","result","pathname","originalRequest","originalResponse","Object","assign","err","console","error","statusCode","body","send"],"mappings":"AAAA,SAASA,KAAK,IAAIC,QAAQ,QAAQ,KAAK,CAAA;AACvC,SAASC,eAAe,EAAEC,cAAc,QAAQ,MAAM,CAAA;AACtD,SAASC,WAAW,QAAQ,mCAAmC,CAAA;AAC/D,SAASC,QAAQ,EAAEC,YAAY,QAA8B,SAAS,CAAA;AACtE,SAASC,WAAW,QAAQ,8BAA8B,CAAA;AAC1D,SACEC,gBAAgB,EAChBC,eAAe,QACV,mCAAmC,CAAA;AAE1C,OAAO,SAASC,aAAa,CAACC,GAAyB,EAAE;IACvD,MAAM,EAAEC,UAAU,CAAA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U,EAChBC,mBAAmB,EACnB,IAAI,CACL;SACF,CAAC,OAAOuB,GAAG,EAAE;YACZC,OAAO,CAACC,KAAK,CAACF,GAAG,CAAC;YAElB,IAAIA,GAAG,YAAY7B,WAAW,EAAE;gBAC9Be,GAAG,CAACiB,UAAU,GAAG,GAAG;gBACpBjB,GAAG,CAACkB,IAAI,CAAC,aAAa,CAAC,CAACC,IAAI,EAAE;aAC/B,MAAM;gBACL,mDAAmD;gBACnD,MAAML,GAAG,CAAA;aACV;SACF;KACF,CAAA;CACF"}

View File

@@ -0,0 +1,134 @@
import devalue from "next/dist/compiled/devalue";
import { join } from "path";
import { parse } from "querystring";
import { isAPIRoute } from "../../../../lib/is-api-route";
import { isDynamicRoute } from "../../../../shared/lib/router/utils";
import { escapeStringRegexp } from "../../../../shared/lib/escape-regexp";
import { BUILD_MANIFEST, ROUTES_MANIFEST, REACT_LOADABLE_MANIFEST } from "../../../../shared/lib/constants";
import { stringifyRequest } from "../../stringify-request";
const nextServerlessLoader = function() {
const { distDir , absolutePagePath , page , buildId , canonicalBase , assetPrefix , absoluteAppPath , absoluteDocumentPath , absoluteErrorPath , absolute404Path , generateEtags , poweredByHeader , basePath , runtimeConfig , previewProps , loadedEnvFiles , i18n , } = typeof this.query === "string" ? parse(this.query.slice(1)) : this.query;
const buildManifest = join(distDir, BUILD_MANIFEST).replace(/\\/g, "/");
const reactLoadableManifest = join(distDir, REACT_LOADABLE_MANIFEST).replace(/\\/g, "/");
const routesManifest = join(distDir, ROUTES_MANIFEST).replace(/\\/g, "/");
const escapedBuildId = escapeStringRegexp(buildId);
const pageIsDynamicRoute = isDynamicRoute(page);
const encodedPreviewProps = devalue(JSON.parse(previewProps));
const envLoading = `
const { processEnv } = require('@next/env')
processEnv(${Buffer.from(loadedEnvFiles, "base64").toString()})
`;
const runtimeConfigImports = runtimeConfig ? `
const { setConfig } = require('next/config')
` : "";
const runtimeConfigSetter = runtimeConfig ? `
const runtimeConfig = ${runtimeConfig}
setConfig(runtimeConfig)
` : "const runtimeConfig = {}";
if (isAPIRoute(page)) {
return `
${envLoading}
${runtimeConfigImports}
${/*
this needs to be called first so its available for any other imports
*/ runtimeConfigSetter}
import 'next/dist/server/node-polyfill-fetch'
import routesManifest from '${routesManifest}'
import { getApiHandler } from 'next/dist/build/webpack/loaders/next-serverless-loader/api-handler'
const rewrites = Array.isArray(routesManifest.rewrites)
? {
afterFiles: routesManifest.rewrites
}
: routesManifest.rewrites
const apiHandler = getApiHandler({
pageModule: require(${stringifyRequest(this, absolutePagePath)}),
rewrites: rewrites,
i18n: ${i18n || "undefined"},
page: "${page}",
basePath: "${basePath}",
pageIsDynamic: ${pageIsDynamicRoute},
encodedPreviewProps: ${encodedPreviewProps}
})
export default apiHandler
`;
} else {
return `
import 'next/dist/server/node-polyfill-fetch'
import routesManifest from '${routesManifest}'
import buildManifest from '${buildManifest}'
import reactLoadableManifest from '${reactLoadableManifest}'
${envLoading}
${runtimeConfigImports}
${// this needs to be called first so its available for any other imports
runtimeConfigSetter}
import { getPageHandler } from 'next/dist/build/webpack/loaders/next-serverless-loader/page-handler'
const documentModule = require(${stringifyRequest(this, absoluteDocumentPath)})
const appMod = require(${stringifyRequest(this, absoluteAppPath)})
let App = appMod.default || appMod.then && appMod.then(mod => mod.default);
const compMod = require(${stringifyRequest(this, absolutePagePath)})
const Component = compMod.default || compMod.then && compMod.then(mod => mod.default)
export default Component
export const getStaticProps = compMod['getStaticProp' + 's'] || compMod.then && compMod.then(mod => mod['getStaticProp' + 's'])
export const getStaticPaths = compMod['getStaticPath' + 's'] || compMod.then && compMod.then(mod => mod['getStaticPath' + 's'])
export const getServerSideProps = compMod['getServerSideProp' + 's'] || compMod.then && compMod.then(mod => mod['getServerSideProp' + 's'])
// kept for detecting legacy exports
export const unstable_getStaticParams = compMod['unstable_getStaticParam' + 's'] || compMod.then && compMod.then(mod => mod['unstable_getStaticParam' + 's'])
export const unstable_getStaticProps = compMod['unstable_getStaticProp' + 's'] || compMod.then && compMod.then(mod => mod['unstable_getStaticProp' + 's'])
export const unstable_getStaticPaths = compMod['unstable_getStaticPath' + 's'] || compMod.then && compMod.then(mod => mod['unstable_getStaticPath' + 's'])
export const unstable_getServerProps = compMod['unstable_getServerProp' + 's'] || compMod.then && compMod.then(mod => mod['unstable_getServerProp' + 's'])
export let config = compMod['confi' + 'g'] || (compMod.then && compMod.then(mod => mod['confi' + 'g'])) || {}
export const _app = App
const rewrites = Array.isArray(routesManifest.rewrites)
? {
afterFiles: routesManifest.rewrites
}
: routesManifest.rewrites
const { renderReqToHTML, render } = getPageHandler({
pageModule: compMod,
pageComponent: Component,
pageConfig: config,
appModule: App,
documentModule: documentModule,
errorModule: require(${stringifyRequest(this, absoluteErrorPath)}),
notFoundModule: ${absolute404Path ? `require(${stringifyRequest(this, absolute404Path)})` : undefined},
pageGetStaticProps: getStaticProps,
pageGetStaticPaths: getStaticPaths,
pageGetServerSideProps: getServerSideProps,
assetPrefix: "${assetPrefix}",
canonicalBase: "${canonicalBase}",
generateEtags: ${generateEtags || "false"},
poweredByHeader: ${poweredByHeader || "false"},
runtimeConfig,
buildManifest,
reactLoadableManifest,
rewrites: rewrites,
i18n: ${i18n || "undefined"},
page: "${page}",
buildId: "${buildId}",
escapedBuildId: "${escapedBuildId}",
basePath: "${basePath}",
pageIsDynamic: ${pageIsDynamicRoute},
encodedPreviewProps: ${encodedPreviewProps}
})
export { renderReqToHTML, render }
`;
}
};
export default nextServerlessLoader;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../build/webpack/loaders/next-serverless-loader/index.ts"],"names":["devalue","join","parse","isAPIRoute","isDynamicRoute","escapeStringRegexp","BUILD_MANIFEST","ROUTES_MANIFEST","REACT_LOADABLE_MANIFEST","stringifyRequest","nextServerlessLoader","distDir","absolutePagePath","page","buildId","canonicalBase","assetPrefix","absoluteAppPath","absoluteDocumentPath","absoluteErrorPath","absolute404Path","generateEtags","poweredByHeader","basePath","runtimeConfig","previewProps","loadedEnvFiles","i18n","query","slice","buildManifest","replace","reactLoadableManifest","routesManifest","escapedBuildId","pageIsDynamicRoute","encodedPreviewProps","JSON","envLoading","Buffer","from","toString","runtimeConfigImports","runtimeConfigSetter","undefined"],"mappings":"AAAA,OAAOA,OAAO,MAAM,4BAA4B,CAAA;AAChD,SAASC,IAAI,QAAQ,MAAM,CAAA;AAC3B,SAASC,KAAK,QAAQ,aAAa,CAAA;AAEnC,SAASC,UAAU,QAAQ,8BAA8B,CAAA;AACzD,SAASC,cAAc,QAAQ,qCAAqC,CAAA;AACpE,SAASC,kBAAkB,QAAQ,sCAAsC,CAAA;AAEzE,SACEC,cAAc,EACdC,eAAe,EACfC,uBAAuB,QAClB,kCAAkC,CAAA;AACzC,SAASC,gBAAgB,QAAQ,yBAAyB,CAAA;AAsB1D,MAAMC,oBAAoB,GAAqC,WAAY;IACzE,MAAM,EACJC,OAAO,CAAA,EACPC,gBAAgB,CAAA,EAChBC,IAAI,CAAA,EACJC,OAAO,CAAA,EACPC,aAAa,CAAA,EACbC,WAAW,CAAA,EACXC,eAAe,CAAA,EACfC,oBAAoB,CAAA,EACpBC,iBAAiB,CAAA,EACjBC,eAAe,CAAA,EACfC,aAAa,CAAA,EACbC,eAAe,CAAA,EACfC,QAAQ,CAAA,EACRC,aAAa,CAAA,EACbC,YAAY,CAAA,EACZC,cAAc,CAAA,EACdC,IAAI,CAAA,IACL,GACC,OAAO,IAAI,CAACC,KAAK,KAAK,QAAQ,GAAG1B,KAAK,CAAC,IAAI,CAAC0B,KAAK,CAACC,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,CAACD,KAAK,AAClE;IAER,MAAME,aAAa,GAAG7B,IAAI,CAACU,OAAO,EAAEL,cAAc,CAAC,CAACyB,OAAO,QAAQ,GAAG,CAAC;IACvE,MAAMC,qBAAqB,GAAG/B,IAAI,CAACU,OAAO,EAAEH,uBAAuB,CAAC,CAACuB,OAAO,QAE1E,GAAG,CACJ;IACD,MAAME,cAAc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G8B,EAAElC,gBAAgB,CAC/C,IAAI,EACJS,oBAAoB,CACrB,CAAC;;6BAEqB,EAAET,gBAAgB,CAAC,IAAI,EAAEQ,eAAe,CAAC,CAAC;;;8BAGzC,EAAER,gBAAgB,CAAC,IAAI,EAAEG,gBAAgB,CAAC,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;6BA6B5C,EAAEH,gBAAgB,CAAC,IAAI,EAAEU,iBAAiB,CAAC,CAAC;wBACjD,EACdC,eAAe,GACX,CAAC,QAAQ,EAAEX,gBAAgB,CAAC,IAAI,EAAEW,eAAe,CAAC,CAAC,CAAC,CAAC,GACrDwB,SAAS,CACd;;;;;sBAKa,EAAE5B,WAAW,CAAC;wBACZ,EAAED,aAAa,CAAC;uBACjB,EAAEM,aAAa,IAAI,OAAO,CAAC;yBACzB,EAAEC,eAAe,IAAI,OAAO,CAAC;;;;;;;cAOxC,EAAEK,IAAI,IAAI,WAAW,CAAC;eACrB,EAAEd,IAAI,CAAC;kBACJ,EAAEC,OAAO,CAAC;yBACH,EAAEoB,cAAc,CAAC;mBACvB,EAAEX,QAAQ,CAAC;uBACP,EAAEY,kBAAkB,CAAC;6BACf,EAAEC,mBAAmB,CAAC;;;IAG/C,CAAC,CAAA;KACF;CACF;AAED,eAAe1B,oBAAoB,CAAA"}

View File

@@ -0,0 +1,327 @@
import { parse as parseUrl, format as formatUrl } from "url";
import { DecodeError, isResSent } from "../../../../shared/lib/utils";
import { sendRenderResult } from "../../../../server/send-payload";
import { getUtils, vercelHeader } from "./utils";
import { renderToHTML } from "../../../../server/render";
import { tryGetPreviewData } from "../../../../server/api-utils/node";
import { denormalizePagePath } from "../../../../shared/lib/page-path/denormalize-page-path";
import { setLazyProp, getCookieParser } from "../../../../server/api-utils";
import { getRedirectStatus } from "../../../../lib/redirect-status";
import getRouteNoAssetPath from "../../../../shared/lib/router/utils/get-route-from-asset-path";
import { PERMANENT_REDIRECT_STATUS } from "../../../../shared/lib/constants";
import RenderResult from "../../../../server/render-result";
import isError from "../../../../lib/is-error";
export function getPageHandler(ctx) {
const { page , pageComponent , pageConfig , pageGetStaticProps , pageGetStaticPaths , pageGetServerSideProps , appModule , documentModule , errorModule , notFoundModule , encodedPreviewProps , pageIsDynamic , generateEtags , poweredByHeader , runtimeConfig , buildManifest , reactLoadableManifest , i18n , buildId , basePath , assetPrefix , canonicalBase , escapedBuildId , } = ctx;
const { handleLocale , handleRewrites , handleBasePath , defaultRouteRegex , dynamicRouteMatcher , interpolateDynamicPath , getParamsFromRouteMatches , normalizeDynamicRouteParams , normalizeVercelUrl , } = getUtils(ctx);
async function renderReqToHTML(req, res, renderMode, _renderOpts, _params) {
let Component;
let App;
let config;
let Document;
let Error;
let notFoundMod;
let getStaticProps;
let getStaticPaths;
let getServerSideProps;
[getStaticProps, getServerSideProps, getStaticPaths, Component, App, config, { default: Document }, { default: Error }, notFoundMod, ] = await Promise.all([
pageGetStaticProps,
pageGetServerSideProps,
pageGetStaticPaths,
pageComponent,
appModule,
pageConfig,
documentModule,
errorModule,
notFoundModule,
]);
const fromExport = renderMode === "export" || renderMode === true;
const nextStartMode = renderMode === "passthrough";
let hasValidParams = true;
setLazyProp({
req: req
}, "cookies", getCookieParser(req.headers));
const options = {
App,
Document,
ComponentMod: {
default: Component
},
buildManifest,
getStaticProps,
getServerSideProps,
getStaticPaths,
reactLoadableManifest,
canonicalBase,
buildId,
assetPrefix,
runtimeConfig: (runtimeConfig || {}).publicRuntimeConfig || {},
previewProps: encodedPreviewProps,
env: process.env,
basePath,
supportsDynamicHTML: false,
..._renderOpts
};
let _nextData = false;
let defaultLocale = i18n == null ? void 0 : i18n.defaultLocale;
let detectedLocale = i18n == null ? void 0 : i18n.defaultLocale;
let parsedUrl;
try {
var ref;
// We need to trust the dynamic route params from the proxy
// to ensure we are using the correct values
const trustQuery = !getStaticProps && req.headers[vercelHeader];
parsedUrl = parseUrl(req.url, true);
let routeNoAssetPath = parsedUrl.pathname;
if (basePath) {
routeNoAssetPath = routeNoAssetPath.replace(new RegExp(`^${basePath}`), "") || "/";
}
const origQuery = Object.assign({}, parsedUrl.query);
handleRewrites(req, parsedUrl);
handleBasePath(req, parsedUrl);
// remove ?amp=1 from request URL if rendering for export
if (fromExport && parsedUrl.query.amp) {
const queryNoAmp = Object.assign({}, origQuery);
delete queryNoAmp.amp;
req.url = formatUrl({
...parsedUrl,
search: undefined,
query: queryNoAmp
});
}
if (parsedUrl.pathname.match(/_next\/data/)) {
_nextData = page !== "/_error";
parsedUrl.pathname = getRouteNoAssetPath(parsedUrl.pathname.replace(new RegExp(`/_next/data/${escapedBuildId}/`), "/"), ".json");
routeNoAssetPath = parsedUrl.pathname;
}
const localeResult = handleLocale(req, res, parsedUrl, routeNoAssetPath, fromExport || nextStartMode);
defaultLocale = (localeResult == null ? void 0 : localeResult.defaultLocale) || defaultLocale;
detectedLocale = (localeResult == null ? void 0 : localeResult.detectedLocale) || detectedLocale;
routeNoAssetPath = (localeResult == null ? void 0 : localeResult.routeNoAssetPath) || routeNoAssetPath;
if (parsedUrl.query.nextInternalLocale) {
detectedLocale = parsedUrl.query.nextInternalLocale;
delete parsedUrl.query.nextInternalLocale;
}
const renderOpts = Object.assign({
Component,
pageConfig: config,
nextExport: fromExport,
isDataReq: _nextData,
locales: i18n == null ? void 0 : i18n.locales,
locale: detectedLocale,
defaultLocale,
domainLocales: i18n == null ? void 0 : i18n.domains,
optimizeCss: process.env.__NEXT_OPTIMIZE_CSS,
nextScriptWorkers: process.env.__NEXT_SCRIPT_WORKERS,
crossOrigin: process.env.__NEXT_CROSS_ORIGIN
}, options);
if (page === "/_error" && !res.statusCode) {
res.statusCode = 404;
}
let params = {};
if (!fromExport && pageIsDynamic) {
const result = normalizeDynamicRouteParams(trustQuery ? parsedUrl.query : dynamicRouteMatcher(parsedUrl.pathname));
hasValidParams = result.hasValidParams;
params = result.params;
}
let nowParams = null;
if (pageIsDynamic && !hasValidParams && ((ref = req.headers) == null ? void 0 : ref["x-now-route-matches"])) {
nowParams = getParamsFromRouteMatches(req, renderOpts, detectedLocale);
}
// make sure to set renderOpts to the correct params e.g. _params
// if provided from worker or params if we're parsing them here
renderOpts.params = _params || params;
normalizeVercelUrl(req, !!trustQuery);
// normalize request URL/asPath for fallback/revalidate pages since the
// proxy sets the request URL to the output's path for fallback pages
if (pageIsDynamic && nowParams && defaultRouteRegex) {
const _parsedUrl = parseUrl(req.url);
_parsedUrl.pathname = interpolateDynamicPath(_parsedUrl.pathname, nowParams);
parsedUrl.pathname = _parsedUrl.pathname;
req.url = formatUrl(_parsedUrl);
}
// make sure to normalize asPath for revalidate and _next/data requests
// since the asPath should match what is shown on the client
if (!fromExport && (getStaticProps || getServerSideProps)) {
// don't include dynamic route params in query while normalizing
// asPath
if (pageIsDynamic && defaultRouteRegex) {
delete parsedUrl.search;
for (const param of Object.keys(defaultRouteRegex.groups)){
delete origQuery[param];
}
}
parsedUrl.pathname = denormalizePagePath(parsedUrl.pathname);
renderOpts.resolvedUrl = formatUrl({
...parsedUrl,
query: origQuery
});
// For getServerSideProps we need to ensure we use the original URL
// and not the resolved URL to prevent a hydration mismatch on asPath
renderOpts.resolvedAsPath = getServerSideProps ? formatUrl({
...parsedUrl,
pathname: routeNoAssetPath,
query: origQuery
}) : renderOpts.resolvedUrl;
}
const isFallback = parsedUrl.query.__nextFallback;
const previewData = tryGetPreviewData(req, res, options.previewProps);
const isPreviewMode = previewData !== false;
if (process.env.__NEXT_OPTIMIZE_FONTS) {
renderOpts.optimizeFonts = process.env.__NEXT_OPTIMIZE_FONTS;
/**
* __webpack_require__.__NEXT_FONT_MANIFEST__ is added by
* font-stylesheet-gathering-plugin
*/ // @ts-ignore
renderOpts.fontManifest = __webpack_require__.__NEXT_FONT_MANIFEST__;
}
let result = await renderToHTML(req, res, page, Object.assign({}, getStaticProps ? {
...parsedUrl.query.amp ? {
amp: "1"
} : {}
} : parsedUrl.query, nowParams ? nowParams : params, _params, isFallback ? {
__nextFallback: "true"
} : {}), renderOpts);
if (!renderMode) {
if (_nextData || getStaticProps || getServerSideProps) {
if (renderOpts.isNotFound) {
res.statusCode = 404;
if (_nextData) {
res.end('{"notFound":true}');
return null;
}
const NotFoundComponent = notFoundMod ? notFoundMod.default : Error;
const errPathname = notFoundMod ? "/404" : "/_error";
const result2 = await renderToHTML(req, res, errPathname, parsedUrl.query, Object.assign({}, options, {
getStaticProps: notFoundMod ? notFoundMod.getStaticProps : undefined,
getStaticPaths: undefined,
getServerSideProps: undefined,
Component: NotFoundComponent,
err: undefined,
locale: detectedLocale,
locales: i18n == null ? void 0 : i18n.locales,
defaultLocale: i18n == null ? void 0 : i18n.defaultLocale
}));
sendRenderResult({
req,
res,
result: result2 ?? RenderResult.empty,
type: "html",
generateEtags,
poweredByHeader,
options: {
private: isPreviewMode || page === "/404",
stateful: !!getServerSideProps,
revalidate: renderOpts.revalidate
}
});
return null;
} else if (renderOpts.isRedirect && !_nextData) {
const redirect = {
destination: renderOpts.pageData.pageProps.__N_REDIRECT,
statusCode: renderOpts.pageData.pageProps.__N_REDIRECT_STATUS,
basePath: renderOpts.pageData.pageProps.__N_REDIRECT_BASE_PATH
};
const statusCode = getRedirectStatus(redirect);
if (basePath && redirect.basePath !== false && redirect.destination.startsWith("/")) {
redirect.destination = `${basePath}${redirect.destination}`;
}
if (statusCode === PERMANENT_REDIRECT_STATUS) {
res.setHeader("Refresh", `0;url=${redirect.destination}`);
}
res.statusCode = statusCode;
res.setHeader("Location", redirect.destination);
res.end(redirect.destination);
return null;
} else {
sendRenderResult({
req,
res,
result: _nextData ? RenderResult.fromStatic(JSON.stringify(renderOpts.pageData)) : result ?? RenderResult.empty,
type: _nextData ? "json" : "html",
generateEtags,
poweredByHeader,
options: {
private: isPreviewMode || renderOpts.is404Page,
stateful: !!getServerSideProps,
revalidate: renderOpts.revalidate
}
});
return null;
}
}
} else if (isPreviewMode) {
res.setHeader("Cache-Control", "private, no-cache, no-store, max-age=0, must-revalidate");
}
if (renderMode) return {
html: result,
renderOpts
};
return result ? result.toUnchunkedString() : null;
} catch (err) {
if (!parsedUrl) {
parsedUrl = parseUrl(req.url, true);
}
if (isError(err) && err.code === "ENOENT") {
res.statusCode = 404;
} else if (err instanceof DecodeError) {
res.statusCode = 400;
} else {
console.error("Unhandled error during request:", err);
// Backwards compat (call getInitialProps in custom error):
try {
await renderToHTML(req, res, "/_error", parsedUrl.query, Object.assign({}, options, {
getStaticProps: undefined,
getStaticPaths: undefined,
getServerSideProps: undefined,
Component: Error,
err: err,
// Short-circuit rendering:
isDataReq: true
}));
} catch (underErrorErr) {
console.error("Failed call /_error subroutine, continuing to crash function:", underErrorErr);
}
// Throw the error to crash the serverless function
if (isResSent(res)) {
console.error("!!! WARNING !!!");
console.error("Your function crashed, but closed the response before allowing the function to exit.\\n" + "This may cause unexpected behavior for the next request.");
console.error("!!! WARNING !!!");
}
throw err;
}
const result2 = await renderToHTML(req, res, "/_error", parsedUrl.query, Object.assign({}, options, {
getStaticProps: undefined,
getStaticPaths: undefined,
getServerSideProps: undefined,
Component: Error,
err: res.statusCode === 404 ? undefined : err
}));
return result2 ? result2.toUnchunkedString() : null;
}
}
return {
renderReqToHTML,
render: async function render(req, res) {
try {
const html = await renderReqToHTML(req, res);
if (html) {
sendRenderResult({
req,
res,
result: RenderResult.fromStatic(html),
type: "html",
generateEtags,
poweredByHeader
});
}
} catch (err) {
console.error(err);
// Throw the error to crash the serverless function
throw err;
}
}
};
}
//# sourceMappingURL=page-handler.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,361 @@
import { format as formatUrl, parse as parseUrl } from "url";
import { parse as parseQs } from "querystring";
import { normalizeLocalePath } from "../../../../shared/lib/i18n/normalize-locale-path";
import { getPathMatch } from "../../../../shared/lib/router/utils/path-match";
import { getNamedRouteRegex } from "../../../../shared/lib/router/utils/route-regex";
import { getRouteMatcher } from "../../../../shared/lib/router/utils/route-matcher";
import { matchHas, prepareDestination } from "../../../../shared/lib/router/utils/prepare-destination";
import { acceptLanguage } from "../../../../server/accept-header";
import { detectLocaleCookie } from "../../../../shared/lib/i18n/detect-locale-cookie";
import { detectDomainLocale } from "../../../../shared/lib/i18n/detect-domain-locale";
import { denormalizePagePath } from "../../../../shared/lib/page-path/denormalize-page-path";
import cookie from "next/dist/compiled/cookie";
import { TEMPORARY_REDIRECT_STATUS } from "../../../../shared/lib/constants";
import { addRequestMeta } from "../../../../server/request-meta";
import { removeTrailingSlash } from "../../../../shared/lib/router/utils/remove-trailing-slash";
import { normalizeRscPath } from "../../../../shared/lib/router/utils/app-paths";
export const vercelHeader = "x-vercel-id";
export function normalizeVercelUrl(req, trustQuery, paramKeys, pageIsDynamic, defaultRouteRegex) {
// make sure to normalize req.url on Vercel to strip dynamic params
// from the query which are added during routing
if (pageIsDynamic && trustQuery && defaultRouteRegex) {
const _parsedUrl = parseUrl(req.url, true);
delete _parsedUrl.search;
for (const param of paramKeys || Object.keys(defaultRouteRegex.groups)){
delete _parsedUrl.query[param];
}
req.url = formatUrl(_parsedUrl);
}
}
export function interpolateDynamicPath(pathname, params, defaultRouteRegex) {
if (!defaultRouteRegex) return pathname;
for (const param of Object.keys(defaultRouteRegex.groups)){
const { optional , repeat } = defaultRouteRegex.groups[param];
let builtParam = `[${repeat ? "..." : ""}${param}]`;
if (optional) {
builtParam = `[${builtParam}]`;
}
const paramIdx = pathname.indexOf(builtParam);
if (paramIdx > -1) {
let paramValue;
const value = params[param];
if (Array.isArray(value)) {
paramValue = value.map((v)=>v && encodeURIComponent(v)).join("/");
} else if (value) {
paramValue = encodeURIComponent(value);
} else {
paramValue = "";
}
pathname = pathname.slice(0, paramIdx) + paramValue + pathname.slice(paramIdx + builtParam.length);
}
}
return pathname;
}
export function getUtils({ page , i18n , basePath , rewrites , pageIsDynamic , trailingSlash }) {
let defaultRouteRegex;
let dynamicRouteMatcher;
let defaultRouteMatches;
if (pageIsDynamic) {
defaultRouteRegex = getNamedRouteRegex(page);
dynamicRouteMatcher = getRouteMatcher(defaultRouteRegex);
defaultRouteMatches = dynamicRouteMatcher(page);
}
function handleRewrites(req, parsedUrl) {
const rewriteParams = {};
let fsPathname = parsedUrl.pathname;
const matchesPage = ()=>{
const fsPathnameNoSlash = removeTrailingSlash(fsPathname || "");
return fsPathnameNoSlash === removeTrailingSlash(page) || (dynamicRouteMatcher == null ? void 0 : dynamicRouteMatcher(fsPathnameNoSlash));
};
const checkRewrite = (rewrite)=>{
const matcher = getPathMatch(rewrite.source + (trailingSlash ? "(/)?" : ""), {
removeUnnamedParams: true,
strict: true
});
let params = matcher(parsedUrl.pathname);
if ((rewrite.has || rewrite.missing) && params) {
const hasParams = matchHas(req, parsedUrl.query, rewrite.has, rewrite.missing);
if (hasParams) {
Object.assign(params, hasParams);
} else {
params = false;
}
}
if (params) {
const { parsedDestination , destQuery } = prepareDestination({
appendParamsToQuery: true,
destination: rewrite.destination,
params: params,
query: parsedUrl.query
});
// if the rewrite destination is external break rewrite chain
if (parsedDestination.protocol) {
return true;
}
Object.assign(rewriteParams, destQuery, params);
Object.assign(parsedUrl.query, parsedDestination.query);
delete parsedDestination.query;
Object.assign(parsedUrl, parsedDestination);
fsPathname = parsedUrl.pathname;
if (basePath) {
fsPathname = fsPathname.replace(new RegExp(`^${basePath}`), "") || "/";
}
if (i18n) {
const destLocalePathResult = normalizeLocalePath(fsPathname, i18n.locales);
fsPathname = destLocalePathResult.pathname;
parsedUrl.query.nextInternalLocale = destLocalePathResult.detectedLocale || params.nextInternalLocale;
}
if (fsPathname === page) {
return true;
}
if (pageIsDynamic && dynamicRouteMatcher) {
const dynamicParams = dynamicRouteMatcher(fsPathname);
if (dynamicParams) {
parsedUrl.query = {
...parsedUrl.query,
...dynamicParams
};
return true;
}
}
}
return false;
};
for (const rewrite1 of rewrites.beforeFiles || []){
checkRewrite(rewrite1);
}
if (fsPathname !== page) {
let finished = false;
for (const rewrite of rewrites.afterFiles || []){
finished = checkRewrite(rewrite);
if (finished) break;
}
if (!finished && !matchesPage()) {
for (const rewrite of rewrites.fallback || []){
finished = checkRewrite(rewrite);
if (finished) break;
}
}
}
return rewriteParams;
}
function handleBasePath(req, parsedUrl) {
// always strip the basePath if configured since it is required
req.url = req.url.replace(new RegExp(`^${basePath}`), "") || "/";
parsedUrl.pathname = parsedUrl.pathname.replace(new RegExp(`^${basePath}`), "") || "/";
}
function getParamsFromRouteMatches(req, renderOpts, detectedLocale) {
return getRouteMatcher(function() {
const { groups , routeKeys } = defaultRouteRegex;
return {
re: {
// Simulate a RegExp match from the \`req.url\` input
exec: (str)=>{
const obj = parseQs(str);
const matchesHasLocale = i18n && detectedLocale && obj["1"] === detectedLocale;
// favor named matches if available
const routeKeyNames = Object.keys(routeKeys || {});
const filterLocaleItem = (val)=>{
if (i18n) {
// locale items can be included in route-matches
// for fallback SSG pages so ensure they are
// filtered
const isCatchAll = Array.isArray(val);
const _val = isCatchAll ? val[0] : val;
if (typeof _val === "string" && i18n.locales.some((item)=>{
if (item.toLowerCase() === _val.toLowerCase()) {
detectedLocale = item;
renderOpts.locale = detectedLocale;
return true;
}
return false;
})) {
// remove the locale item from the match
if (isCatchAll) {
val.splice(0, 1);
}
// the value is only a locale item and
// shouldn't be added
return isCatchAll ? val.length === 0 : true;
}
}
return false;
};
if (routeKeyNames.every((name)=>obj[name])) {
return routeKeyNames.reduce((prev, keyName)=>{
const paramName = routeKeys == null ? void 0 : routeKeys[keyName];
if (paramName && !filterLocaleItem(obj[keyName])) {
prev[groups[paramName].pos] = obj[keyName];
}
return prev;
}, {});
}
return Object.keys(obj).reduce((prev, key)=>{
if (!filterLocaleItem(obj[key])) {
let normalizedKey = key;
if (matchesHasLocale) {
normalizedKey = parseInt(key, 10) - 1 + "";
}
return Object.assign(prev, {
[normalizedKey]: obj[key]
});
}
return prev;
}, {});
}
},
groups
};
}())(req.headers["x-now-route-matches"]);
}
function normalizeDynamicRouteParams(params, ignoreOptional) {
let hasValidParams = true;
if (!defaultRouteRegex) return {
params,
hasValidParams: false
};
params = Object.keys(defaultRouteRegex.groups).reduce((prev, key)=>{
let value = params[key];
if (typeof value === "string") {
value = normalizeRscPath(value, true);
}
if (Array.isArray(value)) {
value = value.map((val)=>{
if (typeof val === "string") {
val = normalizeRscPath(val, true);
}
return val;
});
}
// if the value matches the default value we can't rely
// on the parsed params, this is used to signal if we need
// to parse x-now-route-matches or not
const defaultValue = defaultRouteMatches[key];
const isOptional = defaultRouteRegex.groups[key].optional;
const isDefaultValue = Array.isArray(defaultValue) ? defaultValue.some((defaultVal)=>{
return Array.isArray(value) ? value.some((val)=>val.includes(defaultVal)) : value == null ? void 0 : value.includes(defaultVal);
}) : value == null ? void 0 : value.includes(defaultValue);
if (isDefaultValue || typeof value === "undefined" && !(isOptional && ignoreOptional)) {
hasValidParams = false;
}
// non-provided optional values should be undefined so normalize
// them to undefined
if (isOptional && (!value || Array.isArray(value) && value.length === 1 && // fallback optional catch-all SSG pages have
// [[...paramName]] for the root path on Vercel
(value[0] === "index" || value[0] === `[[...${key}]]`))) {
value = undefined;
delete params[key];
}
// query values from the proxy aren't already split into arrays
// so make sure to normalize catch-all values
if (value && typeof value === "string" && defaultRouteRegex.groups[key].repeat) {
value = value.split("/");
}
if (value) {
prev[key] = value;
}
return prev;
}, {});
return {
params,
hasValidParams
};
}
function handleLocale(req, res, parsedUrl, routeNoAssetPath, shouldNotRedirect) {
if (!i18n) return;
const pathname = parsedUrl.pathname || "/";
let defaultLocale = i18n.defaultLocale;
let detectedLocale = detectLocaleCookie(req, i18n.locales);
let acceptPreferredLocale;
try {
acceptPreferredLocale = i18n.localeDetection !== false ? acceptLanguage(req.headers["accept-language"], i18n.locales) : detectedLocale;
} catch (_) {
acceptPreferredLocale = detectedLocale;
}
const { host } = req.headers || {};
// remove port from host and remove port if present
const hostname = host && host.split(":")[0].toLowerCase();
const detectedDomain = detectDomainLocale(i18n.domains, hostname);
if (detectedDomain) {
defaultLocale = detectedDomain.defaultLocale;
detectedLocale = defaultLocale;
addRequestMeta(req, "__nextIsLocaleDomain", true);
}
// if not domain specific locale use accept-language preferred
detectedLocale = detectedLocale || acceptPreferredLocale;
let localeDomainRedirect;
const localePathResult = normalizeLocalePath(pathname, i18n.locales);
routeNoAssetPath = normalizeLocalePath(routeNoAssetPath, i18n.locales).pathname;
if (localePathResult.detectedLocale) {
detectedLocale = localePathResult.detectedLocale;
req.url = formatUrl({
...parsedUrl,
pathname: localePathResult.pathname
});
addRequestMeta(req, "__nextStrippedLocale", true);
parsedUrl.pathname = localePathResult.pathname;
}
// If a detected locale is a domain specific locale and we aren't already
// on that domain and path prefix redirect to it to prevent duplicate
// content from multiple domains
if (detectedDomain) {
const localeToCheck = localePathResult.detectedLocale ? detectedLocale : acceptPreferredLocale;
const matchedDomain = detectDomainLocale(i18n.domains, undefined, localeToCheck);
if (matchedDomain && matchedDomain.domain !== detectedDomain.domain) {
localeDomainRedirect = `http${matchedDomain.http ? "" : "s"}://${matchedDomain.domain}/${localeToCheck === matchedDomain.defaultLocale ? "" : localeToCheck}`;
}
}
const denormalizedPagePath = denormalizePagePath(pathname);
const detectedDefaultLocale = !detectedLocale || detectedLocale.toLowerCase() === defaultLocale.toLowerCase();
const shouldStripDefaultLocale = false;
// detectedDefaultLocale &&
// denormalizedPagePath.toLowerCase() === \`/\${i18n.defaultLocale.toLowerCase()}\`
const shouldAddLocalePrefix = !detectedDefaultLocale && denormalizedPagePath === "/";
detectedLocale = detectedLocale || i18n.defaultLocale;
if (!shouldNotRedirect && !req.headers[vercelHeader] && i18n.localeDetection !== false && (localeDomainRedirect || shouldAddLocalePrefix || shouldStripDefaultLocale)) {
// set the NEXT_LOCALE cookie when a user visits the default locale
// with the locale prefix so that they aren't redirected back to
// their accept-language preferred locale
if (shouldStripDefaultLocale && acceptPreferredLocale !== defaultLocale) {
const previous = res.getHeader("set-cookie");
res.setHeader("set-cookie", [
...typeof previous === "string" ? [
previous
] : Array.isArray(previous) ? previous : [],
cookie.serialize("NEXT_LOCALE", defaultLocale, {
httpOnly: true,
path: "/"
}),
]);
}
res.setHeader("Location", formatUrl({
// make sure to include any query values when redirecting
...parsedUrl,
pathname: localeDomainRedirect ? localeDomainRedirect : shouldStripDefaultLocale ? basePath || "/" : `${basePath}/${detectedLocale}`
}));
res.statusCode = TEMPORARY_REDIRECT_STATUS;
res.end();
return;
}
detectedLocale = localePathResult.detectedLocale || detectedDomain && detectedDomain.defaultLocale || defaultLocale;
return {
defaultLocale,
detectedLocale,
routeNoAssetPath
};
}
return {
handleLocale,
handleRewrites,
handleBasePath,
defaultRouteRegex,
dynamicRouteMatcher,
defaultRouteMatches,
getParamsFromRouteMatches,
normalizeDynamicRouteParams,
normalizeVercelUrl: (req, trustQuery, paramKeys)=>normalizeVercelUrl(req, trustQuery, paramKeys, pageIsDynamic, defaultRouteRegex),
interpolateDynamicPath: (pathname, params)=>interpolateDynamicPath(pathname, params, defaultRouteRegex)
};
}
//# sourceMappingURL=utils.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,208 @@
import path from "path";
import isEqualLocals from "./runtime/isEqualLocals";
import { stringifyRequest } from "../../stringify-request";
const loaderApi = ()=>{};
loaderApi.pitch = function loader(request) {
const loaderSpan = this.currentTraceSpan.traceChild("next-style-loader");
return loaderSpan.traceFn(()=>{
const options = this.getOptions();
const insert = typeof options.insert === "undefined" ? '"head"' : typeof options.insert === "string" ? JSON.stringify(options.insert) : options.insert.toString();
const injectType = options.injectType || "styleTag";
const esModule = typeof options.esModule !== "undefined" ? options.esModule : false;
delete options.esModule;
switch(injectType){
case "linkTag":
{
const hmrCode = this.hot ? `
if (module.hot) {
module.hot.accept(
${stringifyRequest(this, `!!${request}`)},
function() {
${esModule ? "update(content);" : `content = require(${stringifyRequest(this, `!!${request}`)});
content = content.__esModule ? content.default : content;
update(content);`}
}
);
module.hot.dispose(function() {
update();
});
}` : "";
return `${esModule ? `import api from ${stringifyRequest(this, `!${path.join(__dirname, "runtime/injectStylesIntoLinkTag.js")}`)};
import content from ${stringifyRequest(this, `!!${request}`)};` : `var api = require(${stringifyRequest(this, `!${path.join(__dirname, "runtime/injectStylesIntoLinkTag.js")}`)});
var content = require(${stringifyRequest(this, `!!${request}`)});
content = content.__esModule ? content.default : content;`}
var options = ${JSON.stringify(options)};
options.insert = ${insert};
var update = api(content, options);
${hmrCode}
${esModule ? "export default {}" : ""}`;
}
case "lazyStyleTag":
case "lazySingletonStyleTag":
{
const isSingleton = injectType === "lazySingletonStyleTag";
const hmrCode = this.hot ? `
if (module.hot) {
if (!content.locals || module.hot.invalidate) {
var isEqualLocals = ${isEqualLocals.toString()};
var oldLocals = content.locals;
module.hot.accept(
${stringifyRequest(this, `!!${request}`)},
function () {
${esModule ? `if (!isEqualLocals(oldLocals, content.locals)) {
module.hot.invalidate();
return;
}
oldLocals = content.locals;
if (update && refs > 0) {
update(content);
}` : `content = require(${stringifyRequest(this, `!!${request}`)});
content = content.__esModule ? content.default : content;
if (!isEqualLocals(oldLocals, content.locals)) {
module.hot.invalidate();
return;
}
oldLocals = content.locals;
if (update && refs > 0) {
update(content);
}`}
}
)
}
module.hot.dispose(function() {
if (update) {
update();
}
});
}` : "";
return `${esModule ? `import api from ${stringifyRequest(this, `!${path.join(__dirname, "runtime/injectStylesIntoStyleTag.js")}`)};
import content from ${stringifyRequest(this, `!!${request}`)};` : `var api = require(${stringifyRequest(this, `!${path.join(__dirname, "runtime/injectStylesIntoStyleTag.js")}`)});
var content = require(${stringifyRequest(this, `!!${request}`)});
content = content.__esModule ? content.default : content;
if (typeof content === 'string') {
content = [[module.id, content, '']];
}`}
var refs = 0;
var update;
var options = ${JSON.stringify(options)};
options.insert = ${insert};
options.singleton = ${isSingleton};
var exported = {};
exported.locals = content.locals || {};
exported.use = function() {
if (!(refs++)) {
update = api(content, options);
}
return exported;
};
exported.unuse = function() {
if (refs > 0 && !--refs) {
update();
update = null;
}
};
${hmrCode}
${esModule ? "export default" : "module.exports ="} exported;`;
}
case "styleTag":
case "singletonStyleTag":
default:
{
const isSingleton = injectType === "singletonStyleTag";
const hmrCode = this.hot ? `
if (module.hot) {
if (!content.locals || module.hot.invalidate) {
var isEqualLocals = ${isEqualLocals.toString()};
var oldLocals = content.locals;
module.hot.accept(
${stringifyRequest(this, `!!${request}`)},
function () {
${esModule ? `if (!isEqualLocals(oldLocals, content.locals)) {
module.hot.invalidate();
return;
}
oldLocals = content.locals;
update(content);` : `content = require(${stringifyRequest(this, `!!${request}`)});
content = content.__esModule ? content.default : content;
if (typeof content === 'string') {
content = [[module.id, content, '']];
}
if (!isEqualLocals(oldLocals, content.locals)) {
module.hot.invalidate();
return;
}
oldLocals = content.locals;
update(content);`}
}
)
}
module.hot.dispose(function() {
update();
});
}` : "";
return `${esModule ? `import api from ${stringifyRequest(this, `!${path.join(__dirname, "runtime/injectStylesIntoStyleTag.js")}`)};
import content from ${stringifyRequest(this, `!!${request}`)};` : `var api = require(${stringifyRequest(this, `!${path.join(__dirname, "runtime/injectStylesIntoStyleTag.js")}`)});
var content = require(${stringifyRequest(this, `!!${request}`)});
content = content.__esModule ? content.default : content;
if (typeof content === 'string') {
content = [[module.id, content, '']];
}`}
var options = ${JSON.stringify(options)};
options.insert = ${insert};
options.singleton = ${isSingleton};
var update = api(content, options);
${hmrCode}
${esModule ? "export default" : "module.exports ="} content.locals || {};`;
}
}
});
};
module.exports = loaderApi;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../build/webpack/loaders/next-style-loader/index.js"],"names":["path","isEqualLocals","stringifyRequest","loaderApi","pitch","loader","request","loaderSpan","currentTraceSpan","traceChild","traceFn","options","getOptions","insert","JSON","stringify","toString","injectType","esModule","hmrCode","hot","join","__dirname","isSingleton","module","exports"],"mappings":"AAAA,OAAOA,IAAI,MAAM,MAAM,CAAA;AACvB,OAAOC,aAAa,MAAM,yBAAyB,CAAA;AACnD,SAASC,gBAAgB,QAAQ,yBAAyB,CAAA;AAE1D,MAAMC,SAAS,GAAG,IAAM,EAAE;AAE1BA,SAAS,CAACC,KAAK,GAAG,SAASC,MAAM,CAACC,OAAO,EAAE;IACzC,MAAMC,UAAU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AS,EACT,qCAAqC,CACtC,CAAC,CAAC,CACJ,CAAC;gCACgB,EAAEpB,gBAAgB,CAAC,IAAI,EAAE,CAAC,EAAE,EAAEI,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAC7D,CAAC,kBAAkB,EAAEJ,gBAAgB,CACnC,IAAI,EACJ,CAAC,CAAC,EAAEF,IAAI,CAACqB,IAAI,CACXC,SAAS,EACT,qCAAqC,CACtC,CAAC,CAAC,CACJ,CAAC;kCACkB,EAAEpB,gBAAgB,CAAC,IAAI,EAAE,CAAC,EAAE,EAAEI,OAAO,CAAC,CAAC,CAAC,CAAC;;;;;;aAM9D,CAAC,CACL;;cAEK,EAAEQ,IAAI,CAACC,SAAS,CAACJ,OAAO,CAAC,CAAC;;iBAEvB,EAAEE,MAAM,CAAC;oBACN,EAAEU,WAAW,CAAC;;;;AAIlC,EAAEJ,OAAO,CAAC;;AAEV,EAAED,QAAQ,GAAG,gBAAgB,GAAG,kBAAkB,CAAC,sBAAsB,CAAC,CAAA;iBACnE;SACF;KACF,CAAC,CAAA;CACH;AAEDM,MAAM,CAACC,OAAO,GAAGtB,SAAS"}

View File

@@ -0,0 +1,56 @@
const getTarget = function getTarget() {
const memo = {};
return function memorize(target) {
if (typeof memo[target] === "undefined") {
let styleTarget = document.querySelector(target);
// Special case to return head of iframe instead of iframe itself
if (window.HTMLIFrameElement && styleTarget instanceof window.HTMLIFrameElement) {
try {
// This will throw an exception if access to iframe is blocked
// due to cross-origin restrictions
styleTarget = styleTarget.contentDocument.head;
} catch (e) {
// istanbul ignore next
styleTarget = null;
}
}
memo[target] = styleTarget;
}
return memo[target];
};
}();
module.exports = (url, options)=>{
options = options || {};
options.attributes = typeof options.attributes === "object" ? options.attributes : {};
if (typeof options.attributes.nonce === "undefined") {
const nonce = // eslint-disable-next-line no-undef
typeof __webpack_nonce__ !== "undefined" ? __webpack_nonce__ : null;
if (nonce) {
options.attributes.nonce = nonce;
}
}
const link = document.createElement("link");
link.rel = "stylesheet";
link.href = url;
Object.keys(options.attributes).forEach((key)=>{
link.setAttribute(key, options.attributes[key]);
});
if (typeof options.insert === "function") {
options.insert(link);
} else {
const target = getTarget(options.insert || "head");
if (!target) {
throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");
}
target.appendChild(link);
}
return (newUrl)=>{
if (typeof newUrl === "string") {
link.href = newUrl;
} else {
link.parentNode.removeChild(link);
}
};
};
//# sourceMappingURL=injectStylesIntoLinkTag.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../build/webpack/loaders/next-style-loader/runtime/injectStylesIntoLinkTag.js"],"names":["getTarget","memo","memorize","target","styleTarget","document","querySelector","window","HTMLIFrameElement","contentDocument","head","e","module","exports","url","options","attributes","nonce","__webpack_nonce__","link","createElement","rel","href","Object","keys","forEach","key","setAttribute","insert","Error","appendChild","newUrl","parentNode","removeChild"],"mappings":"AAAA,MAAMA,SAAS,GAAG,AAAC,SAASA,SAAS,GAAG;IACtC,MAAMC,IAAI,GAAG,EAAE;IAEf,OAAO,SAASC,QAAQ,CAACC,MAAM,EAAE;QAC/B,IAAI,OAAOF,IAAI,CAACE,MAAM,CAAC,KAAK,WAAW,EAAE;YACvC,IAAIC,WAAW,GAAGC,QAAQ,CAACC,aAAa,CAACH,MAAM,CAAC;YAEhD,iEAAiE;YACjE,IACEI,MAAM,CAACC,iBAAiB,IACxBJ,WAAW,YAAYG,MAAM,CAACC,iBAAiB,EAC/C;gBACA,IAAI;oBACF,8DAA8D;oBAC9D,mCAAmC;oBACnCJ,WAAW,GAAGA,WAAW,CAACK,eAAe,CAACC,IAAI;iBAC/C,CAAC,OAAOC,CAAC,EAAE;oBACV,uBAAuB;oBACvBP,WAAW,GAAG,IAAI;iBACnB;aACF;YAEDH,IAAI,CAACE,MAAM,CAAC,GAAGC,WAAW;SAC3B;QAED,OAAOH,IAAI,CAACE,MAAM,CAAC,CAAA;KACpB,CAAA;CACF,EAAG;AAEJS,MAAM,CAACC,OA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,UAAU,CAACC,WAAW,CAACd,IAAI,CAAC;SAClC;KACF,CAAA;CACF"}

View File

@@ -0,0 +1,216 @@
const isOldIE = function isOldIE() {
let memo;
return function memorize() {
if (typeof memo === "undefined") {
// Test for IE <= 9 as proposed by Browserhacks
// @see http://browserhacks.com/#hack-e71d8692f65334173fee715c222cb805
// Tests for existence of standard globals is to allow style-loader
// to operate correctly into non-standard environments
// @see https://github.com/webpack-contrib/style-loader/issues/177
memo = Boolean(window && document && document.all && !window.atob);
}
return memo;
};
}();
const getTarget = function getTarget() {
const memo = {};
return function memorize(target) {
if (typeof memo[target] === "undefined") {
let styleTarget = document.querySelector(target);
// Special case to return head of iframe instead of iframe itself
if (window.HTMLIFrameElement && styleTarget instanceof window.HTMLIFrameElement) {
try {
// This will throw an exception if access to iframe is blocked
// due to cross-origin restrictions
styleTarget = styleTarget.contentDocument.head;
} catch (e) {
// istanbul ignore next
styleTarget = null;
}
}
memo[target] = styleTarget;
}
return memo[target];
};
}();
const stylesInDom = [];
function getIndexByIdentifier(identifier) {
let result = -1;
for(let i = 0; i < stylesInDom.length; i++){
if (stylesInDom[i].identifier === identifier) {
result = i;
break;
}
}
return result;
}
function modulesToDom(list, options) {
const idCountMap = {};
const identifiers = [];
for(let i = 0; i < list.length; i++){
const item = list[i];
const id = options.base ? item[0] + options.base : item[0];
const count = idCountMap[id] || 0;
const identifier = id + " " + count.toString();
idCountMap[id] = count + 1;
const index = getIndexByIdentifier(identifier);
const obj = {
css: item[1],
media: item[2],
sourceMap: item[3]
};
if (index !== -1) {
stylesInDom[index].references++;
stylesInDom[index].updater(obj);
} else {
stylesInDom.push({
identifier: identifier,
updater: addStyle(obj, options),
references: 1
});
}
identifiers.push(identifier);
}
return identifiers;
}
function insertStyleElement(options) {
const style = document.createElement("style");
const attributes = options.attributes || {};
if (typeof attributes.nonce === "undefined") {
const nonce = // eslint-disable-next-line no-undef
typeof __webpack_nonce__ !== "undefined" ? __webpack_nonce__ : null;
if (nonce) {
attributes.nonce = nonce;
}
}
Object.keys(attributes).forEach(function(key) {
style.setAttribute(key, attributes[key]);
});
if (typeof options.insert === "function") {
options.insert(style);
} else {
const target = getTarget(options.insert || "head");
if (!target) {
throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");
}
target.appendChild(style);
}
return style;
}
function removeStyleElement(style) {
// istanbul ignore if
if (style.parentNode === null) {
return false;
}
style.parentNode.removeChild(style);
}
/* istanbul ignore next */ const replaceText = function replaceText() {
const textStore = [];
return function replace(index, replacement) {
textStore[index] = replacement;
return textStore.filter(Boolean).join("\n");
};
}();
function applyToSingletonTag(style, index, remove, obj) {
const css = remove ? "" : obj.media ? "@media " + obj.media + " {" + obj.css + "}" : obj.css;
// For old IE
/* istanbul ignore if */ if (style.styleSheet) {
style.styleSheet.cssText = replaceText(index, css);
} else {
const cssNode = document.createTextNode(css);
const childNodes = style.childNodes;
if (childNodes[index]) {
style.removeChild(childNodes[index]);
}
if (childNodes.length) {
style.insertBefore(cssNode, childNodes[index]);
} else {
style.appendChild(cssNode);
}
}
}
function applyToTag(style, options, obj) {
let css = obj.css;
const media = obj.media;
const sourceMap = obj.sourceMap;
if (media) {
style.setAttribute("media", media);
} else {
style.removeAttribute("media");
}
if (sourceMap && typeof btoa !== "undefined") {
css += "\n/*# sourceMappingURL=data:application/json;base64," + btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))) + " */";
}
// For old IE
/* istanbul ignore if */ if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
while(style.firstChild){
style.removeChild(style.firstChild);
}
style.appendChild(document.createTextNode(css));
}
}
let singleton = null;
let singletonCounter = 0;
function addStyle(obj, options) {
let style;
let update;
let remove;
if (options.singleton) {
const styleIndex = singletonCounter++;
style = singleton || (singleton = insertStyleElement(options));
update = applyToSingletonTag.bind(null, style, styleIndex, false);
remove = applyToSingletonTag.bind(null, style, styleIndex, true);
} else {
style = insertStyleElement(options);
update = applyToTag.bind(null, style, options);
remove = function() {
removeStyleElement(style);
};
}
update(obj);
return function updateStyle(newObj) {
if (newObj) {
if (newObj.css === obj.css && newObj.media === obj.media && newObj.sourceMap === obj.sourceMap) {
return;
}
update(obj = newObj);
} else {
remove();
}
};
}
module.exports = function(list, options) {
options = options || {};
// Force single-tag solution on IE6-9, which has a hard limit on the # of <style>
// tags it will allow on a page
if (!options.singleton && typeof options.singleton !== "boolean") {
options.singleton = isOldIE();
}
list = list || [];
let lastIdentifiers = modulesToDom(list, options);
return function update(newList) {
newList = newList || [];
if (Object.prototype.toString.call(newList) !== "[object Array]") {
return;
}
for(let i = 0; i < lastIdentifiers.length; i++){
const identifier = lastIdentifiers[i];
const index = getIndexByIdentifier(identifier);
stylesInDom[index].references--;
}
const newLastIdentifiers = modulesToDom(newList, options);
for(let i1 = 0; i1 < lastIdentifiers.length; i1++){
const identifier = lastIdentifiers[i1];
const index = getIndexByIdentifier(identifier);
if (stylesInDom[index].references === 0) {
stylesInDom[index].updater();
stylesInDom.splice(index, 1);
}
}
lastIdentifiers = newLastIdentifiers;
};
};
//# sourceMappingURL=injectStylesIntoStyleTag.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,26 @@
function isEqualLocals(a, b, isNamedExport) {
if (!a && b || a && !b) {
return false;
}
let p;
for(p in a){
if (isNamedExport && p === "default") {
continue;
}
if (a[p] !== b[p]) {
return false;
}
}
for(p in b){
if (isNamedExport && p === "default") {
continue;
}
if (!a[p]) {
return false;
}
}
return true;
}
module.exports = isEqualLocals;
//# sourceMappingURL=isEqualLocals.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../build/webpack/loaders/next-style-loader/runtime/isEqualLocals.js"],"names":["isEqualLocals","a","b","isNamedExport","p","module","exports"],"mappings":"AAAA,SAASA,aAAa,CAACC,CAAC,EAAEC,CAAC,EAAEC,aAAa,EAAE;IAC1C,IAAI,AAAC,CAACF,CAAC,IAAIC,CAAC,IAAMD,CAAC,IAAI,CAACC,CAAC,AAAC,EAAE;QAC1B,OAAO,KAAK,CAAA;KACb;IAED,IAAIE,CAAC;IAEL,IAAKA,CAAC,IAAIH,CAAC,CAAE;QACX,IAAIE,aAAa,IAAIC,CAAC,KAAK,SAAS,EAAE;YAEpC,SAAQ;SACT;QAED,IAAIH,CAAC,CAACG,CAAC,CAAC,KAAKF,CAAC,CAACE,CAAC,CAAC,EAAE;YACjB,OAAO,KAAK,CAAA;SACb;KACF;IAED,IAAKA,CAAC,IAAIF,CAAC,CAAE;QACX,IAAIC,aAAa,IAAIC,CAAC,KAAK,SAAS,EAAE;YAEpC,SAAQ;SACT;QAED,IAAI,CAACH,CAAC,CAACG,CAAC,CAAC,EAAE;YACT,OAAO,KAAK,CAAA;SACb;KACF;IAED,OAAO,IAAI,CAAA;CACZ;AAEDC,MAAM,CAACC,OAAO,GAAGN,aAAa"}

View File

@@ -0,0 +1,112 @@
/*
Copyright (c) 2017 The swc Project Developers
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.
*/ import { isWasm, transform } from "../../swc";
import { getLoaderSWCOptions } from "../../swc/options";
import path, { isAbsolute } from "path";
async function loaderTransform(parentTrace, source, inputSourceMap) {
// Make the loader async
const filename = this.resourcePath;
let loaderOptions = this.getOptions() || {};
const { isServer , isServerLayer , rootDir , pagesDir , hasReactRefresh , nextConfig , jsConfig , supportedBrowsers , swcCacheDir , hasServerComponents , } = loaderOptions;
const isPageFile = filename.startsWith(pagesDir);
const relativeFilePathFromRoot = path.relative(rootDir, filename);
const swcOptions = getLoaderSWCOptions({
pagesDir,
filename,
isServer,
isServerLayer,
isPageFile,
development: this.mode === "development",
hasReactRefresh,
nextConfig,
jsConfig,
supportedBrowsers,
swcCacheDir,
relativeFilePathFromRoot,
hasServerComponents
});
const programmaticOptions = {
...swcOptions,
filename,
inputSourceMap: inputSourceMap ? JSON.stringify(inputSourceMap) : undefined,
// Set the default sourcemap behavior based on Webpack's mapping flag,
sourceMaps: this.sourceMap,
inlineSourcesContent: this.sourceMap,
// Ensure that Webpack will get a full absolute path in the sourcemap
// so that it can properly map the module back to its internal cached
// modules.
sourceFileName: filename
};
if (!programmaticOptions.inputSourceMap) {
delete programmaticOptions.inputSourceMap;
}
// auto detect development mode
if (this.mode && programmaticOptions.jsc && programmaticOptions.jsc.transform && programmaticOptions.jsc.transform.react && !Object.prototype.hasOwnProperty.call(programmaticOptions.jsc.transform.react, "development")) {
programmaticOptions.jsc.transform.react.development = this.mode === "development";
}
const swcSpan = parentTrace.traceChild("next-swc-transform");
return swcSpan.traceAsyncFn(()=>transform(source, programmaticOptions).then((output)=>{
if (output.eliminatedPackages && this.eliminatedPackages) {
for (const pkg of JSON.parse(output.eliminatedPackages)){
this.eliminatedPackages.add(pkg);
}
}
return [
output.code,
output.map ? JSON.parse(output.map) : undefined
];
}));
}
const EXCLUDED_PATHS = /[\\/](cache[\\/][^\\/]+\.zip[\\/]node_modules|__virtual__)[\\/]/g;
export function pitch() {
const callback = this.async();
(async ()=>{
let loaderOptions = this.getOptions() || {};
if (// TODO: investigate swc file reading in PnP mode?
!process.versions.pnp && loaderOptions.fileReading && !EXCLUDED_PATHS.test(this.resourcePath) && this.loaders.length - 1 === this.loaderIndex && isAbsolute(this.resourcePath) && !await isWasm()) {
const loaderSpan = this.currentTraceSpan.traceChild("next-swc-loader");
this.addDependency(this.resourcePath);
return loaderSpan.traceAsyncFn(()=>loaderTransform.call(this, loaderSpan));
}
})().then((r)=>{
if (r) return callback(null, ...r);
callback();
}, callback);
}
export default function swcLoader(inputSource, inputSourceMap) {
const loaderSpan = this.currentTraceSpan.traceChild("next-swc-loader");
const callback = this.async();
loaderSpan.traceAsyncFn(()=>loaderTransform.call(this, loaderSpan, inputSource, inputSourceMap)).then(([transformedSource, outputSourceMap])=>{
callback(null, transformedSource, outputSourceMap || inputSourceMap);
}, (err)=>{
callback(err);
});
};
// accept Buffers instead of strings
export const raw = true;
//# sourceMappingURL=next-swc-loader.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/webpack/loaders/next-swc-loader.js"],"names":["isWasm","transform","getLoaderSWCOptions","path","isAbsolute","loaderTransform","parentTrace","source","inputSourceMap","filename","resourcePath","loaderOptions","getOptions","isServer","isServerLayer","rootDir","pagesDir","hasReactRefresh","nextConfig","jsConfig","supportedBrowsers","swcCacheDir","hasServerComponents","isPageFile","startsWith","relativeFilePathFromRoot","relative","swcOptions","development","mode","programmaticOptions","JSON","stringify","undefined","sourceMaps","sourceMap","inlineSourcesContent","sourceFileName","jsc","react","Object","prototype","hasOwnProperty","call","swcSpan","traceChild","traceAsyncFn","then","output","eliminatedPackages","pkg","parse","add","code","map","EXCLUDED_PATHS","pitch","callback","async","process","versions","pnp","fileReading","test","loaders","length","loaderIndex","loaderSpan","currentTraceSpan","addDependency","r","swcLoader","inputSource","transformedSource","outputSourceMap","err","raw"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;EA0BE,CAEF,SAASA,MAAM,EAAEC,SAAS,QAAQ,WAAW,CAAA;AAC7C,SAASC,mBAAmB,QAAQ,mBAAmB,CAAA;AACvD,OAAOC,IAAI,IAAIC,UAAU,QAAQ,MAA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Q,CAACkB,GAAG,CAAC;KACd,CACF;CACJ,CAAA;AAED,oCAAoC;AACpC,OAAO,MAAMC,GAAG,GAAG,IAAI,CAAA"}

View File

@@ -0,0 +1,4 @@
const NoopLoader = (source)=>source;
export default NoopLoader;
//# sourceMappingURL=noop-loader.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/webpack/loaders/noop-loader.ts"],"names":["NoopLoader","source"],"mappings":"AAEA,MAAMA,UAAU,GAAqC,CAACC,MAAM,GAAKA,MAAM;AACvE,eAAeD,UAAU,CAAA"}

View File

@@ -0,0 +1,31 @@
/**
* **PostCSS Syntax Error**
*
* Loader wrapper for postcss syntax errors
*
* @class SyntaxError
* @extends Error
*
* @param {Object} err CssSyntaxError
*/ class SyntaxError extends Error {
constructor(error){
super(error);
const { line , column , reason , plugin , file } = error;
this.name = "SyntaxError";
this.message = `${this.name}\n\n`;
if (typeof line !== "undefined") {
this.message += `(${line}:${column}) `;
}
this.message += plugin ? `${plugin}: ` : "";
this.message += file ? `${file} ` : "<css input> ";
this.message += `${reason}`;
const code = error.showSourceCode();
if (code) {
this.message += `\n\n${code}\n`;
}
this.stack = false;
}
}
module.exports = SyntaxError;
//# sourceMappingURL=Error.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../build/webpack/loaders/postcss-loader/src/Error.js"],"names":["SyntaxError","Error","constructor","error","line","column","reason","plugin","file","name","message","code","showSourceCode","stack","module","exports"],"mappings":"AAAA;;;;;;;;;GASG,CACH,MAAMA,WAAW,SAASC,KAAK;IAC7BC,YAAYC,KAAK,CAAE;QACjB,KAAK,CAACA,KAAK,CAAC;QAEZ,MAAM,EAAEC,IAAI,CAAA,EAAEC,MAAM,CAAA,EAAEC,MAAM,CAAA,EAAEC,MAAM,CAAA,EAAEC,IAAI,CAAA,EAAE,GAAGL,KAAK;QAEpD,IAAI,CAACM,IAAI,GAAG,aAAa;QAEzB,IAAI,CAACC,OAAO,GAAG,CAAC,EAAE,IAAI,CAACD,IAAI,CAAC,IAAI,CAAC;QAEjC,IAAI,OAAOL,IAAI,KAAK,WAAW,EAAE;YAC/B,IAAI,CAACM,OAAO,IAAI,CAAC,CAAC,EAAEN,IAAI,CAAC,CAAC,EAAEC,MAAM,CAAC,EAAE,CAAC;SACvC;QAED,IAAI,CAACK,OAAO,IAAIH,MAAM,GAAG,CAAC,EAAEA,MAAM,CAAC,EAAE,CAAC,GAAG,EAAE;QAC3C,IAAI,CAACG,OAAO,IAAIF,IAAI,GAAG,CAAC,EAAEA,IAAI,CAAC,CAAC,CAAC,GAAG,cAAc;QAClD,IAAI,CAACE,OAAO,IAAI,CAAC,EAAEJ,MAAM,CAAC,CAAC;QAE3B,MAAMK,IAAI,GAAGR,KAAK,CAACS,cAAc,EAAE;QAEnC,IAAID,IAAI,EAAE;YACR,IAAI,CAACD,OAAO,IAAI,CAAC,IAAI,EAAEC,IAAI,CAAC,EAAE,CAAC;SAChC;QAED,IAAI,CAACE,KAAK,GAAG,KAAK;KACnB;CACF;AAEDC,MAAM,CAACC,OAAO,GAAGf,WAAW"}

View File

@@ -0,0 +1,26 @@
/**
* **PostCSS Plugin Warning**
*
* Loader wrapper for postcss plugin warnings (`root.messages`)
*
* @class Warning
* @extends Error
*
* @param {Object} warning PostCSS Warning
*/ class Warning extends Error {
constructor(warning){
super(warning);
const { text , line , column , plugin } = warning;
this.name = "Warning";
this.message = `${this.name}\n\n`;
if (typeof line !== "undefined") {
this.message += `(${line}:${column}) `;
}
this.message += plugin ? `${plugin}: ` : "";
this.message += `${text}`;
this.stack = false;
}
}
module.exports = Warning;
//# sourceMappingURL=Warning.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../build/webpack/loaders/postcss-loader/src/Warning.js"],"names":["Warning","Error","constructor","warning","text","line","column","plugin","name","message","stack","module","exports"],"mappings":"AAAA;;;;;;;;;GASG,CACH,MAAMA,OAAO,SAASC,KAAK;IACzBC,YAAYC,OAAO,CAAE;QACnB,KAAK,CAACA,OAAO,CAAC;QAEd,MAAM,EAAEC,IAAI,CAAA,EAAEC,IAAI,CAAA,EAAEC,MAAM,CAAA,EAAEC,MAAM,CAAA,EAAE,GAAGJ,OAAO;QAE9C,IAAI,CAACK,IAAI,GAAG,SAAS;QAErB,IAAI,CAACC,OAAO,GAAG,CAAC,EAAE,IAAI,CAACD,IAAI,CAAC,IAAI,CAAC;QAEjC,IAAI,OAAOH,IAAI,KAAK,WAAW,EAAE;YAC/B,IAAI,CAACI,OAAO,IAAI,CAAC,CAAC,EAAEJ,IAAI,CAAC,CAAC,EAAEC,MAAM,CAAC,EAAE,CAAC;SACvC;QAED,IAAI,CAACG,OAAO,IAAIF,MAAM,GAAG,CAAC,EAAEA,MAAM,CAAC,EAAE,CAAC,GAAG,EAAE;QAC3C,IAAI,CAACE,OAAO,IAAI,CAAC,EAAEL,IAAI,CAAC,CAAC;QAEzB,IAAI,CAACM,KAAK,GAAG,KAAK;KACnB;CACF;AAEDC,MAAM,CAACC,OAAO,GAAGZ,OAAO"}

View File

@@ -0,0 +1,110 @@
import Warning from "./Warning";
import SyntaxError from "./Error";
import { normalizeSourceMap, normalizeSourceMapAfterPostcss } from "./utils";
/**
* **PostCSS Loader**
*
* Loads && processes CSS with [PostCSS](https://github.com/postcss/postcss)
*
* @method loader
*
* @param {String} content Source
* @param {Object} sourceMap Source Map
* @param {Object} meta Meta
*
* @return {callback} callback Result
*/ export default async function loader(content, sourceMap, meta) {
const loaderSpan = this.currentTraceSpan.traceChild("postcss-loader");
const callback = this.async();
loaderSpan.traceAsyncFn(async ()=>{
const options = this.getOptions();
const file = this.resourcePath;
const useSourceMap = typeof options.sourceMap !== "undefined" ? options.sourceMap : this.sourceMap;
const processOptions = {
from: file,
to: file
};
if (useSourceMap) {
processOptions.map = {
inline: false,
annotation: false,
...processOptions.map
};
}
if (sourceMap && processOptions.map) {
processOptions.map.prev = loaderSpan.traceChild("normalize-source-map").traceFn(()=>normalizeSourceMap(sourceMap, this.context));
}
let root;
// Reuse PostCSS AST from other loaders
if (meta && meta.ast && meta.ast.type === "postcss") {
({ root } = meta.ast);
loaderSpan.setAttribute("astUsed", "true");
}
// Initializes postcss with plugins
const { postcssWithPlugins } = await options.postcss();
let result;
try {
result = await loaderSpan.traceChild("postcss-process").traceAsyncFn(()=>postcssWithPlugins.process(root || content, processOptions));
} catch (error) {
if (error.file) {
this.addDependency(error.file);
}
if (error.name === "CssSyntaxError") {
throw new SyntaxError(error);
}
throw error;
}
for (const warning of result.warnings()){
this.emitWarning(new Warning(warning));
}
for (const message of result.messages){
// eslint-disable-next-line default-case
switch(message.type){
case "dependency":
this.addDependency(message.file);
break;
case "build-dependency":
this.addBuildDependency(message.file);
break;
case "missing-dependency":
this.addMissingDependency(message.file);
break;
case "context-dependency":
this.addContextDependency(message.file);
break;
case "dir-dependency":
this.addContextDependency(message.dir);
break;
case "asset":
if (message.content && message.file) {
this.emitFile(message.file, message.content, message.sourceMap, message.info);
}
}
}
// eslint-disable-next-line no-undefined
let map = result.map ? result.map.toJSON() : undefined;
if (map && useSourceMap) {
map = normalizeSourceMapAfterPostcss(map, this.context);
}
const ast = {
type: "postcss",
version: result.processor.version,
root: result.root
};
return [
result.css,
map,
{
ast
}
];
}).then(([css, map, { ast }])=>{
callback == null ? void 0 : callback(null, css, map, {
ast
});
}, (err)=>{
callback == null ? void 0 : callback(err);
});
};
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../build/webpack/loaders/postcss-loader/src/index.js"],"names":["Warning","SyntaxError","normalizeSourceMap","normalizeSourceMapAfterPostcss","loader","content","sourceMap","meta","loaderSpan","currentTraceSpan","traceChild","callback","async","traceAsyncFn","options","getOptions","file","resourcePath","useSourceMap","processOptions","from","to","map","inline","annotation","prev","traceFn","context","root","ast","type","setAttribute","postcssWithPlugins","postcss","result","process","error","addDependency","name","warning","warnings","emitWarning","message","messages","addBuildDependency","addMissingDependency","addContextDependency","dir","emitFile","info","toJSON","undefined","version","processor","css","then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G,CAAC,CAAA;KAChB,CACF;CACJ,CAAA"}

View File

@@ -0,0 +1,63 @@
import path from "path";
const IS_NATIVE_WIN32_PATH = /^[a-z]:[/\\]|^\\\\/i;
const ABSOLUTE_SCHEME = /^[a-z0-9+\-.]+:/i;
function getURLType(source) {
if (source[0] === "/") {
if (source[1] === "/") {
return "scheme-relative";
}
return "path-absolute";
}
if (IS_NATIVE_WIN32_PATH.test(source)) {
return "path-absolute";
}
return ABSOLUTE_SCHEME.test(source) ? "absolute" : "path-relative";
}
function normalizeSourceMap(map, resourceContext) {
let newMap = map;
// Some loader emit source map as string
// Strip any JSON XSSI avoidance prefix from the string (as documented in the source maps specification), and then parse the string as JSON.
if (typeof newMap === "string") {
newMap = JSON.parse(newMap);
}
delete newMap.file;
const { sourceRoot } = newMap;
delete newMap.sourceRoot;
if (newMap.sources) {
newMap.sources = newMap.sources.map((source)=>{
const sourceType = getURLType(source);
// Do no touch `scheme-relative` and `absolute` URLs
if (sourceType === "path-relative" || sourceType === "path-absolute") {
const absoluteSource = sourceType === "path-relative" && sourceRoot ? path.resolve(sourceRoot, path.normalize(source)) : path.normalize(source);
return path.relative(resourceContext, absoluteSource);
}
return source;
});
}
return newMap;
}
function normalizeSourceMapAfterPostcss(map, resourceContext) {
const newMap = map;
// result.map.file is an optional property that provides the output filename.
// Since we don't know the final filename in the webpack build chain yet, it makes no sense to have it.
// eslint-disable-next-line no-param-reassign
delete newMap.file;
// eslint-disable-next-line no-param-reassign
newMap.sourceRoot = "";
// eslint-disable-next-line no-param-reassign
newMap.sources = newMap.sources.map((source)=>{
if (source.indexOf("<") === 0) {
return source;
}
const sourceType = getURLType(source);
// Do no touch `scheme-relative`, `path-absolute` and `absolute` types
if (sourceType === "path-relative") {
return path.resolve(resourceContext, source);
}
return source;
});
return newMap;
}
export { normalizeSourceMap, normalizeSourceMapAfterPostcss };
//# sourceMappingURL=utils.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../build/webpack/loaders/postcss-loader/src/utils.js"],"names":["path","IS_NATIVE_WIN32_PATH","ABSOLUTE_SCHEME","getURLType","source","test","normalizeSourceMap","map","resourceContext","newMap","JSON","parse","file","sourceRoot","sources","sourceType","absoluteSource","resolve","normalize","relative","normalizeSourceMapAfterPostcss","indexOf"],"mappings":"AAAA,OAAOA,IAAI,MAAM,MAAM,CAAA;AAEvB,MAAMC,oBAAoB,wBAAwB;AAClD,MAAMC,eAAe,qBAAqB;AAE1C,SAASC,UAAU,CAACC,MAAM,EAAE;IAC1B,IAAIA,MAAM,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE;QACrB,IAAIA,MAAM,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE;YACrB,OAAO,iBAAiB,CAAA;SACzB;QAED,OAAO,eAAe,CAAA;KACvB;IAED,IAAIH,oBAAoB,CAACI,IAAI,CAACD,MAAM,CAAC,EAAE;QACrC,OAAO,eAAe,CAAA;KACvB;IAED,OAAOF,eAAe,CAACG,IAAI,CAACD,MAAM,CAAC,GAAG,UAAU,GAAG,eAAe,CAAA;CACnE;AAED,SAASE,kBAAkB,CAACC,GAAG,EAAEC,eAAe,EAAE;IAChD,IAAIC,MAAM,GAAGF,GAAG;IAEhB,wCAAwC;IACxC,4IAA4I;IAC5I,IAAI,OAAOE,MAAM,KAAK,QAAQ,EAAE;QAC9BA,MAAM,GAAGC,IAAI,CAACC,KAAK,CAACF,MAAM,CAAC;KAC5B;IAED,OAAOA,MAAM,CAACG,IAAI;IAElB,MAAM,EAAEC,UAAU,CAAA,EAAE,GAAGJ,MAAM;IAE7B,OAAOA,MAAM,CAACI,UAAU;IAExB,IAAIJ,MAAM,CAACK,OAAO,EAAE;QAClBL,MAAM,CAACK,OAAO,GAAGL,MAAM,CAACK,OAAO,CAACP,GAAG,CAAC,CAACH,MAAM,GAAK;YAC9C,MAAMW,UAAU,GAAGZ,UAAU,CAACC,MAAM,CAAC;YAErC,oDAAoD;YACpD,IAAIW,UAAU,KAAK,eAAe,IAAIA,UAAU,KAAK,eAAe,EAAE;gBACpE,MAAMC,cAAc,GAClBD,UAAU,KAAK,eAAe,IAAIF,UAAU,GACxCb,IAAI,CAACiB,OAAO,CAACJ,UAAU,EAAEb,IAAI,CAACkB,SAAS,CAACd,MAAM,CAAC,CAAC,GAChDJ,IAAI,CAACkB,SAAS,CAACd,MAAM,CAAC;gBAE5B,OAAOJ,IAAI,CAACmB,QAAQ,CAACX,eAAe,EAAEQ,cAAc,CAAC,CAAA;aACtD;YAED,OAAOZ,MAAM,CAAA;SACd,CAAC;KACH;IAED,OAAOK,MAAM,CAAA;CACd;AAED,SAASW,8BAA8B,CAACb,GAAG,EAAEC,eAAe,EAAE;IAC5D,MAAMC,MAAM,GAAGF,GAAG;IAElB,6EAA6E;IAC7E,uGAAuG;IACvG,6CAA6C;IAC7C,OAAOE,MAAM,CAACG,IAAI;IAElB,6CAA6C;IAC7CH,MAAM,CAACI,UAAU,GAAG,EAAE;IAEtB,6CAA6C;IAC7CJ,MAAM,CAACK,OAAO,GAAGL,MAAM,CAACK,OAAO,CAACP,GAAG,CAAC,CAACH,MAAM,GAAK;QAC9C,IAAIA,MAAM,CAACiB,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE;YAC7B,OAAOjB,MAAM,CAAA;SACd;QAED,MAAMW,UAAU,GAAGZ,UAAU,CAACC,MAAM,CAAC;QAErC,sEAAsE;QACtE,IAAIW,UAAU,KAAK,eAAe,EAAE;YAClC,OAAOf,IAAI,CAACiB,OAAO,CAACT,eAAe,EAAEJ,MAAM,CAAC,CAAA;SAC7C;QAED,OAAOA,MAAM,CAAA;KACd,CAAC;IAEF,OAAOK,MAAM,CAAA;CACd;AAED,SAASH,kBAAkB,EAAEc,8BAA8B,GAAE"}

View File

@@ -0,0 +1,83 @@
/*
The MIT License (MIT)
Copyright (c) 2016 Ben Holloway
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.
*/ import { SourceMapConsumer } from "next/dist/compiled/source-map";
import valueProcessor from "./lib/value-processor";
import { defaultJoin } from "./lib/join-function";
import process from "./lib/postcss";
/**
* A webpack loader that resolves absolute url() paths relative to their original source file.
* Requires source-maps to do any meaningful work.
* @param {string} content Css content
* @param {object} sourceMap The source-map
* @returns {string|String}
*/ export default async function resolveUrlLoader(content, sourceMap) {
const options = Object.assign({
sourceMap: this.sourceMap,
silent: false,
absolute: false,
keepQuery: false,
root: false,
debug: false,
join: defaultJoin
}, this.getOptions());
let sourceMapConsumer;
if (sourceMap) {
sourceMapConsumer = new SourceMapConsumer(sourceMap);
}
const callback = this.async();
const { postcss } = await options.postcss();
process(postcss, this.resourcePath, content, {
outputSourceMap: Boolean(options.sourceMap),
transformDeclaration: valueProcessor(this.resourcePath, options),
inputSourceMap: sourceMap,
sourceMapConsumer: sourceMapConsumer
}).catch(onFailure).then(onSuccess);
function onFailure(error) {
callback(encodeError("CSS error", error));
}
function onSuccess(reworked) {
if (reworked) {
// complete with source-map
// source-map sources are relative to the file being processed
if (options.sourceMap) {
callback(null, reworked.content, reworked.map);
} else {
callback(null, reworked.content);
}
}
}
function encodeError(label, exception) {
return new Error([
"resolve-url-loader",
": ",
[
label
].concat(typeof exception === "string" && exception || exception instanceof Error && [
exception.message,
exception.stack.split("\n")[1].trim(),
] || []).filter(Boolean).join("\n "),
].join(""));
}
};
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../build/webpack/loaders/resolve-url-loader/index.js"],"names":["SourceMapConsumer","valueProcessor","defaultJoin","process","resolveUrlLoader","content","sourceMap","options","Object","assign","silent","absolute","keepQuery","root","debug","join","getOptions","sourceMapConsumer","callback","async","postcss","resourcePath","outputSourceMap","Boolean","transformDeclaration","inputSourceMap","catch","onFailure","then","onSuccess","error","encodeError","reworked","map","label","exception","Error","concat","message","stack","split","trim","filter"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;EAsBE,CAEF,SAASA,iBAAiB,QAAQ,+BAA+B,CAAA;AACjE,OAAOC,cAAc,MAAM,uBAAuB,CAAA;AAClD,SAASC,WAAW,QAAQ,qBAAqB,CAAA;AACjD,OAAOC,OAAO,MAAM,eAAe,CAAA;AACnC;;;;;;GAMG,CACH,eAAe,eAAeC,gBAAgB,CAACC,OAAO,EAAEC,SAAS,EAAE;IACjE,MAAMC,OAAO,GAAGC,MAAM,CAACC,MAAM,CAC3B;QACEH,SAAS,EAAE,IAAI,CAACA,SAAS;QACzBI,MAAM,EAAE,KAAK;QACbC,QAAQ,EAAE,KAAK;QACfC,SAAS,EAAE,KAAK;QAChBC,IAAI,EAAE,KAAK;QACXC,KAAK,EAAE,KAAK;QACZC,IAAI,EAAEb,WAAW;KAClB,EACD,IAAI,CAACc,UAAU,EAAE,CAClB;IAED,IAAIC,iBAAiB;IACrB,IAAIX,SAAS,EAAE;QACbW,iBAAiB,GAAG,IAAIjB,iBAAiB,CAACM,SAAS,CAAC;KACrD;IAED,MAAMY,QAAQ,GAAG,IAAI,CAACC,KAAK,EAAE;IAC7B,MAAM,EAAEC,OAAO,CAAA,EAAE,GAAG,MAAMb,OAAO,CAACa,OAAO,EAAE;IAC3CjB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;KACF;CACF,CAAA"}

View File

@@ -0,0 +1,52 @@
/*
The MIT License (MIT)
Copyright (c) 2016 Ben Holloway
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.
*/ /**
* Prepend file:// protocol to source path string or source-map sources.
*/ function prepend(candidate) {
if (typeof candidate === "string") {
return "file://" + candidate;
} else if (candidate && typeof candidate === "object" && Array.isArray(candidate.sources)) {
return Object.assign({}, candidate, {
sources: candidate.sources.map(prepend)
});
} else {
throw new Error("expected string|object");
}
}
exports.prepend = prepend;
/**
* Remove file:// protocol from source path string or source-map sources.
*/ function remove(candidate) {
if (typeof candidate === "string") {
return candidate.replace(/^file:\/{2}/, "");
} else if (candidate && typeof candidate === "object" && Array.isArray(candidate.sources)) {
return Object.assign({}, candidate, {
sources: candidate.sources.map(remove)
});
} else {
throw new Error("expected string|object");
}
}
exports.remove = remove;
//# sourceMappingURL=file-protocol.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../build/webpack/loaders/resolve-url-loader/lib/file-protocol.js"],"names":["prepend","candidate","Array","isArray","sources","Object","assign","map","Error","exports","remove","replace"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;EAsBE,CAEF;;GAEG,CACH,SAASA,OAAO,CAACC,SAAS,EAAE;IAC1B,IAAI,OAAOA,SAAS,KAAK,QAAQ,EAAE;QACjC,OAAO,SAAS,GAAGA,SAAS,CAAA;KAC7B,MAAM,IACLA,SAAS,IACT,OAAOA,SAAS,KAAK,QAAQ,IAC7BC,KAAK,CAACC,OAAO,CAACF,SAAS,CAACG,OAAO,CAAC,EAChC;QACA,OAAOC,MAAM,CAACC,MAAM,CAAC,EAAE,EAAEL,SAAS,EAAE;YAClCG,OAAO,EAAEH,SAAS,CAACG,OAAO,CAACG,GAAG,CAACP,OAAO,CAAC;SACxC,CAAC,CAAA;KACH,MAAM;QACL,MAAM,IAAIQ,KAAK,CAAC,wBAAwB,CAAC,CAAA;KAC1C;CACF;AAEDC,OAAO,CAACT,OAAO,GAAGA,OAAO;AAEzB;;GAEG,CACH,SAASU,MAAM,CAACT,SAAS,EAAE;IACzB,IAAI,OAAOA,SAAS,KAAK,QAAQ,EAAE;QACjC,OAAOA,SAAS,CAACU,OAAO,gBAAgB,EAAE,CAAC,CAAA;KAC5C,MAAM,IACLV,SAAS,IACT,OAAOA,SAAS,KAAK,QAAQ,IAC7BC,KAAK,CAACC,OAAO,CAACF,SAAS,CAACG,OAAO,CAAC,EAChC;QACA,OAAOC,MAAM,CAACC,MAAM,CAAC,EAAE,EAAEL,SAAS,EAAE;YAClCG,OAAO,EAAEH,SAAS,CAACG,OAAO,CAACG,GAAG,CAACG,MAAM,CAAC;SACvC,CAAC,CAAA;KACH,MAAM;QACL,MAAM,IAAIF,KAAK,CAAC,wBAAwB,CAAC,CAAA;KAC1C;CACF;AAEDC,OAAO,CAACC,MAAM,GAAGA,MAAM"}

View File

@@ -0,0 +1,183 @@
/*
The MIT License (MIT)
Copyright (c) 2016 Ben Holloway
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.
*/ import path from "path";
import fs from "fs";
const compose = (f, g)=>(...args)=>f(g(...args));
const simpleJoin = compose(path.normalize, path.join);
/**
* The default join function iterates over possible base paths until a suitable join is found.
*
* The first base path is used as fallback for the case where none of the base paths can locate the actual file.
*
* @type {function}
*/ export const defaultJoin = createJoinForPredicate(function predicate(_, uri, base, i, next) {
const absolute = simpleJoin(base, uri);
return fs.existsSync(absolute) ? absolute : next(i === 0 ? absolute : null);
}, "defaultJoin");
function* createIterator(arr) {
for (const i of arr){
yield i;
}
}
/**
* Define a join function by a predicate that tests possible base paths from an iterator.
*
* The `predicate` is of the form:
*
* ```
* function(filename, uri, base, i, next):string|null
* ```
*
* Given the uri and base it should either return:
* - an absolute path success
* - a call to `next(null)` as failure
* - a call to `next(absolute)` where absolute is placeholder and the iterator continues
*
* The value given to `next(...)` is only used if success does not eventually occur.
*
* The `file` value is typically unused but useful if you would like to differentiate behaviour.
*
* You can write a much simpler function than this if you have specific requirements.
*
* @param {function} predicate A function that tests values
* @param {string} [name] Optional name for the resulting join function
*/ function createJoinForPredicate(predicate, name) {
/**
* A factory for a join function with logging.
*
* @param {string} filename The current file being processed
* @param {{debug:function|boolean,root:string}} options An options hash
*/ function join(filename, options) {
const log = createDebugLogger(options.debug);
/**
* Join function proper.
*
* For absolute uri only `uri` will be provided. In this case we substitute any `root` given in options.
*
* @param {string} uri A uri path, relative or absolute
* @param {string|Iterator.<string>} [baseOrIteratorOrAbsent] Optional absolute base path or iterator thereof
* @return {string} Just the uri where base is empty or the uri appended to the base
*/ return function joinProper(uri, baseOrIteratorOrAbsent) {
const iterator = typeof baseOrIteratorOrAbsent === "undefined" && createIterator([
options.root
]) || typeof baseOrIteratorOrAbsent === "string" && createIterator([
baseOrIteratorOrAbsent
]) || baseOrIteratorOrAbsent;
const result = runIterator([]);
log(createJoinMsg, [
filename,
uri,
result,
result.isFound
]);
return typeof result.absolute === "string" ? result.absolute : uri;
function runIterator(accumulator) {
const nextItem = iterator.next();
var base = !nextItem.done && nextItem.value;
if (typeof base === "string") {
const element = predicate(filename, uri, base, accumulator.length, next);
if (typeof element === "string" && path.isAbsolute(element)) {
return Object.assign(accumulator.concat(base), {
isFound: true,
absolute: element
});
} else if (Array.isArray(element)) {
return element;
} else {
throw new Error("predicate must return an absolute path or the result of calling next()");
}
} else {
return accumulator;
}
function next(fallback) {
return runIterator(Object.assign(accumulator.concat(base), typeof fallback === "string" && {
absolute: fallback
}));
}
}
};
}
function toString() {
return "[Function: " + name + "]";
}
return Object.assign(join, name && {
valueOf: toString,
toString: toString
});
}
/**
* Format a debug message.
*
* @param {string} file The file being processed by webpack
* @param {string} uri A uri path, relative or absolute
* @param {Array.<string>} bases Absolute base paths up to and including the found one
* @param {boolean} isFound Indicates the last base was correct
* @return {string} Formatted message
*/ function createJoinMsg(file, uri, bases, isFound) {
return [
"resolve-url-loader: " + pathToString(file) + ": " + uri
].concat(bases.map(pathToString).filter(Boolean)).concat(isFound ? "FOUND" : "NOT FOUND").join("\n ");
/**
* If given path is within `process.cwd()` then show relative posix path, otherwise show absolute posix path.
*
* @param {string} absolute An absolute path
* @return {string} A relative or absolute path
*/ function pathToString(absolute) {
if (!absolute) {
return null;
} else {
const relative = path.relative(process.cwd(), absolute).split(path.sep);
return (relative[0] === ".." ? absolute.split(path.sep) : [
"."
].concat(relative).filter(Boolean)).join("/");
}
}
}
exports.createJoinMsg = createJoinMsg;
/**
* A factory for a log function predicated on the given debug parameter.
*
* The logging function created accepts a function that formats a message and parameters that the function utilises.
* Presuming the message function may be expensive we only call it if logging is enabled.
*
* The log messages are de-duplicated based on the parameters, so it is assumed they are simple types that stringify
* well.
*
* @param {function|boolean} debug A boolean or debug function
* @return {function(function, array)} A logging function possibly degenerate
*/ function createDebugLogger(debug) {
const log = !!debug && (typeof debug === "function" ? debug : console.log);
const cache = {};
return log ? actuallyLog : noop;
function noop() {}
function actuallyLog(msgFn, params) {
const key = JSON.stringify(params);
if (!cache[key]) {
cache[key] = true;
log(msgFn.apply(null, params));
}
}
}
exports.createDebugLogger = createDebugLogger;
//# sourceMappingURL=join-function.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../build/webpack/loaders/resolve-url-loader/lib/join-function.js"],"names":["path","fs","compose","f","g","args","simpleJoin","normalize","join","defaultJoin","createJoinForPredicate","predicate","_","uri","base","i","next","absolute","existsSync","createIterator","arr","name","filename","options","log","createDebugLogger","debug","joinProper","baseOrIteratorOrAbsent","iterator","root","result","runIterator","createJoinMsg","isFound","accumulator","nextItem","done","value","element","length","isAbsolute","Object","assign","concat","Array","isArray","Error","fallback","toString","valueOf","file","bases","pathToString","map","filter","Boolean","relative","process","cwd","split","sep","exports","console","cache","actuallyLog","noop","msgFn","params","key","JSON","stringify","apply"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;EAsBE,CACF,OAAOA,IAAI,MAAM,MAAM,CAAA;AACvB,OAAOC,EAAE,MAAM,IAAI,CAAA;AAEnB,MAAMC,OAAO,GACX,CAACC,CAAC,EAAEC,CAAC,GACL,CAAIC,GAAAA,IAAI,GACNF,CAAC,CAACC,CAAC,IAAIC,IAAI,CAAC,CAAC;AAEjB,MAAMC,UAAU,GAAGJ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AOA,KAAK,KAAK,UAAU,GAAGA,KAAK,GAAGqC,OAAO,CAACvC,GAAG,CAAC;IAC1E,MAAMwC,KAAK,GAAG,EAAE;IAChB,OAAOxC,GAAG,GAAGyC,WAAW,GAAGC,IAAI,CAAA;IAE/B,SAASA,IAAI,GAAG,EAAE;IAElB,SAASD,WAAW,CAACE,KAAK,EAAEC,MAAM,EAAE;QAClC,MAAMC,GAAG,GAAGC,IAAI,CAACC,SAAS,CAACH,MAAM,CAAC;QAClC,IAAI,CAACJ,KAAK,CAACK,GAAG,CAAC,EAAE;YACfL,KAAK,CAACK,GAAG,CAAC,GAAG,IAAI;YACjB7C,GAAG,CAAC2C,KAAK,CAACK,KAAK,CAAC,IAAI,EAAEJ,MAAM,CAAC,CAAC;SAC/B;KACF;CACF;AAEDN,OAAO,CAACrC,iBAAiB,GAAGA,iBAAiB"}

View File

@@ -0,0 +1,69 @@
/*
The MIT License (MIT)
Copyright (c) 2016 Ben Holloway
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.
*/ import path from "path";
import fileProtocol from "./file-protocol";
const ORPHAN_CR_REGEX = /\r(?!\n)(.|\n)?/g;
export default function process(postcss, sourceFile, sourceContent, params) {
// #107 libsass emits orphan CR not considered newline, postcss does consider newline (content vs source-map mismatch)
// prepend file protocol to all sources to avoid problems with source map
return postcss([
postcss.plugin("postcss-resolve-url", postcssPlugin)
]).process(sourceContent, {
from: fileProtocol.prepend(sourceFile),
map: params.outputSourceMap && {
prev: !!params.inputSourceMap && fileProtocol.prepend(params.inputSourceMap),
inline: false,
annotation: false,
sourcesContent: true
}
}).then((result)=>({
content: result.css,
map: params.outputSourceMap ? fileProtocol.remove(result.map.toJSON()) : null
}));
/**
* Plugin for postcss that follows SASS transpilation.
*/ function postcssPlugin() {
return function(styles) {
styles.walkDecls(eachDeclaration);
};
/**
* Process a declaration from the syntax tree.
* @param declaration
*/ function eachDeclaration(declaration) {
const isValid = declaration.value && declaration.value.indexOf("url") >= 0;
if (isValid) {
// reverse the original source-map to find the original source file before transpilation
const startPosApparent = declaration.source.start, startPosOriginal = params.sourceMapConsumer && params.sourceMapConsumer.originalPositionFor(startPosApparent);
// we require a valid directory for the specified file
const directory = startPosOriginal && startPosOriginal.source && fileProtocol.remove(path.dirname(startPosOriginal.source));
if (directory) {
declaration.value = params.transformDeclaration(declaration.value, directory);
} else if (params.sourceMapConsumer) {
throw new Error("source-map information is not available at url() declaration " + (ORPHAN_CR_REGEX.test(sourceContent) ? "(found orphan CR, try removeCR option)" : "(no orphan CR found)"));
}
}
}
}
};
//# sourceMappingURL=postcss.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../build/webpack/loaders/resolve-url-loader/lib/postcss.js"],"names":["path","fileProtocol","ORPHAN_CR_REGEX","process","postcss","sourceFile","sourceContent","params","plugin","postcssPlugin","from","prepend","map","outputSourceMap","prev","inputSourceMap","inline","annotation","sourcesContent","then","result","content","css","remove","toJSON","styles","walkDecls","eachDeclaration","declaration","isValid","value","indexOf","startPosApparent","source","start","startPosOriginal","sourceMapConsumer","originalPositionFor","directory","dirname","transformDeclaration","Error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AAE;gBACX,wFAAwF;gBACxF,MAAMG,gBAAgB,GAAGJ,WAAW,CAACK,MAAM,CAACC,KAAK,EAC/CC,gBAAgB,GACd5B,MAAM,CAAC6B,iBAAiB,IACxB7B,MAAM,CAAC6B,iBAAiB,CAACC,mBAAmB,CAACL,gBAAgB,CAAC;gBAElE,sDAAsD;gBACtD,MAAMM,SAAS,GACbH,gBAAgB,IAChBA,gBAAgB,CAACF,MAAM,IACvBhC,YAAY,CAACsB,MAAM,CAACvB,IAAI,CAACuC,OAAO,CAACJ,gBAAgB,CAACF,MAAM,CAAC,CAAC;gBAC5D,IAAIK,SAAS,EAAE;oBACbV,WAAW,CAACE,KAAK,GAAGvB,MAAM,CAACiC,oBAAoB,CAC7CZ,WAAW,CAACE,KAAK,EACjBQ,SAAS,CACV;iBACF,MAEI,IAAI/B,MAAM,CAAC6B,iBAAiB,EAAE;oBACjC,MAAM,IAAIK,KAAK,CACb,+DAA+D,GAC7D,CAACvC,eAAe,CAACwC,IAAI,CAACpC,aAAa,CAAC,GAChC,wCAAwC,GACxC,sBAAsB,CAAC,CAC9B,CAAA;iBACF;aACF;SACF;KACF;CACF,CAAA"}

View File

@@ -0,0 +1,86 @@
/*
The MIT License (MIT)
Copyright (c) 2016 Ben Holloway
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.
*/ import loaderUtils from "next/dist/compiled/loader-utils2";
import path from "path";
function valueProcessor(filename, options) {
const URL_STATEMENT_REGEX = /(url\s*\()\s*(?:(['"])((?:(?!\2).)*)(\2)|([^'"](?:(?!\)).)*[^'"]))\s*(\))/g;
const directory = path.dirname(filename);
const join = options.join(filename, options);
/**
* Process the given CSS declaration value.
*
* @param {string} value A declaration value that may or may not contain a url() statement
* @param {string|Iterator.<string>} candidate An absolute path that may be the correct base or an Iterator thereof
*/ return function transformValue(value, candidate) {
// allow multiple url() values in the declaration
// split by url statements and process the content
// additional capture groups are needed to match quotations correctly
// escaped quotations are not considered
return value.split(URL_STATEMENT_REGEX).map((token, i, arr)=>{
// we can get groups as undefined under certain match circumstances
const initialised = token || "";
// the content of the url() statement is either in group 3 or group 5
const mod = i % 7;
if (mod === 3 || mod === 5) {
// detect quoted url and unescape backslashes
const before = arr[i - 1], after = arr[i + 1], isQuoted = before === after && (before === "'" || before === '"'), unescaped = isQuoted ? initialised.replace(/\\{2}/g, "\\") : initialised;
// split into uri and query/hash and then find the absolute path to the uri
const split = unescaped.split(/([?#])/g), uri = split[0], absolute = testIsRelative(uri) && join(uri, candidate) || testIsAbsolute(uri) && join(uri), query = options.keepQuery ? split.slice(1).join("") : "";
// use the absolute path in absolute mode or else relative path (or default to initialised)
// #6 - backslashes are not legal in URI
if (!absolute) {
return initialised;
} else if (options.absolute) {
return absolute.replace(/\\/g, "/") + query;
} else {
return loaderUtils.urlToRequest(path.relative(directory, absolute).replace(/\\/g, "/") + query);
}
} else {
return initialised;
}
}).join("");
};
/**
* The loaderUtils.isUrlRequest() doesn't support windows absolute paths on principle. We do not subscribe to that
* dogma so we add path.isAbsolute() check to allow them.
*
* We also eliminate module relative (~) paths.
*
* @param {string|undefined} uri A uri string possibly empty or undefined
* @return {boolean} True for relative uri
*/ function testIsRelative(uri) {
return !!uri && loaderUtils.isUrlRequest(uri, false) && !path.isAbsolute(uri) && uri.indexOf("~") !== 0;
}
/**
* The loaderUtils.isUrlRequest() doesn't support windows absolute paths on principle. We do not subscribe to that
* dogma so we add path.isAbsolute() check to allow them.
*
* @param {string|undefined} uri A uri string possibly empty or undefined
* @return {boolean} True for absolute uri
*/ function testIsAbsolute(uri) {
return !!uri && typeof options.root === "string" && loaderUtils.isUrlRequest(uri, options.root) && (/^\//.test(uri) || path.isAbsolute(uri));
}
}
module.exports = valueProcessor;
//# sourceMappingURL=value-processor.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../build/webpack/loaders/resolve-url-loader/lib/value-processor.js"],"names":["loaderUtils","path","valueProcessor","filename","options","URL_STATEMENT_REGEX","directory","dirname","join","transformValue","value","candidate","split","map","token","i","arr","initialised","mod","before","after","isQuoted","unescaped","replace","uri","absolute","testIsRelative","testIsAbsolute","query","keepQuery","slice","urlToRequest","relative","isUrlRequest","isAbsolute","indexOf","root","test","module","exports"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;EAsBE,CAEF,OAAOA,WAAW,MAAM,kCAAkC,CAAA;AAC1D,OAAOC,IAAI,MAAM,MAAM,CAAA;AAEvB,SAASC,cAAc,CAACC,QAAQ,EAAEC,OAAO,EAAE;IACzC,MAAMC,mBAAmB,+EACqD;IAC9E,MAAMC,SAAS,GAAGL,IAAI,CAACM,OAAO,CAACJ,QAAQ,CAAC;IACxC,MAAMK,IAAI,GAAGJ,OAAO,CAACI,IAAI,CAACL,QAAQ,EAAEC,OAAO,CAAC;IAE5C;;;;;KAKG,CACH,OAAO,SAASK,cAAc,CAACC,KAAK,EAAEC,SAAS,EAAE;QAC/C,iDAAiD;QACjD,mDAAmD;QACnD,sEAAsE;QACtE,yCAAyC;QACzC,OAAOD,KAAK,CACTE,KAAK,CAACP,mBAAmB,CAAC,CAC1BQ,GAAG,CAAC,C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9B,IAAI,CAAC+B,QAAQ,CAAC1B,SAAS,EAAEmB,QAAQ,CAAC,CAACF,OAAO,QAAQ,GAAG,CAAC,GAAGK,KAAK,CAC/D,CAAA;iBACF;aACF,MAEI;gBACH,OAAOX,WAAW,CAAA;aACnB;SACF,CAAC,CACDT,IAAI,CAAC,EAAE,CAAC,CAAA;KACZ,CAAA;IAED;;;;;;;;KAQG,CACH,SAASkB,cAAc,CAACF,GAAG,EAAE;QAC3B,OACE,CAAC,CAACA,GAAG,IACLxB,WAAW,CAACiC,YAAY,CAACT,GAAG,EAAE,KAAK,CAAC,IACpC,CAACvB,IAAI,CAACiC,UAAU,CAACV,GAAG,CAAC,IACrBA,GAAG,CAACW,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CACvB;KACF;IAED;;;;;;KAMG,CACH,SAASR,cAAc,CAACH,GAAG,EAAE;QAC3B,OACE,CAAC,CAACA,GAAG,IACL,OAAOpB,OAAO,CAACgC,IAAI,KAAK,QAAQ,IAChCpC,WAAW,CAACiC,YAAY,CAACT,GAAG,EAAEpB,OAAO,CAACgC,IAAI,CAAC,IAC3C,CAAC,MAAMC,IAAI,CAACb,GAAG,CAAC,IAAIvB,IAAI,CAACiC,UAAU,CAACV,GAAG,CAAC,CAAC,CAC1C;KACF;CACF;AAEDc,MAAM,CAACC,OAAO,GAAGrC,cAAc"}

View File

@@ -0,0 +1,17 @@
import { RSC_MODULE_TYPES } from "../../../shared/lib/constants";
const imageExtensions = [
"jpg",
"jpeg",
"png",
"webp",
"avif"
];
const imageRegex = new RegExp(`\\.(${imageExtensions.join("|")})$`);
export function isClientComponentModule(mod) {
var ref;
const hasClientDirective = ((ref = mod.buildInfo.rsc) == null ? void 0 : ref.type) === RSC_MODULE_TYPES.client;
return hasClientDirective || imageRegex.test(mod.resource);
}
export const regexCSS = /\.(css|scss|sass)(\?.*)?$/;
//# sourceMappingURL=utils.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/webpack/loaders/utils.ts"],"names":["RSC_MODULE_TYPES","imageExtensions","imageRegex","RegExp","join","isClientComponentModule","mod","hasClientDirective","buildInfo","rsc","type","client","test","resource","regexCSS"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,+BAA+B,CAAA;AAEhE,MAAMC,eAAe,GAAG;IAAC,KAAK;IAAE,MAAM;IAAE,KAAK;IAAE,MAAM;IAAE,MAAM;CAAC;AAC9D,MAAMC,UAAU,GAAG,IAAIC,MAAM,CAAC,CAAC,IAAI,EAAEF,eAAe,CAACG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC;AAEnE,OAAO,SAASC,uBAAuB,CAACC,GAGvC,EAAE;QAC0BA,GAAiB;IAA5C,MAAMC,kBAAkB,GAAGD,CAAAA,CAAAA,GAAiB,GAAjBA,GAAG,CAACE,SAAS,CAACC,GAAG,SAAM,GAAvBH,KAAAA,CAAuB,GAAvBA,GAAiB,CAAEI,IAAI,CAAA,KAAKV,gBAAgB,CAACW,MAAM;IAC9E,OAAOJ,kBAAkB,IAAIL,UAAU,CAACU,IAAI,CAACN,GAAG,CAACO,QAAQ,CAAC,CAAA;CAC3D;AAED,OAAO,MAAMC,QAAQ,8BAA8B,CAAA"}