-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
59 lines (53 loc) · 1.76 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import type { UnpluginContextMeta } from 'unplugin'
import type { ResolvedOptions } from '../types'
import { generateNamespacesCode } from './generate-namespaces'
export function pageLoader(options: ResolvedOptions, meta: UnpluginContextMeta) {
const namespacesCode = generateNamespacesCode(options, meta)
return `
export function resolvePage(resolver, transformPage) {
return async name => {
let page = await resolvePluginPage(name)
if (!page) {
page = ${
meta.framework === 'vite'
? 'await resolveVitePage(name, await resolver(name))'
: 'await resolver(name)'
}
}
page = page.default || page
if (transformPage) {
page = transformPage(page, name)
}
return page
}
}
export async function resolvePluginPage(name) {
if (name.includes('${options.separator}')) {
const [namespace, page] = name.split('${options.separator}')
if (namespace && page) {
const namespaces = ${namespacesCode}
if (!namespaces[namespace]) {
throw new Error(\`[inertia-plugin]: Namespace "\${namespace}" not found\`)
}
for (const importedNamespace of namespaces[namespace]) {
if (importedNamespace && typeof importedNamespace === 'function') {
return importedNamespace()
}
}
}
}
}
export async function resolveVitePage(name, pages, throwNotFoundError = true) {
for (const path in pages) {
if (path.endsWith(\`\${name.replace('.', '/')}${options.extension}\`)) {
const module = typeof pages[path] === 'function'
? pages[path]()
: pages[path]
return await Promise.resolve(module).then(module => module.default || module)
}
}
if (throwNotFoundError) {
throw new Error(\`[inertia-plugin]: Page "\${name}" not found\`)
}
}`
}