v1.ts 5.3 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2
import type { Plugin } from 'vite'
import path from 'path'
fxy060608's avatar
fxy060608 已提交
3
import { camelize } from '@vue/shared'
fxy060608's avatar
fxy060608 已提交
4
import {
fxy060608's avatar
fxy060608 已提交
5 6 7 8 9 10 11
  normalizePath,
  parseVueRequest,
  requireResolve,
} from '@dcloudio/uni-cli-shared'
import {
  ClassDeclaration,
  FunctionDeclaration,
fxy060608's avatar
fxy060608 已提交
12
  Module,
fxy060608's avatar
fxy060608 已提交
13
  TsFunctionType,
fxy060608's avatar
fxy060608 已提交
14
  TsInterfaceDeclaration,
fxy060608's avatar
fxy060608 已提交
15
  TsType,
fxy060608's avatar
fxy060608 已提交
16
  TsTypeAliasDeclaration,
fxy060608's avatar
fxy060608 已提交
17 18
  TsTypeAnnotation,
} from '../../types/types'
fxy060608's avatar
fxy060608 已提交
19

fxy060608's avatar
fxy060608 已提交
20
export function uniUtsV1Plugin(): Plugin {
fxy060608's avatar
fxy060608 已提交
21 22
  // 目前仅支持 app-android
  process.env.UNI_APP_PLATFORM = 'app-android'
fxy060608's avatar
fxy060608 已提交
23 24 25 26
  return {
    name: 'uni:uts-v1',
    apply: 'build',
    enforce: 'pre',
fxy060608's avatar
fxy060608 已提交
27 28 29 30 31 32 33 34
    resolveId(id, importer) {
      if (isUtsModuleRoot(id)) {
        return requireResolve(
          id,
          (importer && path.dirname(importer)) || process.env.UNI_INPUT_DIR
        )
      }
    },
fxy060608's avatar
fxy060608 已提交
35
    async transform(code, id, opts) {
fxy060608's avatar
fxy060608 已提交
36 37 38
      if (opts && opts.ssr) {
        return
      }
fxy060608's avatar
fxy060608 已提交
39
      const { filename } = parseVueRequest(id)
fxy060608's avatar
fxy060608 已提交
40 41 42
      if (path.extname(filename) !== '.uts') {
        return
      }
fxy060608's avatar
fxy060608 已提交
43 44
      const pkg = parsePackage(filename)
      if (!pkg) {
fxy060608's avatar
fxy060608 已提交
45 46
        return
      }
fxy060608's avatar
fxy060608 已提交
47
      // 懒加载 uts 编译器
fxy060608's avatar
fxy060608 已提交
48 49
      // eslint-disable-next-line no-restricted-globals
      const { parse } = require('@dcloudio/uts')
fxy060608's avatar
fxy060608 已提交
50
      const ast = await parse(code)
fxy060608's avatar
fxy060608 已提交
51 52 53 54 55
      code = `
import { initUtsProxyClass, initUtsProxyFunction } from '@dcloudio/uni-app'
const pkg = '${pkg}'
${genProxyCode(ast)}
`
fxy060608's avatar
fxy060608 已提交
56 57 58
      // TODO compile uts

      return code
fxy060608's avatar
fxy060608 已提交
59 60 61 62
    },
  }
}

fxy060608's avatar
fxy060608 已提交
63 64 65 66 67 68 69 70 71 72
// 仅限 uni_modules/test-plugin 格式
function isUtsModuleRoot(id: string) {
  const parts = normalizePath(id).split('/')
  if (parts[parts.length - 2] === 'uni_modules') {
    return true
  }
  return false
}

function parsePackage(filepath: string) {
fxy060608's avatar
fxy060608 已提交
73 74 75
  const parts = normalizePath(filepath).split('/')
  const index = parts.findIndex((part) => part === 'uni_modules')
  if (index > -1) {
fxy060608's avatar
fxy060608 已提交
76
    return camelize(parts[index + 1])
fxy060608's avatar
fxy060608 已提交
77 78 79 80
  }
  return ''
}

fxy060608's avatar
fxy060608 已提交
81 82 83 84 85 86 87
function genProxyFunctionCode(
  method: string,
  async: boolean,
  isDefault: boolean = false
) {
  if (isDefault) {
    return `export default initUtsProxyFunction({ pkg, cls: '', method: '${method}', async: ${async} })`
fxy060608's avatar
fxy060608 已提交
88
  }
fxy060608's avatar
fxy060608 已提交
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
  return `export const ${method} = initUtsProxyFunction({ pkg, cls: '', method: '${method}', async: ${async} })`
}

function genProxyClassCode(
  cls: string,
  methods: Record<string, any>,
  isDefault: boolean = false
) {
  if (isDefault) {
    return `export default initUtsProxyClass({ pkg, cls: '${cls}', methods: ${JSON.stringify(
      methods
    )} })`
  }
  return `export const ${cls} = initUtsProxyClass({ pkg, cls: '${cls}', methods: ${JSON.stringify(
    methods
  )} })`
}

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 已提交
127
      }
fxy060608's avatar
fxy060608 已提交
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
    }
  })
  return genProxyClassCode(cls, methods, isDefault)
}

function genFunctionDeclarationCode(
  decl: FunctionDeclaration,
  isDefault: boolean = false
) {
  return genProxyFunctionCode(
    decl.identifier.value,
    decl.async || isReturnPromise(decl.returnType),
    isDefault
  )
}

function genClassDeclarationCode(
  decl: ClassDeclaration,
  isDefault: boolean = false
) {
  const cls = decl.identifier.value
  const methods: Record<string, { async?: boolean }> = {}
  decl.body.forEach((item) => {
    if (item.type === 'ClassMethod') {
      if (item.key.type === 'Identifier') {
        methods[item.key.value] = {
          async:
            item.function.async || isReturnPromise(item.function.returnType),
        }
fxy060608's avatar
fxy060608 已提交
157
      }
fxy060608's avatar
fxy060608 已提交
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
    }
  })
  return genProxyClassCode(cls, methods, isDefault)
}

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 已提交
182
      }
fxy060608's avatar
fxy060608 已提交
183 184 185
    } else if (item.type === 'ExportDefaultDeclaration') {
      if (item.decl.type === 'TsInterfaceDeclaration') {
        code = genTsInterfaceDeclarationCode(item.decl, true)
fxy060608's avatar
fxy060608 已提交
186
      }
fxy060608's avatar
fxy060608 已提交
187
    }
fxy060608's avatar
fxy060608 已提交
188 189 190
    if (code) {
      codes.push(code)
    }
fxy060608's avatar
fxy060608 已提交
191
  })
fxy060608's avatar
fxy060608 已提交
192
  return codes.join(`\n`)
fxy060608's avatar
fxy060608 已提交
193 194
}

fxy060608's avatar
fxy060608 已提交
195 196 197 198
function isFunctionType(type: TsType): type is TsFunctionType {
  return type.type === 'TsFunctionType'
}

fxy060608's avatar
fxy060608 已提交
199 200 201 202 203
function isReturnPromise(anno?: TsTypeAnnotation) {
  if (!anno) {
    return false
  }
  const { typeAnnotation } = anno
fxy060608's avatar
fxy060608 已提交
204 205 206 207 208 209
  return (
    typeAnnotation.type === 'TsTypeReference' &&
    typeAnnotation.typeName.type === 'Identifier' &&
    typeAnnotation.typeName.value === 'Promise'
  )
}