fix: 微信登录补充保存username和role
Some checks failed
continuous-integration/drone/push Build is failing

This commit is contained in:
Agent
2026-04-04 07:35:21 +00:00
parent 756444ef2b
commit d12eea7693
10597 changed files with 817047 additions and 3 deletions

202
node_modules/@dcloudio/uni-console/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

91
node_modules/@dcloudio/uni-console/lib/uni.plugin.js generated vendored Normal file
View File

@@ -0,0 +1,91 @@
'use strict';
var fs = require('fs-extra');
var path = require('path');
var uniCliShared = require('@dcloudio/uni-cli-shared');
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
var fs__default = /*#__PURE__*/_interopDefault(fs);
var path__default = /*#__PURE__*/_interopDefault(path);
const uniConsoleRuntimePlugin = () => {
return {
name: 'uni:console:runtime',
config() {
const isX = process.env.UNI_APP_X === 'true';
const isProd = process.env.NODE_ENV === 'production';
let keepOriginal = true;
if (process.env.UNI_PLATFORM == 'mp-harmony' ||
process.env.UNI_PLATFORM === 'app-harmony') {
keepOriginal = false;
}
const webviewEvalJsCode = isX && process.env.UNI_UTS_PLATFORM === 'app-android'
? fs__default.default.readFileSync(path__default.default.join(__dirname, '../dist/__uniwebview.js'), 'utf-8')
: '';
return {
define: {
'process.env.UNI_CONSOLE_KEEP_ORIGINAL': process.env
.UNI_CONSOLE_KEEP_ORIGINAL
? process.env.UNI_CONSOLE_KEEP_ORIGINAL === 'true'
: keepOriginal,
'process.env.UNI_SOCKET_HOSTS': JSON.stringify(isProd ? '' : process.env.UNI_SOCKET_HOSTS),
'process.env.UNI_SOCKET_PORT': JSON.stringify(isProd ? '' : process.env.UNI_SOCKET_PORT),
'process.env.UNI_SOCKET_ID': JSON.stringify(isProd ? '' : process.env.UNI_SOCKET_ID),
'process.env.UNI_CONSOLE_WEBVIEW_EVAL_JS_CODE': JSON.stringify(webviewEvalJsCode),
},
};
},
};
};
var index = () => {
return [
uniConsoleRuntimePlugin(),
uniCliShared.defineUniMainJsPlugin((opts) => {
let hasRuntimeSocket = uniCliShared.isEnableConsole();
const isX = process.env.UNI_APP_X === 'true';
// 基座类型为custom时不启用运行时socket
// 需要判断自定义基座是否包含socket模块有的话才可以启用
if (isX && process.env.UNI_PLATFORM === 'app') {
if (process.env.HX_USE_BASE_TYPE === 'custom') {
hasRuntimeSocket = false;
}
}
let uniConsolePath = uniCliShared.resolveBuiltIn(path__default.default.join('@dcloudio/uni-console', `dist/${(process.env.UNI_PLATFORM || '').startsWith('mp-') ? 'mp' : 'index'}.esm.js`));
if (isX) {
if (process.env.UNI_UTS_PLATFORM === 'app-android') {
uniConsolePath = uniCliShared.resolveBuiltIn(path__default.default.join('@dcloudio/uni-console', 'src/runtime/app/index.ts'));
}
else if (process.env.UNI_UTS_PLATFORM === 'app-ios') {
uniConsolePath = uniCliShared.resolveBuiltIn(path__default.default.join('@dcloudio/uni-console', 'dist/app.esm.js'));
}
}
else {
if (process.env.UNI_PLATFORM === 'app-harmony') {
uniConsolePath = uniCliShared.resolveBuiltIn(path__default.default.join('@dcloudio/uni-console', 'dist/harmony.jsvm.esm.js'));
}
}
return {
name: 'uni:console-main-js',
enforce:
// android需要提前不然拿到的code是解析后的仅保留import语句的
process.env.UNI_UTS_PLATFORM === 'app-android' ? 'pre' : 'post',
transform(code, id) {
if (!hasRuntimeSocket) {
return;
}
if (!opts.filter(id)) {
return;
}
return {
// 采用绝对路径引入此时tsc失效代码里需要自己处理好各种类型问题
code: `import '${uniCliShared.normalizePath(uniConsolePath)}';${code}`,
map: null,
};
},
};
}),
];
};
module.exports = index;

1
node_modules/@dcloudio/uni-console/license.md generated vendored Normal file
View File

@@ -0,0 +1 @@
[https://dcloud.io/license/uni-app.html](https://dcloud.io/license/uni-app.html)

25
node_modules/@dcloudio/uni-console/package.json generated vendored Normal file
View File

@@ -0,0 +1,25 @@
{
"name": "@dcloudio/uni-console",
"version": "3.0.0-4080720251210001",
"description": "uni-app console",
"module": "dist/index.esm.js",
"files": [
"dist",
"lib",
"src"
],
"repository": {
"type": "git",
"url": "git+https://github.com/dcloudio/uni-app.git",
"directory": "packages/uni-console"
},
"license": "Apache-2.0",
"gitHead": "33e807d66e1fe47e2ee08ad9c59247e37b8884da",
"dependencies": {
"fs-extra": "10.1.0",
"@dcloudio/uni-cli-shared": "3.0.0-4080720251210001"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
}
}

View File

@@ -0,0 +1,113 @@
import type { Plugin } from 'vite'
import fs from 'fs-extra'
import path from 'path'
import {
defineUniMainJsPlugin,
isEnableConsole,
normalizePath,
resolveBuiltIn,
} from '@dcloudio/uni-cli-shared'
const uniConsoleRuntimePlugin = (): Plugin => {
return {
name: 'uni:console:runtime',
config() {
const isX = process.env.UNI_APP_X === 'true'
const isProd = process.env.NODE_ENV === 'production'
let keepOriginal = true
if (
process.env.UNI_PLATFORM == 'mp-harmony' ||
process.env.UNI_PLATFORM === 'app-harmony'
) {
keepOriginal = false
}
const webviewEvalJsCode =
isX && process.env.UNI_UTS_PLATFORM === 'app-android'
? fs.readFileSync(
path.join(__dirname, '../dist/__uniwebview.js'),
'utf-8'
)
: ''
return {
define: {
'process.env.UNI_CONSOLE_KEEP_ORIGINAL': process.env
.UNI_CONSOLE_KEEP_ORIGINAL
? process.env.UNI_CONSOLE_KEEP_ORIGINAL === 'true'
: keepOriginal,
'process.env.UNI_SOCKET_HOSTS': JSON.stringify(
isProd ? '' : process.env.UNI_SOCKET_HOSTS
),
'process.env.UNI_SOCKET_PORT': JSON.stringify(
isProd ? '' : process.env.UNI_SOCKET_PORT
),
'process.env.UNI_SOCKET_ID': JSON.stringify(
isProd ? '' : process.env.UNI_SOCKET_ID
),
'process.env.UNI_CONSOLE_WEBVIEW_EVAL_JS_CODE':
JSON.stringify(webviewEvalJsCode),
},
}
},
}
}
export default () => {
return [
uniConsoleRuntimePlugin(),
defineUniMainJsPlugin((opts) => {
let hasRuntimeSocket = isEnableConsole()
const isX = process.env.UNI_APP_X === 'true'
// 基座类型为custom时不启用运行时socket
// 需要判断自定义基座是否包含socket模块有的话才可以启用
if (isX && process.env.UNI_PLATFORM === 'app') {
if (process.env.HX_USE_BASE_TYPE === 'custom') {
hasRuntimeSocket = false
}
}
let uniConsolePath = resolveBuiltIn(
path.join(
'@dcloudio/uni-console',
`dist/${
(process.env.UNI_PLATFORM || '').startsWith('mp-') ? 'mp' : 'index'
}.esm.js`
)
)
if (isX) {
if (process.env.UNI_UTS_PLATFORM === 'app-android') {
uniConsolePath = resolveBuiltIn(
path.join('@dcloudio/uni-console', 'src/runtime/app/index.ts')
)
} else if (process.env.UNI_UTS_PLATFORM === 'app-ios') {
uniConsolePath = resolveBuiltIn(
path.join('@dcloudio/uni-console', 'dist/app.esm.js')
)
}
} else {
if (process.env.UNI_PLATFORM === 'app-harmony') {
uniConsolePath = resolveBuiltIn(
path.join('@dcloudio/uni-console', 'dist/harmony.jsvm.esm.js')
)
}
}
return {
name: 'uni:console-main-js',
enforce:
// android需要提前不然拿到的code是解析后的仅保留import语句的
process.env.UNI_UTS_PLATFORM === 'app-android' ? 'pre' : 'post',
transform(code: string, id: string) {
if (!hasRuntimeSocket) {
return
}
if (!opts.filter(id)) {
return
}
return {
// 采用绝对路径引入此时tsc失效代码里需要自己处理好各种类型问题
code: `import '${normalizePath(uniConsolePath)}';${code}`,
map: null,
}
},
}
}),
]
}

View File

@@ -0,0 +1,34 @@
import { initRuntimeSocket } from './socket'
export function initRuntimeSocketService(): Promise<boolean> {
const hosts: string = process.env.UNI_SOCKET_HOSTS
const port: string = process.env.UNI_SOCKET_PORT
const id: string = process.env.UNI_SOCKET_ID
if (hosts == '' || port == '' || id == '') return Promise.resolve(false)
let socketTask: SocketTask | null = null
__registerWebViewUniConsole(
(): string => {
return process.env.UNI_CONSOLE_WEBVIEW_EVAL_JS_CODE
},
(data: string) => {
socketTask?.send({
data,
} as SendSocketMessageOptions)
}
)
return Promise.resolve()
.then((): Promise<boolean> => {
return initRuntimeSocket(hosts, port, id).then((socket): boolean => {
if (socket == null) {
return false
}
socketTask = socket
return true
})
})
.catch((): boolean => {
return false
})
}
initRuntimeSocketService()

View File

@@ -0,0 +1,61 @@
/// <reference types="@dcloudio/uni-app-x/types/uni/global" />
// 之所以又写了一份是因为外层的socketconnectSocket的时候必须传入multiple:true
// 但是android又不能传入目前代码里又不能写条件编译之类的。
export function initRuntimeSocket(
hosts: string,
port: string,
id: string
): Promise<SocketTask | null> {
if (hosts == '' || port == '' || id == '') return Promise.resolve(null)
return hosts
.split(',')
.reduce<Promise<SocketTask | null>>(
(
promise: Promise<SocketTask | null>,
host: string
): Promise<SocketTask | null> => {
return promise.then((socket): Promise<SocketTask | null> => {
if (socket != null) return Promise.resolve(socket)
return tryConnectSocket(host, port, id)
})
},
Promise.resolve(null)
)
}
const SOCKET_TIMEOUT = 500
function tryConnectSocket(
host: string,
port: string,
id: string
): Promise<SocketTask | null> {
return new Promise((resolve, reject) => {
const socket = uni.connectSocket({
url: `ws://${host}:${port}/${id}`,
fail() {
resolve(null)
},
})
const timer = setTimeout(() => {
// @ts-expect-error
socket.close({
code: 1006,
reason: 'connect timeout',
} as CloseSocketOptions)
resolve(null)
}, SOCKET_TIMEOUT)
socket.onOpen((e) => {
clearTimeout(timer)
resolve(socket)
})
socket.onClose((e) => {
clearTimeout(timer)
resolve(null)
})
socket.onError((e) => {
clearTimeout(timer)
resolve(null)
})
})
}

View File

@@ -0,0 +1,426 @@
import type { ComponentInternalInstance, ComponentPublicInstance } from 'vue'
import type { MessageType } from './utils'
interface NormalizeResult {
name?: string
type: string
subType?: string
className?: string
description?: string
value?: any
}
interface ObjectResultValue {
properties: Array<NormalizeResult>
}
interface ObjectResult extends NormalizeResult {
value: ObjectResultValue
}
interface ArrayResultValue {
properties: Array<NormalizeResult>
}
interface ArrayResult extends NormalizeResult {
value: ArrayResultValue
}
interface SetResultEntry {
value: NormalizeResult
}
interface SetResultValue {
entries: Array<SetResultEntry>
}
interface SetResult extends NormalizeResult {
value: SetResultValue
}
interface MapResultEntry {
key: NormalizeResult
value: NormalizeResult
}
interface MapResultValue {
entries: Array<MapResultEntry>
}
interface MapResult extends NormalizeResult {
value: MapResultValue
}
export interface Message {
type: MessageType
args: Array<any>
}
export function formatMessage(
type: MessageType,
args: Array<any | null>
): Message {
try {
return {
type,
args: formatArgs(args),
}
} catch (e) {
// originalConsole.error(e)
}
return {
type,
args: [],
}
}
export function formatArgs(args: Array<any | null>) {
return args.map((arg) => formatArg(arg))
}
export function formatArg(arg: any | null, depth: number = 0): NormalizeResult {
if (depth >= 7) {
return {
type: 'object',
value: '[Maximum depth reached]',
}
}
const type = typeof arg
switch (type) {
case 'string':
return formatString(arg as string)
case 'number':
return formatNumber(arg as number)
case 'boolean':
return formatBoolean(arg as boolean)
case 'object':
try {
// 鸿蒙里边 object 可能包含 nativePtr 指针,该指针 typeof 是 object
// 但是又不能访问上边的任意属性否则会报TypeError: Can not get Prototype on non ECMA Object
// 所以这里需要捕获异常,防止报错
return formatObject(arg as object, depth)
} catch (e) {
return {
type: 'object',
value: {
properties: [],
},
}
}
case 'undefined':
return formatUndefined()
case 'function':
return formatFunction(arg as Function)
case 'symbol':
if (__HARMONY__) {
return formatUnknown('symbol', arg as unknown)
} else {
return formatSymbol(arg as symbol)
}
case 'bigint':
return formatBigInt(arg as unknown)
}
}
function formatFunction(value: Function): NormalizeResult {
return {
type: 'function',
value: `function ${value.name}() {}`,
}
}
function formatUndefined(): NormalizeResult {
return {
type: 'undefined',
}
}
function formatBoolean(value: boolean): NormalizeResult {
return {
type: 'boolean',
value: String(value),
}
}
function formatNumber(value: number): NormalizeResult {
return {
type: 'number',
value: String(value),
}
}
function formatBigInt(value: unknown): NormalizeResult {
return {
type: 'bigint',
value: String(value),
}
}
function formatString(value: string): NormalizeResult {
return {
type: 'string',
value,
}
}
function formatSymbol(value: symbol): NormalizeResult {
return {
type: 'symbol',
value: value.description,
}
}
function formatUnknown(type: string, value: unknown): NormalizeResult {
return {
type,
value: String(value),
}
}
function formatObject(value: object, depth: number): NormalizeResult {
if (value === null) {
return {
type: 'null',
}
}
if (!__HARMONY__) {
if (isComponentPublicInstance(value)) {
return formatComponentPublicInstance(value, depth)
}
if (isComponentInternalInstance(value)) {
return formatComponentInternalInstance(value, depth)
}
if (isUniElement(value)) {
return formatUniElement(value, depth)
}
if (isCSSStyleDeclaration(value)) {
return formatCSSStyleDeclaration(value, depth)
}
}
if (Array.isArray(value)) {
return {
type: 'object',
subType: 'array',
value: {
properties: value.map(
(v: any | null, i: number): NormalizeResult =>
formatArrayElement(v, i, depth + 1)
),
},
} as ArrayResult
}
if (value instanceof Set) {
return {
type: 'object',
subType: 'set',
className: 'Set',
description: `Set(${value.size})`,
value: {
entries: Array.from(value).map(
(v: any | null): SetResultEntry => formatSetEntry(v, depth + 1)
),
},
} as SetResult
}
if (value instanceof Map) {
return {
type: 'object',
subType: 'map',
className: 'Map',
description: `Map(${value.size})`,
value: {
entries: Array.from(value.entries()).map(
(v: Array<any | null>): MapResultEntry => formatMapEntry(v, depth + 1)
),
},
} as MapResult
}
if (value instanceof Promise) {
return {
type: 'object',
subType: 'promise',
value: {
properties: [],
},
} as ObjectResult
}
if (value instanceof RegExp) {
return {
type: 'object',
subType: 'regexp',
value: String(value),
className: 'Regexp',
}
}
if (value instanceof Date) {
return {
type: 'object',
subType: 'date',
value: String(value),
className: 'Date',
}
}
if (value instanceof Error) {
return {
type: 'object',
subType: 'error',
value: value.message || String(value),
className: value.name || 'Error',
}
}
let className: string | undefined = undefined
if (!__HARMONY__) {
const constructor = value.constructor
if (constructor) {
// @ts-expect-error
if (constructor.get$UTSMetadata$) {
// @ts-expect-error
className = constructor.get$UTSMetadata$().name
}
}
}
let entries = Object.entries(value)
if (isHarmonyBuilderParams(value)) {
entries = entries.filter(
([key]) => key !== 'modifier' && key !== 'nodeContent'
)
}
return {
type: 'object',
className,
value: {
properties: entries.map(
(entry: [string, any | null]): NormalizeResult =>
formatObjectProperty(entry[0], entry[1], depth + 1)
),
},
} as ObjectResult
}
function isHarmonyBuilderParams(value: any) {
return value.modifier && value.modifier._attribute && value.nodeContent
}
function isComponentPublicInstance(
value: any
): value is ComponentPublicInstance {
return value.$ && isComponentInternalInstance(value.$)
}
function isComponentInternalInstance(
value: any
): value is ComponentInternalInstance {
return value.type && value.uid != null && value.appContext
}
function formatComponentPublicInstance(
value: ComponentPublicInstance,
depth: number
) {
return {
type: 'object',
className: 'ComponentPublicInstance',
value: {
properties: Object.entries(value.$.type).map(
([name, value]): NormalizeResult =>
formatObjectProperty(name, value, depth + 1)
),
},
}
}
function formatComponentInternalInstance(
value: ComponentInternalInstance,
depth: number
) {
return {
type: 'object',
className: 'ComponentInternalInstance',
value: {
properties: Object.entries(value.type).map(
([name, value]): NormalizeResult =>
formatObjectProperty(name, value, depth + 1)
),
},
}
}
function isUniElement(value: any): value is UniElement {
return value.style && value.tagName != null && value.nodeName != null
}
function formatUniElement(value: UniElement, depth: number) {
return {
type: 'object',
// 非 x 没有 UniElement 的概念
// className: 'UniElement',
value: {
properties: Object.entries(value)
.filter(([name]) =>
[
'id',
'tagName',
'nodeName',
'dataset',
'offsetTop',
'offsetLeft',
'style',
].includes(name)
)
.map(
([name, value]): NormalizeResult =>
formatObjectProperty(name, value, depth + 1)
),
},
}
}
function isCSSStyleDeclaration(
value: any
): value is CSSStyleDeclaration & { $styles: Record<string, string | null> } {
return (
typeof value.getPropertyValue === 'function' &&
typeof value.setProperty === 'function' &&
value.$styles
)
}
function formatCSSStyleDeclaration(
style: CSSStyleDeclaration & { $styles: Record<string, string | null> },
depth: number
) {
return {
type: 'object',
value: {
properties: Object.entries(style.$styles).map(([name, value]) =>
formatObjectProperty(name, value, depth + 1)
),
},
}
}
function formatObjectProperty(name: string, value: any | null, depth: number) {
const result = formatArg(value, depth)
result.name = name
return result
}
function formatArrayElement(value: any | null, index: number, depth: number) {
const result = formatArg(value, depth)
result.name = `${index}`
return result
}
function formatSetEntry(value: any | null, depth: number): SetResultEntry {
return {
value: formatArg(value, depth),
}
}
function formatMapEntry(
value: Array<any | null>,
depth: number
): MapResultEntry {
return {
key: formatArg(value[0], depth),
value: formatArg(value[1], depth),
}
}

View File

@@ -0,0 +1,144 @@
import { sendErrorMessages } from '../error'
import type { SendFn } from '../utils'
import { type Message, formatMessage } from './format'
import { CONSOLE_TYPES, type MessageType, originalConsole } from './utils'
let sendConsole: SendFn = null
const messageQueue: Message[] = []
const messageExtra: Record<string, any> = {}
const EXCEPTION_BEGIN_MARK = '---BEGIN:EXCEPTION---'
const EXCEPTION_END_MARK = '---END:EXCEPTION---'
function sendConsoleMessages(messages: Message[]) {
if (sendConsole == null) {
messageQueue.push(...messages)
return
}
sendConsole(
JSON.stringify(
Object.assign(
{
type: 'console',
data: messages,
},
messageExtra
)
)
)
}
export function setSendConsole(value: SendFn, extra: Record<string, any> = {}) {
sendConsole = value
Object.assign(messageExtra, extra)
if (value != null && messageQueue.length > 0) {
const messages = messageQueue.slice()
messageQueue.length = 0
sendConsoleMessages(messages)
}
}
const atFileRegex = /^\s*at\s+[\w/./-]+:\d+$/
export function rewriteConsole() {
if (__HARMONY_JSVM__) {
if (
typeof UTSProxyObject === 'object' &&
UTSProxyObject !== null &&
typeof UTSProxyObject.invokeSync === 'function'
) {
UTSProxyObject.invokeSync('__UniConsole', 'setSendConsoleMessages', [
sendConsoleMessages,
])
}
}
function wrapConsole(type: MessageType) {
return function (...args: any[]) {
if (process.env.UNI_CONSOLE_KEEP_ORIGINAL) {
const originalArgs = [...args]
if (originalArgs.length) {
const maybeAtFile = originalArgs[originalArgs.length - 1]
// 移除最后的 at pages/index/index.uvue:6
if (
typeof maybeAtFile === 'string' &&
atFileRegex.test(maybeAtFile)
) {
originalArgs.pop()
}
}
originalConsole[type](...originalArgs)
}
if (type === 'error' && args.length === 1) {
const arg = args[0]
if (typeof arg === 'string' && arg.startsWith(EXCEPTION_BEGIN_MARK)) {
const startIndex = EXCEPTION_BEGIN_MARK.length
const endIndex = arg.length - EXCEPTION_END_MARK.length
sendErrorMessages([arg.slice(startIndex, endIndex)])
return
} else if (arg instanceof Error) {
sendErrorMessages([arg])
return
}
}
sendConsoleMessages([formatMessage(type, args)])
}
}
// 百度小程序不允许赋值,所以需要判断是否可写
if (isConsoleWritable()) {
CONSOLE_TYPES.forEach((type) => {
console[type] = wrapConsole(type)
})
return function restoreConsole() {
CONSOLE_TYPES.forEach((type) => {
console[type] = originalConsole[type]
})
}
} else {
if (!process.env.UNI_CONSOLE_WEBVIEW) {
if (typeof uni !== 'undefined' && uni.__f__) {
const oldLog = uni.__f__
if (oldLog) {
// 重写 uni.__f__ 方法这样的话仅能打印开发者代码里的日志其他没有被重写为__f__的日志将无法打印比如uni-app框架、小程序框架等
uni.__f__ = function (...args: any[]) {
const [type, filename, ...rest] = args
// 原始日志移除 filename
oldLog(type, '', ...rest)
sendConsoleMessages([formatMessage(type, [...rest, filename])])
}
return function restoreConsole() {
uni.__f__ = oldLog
}
}
}
}
}
return function restoreConsole() {
if (__HARMONY_JSVM__) {
if (
typeof UTSProxyObject === 'object' &&
UTSProxyObject !== null &&
typeof UTSProxyObject.invokeSync === 'function'
) {
UTSProxyObject.invokeSync('__UniConsole', 'restoreConsole', [])
}
}
}
}
function isConsoleWritable() {
const value = console.log
const sym = Symbol()
try {
// @ts-expect-error
console.log = sym
} catch (ex) {
return false
}
// @ts-expect-error
const isWritable = console.log === sym
console.log = value
return isWritable
}

View File

@@ -0,0 +1,11 @@
export const CONSOLE_TYPES = ['log', 'warn', 'error', 'info', 'debug'] as const
export type MessageType = 'log' | 'warn' | 'error' | 'info' | 'debug'
export const originalConsole = /*@__PURE__*/ CONSOLE_TYPES.reduce(
(methods, type) => {
methods[type] = console[type].bind(console)
return methods
},
{} as Record<MessageType, typeof console.log>
)

117
node_modules/@dcloudio/uni-console/src/runtime/error.ts generated vendored Normal file
View File

@@ -0,0 +1,117 @@
import { originalConsole } from './console/utils'
import type { SendFn } from './utils'
let sendError: SendFn = null
// App.onError会监听到两类错误一类是小程序自身抛出的一类是 vue 的 errorHandler 触发的
// uni.onError 和 App.onError 会同时监听到错误(主要是App.onError监听之前的错误),所以需要用 Set 来去重
// uni.onError 会在 App.onError 上边同时增加监听,因为要监听 vue 的errorHandler
// 目前 vue 的 errorHandler 仅会callHook('onError')所以需要把uni.onError的也挂在 App.onError 上
const errorQueue: Set<any> = new Set()
const errorExtra: Record<string, any> = {}
export function sendErrorMessages(errors: any[]) {
if (sendError == null) {
errors.forEach((error) => {
errorQueue.add(error)
})
return
}
const data = errors
.map((err) => {
if (typeof err === 'string') {
return err
}
const isPromiseRejection = err && 'promise' in err && 'reason' in err
const prefix = isPromiseRejection ? 'UnhandledPromiseRejection: ' : ''
if (isPromiseRejection) {
err = err.reason
}
if (err instanceof Error && err.stack) {
if (err.message && !err.stack.includes(err.message)) {
return `${prefix}${err.message}
${err.stack}`
}
return `${prefix}${err.stack}`
}
if (typeof err === 'object' && err !== null) {
try {
return prefix + JSON.stringify(err)
} catch (err) {
return prefix + String(err)
}
}
return prefix + String(err)
})
.filter(Boolean)
if (data.length > 0) {
sendError(
JSON.stringify(
Object.assign(
{
type: 'error',
data,
},
errorExtra
)
)
)
}
}
export function setSendError(value: SendFn, extra: Record<string, any> = {}) {
sendError = value
Object.assign(errorExtra, extra)
if (value != null && errorQueue.size > 0) {
const errors = Array.from(errorQueue)
errorQueue.clear()
sendErrorMessages(errors)
}
}
export function initOnError() {
function onError(error: any) {
try {
// 小红书小程序 socket.send 时会报错onError错误信息为
// Cannot create property 'errMsg' on string 'taskId'
// 导致陷入死循环
if (
typeof PromiseRejectionEvent !== 'undefined' &&
error instanceof PromiseRejectionEvent &&
error.reason instanceof Error &&
error.reason.message &&
error.reason.message.includes(
`Cannot create property 'errMsg' on string 'taskId`
)
) {
return
}
if (process.env.UNI_CONSOLE_KEEP_ORIGINAL) {
originalConsole.error(error)
}
sendErrorMessages([error])
} catch (err) {
originalConsole.error(err)
}
}
if (typeof uni !== 'undefined') {
if (typeof uni.onError === 'function') {
uni.onError(onError)
}
if (typeof uni.onUnhandledRejection === 'function') {
uni.onUnhandledRejection(onError)
}
}
return function offError() {
if (typeof uni !== 'undefined') {
if (typeof uni.offError === 'function') {
uni.offError(onError)
}
if (typeof uni.offUnhandledRejection === 'function') {
uni.offUnhandledRejection(onError)
}
}
}
}

View File

@@ -0,0 +1,7 @@
import { formatMessage } from './console/format'
import type { MessageType } from './console/utils'
export function __f__(type: MessageType, filename: string, ...args: any[]) {
const message = formatMessage(type, [...args, filename])
return message
}

123
node_modules/@dcloudio/uni-console/src/runtime/index.ts generated vendored Normal file
View File

@@ -0,0 +1,123 @@
import { initRuntimeSocket } from './socket'
import { rewriteConsole, setSendConsole } from './console'
import { initOnError, setSendError } from './error'
import { originalConsole } from './console/utils'
export function initRuntimeSocketService(): Promise<boolean> {
const hosts: string = process.env.UNI_SOCKET_HOSTS
const port: string = process.env.UNI_SOCKET_PORT
const id: string = process.env.UNI_SOCKET_ID
if (!hosts || !port || !id) return Promise.resolve(false)
// 百度小程序需要延迟初始化不然会存在循环引用问题vendor.js
const lazy = typeof swan !== 'undefined'
// 重写需要同步,避免丢失早期日志信息
let restoreError = lazy ? () => {} : initOnError()
let restoreConsole = lazy ? () => {} : rewriteConsole()
// 百度小程序需要异步初始化,不然调用 uni.connectSocket 会循环引入vendor.js
return Promise.resolve().then(() => {
if (lazy) {
restoreError = initOnError()
restoreConsole = rewriteConsole()
}
return initRuntimeSocket(hosts, port, id).then((socket) => {
if (!socket) {
restoreError()
restoreConsole()
originalConsole.error(
wrapError('开发模式下日志通道建立 socket 连接失败。')
)
// @ts-expect-error
if (__PLATFORM__ === 'mp') {
originalConsole.error(
wrapError('小程序平台,请勾选不校验合法域名配置。')
)
}
originalConsole.error(
wrapError('如果是运行到真机,请确认手机与电脑处于同一网络。')
)
return false
}
// @ts-expect-error
if (__PLATFORM__ === 'mp') {
initMiniProgramGlobalFlag()
}
socket.onClose(() => {
if (process.env.UNI_DEBUG) {
originalConsole.log(
`uni-app:[${Date.now()}][socket]`,
'connect close and restore'
)
}
// @ts-expect-error
if (__PLATFORM__ === 'mp') {
originalConsole.error(
wrapError(
'开发模式下日志通道 socket 连接关闭,请在 HBuilderX 中重新运行。'
)
)
} else {
originalConsole.error(
wrapError(
'手机端日志通道 socket 连接已断开,请重启基座应用或重新运行。'
)
)
}
restoreError()
restoreConsole()
})
setSendConsole((data: string) => {
if (process.env.UNI_DEBUG) {
originalConsole.log(`uni-app:[${Date.now()}][console]`, data)
}
socket!.send({
data,
})
})
setSendError((data: string) => {
if (process.env.UNI_DEBUG) {
originalConsole.log(`uni-app:[${Date.now()}][error]`, data)
}
socket!.send({
data,
})
})
return true
})
})
}
const ERROR_CHAR = '\u200C'
function wrapError(error: string) {
return `${ERROR_CHAR}${error}${ERROR_CHAR}`
}
function initMiniProgramGlobalFlag() {
if (typeof wx !== 'undefined') {
// @ts-expect-error
wx.__uni_console__ = true
// @ts-expect-error
} else if (typeof my !== 'undefined') {
// @ts-expect-error
my.__uni_console__ = true
} else if (typeof tt !== 'undefined') {
tt.__uni_console__ = true
} else if (typeof swan !== 'undefined') {
swan.__uni_console__ = true
} else if (typeof qq !== 'undefined') {
qq.__uni_console__ = true
} else if (typeof ks !== 'undefined') {
ks.__uni_console__ = true
} else if (typeof jd !== 'undefined') {
jd.__uni_console__ = true
} else if (typeof xhs !== 'undefined') {
xhs.__uni_console__ = true
} else if (typeof has !== 'undefined') {
has.__uni_console__ = true
} else if (typeof qa !== 'undefined') {
qa.__uni_console__ = true
}
}
initRuntimeSocketService()

View File

@@ -0,0 +1,61 @@
/// <reference types="@dcloudio/uni-app-x/types/uni/global" />
export function initRuntimeSocket(
hosts: string,
port: string,
id: string
): Promise<SocketTask | null> {
if (hosts == '' || port == '' || id == '') return Promise.resolve(null)
return hosts
.split(',')
.reduce<Promise<SocketTask | null>>(
(
promise: Promise<SocketTask | null>,
host: string
): Promise<SocketTask | null> => {
return promise.then((socket): Promise<SocketTask | null> => {
if (socket != null) return Promise.resolve(socket)
return tryConnectSocket(host, port, id)
})
},
Promise.resolve(null)
)
}
const SOCKET_TIMEOUT = 500
function tryConnectSocket(
host: string,
port: string,
id: string
): Promise<SocketTask | null> {
return new Promise((resolve, reject) => {
const socket = uni.connectSocket({
url: `ws://${host}:${port}/${id}`,
multiple: true, // 支付宝小程序 是否开启多实例
fail() {
resolve(null)
},
})
const timer = setTimeout(() => {
// @ts-expect-error
socket.close({
code: 1006,
reason: 'connect timeout',
} as CloseSocketOptions)
resolve(null)
}, SOCKET_TIMEOUT)
socket.onOpen((e) => {
clearTimeout(timer)
resolve(socket)
})
socket.onClose((e) => {
clearTimeout(timer)
resolve(null)
})
socket.onError((e) => {
clearTimeout(timer)
resolve(null)
})
})
}

View File

@@ -0,0 +1 @@
export type SendFn = ((msg: string) => void) | null

View File

@@ -0,0 +1,66 @@
import { rewriteConsole, setSendConsole } from '../console'
import { sendErrorMessages, setSendError } from '../error'
declare global {
interface Window {
__UNI_CONSOLE_WEBVIEW__: boolean
__UNI_PAGE_ROUTE__: string
}
}
function initUniWebviewRuntimeService() {
if (window.__UNI_CONSOLE_WEBVIEW__) return
window.__UNI_CONSOLE_WEBVIEW__ = true
const channel = `[web-view]${
window.__UNI_PAGE_ROUTE__ ? `[${window.__UNI_PAGE_ROUTE__}]` : ''
}`
rewriteConsole()
setSendConsole(
(data: string) => {
sendToService(data)
},
{
channel,
}
)
setSendError(
(data: string) => {
sendToService(data)
},
{
channel,
}
)
// 监听同步错误
window.addEventListener('error', (event) => {
sendErrorMessages([event.error])
})
// 监听Promise未处理的异步错误
window.addEventListener('unhandledrejection', (event) => {
sendErrorMessages([event])
})
}
function sendToService(data: string) {
// 发送数据到 service 层
const serviceMessage = {
type: 'WEB_INVOKE_APPSERVICE',
args: {
data: {
name: 'console',
arg: data,
},
},
}
// @ts-expect-error
if (window.__uniapp_x_postMessageToService) {
// @ts-expect-error
return window.__uniapp_x_postMessageToService(serviceMessage)
} else {
// @ts-expect-error
return window.__uniapp_x_.postMessageToService(
JSON.stringify(serviceMessage)
)
}
}
initUniWebviewRuntimeService()