@codesys/mcp-toolkit
Version:
Model Context Protocol (MCP) server for CODESYS automation platform
176 lines (175 loc) • 7 kB
JavaScript
/**
* Script Loader Module
* Centralizes loading and management of Python script templates
*
* This module:
* - Loads script templates from the /scripts directory
* - Provides script template interpolation functions
* - Manages script parameter substitution
*/
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 () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.loadScriptTemplate = loadScriptTemplate;
exports.loadScriptTemplateSync = loadScriptTemplateSync;
exports.interpolateScript = interpolateScript;
exports.combineScripts = combineScripts;
exports.preloadAllScriptTemplates = preloadAllScriptTemplates;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const util_1 = require("util");
const readFileAsync = (0, util_1.promisify)(fs.readFile);
// Try multiple possible script locations:
// 1. Next to the JS files in dist/scripts (when running from node_modules)
// 2. In the src/scripts directory (when running from source)
function findScriptsDir() {
const possiblePaths = [
path.join(__dirname, 'scripts'), // dist/scripts
path.join(__dirname, '..', 'src', 'scripts'), // src/scripts from dist
path.join(__dirname, '..', '..', 'src', 'scripts') // src/scripts from node_modules
];
for (const dir of possiblePaths) {
if (fs.existsSync(dir)) {
return dir;
}
}
// Default to the first path and let it fail with a clear error if needed
return possiblePaths[0];
}
const SCRIPTS_DIR = findScriptsDir();
// Cache for loaded scripts to avoid repeated file system access
const scriptCache = {};
/**
* Loads a script template from the scripts directory
* @param scriptName The name of the script file (without .py extension)
* @returns The script content as a string
*/
function loadScriptTemplate(scriptName) {
return __awaiter(this, void 0, void 0, function* () {
// Add .py extension if not provided
const fileName = scriptName.endsWith('.py') ? scriptName : `${scriptName}.py`;
const filePath = path.join(SCRIPTS_DIR, fileName);
// Return from cache if available
if (scriptCache[fileName]) {
return scriptCache[fileName];
}
try {
const content = yield readFileAsync(filePath, 'utf8');
// Store in cache for future use
scriptCache[fileName] = content;
return content;
}
catch (error) {
throw new Error(`Failed to load script template '${fileName}': ${error.message}`);
}
});
}
/**
* Loads a script template synchronously (for use during startup)
* @param scriptName The name of the script file (without .py extension)
* @returns The script content as a string
*/
function loadScriptTemplateSync(scriptName) {
// Add .py extension if not provided
const fileName = scriptName.endsWith('.py') ? scriptName : `${scriptName}.py`;
const filePath = path.join(SCRIPTS_DIR, fileName);
// Return from cache if available
if (scriptCache[fileName]) {
return scriptCache[fileName];
}
try {
const content = fs.readFileSync(filePath, 'utf8');
// Store in cache for future use
scriptCache[fileName] = content;
return content;
}
catch (error) {
throw new Error(`Failed to load script template '${fileName}': ${error.message}`);
}
}
/**
* Interpolates parameters into a script template
* @param template The script template string
* @param params Object containing parameter names and values
* @returns The script with parameter values substituted
*/
function interpolateScript(template, params) {
let result = template;
// Replace each parameter in the template
for (const [key, value] of Object.entries(params)) {
// Convert value to string and escape backslashes for Python
const escapedValue = String(value).replace(/\\/g, '\\\\');
// Replace {PARAM_NAME} with the escaped value
const paramPattern = new RegExp(`\\{${key}\\}`, 'g');
result = result.replace(paramPattern, escapedValue);
}
return result;
}
/**
* Combines multiple script fragments with proper indentation
* @param scripts Object containing named script fragments
* @returns Combined script content
*/
function combineScripts(scripts) {
return Object.values(scripts).join('\n\n');
}
/**
* Load all script templates from the scripts directory
* This is useful during development to preload the cache
*/
function preloadAllScriptTemplates() {
return __awaiter(this, void 0, void 0, function* () {
try {
const files = fs.readdirSync(SCRIPTS_DIR);
for (const file of files) {
if (file.endsWith('.py')) {
yield loadScriptTemplate(file);
}
}
}
catch (error) {
console.error(`Failed to preload script templates: ${error.message}`);
}
});
}
;