kotlin.ts 7.1 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3
import path from 'path'
import fs from 'fs-extra'
import { relative } from '../utils'
fxy060608's avatar
fxy060608 已提交
4
import { originalPositionFor, originalPositionForSync } from '../sourceMap'
fxy060608's avatar
fxy060608 已提交
5
import { generateCodeFrame, lineColumnToStartEnd, splitRE } from './utils'
fxy060608's avatar
fxy060608 已提交
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

export interface MessageSourceLocation {
  type: 'exception' | 'error' | 'warning' | 'info' | 'logging' | 'output'
  message: string
  file?: string
  line?: number
  column?: number
  code?: string
}

interface GenerateCodeFrameOptions {
  inputDir: string
  sourceMapDir: string
  replaceTabsWithSpace?: boolean
  format: (msg: MessageSourceLocation) => string
}

export function hbuilderFormatter(m: MessageSourceLocation) {
  const msgs: string[] = []
  let msg = m.type + ': ' + m.message
  if (m.type === 'warning') {
    // 忽略部分警告
    if (msg.includes(`Classpath entry points to a non-existent location:`)) {
      return ''
    }
    msg
      .replace(/\r\n/g, '\n')
      .split('\n')
      .forEach((m) => {
        msgs.push('\u200B' + m + '\u200B')
      })
  } else if (m.type === 'error' || m.type === 'exception') {
    msg
      .replace(/\r\n/g, '\n')
      .split('\n')
      .forEach((m) => {
        msgs.push('\u200C' + m + '\u200C')
      })
  } else {
    msgs.push(msg)
  }
  if (m.file) {
    if (m.file.includes('?')) {
      ;[m.file] = m.file.split('?')
    }
    msgs.push(`at ${m.file}:${m.line}:${m.column}`)
  }
fxy060608's avatar
fxy060608 已提交
53 54 55
  if (m.code) {
    msgs.push(m.code)
  }
fxy060608's avatar
fxy060608 已提交
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
  return msgs.join('\n')
}

export async function parseUTSKotlinStacktrace(
  messages: MessageSourceLocation[],
  options: GenerateCodeFrameOptions
) {
  if (typeof messages === 'string') {
    try {
      messages = JSON.parse(messages)
    } catch (e) {}
  }
  const msgs: string[] = []
  if (Array.isArray(messages) && messages.length) {
    for (const m of messages) {
      if (m.file) {
fxy060608's avatar
fxy060608 已提交
72 73 74 75 76
        const sourceMapFile = resolveSourceMapFile(
          m.file,
          options.sourceMapDir,
          options.inputDir
        )
fxy060608's avatar
fxy060608 已提交
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
        if (sourceMapFile) {
          const originalPosition = await originalPositionFor({
            sourceMapFile,
            line: m.line!,
            column: m.column!,
            withSourceContent: true,
          })

          if (originalPosition.source && originalPosition.sourceContent) {
            m.file = originalPosition.source.split('?')[0]
            if (originalPosition.line !== null) {
              m.line = originalPosition.line
            }
            if (originalPosition.column !== null) {
              m.column = originalPosition.column
            }
            if (
              originalPosition.line !== null &&
              originalPosition.column !== null
            ) {
              m.code = generateCodeFrame(originalPosition.sourceContent, {
                line: originalPosition.line,
                column: originalPosition.column,
              }).replace(/\t/g, ' ')
            }
          }
        }
      }
      const msg = options.format(m)
      if (msg) {
        msgs.push(msg)
      }
    }
  }
  return msgs.join('\n')
}
fxy060608's avatar
fxy060608 已提交
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

function resolveSourceMapFile(
  file: string,
  sourceMapDir: string,
  inputDir: string
) {
  const sourceMapFile = path.resolve(
    sourceMapDir,
    relative(file, inputDir) + '.map'
  )
  if (fs.existsSync(sourceMapFile)) {
    return sourceMapFile
  }
}

const DEFAULT_APPID = 'HBuilder'

function normalizeAppid(appid: string) {
  return appid.replace(/_/g, '')
}
function createRegExp(appid: string) {
  return new RegExp('uni\\.' + appid + '\\.(.*)\\..*\\(*\\.kt:([0-9]+)\\)')
}

let kotlinManifest = {
  mtimeMs: 0,
  manifest: {} as Record<string, string>,
}

fxy060608's avatar
fxy060608 已提交
142 143 144 145 146
export interface KotlinManifestCache {
  version: string
  env: Record<string, string>
  files: Record<string, Record<string, string>>
}
fxy060608's avatar
fxy060608 已提交
147 148 149 150 151
function updateUTSKotlinSourceMapManifestCache(cacheDir: string) {
  const manifestFile = path.resolve(cacheDir, 'src/.manifest.json')
  const stats = fs.statSync(manifestFile)
  if (stats.isFile()) {
    if (kotlinManifest.mtimeMs !== stats.mtimeMs) {
fxy060608's avatar
fxy060608 已提交
152 153 154 155 156 157 158 159 160 161 162 163
      const { files } = fs.readJSONSync(manifestFile) as KotlinManifestCache
      if (files) {
        const classManifest: Record<string, string> = {}
        Object.keys(files).forEach((name) => {
          const kotlinClass = files[name].class
          if (kotlinClass) {
            classManifest[kotlinClass] = name
          }
        })
        kotlinManifest.mtimeMs = stats.mtimeMs
        kotlinManifest.manifest = classManifest
      }
fxy060608's avatar
fxy060608 已提交
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
    }
  }
}

function parseFilenameByClassName(className: string) {
  return kotlinManifest.manifest[className.split('$')[0]] || 'index.kt'
}

function resolveSourceMapFileByKtFile(file: string, sourceMapDir: string) {
  const sourceMapFile = path.resolve(sourceMapDir, file + '.map')
  if (fs.existsSync(sourceMapFile)) {
    return sourceMapFile
  }
}

fxy060608's avatar
fxy060608 已提交
179 180 181 182 183
const COLORS: Record<string, string> = {
  warn: '\u200B',
  error: '\u200C',
}

fxy060608's avatar
fxy060608 已提交
184 185 186
interface GenerateRuntimeCodeFrameOptions {
  appid: string
  cacheDir: string
fxy060608's avatar
fxy060608 已提交
187
  logType?: 'log' | 'info' | 'warn' | 'debug' | 'error'
fxy060608's avatar
fxy060608 已提交
188 189 190 191 192 193
}

function resolveSourceMapDirByCacheDir(cacheDir: string) {
  return path.resolve(cacheDir, 'sourceMap')
}

fxy060608's avatar
fxy060608 已提交
194
export function parseUTSKotlinRuntimeStacktrace(
fxy060608's avatar
fxy060608 已提交
195 196 197 198 199
  stacktrace: string,
  options: GenerateRuntimeCodeFrameOptions
) {
  const appid = normalizeAppid(options.appid || DEFAULT_APPID)
  if (!stacktrace.includes('uni.' + appid + '.')) {
fxy060608's avatar
fxy060608 已提交
200
    return ''
fxy060608's avatar
fxy060608 已提交
201 202 203 204 205 206 207
  }
  updateUTSKotlinSourceMapManifestCache(options.cacheDir)
  const re = createRegExp(appid)
  const res: string[] = []
  const lines = stacktrace.split(splitRE)
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i]
fxy060608's avatar
fxy060608 已提交
208
    const codes = parseUTSKotlinRuntimeStacktraceLine(
fxy060608's avatar
fxy060608 已提交
209 210 211 212
      line,
      re,
      resolveSourceMapDirByCacheDir(options.cacheDir)
    )
fxy060608's avatar
fxy060608 已提交
213 214 215 216
    if (codes.length && res.length) {
      const color = options.logType
        ? COLORS[options.logType as string] || ''
        : ''
217
      let error = 'error: ' + res[0]
fxy060608's avatar
fxy060608 已提交
218 219 220
      if (color) {
        error = color + error + color
      }
fxy060608's avatar
fxy060608 已提交
221
      return [error, ...codes].join('\n')
fxy060608's avatar
fxy060608 已提交
222 223 224 225
    } else {
      res.push(line)
    }
  }
fxy060608's avatar
fxy060608 已提交
226
  return ''
fxy060608's avatar
fxy060608 已提交
227 228
}

fxy060608's avatar
fxy060608 已提交
229
function parseUTSKotlinRuntimeStacktraceLine(
fxy060608's avatar
fxy060608 已提交
230 231 232 233
  lineStr: string,
  re: RegExp,
  sourceMapDir: string
) {
fxy060608's avatar
fxy060608 已提交
234
  const lines: string[] = []
fxy060608's avatar
fxy060608 已提交
235 236
  const matches = lineStr.match(re)
  if (!matches) {
fxy060608's avatar
fxy060608 已提交
237
    return lines
fxy060608's avatar
fxy060608 已提交
238
  }
fxy060608's avatar
fxy060608 已提交
239

fxy060608's avatar
fxy060608 已提交
240 241 242 243 244 245
  const [, className, line] = matches
  const sourceMapFile = resolveSourceMapFileByKtFile(
    parseFilenameByClassName(className),
    sourceMapDir
  )
  if (!sourceMapFile) {
fxy060608's avatar
fxy060608 已提交
246
    return lines
fxy060608's avatar
fxy060608 已提交
247
  }
fxy060608's avatar
fxy060608 已提交
248
  const originalPosition = originalPositionForSync({
fxy060608's avatar
fxy060608 已提交
249 250 251 252 253 254
    sourceMapFile,
    line: parseInt(line),
    column: 0,
    withSourceContent: true,
  })
  if (originalPosition.source && originalPosition.sourceContent) {
fxy060608's avatar
fxy060608 已提交
255 256 257 258 259
    lines.push(
      `at ${originalPosition.source.split('?')[0]}:${originalPosition.line}:${
        originalPosition.column
      }`
    )
fxy060608's avatar
fxy060608 已提交
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
    if (originalPosition.line !== null && originalPosition.column !== null) {
      const { start, end } = lineColumnToStartEnd(
        originalPosition.sourceContent,
        originalPosition.line,
        originalPosition.column
      )
      lines.push(
        generateCodeFrame(originalPosition.sourceContent, start, end).replace(
          /\t/g,
          ' '
        )
      )
    }
  }
  return lines
}