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,72 @@
import chalk from "next/dist/compiled/chalk";
import path from "path";
export var MessageSeverity;
(function(MessageSeverity) {
MessageSeverity[MessageSeverity["Warning"] = 1] = "Warning";
MessageSeverity[MessageSeverity["Error"] = 2] = "Error";
})(MessageSeverity || (MessageSeverity = {}));
function pluginCount(messages) {
let nextPluginWarningCount = 0;
let nextPluginErrorCount = 0;
for(let i = 0; i < messages.length; i++){
const { severity , ruleId } = messages[i];
if (ruleId == null ? void 0 : ruleId.includes("@next/next")) {
if (severity === 1) {
nextPluginWarningCount += 1;
} else {
nextPluginErrorCount += 1;
}
}
}
return {
nextPluginErrorCount,
nextPluginWarningCount
};
}
function formatMessage(dir, messages, filePath) {
let fileName = path.posix.normalize(path.relative(dir, filePath).replace(/\\/g, "/"));
if (!fileName.startsWith(".")) {
fileName = "./" + fileName;
}
let output = "\n" + chalk.cyan(fileName);
for(let i = 0; i < messages.length; i++){
const { message , severity , line , column , ruleId } = messages[i];
output = output + "\n";
if (line && column) {
output = output + chalk.yellow(line.toString()) + ":" + chalk.yellow(column.toString()) + " ";
}
if (severity === 1) {
output += chalk.yellow.bold("Warning") + ": ";
} else {
output += chalk.red.bold("Error") + ": ";
}
output += message;
if (ruleId) {
output += " " + chalk.gray.bold(ruleId);
}
}
return output;
}
export function formatResults(baseDir, results, format) {
let totalNextPluginErrorCount = 0;
let totalNextPluginWarningCount = 0;
let resultsWithMessages = results.filter(({ messages })=>{
return messages == null ? void 0 : messages.length;
});
// Track number of Next.js plugin errors and warnings
resultsWithMessages.forEach(({ messages })=>{
const res = pluginCount(messages);
totalNextPluginErrorCount += res.nextPluginErrorCount;
totalNextPluginWarningCount += res.nextPluginWarningCount;
});
// Use user defined formatter or Next.js's built-in custom formatter
const output = format ? format(resultsWithMessages) : resultsWithMessages.map(({ messages , filePath })=>formatMessage(baseDir, messages, filePath)).join("\n");
return {
output: output,
outputWithMessages: resultsWithMessages.length > 0 ? output + `\n\n${chalk.cyan("info")} - Need to disable some ESLint rules? Learn more here: https://nextjs.org/docs/basic-features/eslint#disabling-rules` : "",
totalNextPluginErrorCount,
totalNextPluginWarningCount
};
}
//# sourceMappingURL=customFormatter.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../lib/eslint/customFormatter.ts"],"names":["chalk","path","MessageSeverity","Warning","Error","pluginCount","messages","nextPluginWarningCount","nextPluginErrorCount","i","length","severity","ruleId","includes","formatMessage","dir","filePath","fileName","posix","normalize","relative","replace","startsWith","output","cyan","message","line","column","yellow","toString","bold","red","gray","formatResults","baseDir","results","format","totalNextPluginErrorCount","totalNextPluginWarningCount","resultsWithMessages","filter","forEach","res","map","join","outputWithMessages"],"mappings":"AAAA,OAAOA,KAAK,MAAM,0BAA0B,CAAA;AAC5C,OAAOC,IAAI,MAAM,MAAM,CAAA;WAGhB,eAGN;UAHWC,eAAe;IAAfA,eAAe,CAAfA,eAAe,CACzBC,SAAO,IAAG,CAAC,IAAXA,SAAO;IADGD,eAAe,CAAfA,eAAe,CAEzBE,OAAK,IAAG,CAAC,IAATA,OAAK;GAFKF,eAAe,KAAfA,eAAe;AAsB3B,SAASG,WAAW,CAACC,QAAuB,EAG1C;IACA,IAAIC,sBAAsB,GAAG,CAAC;IAC9B,IAAIC,oBAAoB,GAAG,CAAC;IAE5B,IAAK,IAAIC,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGH,QAAQ,CAACI,MAAM,EAAED,CAAC,EAAE,CAAE;QACxC,MAAM,EAAEE,QAAQ,CAAA,EAAEC,MAAM,CAAA,EAAE,GAAGN,QAAQ,CAACG,CAAC,CAAC;QAExC,IAAIG,MAAM,QAAU,GAAhBA,KAAAA,CAAgB,GAAhBA,MAAM,CAAEC,QAAQ,CAAC,YAAY,CAAC,EAAE;YAClC,IAAIF,QAAQ,KAhCN,CAAC,AAgCiC,EAAE;gBAC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AAK,CAACwB,IAAI,CACf,MAAM,CACP,CAAC,qHAAqH,CAAC,GACxH,EAAE;QACRa,yBAAyB;QACzBC,2BAA2B;KAC5B,CAAA;CACF"}

View File

@@ -0,0 +1,37 @@
import { promises as fs } from "fs";
export async function hasEslintConfiguration(eslintrcFile, packageJsonConfig) {
const configObject = {
exists: false,
emptyEslintrc: false,
emptyPkgJsonConfig: false
};
if (eslintrcFile) {
const content = await fs.readFile(eslintrcFile, {
encoding: "utf8"
}).then((txt)=>txt.trim().replace(/\n/g, ""), ()=>null);
if (content === "" || content === "{}" || content === "---" || content === "module.exports = {}") {
return {
...configObject,
emptyEslintrc: true
};
}
return {
...configObject,
exists: true
};
} else if (packageJsonConfig == null ? void 0 : packageJsonConfig.eslintConfig) {
if (Object.keys(packageJsonConfig == null ? void 0 : packageJsonConfig.eslintConfig).length) {
return {
...configObject,
exists: true
};
}
return {
...configObject,
emptyPkgJsonConfig: true
};
}
return configObject;
}
//# sourceMappingURL=hasEslintConfiguration.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../lib/eslint/hasEslintConfiguration.ts"],"names":["promises","fs","hasEslintConfiguration","eslintrcFile","packageJsonConfig","configObject","exists","emptyEslintrc","emptyPkgJsonConfig","content","readFile","encoding","then","txt","trim","replace","eslintConfig","Object","keys","length"],"mappings":"AAAA,SAASA,QAAQ,IAAIC,EAAE,QAAQ,IAAI,CAAA;AASnC,OAAO,eAAeC,sBAAsB,CAC1CC,YAA2B,EAC3BC,iBAA+C,EACrB;IAC1B,MAAMC,YAAY,GAAG;QACnBC,MAAM,EAAE,KAAK;QACbC,aAAa,EAAE,KAAK;QACpBC,kBAAkB,EAAE,KAAK;KAC1B;IAED,IAAIL,YAAY,EAAE;QAChB,MAAMM,OAAO,GAAG,MAAMR,EAAE,CAACS,QAAQ,CAACP,YAAY,EAAE;YAAEQ,QAAQ,EAAE,MAAM;SAAE,CAAC,CAACC,IAAI,CACxE,CAACC,GAAG,GAAKA,GAAG,CAACC,IAAI,EAAE,CAACC,OAAO,QAAQ,EAAE,CAAC,EACtC,IAAM,IAAI,CACX;QAED,IACEN,OAAO,KAAK,EAAE,IACdA,OAAO,KAAK,IAAI,IAChBA,OAAO,KAAK,KAAK,IACjBA,OAAO,KAAK,qBAAqB,EACjC;YACA,OAAO;gBAAE,GAAGJ,YAAY;gBAAEE,aAAa,EAAE,IAAI;aAAE,CAAA;SAChD;QACD,OAAO;YAAE,GAAGF,YAAY;YAAEC,MAAM,EAAE,IAAI;SAAE,CAAA;KACzC,MAAM,IAAIF,iBAAiB,QAAc,GAA/BA,KAAAA,CAA+B,GAA/BA,iBAAiB,CAAEY,YAAY,EAAE;QAC1C,IAAIC,MAAM,CAACC,IAAI,CAACd,iBAAiB,QAAc,GAA/BA,KAAAA,CAA+B,GAA/BA,iBAAiB,CAAEY,YAAY,CAAC,CAACG,MAAM,EAAE;YACvD,OAAO;gBAAE,GAAGd,YAAY;gBAAEC,MAAM,EAAE,IAAI;aAAE,CAAA;SACzC;QACD,OAAO;YAAE,GAAGD,YAAY;YAAEG,kBAAkB,EAAE,IAAI;SAAE,CAAA;KACrD;IACD,OAAOH,YAAY,CAAA;CACpB"}

View File

@@ -0,0 +1,246 @@
import { promises as fs } from "fs";
import chalk from "next/dist/compiled/chalk";
import path from "path";
import findUp from "next/dist/compiled/find-up";
import semver from "next/dist/compiled/semver";
import * as CommentJson from "next/dist/compiled/comment-json";
import { formatResults } from "./customFormatter";
import { writeDefaultConfig } from "./writeDefaultConfig";
import { hasEslintConfiguration } from "./hasEslintConfiguration";
import { writeOutputFile } from "./writeOutputFile";
import { ESLINT_PROMPT_VALUES } from "../constants";
import { existsSync, findPagesDir } from "../find-pages-dir";
import { installDependencies } from "../install-dependencies";
import { hasNecessaryDependencies } from "../has-necessary-dependencies";
import * as Log from "../../build/output/log";
import isError, { getProperError } from "../is-error";
import { getPkgManager } from "../helpers/get-pkg-manager";
// 0 is off, 1 is warn, 2 is error. See https://eslint.org/docs/user-guide/configuring/rules#configuring-rules
const VALID_SEVERITY = [
"off",
"warn",
"error"
];
function isValidSeverity(severity) {
return VALID_SEVERITY.includes(severity);
}
const requiredPackages = [
{
file: "eslint",
pkg: "eslint",
exportsRestrict: false
},
{
file: "eslint-config-next",
pkg: "eslint-config-next",
exportsRestrict: false
},
];
async function cliPrompt() {
console.log(chalk.bold(`${chalk.cyan("?")} How would you like to configure ESLint? https://nextjs.org/docs/basic-features/eslint`));
try {
const cliSelect = (await Promise.resolve(require("next/dist/compiled/cli-select"))).default;
const { value } = await cliSelect({
values: ESLINT_PROMPT_VALUES,
valueRenderer: ({ title , recommended }, selected)=>{
const name = selected ? chalk.bold.underline.cyan(title) : title;
return name + (recommended ? chalk.bold.yellow(" (recommended)") : "");
},
selected: chalk.cyan("\u276F "),
unselected: " "
});
return {
config: value == null ? void 0 : value.config
};
} catch {
return {
config: null
};
}
}
async function lint(baseDir, lintDirs, eslintrcFile, pkgJsonPath, hasAppDir, { lintDuringBuild =false , eslintOptions =null , reportErrorsOnly =false , maxWarnings =-1 , formatter =null , outputFile =null }) {
try {
var ref, ref1;
// Load ESLint after we're sure it exists:
const deps = await hasNecessaryDependencies(baseDir, requiredPackages);
const packageManager = getPkgManager(baseDir);
if (deps.missing.some((dep)=>dep.pkg === "eslint")) {
Log.error(`ESLint must be installed${lintDuringBuild ? " in order to run during builds:" : ":"} ${chalk.bold.cyan((packageManager === "yarn" ? "yarn add --dev" : packageManager === "pnpm" ? "pnpm install --save-dev" : "npm install --save-dev") + " eslint")}`);
return null;
}
const mod = await Promise.resolve(require(deps.resolved.get("eslint")));
const { ESLint } = mod;
let eslintVersion = (ESLint == null ? void 0 : ESLint.version) ?? (mod == null ? void 0 : (ref = mod.CLIEngine) == null ? void 0 : ref.version);
if (!eslintVersion || semver.lt(eslintVersion, "7.0.0")) {
return `${chalk.red("error")} - Your project has an older version of ESLint installed${eslintVersion ? " (" + eslintVersion + ")" : ""}. Please upgrade to ESLint version 7 or above`;
}
let options = {
useEslintrc: true,
baseConfig: {},
errorOnUnmatchedPattern: false,
extensions: [
".js",
".jsx",
".ts",
".tsx"
],
cache: true,
...eslintOptions
};
let eslint = new ESLint(options);
let nextEslintPluginIsEnabled = false;
const nextRulesEnabled = new Map();
for (const configFile of [
eslintrcFile,
pkgJsonPath
]){
var ref2;
if (!configFile) continue;
const completeConfig = await eslint.calculateConfigForFile(configFile);
if ((ref2 = completeConfig.plugins) == null ? void 0 : ref2.includes("@next/next")) {
nextEslintPluginIsEnabled = true;
for (const [name, [severity]] of Object.entries(completeConfig.rules)){
if (!name.startsWith("@next/next/")) {
continue;
}
if (typeof severity === "number" && severity >= 0 && severity < VALID_SEVERITY.length) {
nextRulesEnabled.set(name, VALID_SEVERITY[severity]);
} else if (typeof severity === "string" && isValidSeverity(severity)) {
nextRulesEnabled.set(name, severity);
}
}
break;
}
}
const pagesDir = findPagesDir(baseDir, hasAppDir).pagesDir;
const pagesDirRules = pagesDir ? [
"@next/next/no-html-link-for-pages"
] : [];
if (nextEslintPluginIsEnabled) {
let updatedPagesDir = false;
for (const rule of pagesDirRules){
var ref3, ref4;
if (!((ref3 = options.baseConfig.rules) == null ? void 0 : ref3[rule]) && !((ref4 = options.baseConfig.rules) == null ? void 0 : ref4[rule.replace("@next/next", "@next/babel-plugin-next")])) {
if (!options.baseConfig.rules) {
options.baseConfig.rules = {};
}
options.baseConfig.rules[rule] = [
1,
pagesDir
];
updatedPagesDir = true;
}
}
if (updatedPagesDir) {
eslint = new ESLint(options);
}
} else {
Log.warn("The Next.js plugin was not detected in your ESLint configuration. See https://nextjs.org/docs/basic-features/eslint#migrating-existing-config");
}
const lintStart = process.hrtime();
let results = await eslint.lintFiles(lintDirs);
let selectedFormatter = null;
if (options.fix) await ESLint.outputFixes(results);
if (reportErrorsOnly) results = await ESLint.getErrorResults(results) // Only return errors if --quiet flag is used
;
if (formatter) selectedFormatter = await eslint.loadFormatter(formatter);
const formattedResult = formatResults(baseDir, results, selectedFormatter == null ? void 0 : selectedFormatter.format);
const lintEnd = process.hrtime(lintStart);
const totalWarnings = results.reduce((sum, file)=>sum + file.warningCount, 0);
if (outputFile) await writeOutputFile(outputFile, formattedResult.output);
return {
output: formattedResult.outputWithMessages,
isError: ((ref1 = ESLint.getErrorResults(results)) == null ? void 0 : ref1.length) > 0 || maxWarnings >= 0 && totalWarnings > maxWarnings,
eventInfo: {
durationInSeconds: lintEnd[0],
eslintVersion: eslintVersion,
lintedFilesCount: results.length,
lintFix: !!options.fix,
nextEslintPluginVersion: nextEslintPluginIsEnabled && deps.resolved.has("eslint-config-next") ? require(path.join(path.dirname(deps.resolved.get("eslint-config-next")), "package.json")).version : null,
nextEslintPluginErrorsCount: formattedResult.totalNextPluginErrorCount,
nextEslintPluginWarningsCount: formattedResult.totalNextPluginWarningCount,
nextRulesEnabled: Object.fromEntries(nextRulesEnabled)
}
};
} catch (err) {
if (lintDuringBuild) {
Log.error(`ESLint: ${isError(err) && err.message ? err.message.replace(/\n/g, " ") : err}`);
return null;
} else {
throw getProperError(err);
}
}
}
export async function runLintCheck(baseDir, lintDirs, hasAppDir, opts) {
const { lintDuringBuild =false , eslintOptions =null , reportErrorsOnly =false , maxWarnings =-1 , formatter =null , outputFile =null , strict =false , } = opts;
try {
// Find user's .eslintrc file
// See: https://eslint.org/docs/user-guide/configuring/configuration-files#configuration-file-formats
const eslintrcFile = await findUp([
".eslintrc.js",
".eslintrc.cjs",
".eslintrc.yaml",
".eslintrc.yml",
".eslintrc.json",
".eslintrc",
], {
cwd: baseDir
}) ?? null;
const pkgJsonPath = await findUp("package.json", {
cwd: baseDir
}) ?? null;
let packageJsonConfig = null;
if (pkgJsonPath) {
const pkgJsonContent = await fs.readFile(pkgJsonPath, {
encoding: "utf8"
});
packageJsonConfig = CommentJson.parse(pkgJsonContent);
}
const config = await hasEslintConfiguration(eslintrcFile, packageJsonConfig);
let deps;
if (config.exists) {
// Run if ESLint config exists
return await lint(baseDir, lintDirs, eslintrcFile, pkgJsonPath, hasAppDir, {
lintDuringBuild,
eslintOptions,
reportErrorsOnly,
maxWarnings,
formatter,
outputFile
});
} else {
// Display warning if no ESLint configuration is present inside
// config file during "next build", no warning is shown when
// no eslintrc file is present
if (lintDuringBuild) {
if (config.emptyPkgJsonConfig || config.emptyEslintrc) {
Log.warn(`No ESLint configuration detected. Run ${chalk.bold.cyan("next lint")} to begin setup`);
}
return null;
} else {
// Ask user what config they would like to start with for first time "next lint" setup
const { config: selectedConfig } = strict ? ESLINT_PROMPT_VALUES.find((opt)=>opt.title === "Strict") : await cliPrompt();
if (selectedConfig == null) {
// Show a warning if no option is selected in prompt
Log.warn("If you set up ESLint yourself, we recommend adding the Next.js ESLint plugin. See https://nextjs.org/docs/basic-features/eslint#migrating-existing-config");
return null;
} else {
// Check if necessary deps installed, and install any that are missing
deps = await hasNecessaryDependencies(baseDir, requiredPackages);
if (deps.missing.length > 0) await installDependencies(baseDir, deps.missing, true);
// Write default ESLint config.
// Check for /pages and src/pages is to make sure this happens in Next.js folder
if (existsSync(path.join(baseDir, "pages")) || existsSync(path.join(baseDir, "src/pages"))) {
await writeDefaultConfig(baseDir, config, selectedConfig, eslintrcFile, pkgJsonPath, packageJsonConfig);
}
}
Log.ready(`ESLint has successfully been configured. Run ${chalk.bold.cyan("next lint")} again to view warnings and errors.`);
return null;
}
}
} catch (err) {
throw err;
}
}
//# sourceMappingURL=runLintCheck.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,31 @@
import { promises as fs } from "fs";
import chalk from "next/dist/compiled/chalk";
import os from "os";
import path from "path";
import * as CommentJson from "next/dist/compiled/comment-json";
import * as Log from "../../build/output/log";
export async function writeDefaultConfig(baseDir, { exists , emptyEslintrc , emptyPkgJsonConfig }, selectedConfig, eslintrcFile, pkgJsonPath, packageJsonConfig) {
if (!exists && emptyEslintrc && eslintrcFile) {
const ext = path.extname(eslintrcFile);
let newFileContent;
if (ext === ".yaml" || ext === ".yml") {
newFileContent = "extends: 'next'";
} else {
newFileContent = CommentJson.stringify(selectedConfig, null, 2);
if (ext === ".js") {
newFileContent = "module.exports = " + newFileContent;
}
}
await fs.writeFile(eslintrcFile, newFileContent + os.EOL);
Log.info(`We detected an empty ESLint configuration file (${chalk.bold(path.basename(eslintrcFile))}) and updated it for you!`);
} else if (!exists && emptyPkgJsonConfig && packageJsonConfig) {
packageJsonConfig.eslintConfig = selectedConfig;
if (pkgJsonPath) await fs.writeFile(pkgJsonPath, CommentJson.stringify(packageJsonConfig, null, 2) + os.EOL);
Log.info(`We detected an empty ${chalk.bold("eslintConfig")} field in package.json and updated it for you!`);
} else if (!exists) {
await fs.writeFile(path.join(baseDir, ".eslintrc.json"), CommentJson.stringify(selectedConfig, null, 2) + os.EOL);
console.log(chalk.green(`We created the ${chalk.bold(".eslintrc.json")} file for you and included your selected configuration.`));
}
}
//# sourceMappingURL=writeDefaultConfig.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../lib/eslint/writeDefaultConfig.ts"],"names":["promises","fs","chalk","os","path","CommentJson","Log","writeDefaultConfig","baseDir","exists","emptyEslintrc","emptyPkgJsonConfig","selectedConfig","eslintrcFile","pkgJsonPath","packageJsonConfig","ext","extname","newFileContent","stringify","writeFile","EOL","info","bold","basename","eslintConfig","join","console","log","green"],"mappings":"AAAA,SAASA,QAAQ,IAAIC,EAAE,QAAQ,IAAI,CAAA;AACnC,OAAOC,KAAK,MAAM,0BAA0B,CAAA;AAC5C,OAAOC,EAAE,MAAM,IAAI,CAAA;AACnB,OAAOC,IAAI,MAAM,MAAM,CAAA;AACvB,YAAYC,WAAW,MAAM,iCAAiC,CAAA;AAG9D,YAAYC,GAAG,MAAM,wBAAwB,CAAA;AAE7C,OAAO,eAAeC,kBAAkB,CACtCC,OAAe,EACf,EAAEC,MAAM,CAAA,EAAEC,aAAa,CAAA,EAAEC,kBAAkB,CAAA,EAAmB,EAC9DC,cAAmB,EACnBC,YAA2B,EAC3BC,WAA0B,EAC1BC,iBAA+C,EAC/C;IACA,IAAI,CAACN,MAAM,IA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T,EAAE,CAACkB,GAAG,CACxD;QAEDM,OAAO,CAACC,GAAG,CACT1B,KAAK,CAAC2B,KAAK,CACT,CAAC,eAAe,EAAE3B,KAAK,CAACqB,IAAI,CAC1B,gBAAgB,CACjB,CAAC,uDAAuD,CAAC,CAC3D,CACF;KACF;CACF"}

View File

@@ -0,0 +1,38 @@
import { promises as fs } from "fs";
import path from "path";
import * as Log from "../../build/output/log";
import isError from "../../lib/is-error";
/**
* Check if a given file path is a directory or not.
* Returns `true` if the path is a directory.
*/ async function isDirectory(/** The path to a file to check. */ filePath) {
try {
return (await fs.stat(filePath)).isDirectory();
} catch (error) {
if (isError(error) && (error.code === "ENOENT" || error.code === "ENOTDIR")) {
return false;
}
throw error;
}
}
/**
* Create a file with eslint output data
*/ export async function writeOutputFile(/** The name file that needs to be created */ outputFile, /** The data that needs to be inserted into the file */ outputData) {
const filePath = path.resolve(process.cwd(), outputFile);
if (await isDirectory(filePath)) {
Log.error(`Cannot write to output file path, it is a directory: ${filePath}`);
} else {
try {
await fs.mkdir(path.dirname(filePath), {
recursive: true
});
await fs.writeFile(filePath, outputData);
Log.info(`The output file has been created: ${filePath}`);
} catch (err) {
Log.error(`There was a problem writing the output file: ${filePath}`);
console.error(err);
}
}
}
//# sourceMappingURL=writeOutputFile.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../lib/eslint/writeOutputFile.ts"],"names":["promises","fs","path","Log","isError","isDirectory","filePath","stat","error","code","writeOutputFile","outputFile","outputData","resolve","process","cwd","mkdir","dirname","recursive","writeFile","info","err","console"],"mappings":"AAAA,SAASA,QAAQ,IAAIC,EAAE,QAAQ,IAAI,CAAA;AACnC,OAAOC,IAAI,MAAM,MAAM,CAAA;AACvB,YAAYC,GAAG,MAAM,wBAAwB,CAAA;AAC7C,OAAOC,OAAO,MAAM,oBAAoB,CAAA;AAExC;;;GAGG,CACH,eAAeC,WAAW,CACxB,oCAAoC,CACpCC,QAAgB,EACE;IAClB,IAAI;QACF,OAAO,C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