import type { ClientManifest } from './index'
export type AsyncFileMapper = (files: Array<string>) => Array<string>
export function createMapper(clientManifest: ClientManifest): AsyncFileMapper {
const map = createMap(clientManifest)
return function mapper(moduleIds: Array<string>): Array<string> {
const res = new Set<string>()
for (let i = 0; i < moduleIds.length; i++) {
const mapped = map.get(moduleIds[i])
if (mapped) {
for (let j = 0; j < mapped.length; j++) {
res.add(mapped[j])
}
}
}
return Array.from(res)
}
}
function createMap(clientManifest) {
const map = new Map()
Object.keys(clientManifest.modules).forEach(id => {
map.set(id, mapIdToFile(id, clientManifest))
})
return map
}
function mapIdToFile(id, clientManifest) {
const files: string[] = []
const fileIndices = clientManifest.modules[id]
if (fileIndices) {
fileIndices.forEach(index => {
const file = clientManifest.all[index]
if (
file &&
(clientManifest.async.indexOf(file) > -1 ||
!/\.(js|css)($|\?)/.test(file))
) {
files.push(file)
}
})
}
return files
}