All files / rusted-chromium versions.ts

99.07% Statements 107/108
97.22% Branches 70/72
100% Functions 15/15
99.06% Lines 106/107

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 2485x   5x 5x 5x 5x 5x             5x 5x 5x   5x 5x 5x   5x 17x   17x 1x   16x                       16x   16x 33x   1x     32x 20x   20x           20x 14x 11x       12x 12x             21x   21x       21x 3x 3x     21x 39x   21x   5x 4x 4x 3x 3x     1x   4x     13x 10x 10x   7x   7x     3x   10x     3x         1x         16x   16x       16x 4x     16x   16x       1x   1x   1x               1x                 21x 21x 21x   21x 11x     21x         22x 7x   7x 7x   2x               5x 7x   7x   7x     7x 8x 6x       7x 1x     6x   6x 2x     4x 4x 5x     4x     5x 10x 1x     9x   9x 31x 31x 30x       9x       9x 1x 4x 4x 4x 4x       8x    
import { parse, HTMLElement as NodeParserHTMLElement } from 'node-html-parser'
 
import { fetchBranchPosition, fetchChromeUrl, fetchChromiumTags } from './api'
import { ComparableVersion } from './commons/ComparableVersion'
import { SEARCH_BINARY } from './commons/loggerTexts'
import { MappedVersion } from './commons/MappedVersion'
import { Compared } from './interfaces/enums'
import type { ContinueFetchingChromeUrlReturn, GetChromeDownloadUrlReturn } from './interfaces/function.interfaces'
import { ContinueFetchingChromeUrlParams } from './interfaces/function.interfaces'
import type { IChromeFullConfig, IChromeSingleConfig, IChromeConfig } from './interfaces/interfaces'
import { DownloadReportEntry } from './interfaces/interfaces'
import type { IOSSettings } from './interfaces/os.interfaces'
import type { OSSetting } from './interfaces/os.interfaces'
import { logger } from './log/logger'
import { spinner } from './log/spinner'
import { userSelectedVersion } from './select'
import { Store } from './store/Store'
import { storeNegativeHit } from './store/storeNegativeHit'
import { detectOperatingSystem } from './utils'
import { sortDescendingMappedVersions } from './utils/sort.utils'
 
export async function getChromeDownloadUrl(config: IChromeConfig, mappedVersions: MappedVersion[]): Promise<GetChromeDownloadUrlReturn> {
    const oSSetting = detectOperatingSystem(config)
 
    if (config.single !== null) {
        return getChromeUrlForSingle(config, oSSetting, mappedVersions[0])
    } else {
        return getChromeUrlForFull(config, oSSetting, mappedVersions)
    }
}
 
async function continueFetchingChromeUrl({
    config,
    mappedVersions,
    osSetting,
    version: selectedVersion,
}: ContinueFetchingChromeUrlParams): Promise<ContinueFetchingChromeUrlReturn> {
 
    let chromeUrl: string | undefined
    const report: DownloadReportEntry[] = []
 
    do {
        if (!selectedVersion) {
            // no version to check for binary available, exiting...
            break
        }
 
        if (!selectedVersion.disabled) {
            chromeUrl = await fetchChromeUrlForVersion(config, osSetting, selectedVersion)
 
            report.push({
                binaryExists: !!chromeUrl,
                download: config.download,
                version: selectedVersion,
            })
 
            if (chromeUrl) {
                if (config.download) {
                    return { chromeUrl, report, selectedVersion }
                }
            }
        } else {
            logger.warn('Already disabled version!')
            report.push({
                binaryExists: false,
                download: config.download,
                version: selectedVersion,
            })
        }
 
        await storeIfNoBinary(config, chromeUrl, selectedVersion)
 
        Iif (!chromeUrl && !selectedVersion.disabled) {
            spinner.error()
        }
 
        if (chromeUrl && !config.download) {
            chromeUrl = undefined
            logger.warn('Not downloading binary.')
        }
 
        const sVersion: MappedVersion = selectedVersion
        const index = mappedVersions.findIndex(mappedVersion => mappedVersion.value === sVersion.value)
 
        switch (config.onFail) {
            case 'increase': {
                if (index > 0) {
                    selectedVersion = mappedVersions[index - 1]
                    if (!selectedVersion.disabled) {
                        const higherLower = config.inverse ? 'lower' : 'higher'
                        logger.info(`Continue with next ${higherLower} version "${selectedVersion.value}"`)
                    }
                } else {
                    return { chromeUrl: undefined, report, selectedVersion: undefined }
                }
                break
            }
            case 'decrease': {
                if (index < mappedVersions.length - 1) {
                    selectedVersion = mappedVersions[index + 1]
                    if (!selectedVersion.disabled) {
 
                        const higherLower = config.inverse ? 'higher' : 'lower'
                        
                        logger.info(`Continue with next ${higherLower} version "${selectedVersion.value}"`)
                    }
                } else {
                    return { chromeUrl: undefined, report, selectedVersion: undefined }
                }
                break
            }
            case 'nothing': {
                selectedVersion = await userSelectedVersion(mappedVersions, config)
            }
        }
    } while (!chromeUrl || !config.download)
 
    return { chromeUrl, report, selectedVersion }
}
 
async function getChromeUrlForFull(config: IChromeFullConfig, osSetting: OSSetting, mappedVersions: MappedVersion[]): Promise<GetChromeDownloadUrlReturn> {
 
    const isAutoSearch = !config.interactive && config.onFail === 'decrease'
 
    const version = isAutoSearch
        ? mappedVersions[0]
        : await userSelectedVersion(mappedVersions, config)
 
    if (isAutoSearch && !!version) {
        logger.info(`Auto-searching with version ${version.value}`)
    }
 
    const { chromeUrl, report, selectedVersion } = await continueFetchingChromeUrl({config, osSetting, version, mappedVersions})
 
    return { chromeUrl, selectedVersion, filenameOS: osSetting.filename, report }
}
 
async function getChromeUrlForSingle(config: IChromeSingleConfig, oSSetting: OSSetting, selectedVersion: MappedVersion): Promise<GetChromeDownloadUrlReturn> {
    const chromeUrl = await fetchChromeUrlForVersion(config, oSSetting, selectedVersion)
 
    await storeIfNoBinary(config, chromeUrl, selectedVersion)
 
    const report: DownloadReportEntry[] = [
        {
            binaryExists: !!chromeUrl,
            download: config.download,
            version: selectedVersion,
        }
    ]
 
    return {
        chromeUrl,
        filenameOS: oSSetting.filename,
        report,
        selectedVersion,
    }
}
 
async function fetchChromeUrlForVersion(config: IChromeConfig, osSettings: IOSSettings, version: MappedVersion): Promise<string | undefined> {
    const branchPosition = await fetchBranchPosition(version.value)
    spinner.start(SEARCH_BINARY)
    const chromeUrl = await fetchChromeUrl(branchPosition, osSettings)
 
    if (chromeUrl && config.download) {
        spinner.success()
    }
 
    return chromeUrl
 
}
 
async function storeIfNoBinary(config: IChromeConfig, chromeUrl: string | undefined, version: MappedVersion): Promise<void> {
    if (!chromeUrl && !version.disabled) {
        spinner.error()
        // disable the version in the prompt
        version.disable()
        if (config.store) {
            // TODO: remove await?
            await storeNegativeHit(version.comparable, config.os, config.arch)
        }
    }
}
 
/**
 * Parses the chromium tags and returns all chromium versions
 */
export async function loadVersions(): Promise<string[]> {
    const tags = await fetchChromiumTags()
 
    const parsedTags = parse(tags) as (NodeParserHTMLElement & { valid: boolean })
 
    const h3s = parsedTags.querySelectorAll('h3')
 
    let tagsHeadline: NodeParserHTMLElement | undefined
    h3s.forEach((h3: NodeParserHTMLElement) => {
        if (h3.innerHTML === 'Tags') {
            tagsHeadline = h3
        }
    })
 
    if (!tagsHeadline) {
        throw new Error('Tags headline not found in HTML')
    }
 
    const tagsList = tagsHeadline.parentNode?.childNodes?.[1]
 
    if (!tagsList) {
        throw new Error('No list of tags found under tags headline')
    }
 
    const versions: string[] = []
    tagsList.childNodes.forEach(tag => {
        versions.push(tag.text)
    })
 
    return versions
}
 
export function mapVersions(versions: string[], config: IChromeConfig, store: Store): MappedVersion[] {
    if (config.single !== null) {
        return [new MappedVersion(config.single, false)]
    }
 
    const versionSet = store.getBy(config.os, config.arch)
 
    const filteredVersions = versions
        .map(version => new MappedVersion(version, versionSet.has(version)))
        .filter(version => !config.hideNegativeHits || !version.disabled)
        .filter(version => ComparableVersion.compare(version.comparable, config.min) !== Compared.LESS
            && ComparableVersion.compare(version.comparable, config.max) !== Compared.GREATER)
        .sort(sortDescendingMappedVersions)
 
    const versionRegardingInverse = config.inverse
        ? filteredVersions.reverse()
        : filteredVersions
 
    if (config.onlyNewestMajor) {
        return versionRegardingInverse.filter((version, index, versionArray) => { 
            const previous = versionArray[index - 1]
            const previousMajor = previous?.value?.split('.')[0]
            const currentMajor = version.value.split('.')[0]
            return (currentMajor !== previousMajor || previous.disabled) && !version.disabled
        }).slice(0, Number(config.results))
    }
 
    return versionRegardingInverse.slice(0, Number(config.results))
}