2024-07-17 02:23:21 +02:00
|
|
|
import { expandGlob } from '$std/fs/mod.ts'
|
2024-07-16 23:52:06 +02:00
|
|
|
import { SessionHandlers } from ':src/session/mod.ts'
|
|
|
|
import { respondApi } from ':src/utils.ts'
|
2024-07-17 13:08:36 +02:00
|
|
|
import { BUILD_ID } from '$fresh/src/server/build_id.ts'
|
|
|
|
import { encodeBase64 } from '@std/encoding'
|
2024-07-16 23:52:06 +02:00
|
|
|
|
2024-07-17 02:23:21 +02:00
|
|
|
export type PrecacheResponse = { version: string; preCachedUrls: string[] }
|
2024-07-16 23:52:06 +02:00
|
|
|
|
2024-07-17 13:08:36 +02:00
|
|
|
async function getVersion() {
|
2024-07-17 13:21:58 +02:00
|
|
|
const versionBytes = new TextEncoder().encode(BUILD_ID)
|
2024-07-17 13:08:36 +02:00
|
|
|
const versionHash = await crypto.subtle.digest('SHA-256', versionBytes)
|
|
|
|
return encodeBase64(versionHash)
|
|
|
|
}
|
2024-07-16 23:52:06 +02:00
|
|
|
|
|
|
|
export const handler: SessionHandlers = {
|
|
|
|
async GET() {
|
|
|
|
try {
|
2024-07-17 02:23:21 +02:00
|
|
|
const preCachedUrls: string[] = ['/', '/imports/markdown_css']
|
2024-07-16 23:52:06 +02:00
|
|
|
const paths = ['/static/**', '/_fresh/static/**']
|
2024-07-17 02:23:21 +02:00
|
|
|
const routes = '/routes/*/index.tsx'
|
2024-07-17 13:08:36 +02:00
|
|
|
const version = await getVersion()
|
2024-07-16 23:52:06 +02:00
|
|
|
|
|
|
|
//Pre-cache routes
|
|
|
|
for await (const route of expandGlob(routes, { root: '.' })) {
|
2024-07-17 02:23:21 +02:00
|
|
|
if (!route.isFile) continue
|
|
|
|
//@ts-expect-error parentPath is missing from type definition
|
|
|
|
preCachedUrls.push(strip(routes, route.parentPath))
|
2024-07-16 23:52:06 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Pre-cache files
|
|
|
|
for (const path of paths) {
|
|
|
|
for await (const entry of expandGlob(path, { root: '.' })) {
|
2024-07-17 02:23:21 +02:00
|
|
|
if (!entry.isFile) continue
|
|
|
|
preCachedUrls.push(strip(path, entry.path))
|
2024-07-16 23:52:06 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return respondApi<'success', PrecacheResponse>('success', {
|
|
|
|
version,
|
2024-07-17 02:23:21 +02:00
|
|
|
preCachedUrls,
|
2024-07-16 23:52:06 +02:00
|
|
|
})
|
|
|
|
} catch (error) {
|
|
|
|
return respondApi('error', error)
|
|
|
|
}
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2024-07-17 02:23:21 +02:00
|
|
|
function strip(root: string, path: string) {
|
2024-07-16 23:52:06 +02:00
|
|
|
return path
|
|
|
|
// Force unix/web separator
|
|
|
|
.replaceAll('\\', '/')
|
|
|
|
.replace(
|
|
|
|
// Remove root slash and glob *
|
|
|
|
root.slice(1).replaceAll('*', ''),
|
|
|
|
'/',
|
|
|
|
)
|
|
|
|
}
|