UNPKG

@shipengine/connect-loader

Version:

Internal library for loading ShipEngine Connect apps

96 lines 2.98 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.readFile = void 0; const internal_1 = require("@shipengine/connect-sdk/lib/internal"); const fs_1 = require("fs"); const jsYaml = require("js-yaml"); const json5 = require("json5"); const path = require("path"); /** * Reads a file based on its file extension */ async function readFile(filePath) { switch (path.extname(filePath)) { case '.yml': case '.yaml': return readYamlFile(filePath); case '.json': case '.jsonc': case '.json5': return readJsonFile(filePath); case '.js': case '.mjs': return importJavaScriptModule(filePath); case '.ts': throw new Error(`Invalid file reference "${filePath}. Reference the compiled Javascript file instead of the Typescript source file.`); default: return readTextFile(filePath); } } exports.readFile = readFile; /** * Returns the parsed contents of the specified YAML file */ async function readYamlFile(filePath) { const yaml = await readTextFile(filePath); try { const parsedYaml = jsYaml.safeLoad(yaml, { filename: path.basename(filePath), }); return parsedYaml; } catch (originalError) { throw internal_1.error(internal_1.SystemErrorCode.Syntax, `Unable to parse ${path.basename(filePath)}.`, { originalError, }); } } /** * Returns the parsed contents of the specified JSON file */ async function readJsonFile(filePath) { const json = await readTextFile(filePath); try { return json5.parse(json); } catch (originalError) { throw internal_1.error(internal_1.SystemErrorCode.Syntax, `Unable to parse ${path.basename(filePath)}.`, { originalError, }); } } /** * Returns the contents of the specified UTF-8 text file */ async function readTextFile(filePath) { try { return await fs_1.promises.readFile(filePath, 'utf8'); } catch (originalError) { throw internal_1.error(internal_1.SystemErrorCode.Filesystem, `Unable to read ${filePath}.`, { originalError, }); } } /** * Returns the default export of the specified JavaScript module */ async function importJavaScriptModule(filePath) { try { const exports = (await Promise.resolve().then(() => require(filePath))); if ('default' in exports) { // This appears to be an ECMAScript module, so return its default export return exports.default; } else { // This appears to be a CommonJS module, so return the module exports return exports; } } catch (originalError) { throw internal_1.error(internal_1.SystemErrorCode.Filesystem, `Unable to import ${path.basename(filePath)}.`, { originalError, }); } } //# sourceMappingURL=read-file.js.map