latest
eser/stackThis package works with Node.js, Deno, BunIt is unknown whether this package works with Cloudflare Workers, Browsers
JSR Score
41%
Published
3 months ago (0.7.20)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license. import * as colors from "jsr:/@std/fmt@^0.225.6/colors"; import * as posix from "jsr:/@std/path@^1.0.0/posix"; import * as jsRuntime from "jsr:/@eser/standards@^0.7.20/js-runtime"; import { type BuildSnapshot, type BuildSnapshotSerialized } from "./mod.ts"; import { setBuildId } from "./build-id.ts"; export type AotSnapshotState = { files: Map<string, string>; dependencyMapping: Map<string, Array<string>>; }; export const createAotSnapshotState = ( files: Map<string, string>, dependencyMapping: Map<string, Array<string>>, ): AotSnapshotState => { return { files: files, dependencyMapping: dependencyMapping, }; }; export class AotSnapshot implements BuildSnapshot { readonly state: AotSnapshotState; constructor(state: AotSnapshotState) { this.state = state; } get paths(): Array<string> { return Array.from(this.state.files.keys()); } async read(pathStr: string): Promise<ReadableStream<Uint8Array> | null> { const filePath = this.state.files.get(pathStr); if (filePath !== undefined) { try { const file = await jsRuntime.current.open(filePath, { read: true }); return file.readable; } catch (_err) { return null; } } // Handler will turn this into a 404 return null; } dependencies(pathStr: string): Array<string> { return this.state.dependencyMapping.get(pathStr) ?? []; } } export const loadAotSnapshot = async ( snapshotDirPath: string, ): Promise<BuildSnapshot | null> => { try { if (!(await jsRuntime.current.stat(snapshotDirPath)).isDirectory) { return null; } console.log( `Using snapshot found at ${colors.cyan(snapshotDirPath)}`, ); const snapshotPath = posix.join(snapshotDirPath, "snapshot.json"); const json = JSON.parse( await jsRuntime.current.readTextFile(snapshotPath), ) as BuildSnapshotSerialized; setBuildId(json.build_id); const dependencies = new Map<string, Array<string>>( Object.entries(json.files), ); const files = new Map<string, string>(); Object.keys(json.files).forEach((name) => { const filePath = posix.join(snapshotDirPath, name); files.set(name, filePath); }); return new AotSnapshot(createAotSnapshotState(files, dependencies)); } catch (err) { if (!(err instanceof jsRuntime.current.errors.NotFound)) { throw err; } return null; } };