perf: cache resolved urls

This commit is contained in:
Julien Oculi 2024-02-05 17:56:23 +01:00
parent 95ba3dc581
commit d263aca30f
3 changed files with 14 additions and 7 deletions

View file

@ -1,6 +1,6 @@
import { join, parse, resolve, toFileUrl } from '$std/path/mod.ts'
import { bundleAsync } from 'lightningcss'
import { Logger, cssImports, uInt8ArrayConcat } from './helpers.ts'
import { cssImports, cssUrls, Logger, uInt8ArrayConcat } from './helpers.ts'
export async function builder(
{ filename, dev, assetDir, remote }: {
@ -91,17 +91,23 @@ export async function builder(
cache(url, remote, assetDir)
}
return { loc, url }
}
}
},
},
})
return { code, map }
}
async function cache(url: string, base: string, assetDir: string) {
const filepath = join(assetDir, url.split('?')[0])
const fullUrl = new URL(url, base)
if (cssUrls.has(fullUrl.pathname)) {
return
}
cssUrls.set(fullUrl.pathname, filepath)
const response = await fetch(fullUrl)
const file = await response.arrayBuffer()
const filepath = join(assetDir, url.split('?')[0])
await Deno.writeFile(filepath, new Uint8Array(file))
}

View file

@ -26,6 +26,7 @@ export async function hashFile(file: ArrayBuffer): Promise<string> {
}
export const cssImports: Map<string, string> = new Map()
export const cssUrls: Map<string, string> = new Map()
export function uInt8ArrayConcat(a: Uint8Array, b: Uint8Array) {
const dest = new Uint8Array(a.length + b.length)

View file

@ -43,8 +43,8 @@ export function cssHandler(sourceDir: string): MiddlewareHandler {
return new Response(file, {
headers: {
'Content-Type': contentType(ext) ?? 'text/plain; charset=utf-8'
}
'Content-Type': contentType(ext) ?? 'text/plain; charset=utf-8',
},
})
} catch {
return resp