|
| 1 | +import * as path from 'path'; |
| 2 | + |
| 3 | +import * as parse5 from 'parse5'; |
| 4 | +import { HookContext } from '@ionic/cli-utils'; |
| 5 | + |
| 6 | +import { readFile, writeFile } from './utils/fs'; |
| 7 | +import { findElementByAttribute, findElementByTag, findElementsByTag } from './utils/html'; |
| 8 | + |
| 9 | +const ta = parse5.treeAdapters.default; |
| 10 | + |
| 11 | +export default async function (ctx: HookContext) { |
| 12 | + if (ctx.name !== 'build:before' || ctx.build.engine !== 'cordova') { |
| 13 | + return; |
| 14 | + } |
| 15 | + |
| 16 | + const indexPath = path.resolve(ctx.project.srcDir, 'index.html'); |
| 17 | + const origIndexPath = path.resolve(ctx.project.srcDir, 'index.html.orig'); |
| 18 | + const indexContents = await readFile(indexPath); |
| 19 | + |
| 20 | + const index = parse5.parse(indexContents) as parse5.AST.Default.Document; |
| 21 | + const rootNode = findElementByTag(index.childNodes as parse5.AST.Default.Element[], 'html'); |
| 22 | + |
| 23 | + if (!rootNode) { |
| 24 | + throw new Error('No root node in index.html'); |
| 25 | + } |
| 26 | + |
| 27 | + const namespaceURI = rootNode.namespaceURI; |
| 28 | + |
| 29 | + const headNode = findElementByTag(rootNode.childNodes as parse5.AST.Default.Element[], 'head'); |
| 30 | + const bodyNode = findElementByTag(rootNode.childNodes as parse5.AST.Default.Element[], 'body'); |
| 31 | + |
| 32 | + if (!headNode || !bodyNode) { |
| 33 | + throw new Error('No head or body node in index.html'); |
| 34 | + } |
| 35 | + |
| 36 | + const cdvattr = { name: 'src', value: 'cordova.js' }; |
| 37 | + const scriptNodes = findElementsByTag([...headNode.childNodes, ...bodyNode.childNodes] as parse5.AST.Default.Element[], 'script'); |
| 38 | + const scriptNode = findElementByAttribute(scriptNodes, cdvattr); |
| 39 | + |
| 40 | + if (!scriptNode) { |
| 41 | + const el = ta.createElement('script', namespaceURI, [cdvattr]); |
| 42 | + ta.appendChild(headNode, el); |
| 43 | + } |
| 44 | + |
| 45 | + const serialized = parse5.serialize(index); |
| 46 | + |
| 47 | + await Promise.all([ |
| 48 | + writeFile(origIndexPath, indexContents), |
| 49 | + writeFile(indexPath, serialized), |
| 50 | + ]); |
| 51 | +} |
0 commit comments