Skip to content

Instantly share code, notes, and snippets.

@ball6847
Created February 4, 2022 13:55
Show Gist options
  • Save ball6847/94b7d102308f6376686605c6e3756ab5 to your computer and use it in GitHub Desktop.
Save ball6847/94b7d102308f6376686605c6e3756ab5 to your computer and use it in GitHub Desktop.
#!/usr/bin/env -S deno run --unstable --allow-read --allow-write --allow-run --allow-net
import { ensureDirSync } from "https://deno.land/std@0.123.0/fs/mod.ts";
import { join } from "https://deno.land/std@0.123.0/path/mod.ts";
import pLimit from "https://cdn.skypack.dev/p-limit@v4.0.0";
function readJson(file: string) {
const jsonString = Deno.readTextFileSync(file);
const json = JSON.parse(jsonString);
return json;
}
function denoCache(file: string) {
return Deno.run({ cmd: [Deno.execPath(), "cache", file] }).status();
}
async function hasDefaultExport(url: string) {
const code = `import __default from "${url}";`;
const p = Deno.run({
cmd: [Deno.execPath(), "eval", code],
stdout: "piped",
stderr: "piped",
});
await p.status();
const stderr = new TextDecoder().decode(await p.stderrOutput());
return stderr.indexOf("does not provide an export named 'default'") === -1;
}
// start actual code
const limit = pLimit(4);
const __dirname = new URL(".", import.meta.url).pathname;
const dirname = "deno_modules";
const target = join(__dirname, dirname);
const extension = ".ts";
const importMap = await readJson("./import_map.json");
// create all files and update cache
// TODO: handle remove, and compare hash before updating
const entries = Object.entries(importMap.imports).map(([key, value]) =>
limit(async () => {
const name = `${key}${extension}`;
const filepath = join(target, name);
console.log(`processing ${filepath}`);
ensureDirSync(target);
const withDefault = await hasDefaultExport(value as string);
const source = !withDefault
? `export * from "${value}";
`
: `export * from "${value}";
import ${key} from "${value}";
export default ${key};
`;
Deno.writeTextFileSync(filepath, source);
await denoCache(filepath);
})
);
await Promise.all(entries);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment