[add] require support

This commit is contained in:
2025-08-03 15:55:20 +01:00
parent e018f253f1
commit ef886bf610
2 changed files with 67 additions and 44 deletions

View File

@@ -1,11 +1,11 @@
import { readFileSync ,mkdirSync} from 'node:fs'; import { readFileSync, mkdirSync } from 'node:fs';
import { writeFile } from 'node:fs/promises'; import { writeFile } from 'node:fs/promises';
import { Project} from 'ts-morph'; import { Project } from 'ts-morph';
import {getSliceAndInfoSync} from 'slice-js/src/slice-code/test/helpers/utils.js'; import { getSliceAndInfoSync } from 'slice-js/src/slice-code/test/helpers/utils.js';
import path from 'node:path'; import path from 'node:path';
import { getImportCallsAndArgumentTypes } from './tsCalls.mjs'; import { getImportCallsAndArgumentTypes, isNodeModule, isRelativeModule, logCallList } from './tsCalls.mjs';
import { wpCompress } from './bundle/index.mjs'; import { wpCompress } from './bundle/index.mjs';
import { LibraryTypesRecorder } from './libcalls.mjs'; import { LibraryTypesRecorder } from './libcalls.mjs';
/** /**
@@ -22,10 +22,10 @@ export async function sliceAndWriteCalls(calls, FILE_PATH) {
continue; continue;
} }
console.log(`Slicing module ${moduleName} - ${callBox.size} calls`); console.log(`Slicing module ${moduleName} - ${callBox.size} calls`);
// const relatedModuleNamePath = import.meta.resolve(moduleName); // const relatedModuleNamePath = import.meta.resolve(moduleName);
// console.log(`Related module path`, relatedModuleNamePath); // console.log(`Related module path`, relatedModuleNamePath);
const relatedModuleNamePath = await wpCompress(moduleName) const relatedModuleNamePath = await wpCompress(moduleName)
const fileSource = readFileSync(relatedModuleNamePath).toString('utf-8'); const fileSource = readFileSync(relatedModuleNamePath).toString('utf-8');
// continue; // TODO - handle relative modules // continue; // TODO - handle relative modules
@@ -39,10 +39,10 @@ export async function sliceAndWriteCalls(calls, FILE_PATH) {
}); });
}); });
}, relatedModuleNamePath); }, relatedModuleNamePath);
// console.log(`Sliced code ${moduleName}\n`,slicedCode); // console.log(`Sliced code ${moduleName}\n`,slicedCode);
// continue; // continue;
const writePath = path.resolve('./dist', moduleName,'index.cjs'); const writePath = path.resolve('./dist', moduleName, 'index.cjs');
if (writePath === moduleName) { if (writePath === moduleName) {
throw Error("Unexpected Directory rewrite. Not allowed."); throw Error("Unexpected Directory rewrite. Not allowed.");
} }
@@ -60,9 +60,9 @@ export async function sliceAndWriteCalls(calls, FILE_PATH) {
function main() { function main() {
// const FILE_PATH = './test_src/index.cjs'; // const FILE_PATH = './test_src/index.cjs';
const FILE_PATH = './test_src/index.mjs'; const FILE_PATH = './test_src/index.cjs';
const project = new Project({compilerOptions:{allowJs: true, checkJs: false,}}); const project = new Project({ compilerOptions: { allowJs: true, checkJs: false, } });
project.addSourceFileAtPathIfExists(FILE_PATH); project.addSourceFileAtPathIfExists(FILE_PATH);
// const project = tsc.createProgram([FILE_PATH],); // const project = tsc.createProgram([FILE_PATH],);
@@ -72,13 +72,13 @@ function main() {
const importDecls = sourceFile.getImportStringLiterals() const importDecls = sourceFile.getImportStringLiterals()
// foreach library, get a list of import calls // foreach library, get a list of import calls
const calls = getImportCallsAndArgumentTypes(importDecls,checker,FILE_PATH); const calls = getImportCallsAndArgumentTypes(importDecls, checker, FILE_PATH);
const callMap = calls.generateAllArgumentsForRecordedCalls(); const callMap = calls.generateAllArgumentsForRecordedCalls();
logCallList(callMap); logCallList(callMap,FILE_PATH);
sliceAndWriteCalls(callMap, FILE_PATH).then(()=>{ sliceAndWriteCalls(callMap, FILE_PATH).then(() => {
console.log("Slicing and writing calls done"); console.log("Slicing and writing calls done");
}); });
} }
@@ -86,35 +86,6 @@ function main() {
if (process.argv[1] === import.meta.filename) { if (process.argv[1] === import.meta.filename) {
console.log("[SafeImport] started"); console.log("[SafeImport] started");
main(); main();
// console.log("done");
} }
export function logCallList(calls) {
console.log(`[Call Log] Call List for ${calls.size} modules`);
for (const [moduleName, callBoxes] of calls.entries()) {
if (isRelativeModule(moduleName)) {
console.log('Importing', moduleName, callBoxes);
} else {
console.log(`Module "${moduleName}" - System module. FIXME skipping`);
}
}
console.log(`Call List`, calls);
console.log(`[Call Log] End List for ${calls.size} modules`);
}
function isRelativeModule(moduleName) {
return moduleName.startsWith('.');
}
/**
* True if an inbuilt Node.js module.
* @param {string} moduleName
* @returns
*/
function isNodeModule(moduleName) {
if(moduleName.startsWith('node:')) return true;
const nodeModules = ['fs', 'fs/promises', 'path', 'http', 'https', 'os', 'crypto']
return nodeModules.includes(moduleName);
}

View File

@@ -52,9 +52,29 @@ export function getImportCallsAndArgumentTypes(importDecls, checker, mainFilePat
// this is a variable declaration // this is a variable declaration
const varDecl = parent; const varDecl = parent;
const varName = varDecl.getName(); const varName = varDecl.getName();
const varDecls = varDecl.getNameNode();
// default import
if( varDecls.isKind(SyntaxKind.Identifier)) {
recordImportedIdentifierUsage(varDecls, mainFilePath, libraryCallsRecorder, importStringDecl, true);
}else if(varDecls.isKind(SyntaxKind.ObjectBindingPattern)) {
const destructuredElements = varDecls.getElements();
for (const destructuredElement of destructuredElements) {
const destructuredElementName = destructuredElement.getNameNode();
if (destructuredElementName.isKind(SyntaxKind.Identifier)) {
recordImportedIdentifierUsage(destructuredElementName, mainFilePath, libraryCallsRecorder, importStringDecl);
} else if (destructuredElementName.isKind(SyntaxKind.ObjectBindingPattern)) {
// TODO handle object binding pattern
console.warn("Nested binding pattern not handled yet", destructuredElementName.getText());
} else {
console.error("Unexpected destructured element", destructuredElementName.getText());
}
}
}
console.log("Variable name", varName); console.log("Variable name", varName);
// check if declaration is identifier or object pattern // check if declaration is identifier or object pattern
} }
console.log("Require arguments. Skipping");
continue;
throw Error("Not implemented yet"); throw Error("Not implemented yet");
} }
} }
@@ -222,4 +242,36 @@ function recordImportedIdentifierUsage(importNode, mainFilePath, libraryCallsRec
} }
} }
} }
/**
*
* @param {*} calls
* @param {string} fileName
*/
export function logCallList(calls,fileName) {
console.log(`--- [Call Log List: ${fileName}] ---`)
console.log(`[Call Log] Call List for ${calls.size} modules`);
for (const [moduleName, callBoxes] of calls.entries()) {
if (isRelativeModule(moduleName) || isNodeModule(moduleName)) {
console.log(`Local/sys Module "${moduleName}" - System module. FIXME skipping`);
} else {
console.log('Library Module', moduleName, callBoxes);
}
}
console.log(`Call List`, calls);
console.log(`--- [Call Log End List: ${fileName}] ---`);
}
export function isRelativeModule(moduleName) {
return moduleName.startsWith('.');
}
/**
* True if an inbuilt Node.js module.
* @param {string} moduleName
* @returns
*/
export function isNodeModule(moduleName) {
if (moduleName.startsWith('node:')) return true;
const nodeModules = ['fs', 'fs/promises', 'path', 'http', 'https', 'os', 'crypto'];
return nodeModules.includes(moduleName);
}