UNPKG

@cloud-copilot/iam-data

Version:
73 lines 2.61 kB
// @ts-ignore const root = import.meta.url; // @ts-ignore const environmentRoot = import.meta.env?.IAM_DATA_ROOT; let resolvedRoot = undefined; let useFetch = false; const fileSystem = root.startsWith('file://'); /** * Get a data file from the data directory in ESM * * @param file the path to the file to retrieve data for. * @returns the data from the file */ export async function readRelativeFile(pathParts) { /* * Maybe a little too optimized here. Want to only resolve the root once, but we have to do it inside the * function, so caching it here. */ if (!resolvedRoot) { if (fileSystem) { if (environmentRoot && environmentRoot !== '') { if (environmentRoot.startsWith('file://')) { resolvedRoot = new URL(environmentRoot).href; } else { const { resolve: pathResolve } = await import('node:path'); const { pathToFileURL } = await import('node:url'); resolvedRoot = pathToFileURL(pathResolve(environmentRoot)).href; } } else { resolvedRoot = new URL('../../', root).href; } } else { if (environmentRoot && environmentRoot !== '') { useFetch = true; resolvedRoot = environmentRoot; if (!resolvedRoot.endsWith('/')) { resolvedRoot = resolvedRoot + '/'; } } else { resolvedRoot = '../../'; } } if (!resolvedRoot.endsWith('/')) { resolvedRoot = resolvedRoot + '/'; } } if (fileSystem) { const { readFile } = await import('fs/promises'); const { join } = await import('node:path'); const { fileURLToPath } = await import('node:url'); const relativePath = join(...pathParts); const fileUrl = new URL(relativePath, resolvedRoot); const contents = await readFile(fileURLToPath(fileUrl), 'utf-8'); return JSON.parse(contents); } else if (useFetch) { const dataUrl = resolvedRoot + pathParts.join('/'); const response = await fetch(dataUrl); if (!response.ok) { throw new Error(`Failed to fetch JSON data from ${dataUrl}`); } return await response.json(); } else { const contents = await import(resolvedRoot + pathParts.join('/')); return await contents.default; } } //# sourceMappingURL=readRelativeFileEsm.js.map