提交 14278bb9 编写于 作者: fxy060608's avatar fxy060608

wip(uts): compiler

上级 0d299c60
...@@ -17,4 +17,5 @@ packages/uni-mp-toutiao/lib ...@@ -17,4 +17,5 @@ packages/uni-mp-toutiao/lib
packages/uni-mp-vue/lib packages/uni-mp-vue/lib
packages/uni-mp-weixin/lib packages/uni-mp-weixin/lib
packages/uni-mp-quickapp-webview/lib packages/uni-mp-quickapp-webview/lib
packages/vite-plugin-uni/lib packages/vite-plugin-uni/lib
\ No newline at end of file packages/uni-uts-vite/lib
\ No newline at end of file
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
"output": { "output": {
"format": "cjs" "format": "cjs"
}, },
"external": ["@dcloudio/uni-app-vite"] "external": ["@dcloudio/uni-app-vite", "@dcloudio/uni-uts-vite"]
}, },
{ {
"input": { "input": {
......
'use strict'; 'use strict';
var uniAppVite = require('@dcloudio/uni-app-vite'); var appVite = require('@dcloudio/uni-app-vite');
var utsVite = require('@dcloudio/uni-uts-vite');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var uniAppVite__default = /*#__PURE__*/_interopDefaultLegacy(uniAppVite); var appVite__default = /*#__PURE__*/_interopDefaultLegacy(appVite);
var utsVite__default = /*#__PURE__*/_interopDefaultLegacy(utsVite);
var index = [appVite__default["default"], utsVite__default["default"]];
module.exports = index;
module.exports = uniAppVite__default["default"];
export { default } from '@dcloudio/uni-app-vite' import appVite from '@dcloudio/uni-app-vite'
import utsVite from '@dcloudio/uni-uts-vite'
export default [appVite, utsVite]
...@@ -386,8 +386,21 @@ function createNativeEvent(evt, htmlElement = false) { ...@@ -386,8 +386,21 @@ function createNativeEvent(evt, htmlElement = false) {
event.touches = evt.touches; event.touches = evt.touches;
event.changedTouches = evt.changedTouches; event.changedTouches = evt.changedTouches;
} }
{
wrapperEvent(event, evt);
}
return event; return event;
} }
function wrapperEvent(event, evt) {
shared.extend(event, {
preventDefault() {
return evt.preventDefault();
},
stopPropagation() {
return evt.stopPropagation();
}
});
}
const invokeOnCallback = (name, res) => UniServiceJSBridge.emit("api." + name, res); const invokeOnCallback = (name, res) => UniServiceJSBridge.emit("api." + name, res);
let invokeViewMethodId = 1; let invokeViewMethodId = 1;
function publishViewMethodName() { function publishViewMethodName() {
...@@ -1644,15 +1657,10 @@ function resolveColor(color) { ...@@ -1644,15 +1657,10 @@ function resolveColor(color) {
color[3] = color[3] / 255; color[3] = color[3] / 255;
return "rgba(" + color.join(",") + ")"; return "rgba(" + color.join(",") + ")";
} }
function processTouches(target, touches) { function processTouches(rect, touches) {
const eventTarget = target; Array.from(touches).forEach((touch) => {
let boundingClientRect = eventTarget.getBoundingClientRect(); touch.x = touch.clientX - rect.left;
return Array.from(touches).map((touch) => { touch.y = touch.clientY - rect.top;
return {
identifier: touch.identifier,
x: touch.clientX - boundingClientRect.left,
y: touch.clientY - boundingClientRect.top
};
}); });
} }
let tempCanvas; let tempCanvas;
...@@ -1755,16 +1763,10 @@ function useListeners(props2, Listeners, trigger) { ...@@ -1755,16 +1763,10 @@ function useListeners(props2, Listeners, trigger) {
let eventHandler = []; let eventHandler = [];
if (existing) { if (existing) {
eventHandler.push(withWebEvent(($event) => { eventHandler.push(withWebEvent(($event) => {
trigger(event.replace("on", "").toLocaleLowerCase(), shared.extend({}, (() => { const rect = $event.currentTarget.getBoundingClientRect();
let obj = {}; processTouches(rect, $event.touches);
for (const key in $event) { processTouches(rect, $event.changedTouches);
obj[key] = $event[key]; trigger(event.replace("on", "").toLocaleLowerCase(), $event);
}
return obj;
})(), {
touches: processTouches($event.currentTarget, $event.touches),
changedTouches: processTouches($event.currentTarget, $event.changedTouches)
}));
})); }));
} }
if (props2.disableScroll && event === "onTouchmove") { if (props2.disableScroll && event === "onTouchmove") {
......
...@@ -1271,7 +1271,6 @@ function $nne(evt, eventValue, instance2) { ...@@ -1271,7 +1271,6 @@ function $nne(evt, eventValue, instance2) {
res.changedTouches = normalizeTouchEvent(evt.changedTouches, top); res.changedTouches = normalizeTouchEvent(evt.changedTouches, top);
} }
{ {
wrapperEvent(res, evt);
return wrapperH5WxsEvent(res, eventValue, instance2) || [res]; return wrapperH5WxsEvent(res, eventValue, instance2) || [res];
} }
} }
...@@ -1297,6 +1296,9 @@ function createNativeEvent(evt, htmlElement = false) { ...@@ -1297,6 +1296,9 @@ function createNativeEvent(evt, htmlElement = false) {
event.touches = evt.touches; event.touches = evt.touches;
event.changedTouches = evt.changedTouches; event.changedTouches = evt.changedTouches;
} }
{
wrapperEvent(event, evt);
}
return event; return event;
} }
function wrapperEvent(event, evt) { function wrapperEvent(event, evt) {
...@@ -6559,15 +6561,10 @@ function resolveColor(color) { ...@@ -6559,15 +6561,10 @@ function resolveColor(color) {
color[3] = color[3] / 255; color[3] = color[3] / 255;
return "rgba(" + color.join(",") + ")"; return "rgba(" + color.join(",") + ")";
} }
function processTouches(target, touches) { function processTouches(rect, touches) {
const eventTarget = target; Array.from(touches).forEach((touch) => {
let boundingClientRect = eventTarget.getBoundingClientRect(); touch.x = touch.clientX - rect.left;
return Array.from(touches).map((touch) => { touch.y = touch.clientY - rect.top;
return {
identifier: touch.identifier,
x: touch.clientX - boundingClientRect.left,
y: touch.clientY - boundingClientRect.top
};
}); });
} }
let tempCanvas; let tempCanvas;
...@@ -6673,16 +6670,10 @@ function useListeners(props2, Listeners, trigger) { ...@@ -6673,16 +6670,10 @@ function useListeners(props2, Listeners, trigger) {
let eventHandler = []; let eventHandler = [];
if (existing) { if (existing) {
eventHandler.push(withWebEvent(($event) => { eventHandler.push(withWebEvent(($event) => {
trigger(event.replace("on", "").toLocaleLowerCase(), extend({}, (() => { const rect = $event.currentTarget.getBoundingClientRect();
let obj = {}; processTouches(rect, $event.touches);
for (const key in $event) { processTouches(rect, $event.changedTouches);
obj[key] = $event[key]; trigger(event.replace("on", "").toLocaleLowerCase(), $event);
}
return obj;
})(), {
touches: processTouches($event.currentTarget, $event.touches),
changedTouches: processTouches($event.currentTarget, $event.changedTouches)
}));
})); }));
} }
if (props2.disableScroll && event === "onTouchmove") { if (props2.disableScroll && event === "onTouchmove") {
......
const moduleName = '__MODULE_NAME__' const moduleName = '__MODULE_NAME__';
const moduleDefine = '__MODULE_DEFINE__' const moduleDefine = '__MODULE_DEFINE__';
var module = initModule(moduleDefine) var module = initModule(moduleDefine);
let callbackId = 1 let callbackId = 1;
const objectToString = Object.prototype.toString const objectToString = Object.prototype.toString;
const toTypeString = (value) => objectToString.call(value) const toTypeString = (value) => objectToString.call(value);
const isPlainObject = (val) => toTypeString(val) === '[object Object]' const isPlainObject = (val) => toTypeString(val) === '[object Object]';
const callbacks = {} const callbacks = {};
function normalizeArg(arg) { function normalizeArg(arg) {
if (typeof arg === 'function') { if (typeof arg === 'function') {
const id = callbackId++ const id = callbackId++;
callbacks[id] = arg callbacks[id] = arg;
return id return id;
} else if (isPlainObject(arg)) { }
Object.keys(arg).forEach((name) => { else if (isPlainObject(arg)) {
arg[name] = normalizeArg(arg[name]) Object.keys(arg).forEach((name) => {
}) ;
} arg[name] = normalizeArg(arg[name]);
return arg });
} }
function isProxyInvokeCallbackResponse(res) { return arg;
return !!res.name }
} function isProxyInvokeCallbackResponse(res) {
function moduleGetter(proxy, module, method, defines) { return !!res.name;
const invokeCallback = ({ id, name, params, keepAlive }) => { }
const callback = callbacks[id] function moduleGetter(proxy, module, method, defines) {
if (callback) { const invokeCallback = ({ id, name, params, keepAlive, }) => {
callback(...params) const callback = callbacks[id];
if (!keepAlive) { if (callback) {
delete callbacks[id] callback(...params);
} if (!keepAlive) {
} else { delete callbacks[id];
console.error(`${module}.${method} ${name} is not found`) }
} }
} else {
return (...args) => { console.error(`${module}.${method} ${name} is not found`);
const params = args.map((arg) => normalizeArg(arg)) }
const invokeArgs = { module, method, params, async: !!defines.async } };
if (defines.async) { return (...args) => {
return new Promise((resolve, reject) => { const params = args.map((arg) => normalizeArg(arg));
proxy.invoke(invokeArgs, (res) => { const invokeArgs = { module, method, params, async: !!defines.async };
if (isProxyInvokeCallbackResponse(res)) { if (defines.async) {
invokeCallback(res) return new Promise((resolve, reject) => {
} else { proxy.invoke(invokeArgs, (res) => {
if (res.errMsg) { if (isProxyInvokeCallbackResponse(res)) {
reject(res.errMsg) invokeCallback(res);
} else { }
resolve(res.params) else {
} if (res.errMsg) {
} reject(res.errMsg);
}) }
}) else {
} resolve(res.params);
return proxy.invoke(invokeArgs, invokeCallback) }
} }
} });
function initModule(moduleDefine) { });
let proxy }
const moduleProxy = {} return proxy.invoke(invokeArgs, invokeCallback);
for (const methodName in moduleDefine) { };
Object.defineProperty(moduleProxy, methodName, { }
enumerable: true, function initModule(moduleDefine) {
configurable: true, let proxy;
get: () => { const moduleProxy = {};
if (!proxy) { for (const methodName in moduleDefine) {
proxy = uni.requireNativePlugin('proxy-module') Object.defineProperty(moduleProxy, methodName, {
} enumerable: true,
return moduleGetter( configurable: true,
proxy, get: () => {
moduleName, if (!proxy) {
methodName, proxy = uni.requireNativePlugin('proxy-module');
moduleDefine[methodName] }
) return moduleGetter(proxy, moduleName, methodName, moduleDefine[methodName]);
}, },
}) });
} }
return moduleProxy;
} }
export { module as default, normalizeArg } export { module as default, normalizeArg };
...@@ -119,4 +119,5 @@ function initModule(moduleDefine: Record<string, ModuleMethodDefine>) { ...@@ -119,4 +119,5 @@ function initModule(moduleDefine: Record<string, ModuleMethodDefine>) {
}, },
}) })
} }
return moduleProxy
} }
import type { Plugin } from 'vite' import type { Plugin } from 'vite'
import fs from 'fs' import fs from 'fs'
import path from 'path' import path from 'path'
import { parseJson, parseVueRequest } from '@dcloudio/uni-cli-shared' import { normalizePath, parseVueRequest } from '@dcloudio/uni-cli-shared'
import { import {
ExportDefaultDeclaration, ExportDefaultDeclaration,
Module, Module,
TsFunctionType,
TsType,
TsTypeAnnotation, TsTypeAnnotation,
} from '../../types/types' } from '../../types/types'
// 需要区分 android,iOS // 需要区分 android,iOS
...@@ -15,40 +17,22 @@ export function uniUtsV1Plugin(): Plugin { ...@@ -15,40 +17,22 @@ export function uniUtsV1Plugin(): Plugin {
name: 'uni:uts-v1', name: 'uni:uts-v1',
apply: 'build', apply: 'build',
enforce: 'pre', enforce: 'pre',
resolveId(id) { async transform(code, id, opts) {
if (!id.includes('uni_modules')) {
return
}
const pkgPath = path.join(id, 'package.json')
if (!fs.existsSync(pkgPath)) {
return
}
const pkg = parseJson(fs.readFileSync(pkgPath, 'utf-8'))
if (pkg.uni_modules?.type !== 'uts') {
return
}
return (
path.join(id, pkg.main || 'interface.uts') +
'?module=' +
path.basename(path.dirname(pkgPath))
)
},
transform(code, id, opts) {
if (opts && opts.ssr) { if (opts && opts.ssr) {
return return
} }
const { filename, query } = parseVueRequest(id) const { filename } = parseVueRequest(id)
if (path.extname(filename) !== '.uts') { if (path.extname(filename) !== '.uts') {
return return
} }
const moduleName = (query as any).module as string const moduleName = parseModuleId(filename)
if (!moduleName) { if (!moduleName) {
return return
} }
// 懒加载 uts // 懒加载 uts
// eslint-disable-next-line no-restricted-globals // eslint-disable-next-line no-restricted-globals
const { parse } = require('@dcloudio/uts') const { parse } = require('@dcloudio/uts')
const ast = parse(code) const ast = await parse(code)
if (!moduleCode) { if (!moduleCode) {
moduleCode = fs.readFileSync( moduleCode = fs.readFileSync(
path.resolve(__dirname, '../../lib/module.js'), path.resolve(__dirname, '../../lib/module.js'),
...@@ -62,6 +46,15 @@ export function uniUtsV1Plugin(): Plugin { ...@@ -62,6 +46,15 @@ export function uniUtsV1Plugin(): Plugin {
} }
} }
function parseModuleId(filepath: string) {
const parts = normalizePath(filepath).split('/')
const index = parts.findIndex((part) => part === 'uni_modules')
if (index > -1) {
return parts[index + 1]
}
return ''
}
function parseModuleDefines(ast: Module) { function parseModuleDefines(ast: Module) {
const module: Record<string, { async: boolean }> = {} const module: Record<string, { async: boolean }> = {}
const defaultDecl = ast.body.find( const defaultDecl = ast.body.find(
...@@ -72,17 +65,39 @@ function parseModuleDefines(ast: Module) { ...@@ -72,17 +65,39 @@ function parseModuleDefines(ast: Module) {
} }
const body = defaultDecl.decl.body.body const body = defaultDecl.decl.body.body
body.forEach((item) => { body.forEach((item) => {
if (item.type !== 'TsMethodSignature' || item.key.type !== 'Identifier') { if (item.type === 'TsPropertySignature') {
return const { key, typeAnnotation } = item
} if (key.type !== 'Identifier') {
const methodName = item.key.value return
module[methodName] = { }
async: item.typeAnn ? isReturnPromise(item.typeAnn) : false, if (!typeAnnotation) {
return
}
const functionType = typeAnnotation.typeAnnotation
if (!isFunctionType(functionType)) {
return
}
const methodName = key.value
module[methodName] = {
async: isReturnPromise(functionType.typeAnnotation),
}
} else if (item.type === 'TsMethodSignature') {
if (item.key.type !== 'Identifier') {
return
}
const methodName = item.key.value
module[methodName] = {
async: item.typeAnn ? isReturnPromise(item.typeAnn) : false,
}
} }
}) })
return module return module
} }
function isFunctionType(type: TsType): type is TsFunctionType {
return type.type === 'TsFunctionType'
}
function isReturnPromise({ typeAnnotation }: TsTypeAnnotation) { function isReturnPromise({ typeAnnotation }: TsTypeAnnotation) {
return ( return (
typeAnnotation.type === 'TsTypeReference' && typeAnnotation.type === 'TsTypeReference' &&
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册