|
| 1 | +import { existsSync } from 'node:fs' |
| 2 | +import { dirname, join } from 'node:path' |
| 3 | +import { mkdir, readFile, writeFile as writeFile_ } from 'node:fs/promises' |
| 4 | + |
| 5 | +import { normalizePath } from 'vite' |
| 6 | +import type { PageContext } from './context' |
| 7 | + |
| 8 | +export function getDeclaration(ctx: PageContext) { |
| 9 | + const subPagesPath = ctx.subPageMetaData.map((sub) => { |
| 10 | + return sub.pages.map(v => (`"${normalizePath(join(sub.root, v.path))}"`)) |
| 11 | + }).flat() |
| 12 | + const tabsPagesPath = ctx.pagesGlobConfig?.tabBar?.list?.map((v) => { |
| 13 | + return `"${v.pagePath}"` |
| 14 | + }) ?? [] |
| 15 | + const allPagesPath = [...ctx.pageMetaData.filter(page => !tabsPagesPath.includes(page.path)).map(v => `"${v.path}"`), ...subPagesPath] |
| 16 | + const code = `/* eslint-disable */ |
| 17 | +/* prettier-ignore */ |
| 18 | +// @ts-nocheck |
| 19 | +// Generated by vite-plugin-uni-pages |
| 20 | +
|
| 21 | +interface NavigateToOptions { |
| 22 | + url: ${allPagesPath.join(' |\n ')}; |
| 23 | +} |
| 24 | +interface RedirectToOptions extends NavigateToOptions {} |
| 25 | +
|
| 26 | +interface SwitchTabOptions { |
| 27 | + ${tabsPagesPath.length ? `url: ${tabsPagesPath.join(' | ')}` : ''} |
| 28 | +} |
| 29 | +
|
| 30 | +type ReLaunchOptions = NavigateToOptions | SwitchTabOptions; |
| 31 | +
|
| 32 | +declare interface Uni { |
| 33 | + navigateTo(options: UniNamespace.NavigateToOptions & NavigateToOptions): void; |
| 34 | + redirectTo(options: UniNamespace.RedirectToOptions & RedirectToOptions): void; |
| 35 | + switchTab(options: UniNamespace.SwitchTabOptions & SwitchTabOptions): void; |
| 36 | + reLaunch(options: UniNamespace.ReLaunchOptions & ReLaunchOptions): void; |
| 37 | +} |
| 38 | +` |
| 39 | + return code |
| 40 | +} |
| 41 | + |
| 42 | +async function writeFile(filePath: string, content: string) { |
| 43 | + await mkdir(dirname(filePath), { recursive: true }) |
| 44 | + return await writeFile_(filePath, content, 'utf-8') |
| 45 | +} |
| 46 | + |
| 47 | +export async function writeDeclaration(ctx: PageContext, filepath: string) { |
| 48 | + const originalContent = existsSync(filepath) ? await readFile(filepath, 'utf-8') : '' |
| 49 | + |
| 50 | + const code = getDeclaration(ctx) |
| 51 | + if (!code) |
| 52 | + return |
| 53 | + |
| 54 | + if (code !== originalContent) |
| 55 | + await writeFile(filepath, code) |
| 56 | +} |
0 commit comments