v1.ts 7.4 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2
import type { Plugin } from 'vite'
import path from 'path'
fxy060608's avatar
fxy060608 已提交
3
import { isInHBuilderX, parseVueRequest } from '@dcloudio/uni-cli-shared'
fxy060608's avatar
fxy060608 已提交
4 5
import {
  ClassDeclaration,
fxy060608's avatar
fxy060608 已提交
6 7
  ClassExpression,
  Expression,
fxy060608's avatar
fxy060608 已提交
8
  FunctionDeclaration,
fxy060608's avatar
fxy060608 已提交
9 10
  FunctionExpression,
  Identifier,
fxy060608's avatar
fxy060608 已提交
11
  Module,
fxy060608's avatar
fxy060608 已提交
12
  TsFunctionType,
fxy060608's avatar
fxy060608 已提交
13
  TsInterfaceDeclaration,
fxy060608's avatar
fxy060608 已提交
14
  TsType,
fxy060608's avatar
fxy060608 已提交
15
  TsTypeAliasDeclaration,
fxy060608's avatar
fxy060608 已提交
16
  TsTypeAnnotation,
fxy060608's avatar
fxy060608 已提交
17
  VariableDeclaration,
fxy060608's avatar
fxy060608 已提交
18
} from '../../types/types'
fxy060608's avatar
fxy060608 已提交
19
import { compile, parsePackage } from '../utils/compiler'
fxy060608's avatar
fxy060608 已提交
20

fxy060608's avatar
fxy060608 已提交
21
export function uniUtsV1Plugin(): Plugin {
fxy060608's avatar
fxy060608 已提交
22
  let isFirst = true
fxy060608's avatar
fxy060608 已提交
23 24 25 26
  return {
    name: 'uni:uts-v1',
    apply: 'build',
    enforce: 'pre',
fxy060608's avatar
fxy060608 已提交
27
    async transform(code, id, opts) {
fxy060608's avatar
fxy060608 已提交
28 29 30
      if (opts && opts.ssr) {
        return
      }
fxy060608's avatar
fxy060608 已提交
31 32 33 34
      // 目前仅支持app-android
      if (process.env.UNI_UTS_PLATFORM !== 'app-android') {
        return
      }
fxy060608's avatar
fxy060608 已提交
35
      const { filename } = parseVueRequest(id)
fxy060608's avatar
fxy060608 已提交
36 37 38
      if (path.extname(filename) !== '.uts') {
        return
      }
fxy060608's avatar
fxy060608 已提交
39 40
      const pkg = parsePackage(filename)
      if (!pkg) {
fxy060608's avatar
fxy060608 已提交
41 42
        return
      }
fxy060608's avatar
fxy060608 已提交
43
      // 懒加载 uts 编译器
fxy060608's avatar
fxy060608 已提交
44 45
      // eslint-disable-next-line no-restricted-globals
      const { parse } = require('@dcloudio/uts')
fxy060608's avatar
fxy060608 已提交
46
      const ast = await parse(code, { noColor: isInHBuilderX() })
fxy060608's avatar
fxy060608 已提交
47 48 49
      code = `
import { initUtsProxyClass, initUtsProxyFunction } from '@dcloudio/uni-app'
const pkg = '${pkg}'
fxy060608's avatar
fxy060608 已提交
50
const cls = 'IndexKt'
fxy060608's avatar
fxy060608 已提交
51 52
${genProxyCode(ast)}
`
fxy060608's avatar
fxy060608 已提交
53 54 55 56 57 58 59 60 61 62 63 64 65
      const dexFile = await compile(id)
      if (!isFirst && dexFile) {
        const files = []
        if (process.env.UNI_APP_CHANGED_DEX_FILES) {
          try {
            files.push(...JSON.parse(process.env.UNI_APP_CHANGED_DEX_FILES))
          } catch (e) {}
        }
        files.push(dexFile)
        process.env.UNI_APP_CHANGED_DEX_FILES = JSON.stringify([
          ...new Set(files),
        ])
      }
fxy060608's avatar
fxy060608 已提交
66
      return code
fxy060608's avatar
fxy060608 已提交
67
    },
fxy060608's avatar
fxy060608 已提交
68 69 70
    buildEnd() {
      isFirst = false
    },
fxy060608's avatar
fxy060608 已提交
71 72 73
  }
}

fxy060608's avatar
fxy060608 已提交
74 75 76 77 78 79
function genProxyFunctionCode(
  method: string,
  async: boolean,
  isDefault: boolean = false
) {
  if (isDefault) {
fxy060608's avatar
fxy060608 已提交
80
    return `export default initUtsProxyFunction(${async}, { package: pkg, class: cls, name: '${method}'})`
fxy060608's avatar
fxy060608 已提交
81
  }
fxy060608's avatar
fxy060608 已提交
82
  return `export const ${method} = initUtsProxyFunction(${async}, { package: pkg, class: cls, name: '${method}'})`
fxy060608's avatar
fxy060608 已提交
83 84 85 86
}

function genProxyClassCode(
  cls: string,
fxy060608's avatar
fxy060608 已提交
87 88 89 90 91 92
  options: {
    methods: Record<string, any>
    staticMethods: Record<string, any>
    props: string[]
    staticProps: string[]
  },
fxy060608's avatar
fxy060608 已提交
93 94 95
  isDefault: boolean = false
) {
  if (isDefault) {
fxy060608's avatar
fxy060608 已提交
96 97
    return `export default initUtsProxyClass({ package: pkg, class: '${cls}', ...${JSON.stringify(
      options
fxy060608's avatar
fxy060608 已提交
98 99
    )} })`
  }
fxy060608's avatar
fxy060608 已提交
100 101
  return `export const ${cls} = initUtsProxyClass({ package: pkg, class: '${cls}', ...${JSON.stringify(
    options
fxy060608's avatar
fxy060608 已提交
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
  )} })`
}

function genTsTypeAliasDeclarationCode(decl: TsTypeAliasDeclaration) {
  if (isFunctionType(decl.typeAnnotation)) {
    return genProxyFunctionCode(
      decl.id.value,
      isReturnPromise(decl.typeAnnotation.typeAnnotation)
    )
  }
}
function genTsInterfaceDeclarationCode(
  decl: TsInterfaceDeclaration,
  isDefault: boolean = false
) {
  const cls = decl.id.value
  const methods: Record<string, { async?: boolean }> = {}
  decl.body.body.forEach((item) => {
    if (item.type === 'TsMethodSignature') {
      if (item.key.type === 'Identifier') {
        methods[item.key.value] = {
          async: isReturnPromise(item.typeAnn),
        }
fxy060608's avatar
fxy060608 已提交
125
      }
fxy060608's avatar
fxy060608 已提交
126 127
    }
  })
fxy060608's avatar
fxy060608 已提交
128 129 130 131 132
  return genProxyClassCode(
    cls,
    { methods, staticMethods: {}, props: [], staticProps: [] },
    isDefault
  )
fxy060608's avatar
fxy060608 已提交
133 134 135
}

function genFunctionDeclarationCode(
fxy060608's avatar
fxy060608 已提交
136
  decl: FunctionDeclaration | FunctionExpression,
fxy060608's avatar
fxy060608 已提交
137 138 139
  isDefault: boolean = false
) {
  return genProxyFunctionCode(
fxy060608's avatar
fxy060608 已提交
140
    decl.identifier!.value,
fxy060608's avatar
fxy060608 已提交
141 142 143 144 145 146
    decl.async || isReturnPromise(decl.returnType),
    isDefault
  )
}

function genClassDeclarationCode(
fxy060608's avatar
fxy060608 已提交
147
  decl: ClassDeclaration | ClassExpression,
fxy060608's avatar
fxy060608 已提交
148 149
  isDefault: boolean = false
) {
fxy060608's avatar
fxy060608 已提交
150
  const cls = decl.identifier!.value
fxy060608's avatar
fxy060608 已提交
151
  const methods: Record<string, { async?: boolean }> = {}
fxy060608's avatar
fxy060608 已提交
152 153 154
  const staticMethods: Record<string, { async?: boolean }> = {}
  const props: string[] = []
  const staticProps: string[] = []
fxy060608's avatar
fxy060608 已提交
155 156 157
  decl.body.forEach((item) => {
    if (item.type === 'ClassMethod') {
      if (item.key.type === 'Identifier') {
fxy060608's avatar
fxy060608 已提交
158 159
        const name = item.key.value
        const value = {
fxy060608's avatar
fxy060608 已提交
160 161 162
          async:
            item.function.async || isReturnPromise(item.function.returnType),
        }
fxy060608's avatar
fxy060608 已提交
163 164 165 166 167 168 169 170 171 172 173 174 175
        if (item.isStatic) {
          staticMethods[name] = value
        } else {
          methods[name] = value
        }
      }
    } else if (item.type === 'ClassProperty') {
      if (item.key.type === 'Identifier') {
        if (item.isStatic) {
          staticProps.push(item.key.value)
        } else {
          props.push(item.key.value)
        }
fxy060608's avatar
fxy060608 已提交
176
      }
fxy060608's avatar
fxy060608 已提交
177 178
    }
  })
fxy060608's avatar
fxy060608 已提交
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
  return genProxyClassCode(
    cls,
    { methods, staticMethods, props, staticProps },
    isDefault
  )
}

function genInitCode(expr: Expression) {
  switch (expr.type) {
    case 'BooleanLiteral':
      return expr.value + ''
    case 'NumericLiteral':
      return expr.value + ''
    case 'StringLiteral':
      return expr.value
  }
  return ''
}

function genVariableDeclarationCode(decl: VariableDeclaration) {
fxy060608's avatar
fxy060608 已提交
199
  // 目前仅支持 const 的 boolean,number,string
fxy060608's avatar
fxy060608 已提交
200 201
  const lits = ['BooleanLiteral', 'NumericLiteral', 'StringLiteral']
  if (
fxy060608's avatar
fxy060608 已提交
202
    decl.kind === 'const' &&
fxy060608's avatar
fxy060608 已提交
203 204 205 206 207 208 209 210 211 212 213 214 215 216
    !decl.declarations.find((d) => {
      if (d.id.type !== 'Identifier') {
        return true
      }
      if (!d.init) {
        return true
      }
      const type = d.init.type
      if (!lits.includes(type)) {
        return true
      }
      return false
    })
  ) {
fxy060608's avatar
fxy060608 已提交
217
    return `export ${decl.kind} ${decl.declarations
fxy060608's avatar
fxy060608 已提交
218 219 220
      .map((d) => `${(d.id as Identifier).value} = ${genInitCode(d.init!)}`)
      .join(', ')}`
  }
fxy060608's avatar
fxy060608 已提交
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
}

function genProxyCode({ body }: Module) {
  const codes: string[] = []
  body.forEach((item) => {
    let code: string | undefined
    if (item.type === 'ExportDeclaration') {
      const decl = item.declaration
      switch (decl.type) {
        case 'FunctionDeclaration':
          code = genFunctionDeclarationCode(decl, false)
          break
        case 'ClassDeclaration':
          code = genClassDeclarationCode(decl, false)
          break
        case 'TsTypeAliasDeclaration':
          code = genTsTypeAliasDeclarationCode(decl)
          break
        case 'TsInterfaceDeclaration':
          code = genTsInterfaceDeclarationCode(decl, false)
          break
fxy060608's avatar
fxy060608 已提交
242 243 244
        case 'VariableDeclaration':
          code = genVariableDeclarationCode(decl)
          break
fxy060608's avatar
fxy060608 已提交
245
      }
fxy060608's avatar
fxy060608 已提交
246
    } else if (item.type === 'ExportDefaultDeclaration') {
fxy060608's avatar
fxy060608 已提交
247 248 249 250 251 252 253 254 255 256
      const decl = item.decl
      if (decl.type === 'TsInterfaceDeclaration') {
        code = genTsInterfaceDeclarationCode(decl, true)
      } else if (decl.type === 'ClassExpression') {
        if (decl.identifier) {
          // export default class test{}
          code = genClassDeclarationCode(decl, false)
        }
      } else if (decl.type === 'FunctionExpression') {
        if (decl.identifier) {
fxy060608's avatar
fxy060608 已提交
257
          code = genFunctionDeclarationCode(decl, true)
fxy060608's avatar
fxy060608 已提交
258
        }
fxy060608's avatar
fxy060608 已提交
259
      }
fxy060608's avatar
fxy060608 已提交
260
    }
fxy060608's avatar
fxy060608 已提交
261 262 263
    if (code) {
      codes.push(code)
    }
fxy060608's avatar
fxy060608 已提交
264
  })
fxy060608's avatar
fxy060608 已提交
265
  return codes.join(`\n`)
fxy060608's avatar
fxy060608 已提交
266 267
}

fxy060608's avatar
fxy060608 已提交
268 269 270 271
function isFunctionType(type: TsType): type is TsFunctionType {
  return type.type === 'TsFunctionType'
}

fxy060608's avatar
fxy060608 已提交
272 273 274 275 276
function isReturnPromise(anno?: TsTypeAnnotation) {
  if (!anno) {
    return false
  }
  const { typeAnnotation } = anno
fxy060608's avatar
fxy060608 已提交
277 278 279 280 281 282
  return (
    typeAnnotation.type === 'TsTypeReference' &&
    typeAnnotation.typeName.type === 'Identifier' &&
    typeAnnotation.typeName.value === 'Promise'
  )
}