next-dev
Version:
Tentu, berikut adalah markdown yang telah diperbaiki:
153 lines (152 loc) • 7.4 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = __importDefault(require("path"));
const readdirp_1 = __importDefault(require("readdirp"));
const fs_1 = __importDefault(require("fs"));
const parser = __importStar(require("@babel/parser"));
const traverse_1 = __importDefault(require("@babel/traverse"));
const prettier_1 = __importDefault(require("prettier"));
async function generateDevBox(argv) {
const log = argv.log;
console.log(log ? "START WITH LOG" : "START WITHOUT LOG ");
for await (const entry of (0, readdirp_1.default)(path_1.default.join(process.cwd(), '/src/ui'), { fileFilter: ['*.tsx'] })) {
let fileContent = await fs_1.default.promises.readFile(entry.fullPath, 'utf8');
fileContent = useDevModify(fileContent, log);
if (fileContent.includes("use dev")) {
await processDevBox({ stringCode: fileContent, fullPath: entry.fullPath, log });
}
}
console.log(`✨✨✨ DONE ✨✨✨`);
}
exports.default = generateDevBox;
function useDevModify(text, log) {
const lines = text.split('\n');
// Check if "use dev" is already in the first or second line
if (lines.length > 0 && lines[0].includes('use dev')) {
log && console.log(`use dev already present in ${path_1.default.basename(lines[0])}`);
return text; // "use dev" already present in the first line, no need to modify
}
if (lines.length > 1 && lines[1].includes('use dev')) {
log && console.log(`use dev already present in ${path_1.default.basename(lines[1])}`);
return text; // "use dev" already present in the second line, no need to modify
}
// Check if the first line has "use client"
if (lines.length > 0 && lines[0].includes('use client')) {
// If the second line is empty, add "use dev"
log && console.log(`use dev added to ${path_1.default.basename(lines[0])}`);
if (lines.length === 1 || lines[1].trim() === '') {
log && console.log(`use dev added to ${path_1.default.basename(lines[0])}`);
lines.splice(1, 0, '\"use dev\"'); // Add "use dev" to the second line
}
else {
log && console.log(`use dev added to ${path_1.default.basename(lines[1])}`);
lines.splice(1, 0, '\"use dev\"'); // Insert "use dev" at the second line
}
}
else {
// Add "use dev" to the first line
log && console.log(`use dev added to ${path_1.default.basename(lines[0])}`);
lines.unshift('\"use dev\"');
}
return lines.join('\n');
}
async function processDevBox({ stringCode, fullPath, log }) {
let formattedCode = await prettier_1.default.format(stringCode, { parser: "typescript" });
let ast;
try {
// Parse code into AST
ast = parser.parse(formattedCode, {
sourceType: "module",
plugins: ["jsx", "typescript"]
});
}
catch (error) {
console.error(`Parsing error: ${fullPath}`.red, error.message);
return;
}
let hasDevBoxImport = false;
try {
const newCodeSegments = [];
let lastIndex = 0;
(0, traverse_1.default)(ast, {
ImportDeclaration(path) {
if (path.node.source.value === "next-dev") {
path.node.specifiers.forEach((specifier) => {
if (specifier.imported.name === "DevBox") {
hasDevBoxImport = true;
}
});
}
},
ReturnStatement(innerPath) {
if (innerPath.node.argument && innerPath.node.argument.type === "JSXElement") {
const jsxElement = innerPath.node.argument;
if (jsxElement.openingElement.type === "JSXOpeningElement" &&
jsxElement.openingElement.name.name === "DevBox") {
// Update the path value
const start = jsxElement.loc.start.index;
const end = jsxElement.loc.end.index;
const mainBody = formattedCode.substring(start, end);
const line = jsxElement.loc.start.line;
const pathStringValue = `vscode://file/${fullPath}:${line + 1}:1`;
const newPathAttribute = `path="${Buffer.from(pathStringValue).toString('base64')}"`;
const updatedBody = mainBody.replace(/path=".*?"/, newPathAttribute);
newCodeSegments.push(formattedCode.substring(lastIndex, start));
newCodeSegments.push(updatedBody);
lastIndex = end;
return;
}
const start = jsxElement.loc.start.index;
const end = jsxElement.loc.end.index;
const mainBody = formattedCode.substring(start, end);
const line = jsxElement.loc.start.line;
const pathStringValue = `vscode://file/${fullPath}:${line + 1}:1`;
newCodeSegments.push(formattedCode.substring(lastIndex, start));
newCodeSegments.push(`<DevBox path="${Buffer.from(pathStringValue).toString('base64')}">\n${mainBody}\n</DevBox>`);
lastIndex = end;
}
}
});
newCodeSegments.push(formattedCode.substring(lastIndex));
let newCode = newCodeSegments.join('');
if (!hasDevBoxImport) {
log && console.log("Importing DevBox...".green, fullPath);
newCode = newCode.replace(/['"]\s*use dev\s*['"]/g, `'use dev';\nimport { DevBox } from 'next-dev';`);
}
else {
log && console.log("DevBox already imported, skipping...".yellow, fullPath);
}
const finalFormattedCode = await prettier_1.default.format(newCode, { parser: "typescript" });
await fs_1.default.promises.writeFile(fullPath, finalFormattedCode, "utf8");
log && console.log(`Updated file: ${fullPath}`);
}
catch (error) {
console.error(`Traversal error: ${fullPath}`.red, error.message);
}
}