github.com/Redstoneguy129/cli@v0.0.0-20230211220159-15dca4e91917/internal/utils/denos/build.ts (about) 1 import * as path from "https://deno.land/std@0.127.0/path/mod.ts"; 2 import {writeAll} from "https://deno.land/std@0.162.0/streams/conversion.ts"; 3 import {compress} from "https://deno.land/x/brotli@0.1.7/mod.ts"; 4 5 import {build} from "https://deno.land/x/eszip@v0.30.0/mod.ts"; 6 import {load} from "https://deno.land/x/eszip@v0.30.0/loader.ts"; 7 8 const virtualBasePath = "file:///src/"; 9 10 async function buildAndWrite(p: string, importMapPath: string) { 11 const funcDirPath = path.dirname(p); 12 const entrypoint = new URL("index.ts", virtualBasePath).href; 13 14 const eszip = await build([entrypoint], async (specifier: string) => { 15 const url = new URL(specifier); 16 if (url.protocol === 'file:') { 17 console.error(specifier) 18 // if the path is `file:///*`, treat it as a path from parent directory 19 let actualPath = specifier.replace('file:///', `./${funcDirPath}/../`); 20 // if the path is `file:///src/*`, treat it as a relative path from current dir 21 if (specifier.startsWith(virtualBasePath)) { 22 actualPath = specifier.replace(virtualBasePath, `./${funcDirPath}/`); 23 } 24 25 // If an import map path is set read file from the given path. 26 // Otherwise default to `import_map.json` in functions directory. 27 if (specifier.endsWith('import_map.json') && importMapPath) { 28 actualPath = importMapPath 29 } 30 try { 31 const content = await Deno.readTextFile(actualPath); 32 return { 33 kind: "module", 34 specifier, 35 content 36 } 37 } catch (e) { 38 if((e instanceof Deno.errors.NotFound) && actualPath.endsWith('import_map.json')) { 39 // if there's no import_map.json, set an empty one 40 return { 41 kind: "module", 42 specifier, 43 content: `{ "imports": {} }` 44 } 45 } else { 46 throw e; 47 } 48 } 49 } 50 51 return load(specifier); 52 }, "file:///src/import_map.json"); 53 // compress ESZIP payload using Brotli 54 const compressed = compress(eszip); 55 56 // add a marker frame to the start of the payload 57 const marker = new TextEncoder().encode("EZBR"); 58 59 const combinedPayload = new Uint8Array(marker.length + compressed.length); 60 combinedPayload.set(marker); 61 combinedPayload.set(compressed, marker.length); 62 63 await writeAll(Deno.stdout, combinedPayload); 64 } 65 66 buildAndWrite(Deno.args[0], Deno.args[1]);