import fs from 'fs'; import path from 'path'; import { SymbolTable } from '../config/_symbols'; import { ApplicationError } from '../runtime/_errors'; const ENTRYPOINT_FILENAMES = ['index.js']; export class EntrypointNotFoundException extends Error { constructor(message?: string) { super(message); this.name = 'EntrypointNotFoundException'; } } function isFile(filepath: string) { try { const stats = fs.statSync(filepath); if (stats.isFile()) { return true; } } catch { /* file does not exist */ } return false; } // In the python SDK equivalent it also handles the case where // entrypoint is not specified. In the Node world, this will not work // because this code will be loaded at whatever current directory it lives // very likely eg. /node_modules/jetpack-sdk/dist/... // We cannot assume the current directory as the user app directory, and // entrypoint provided has to be an absolute path for now. function tryToFindEntrypoint(userEntrypoint: string) { // check if provided entrypoint is valid if (isFile(userEntrypoint)) { return userEntrypoint; } // Handle the case where entrypoint is a directory const entryFile = ENTRYPOINT_FILENAMES.find((filename: string) => { const fullPath = path.join(userEntrypoint, filename); return isFile(fullPath); }); if (entryFile) { return path.join(userEntrypoint, entryFile); } throw new EntrypointNotFoundException( `Entrypoint ${userEntrypoint} not found`, ); } async function loadUserEntrypoint(userEntrypoint: string) { if (!userEntrypoint) { throw new ApplicationError( 'jetpack entrypoint not set: please add `ENV JETPACK_ENTRYPOINT ` to your Dockerfile.', ); } const entrypointPath = tryToFindEntrypoint(userEntrypoint); return import(entrypointPath); } export const loadEntrypoint = async (entrypoint: string) => { await loadUserEntrypoint(entrypoint); return SymbolTable.registeredFunctions; }; export const loadRegisteredFunc = async (entrypoint: string, qualifiedSymbol: string) => { const registeredFuncs = await loadEntrypoint(entrypoint); const func = registeredFuncs[qualifiedSymbol]; if (!func) { throw new Error(`unable to find ${qualifiedSymbol}`); } return func; };