Skip to content

feat: list custom APIs from registerApi in Object.keys(wx)#234

Merged
dos1in merged 3 commits into
didi:mainfrom
EchoTechFE:feat/enumerable-registered-apis
May 25, 2026
Merged

feat: list custom APIs from registerApi in Object.keys(wx)#234
dos1in merged 3 commits into
didi:mainfrom
EchoTechFE:feat/enumerable-registered-apis

Conversation

@lbb00

@lbb00 lbb00 commented May 22, 2026

Copy link
Copy Markdown
Contributor

问题:

通过 MiniApp.registerApi 注册的自定义 API,在小程序中可以通过 wx.<name>()调用,但不会出现在 Object.keys(wx) 里。

Taro 小程序运行时会由 @tarojs/sharedprocessApis 根据 Object.keys(wx) 一次性生成 Taro.xxx 包装。由于自定义API 无法被枚举到,Taro 也不会为它们生成对应的 Taro.<name>。这导致无法使用 Taro.xxx 调用注册的自定 API。

修复方案:

给 service 层 wx 补上 ownKeys / getOwnPropertyDescriptor / has 拦截器,让已注册的自定义 API 名字能被Object.keys(wx) 枚举到

The service-layer `wx` Proxy had only get/set traps, so APIs registered
via MiniApp.registerApi were callable but invisible to Object.keys(wx).
Frameworks that build their API surface by enumeration — e.g. Taro's
processApis — never generated wrappers for them.

Add has/ownKeys/getOwnPropertyDescriptor traps (guarded for
non-extensible targets) backed by a name set fed from each platform's
container/native layer: web via the service Worker config, native via a
globalThis.__diminaRegisteredApis global. The names are snapshotted from
whatever is registered before the worker starts — register custom APIs
before presentView.
@lbb00 lbb00 force-pushed the feat/enumerable-registered-apis branch from dea3147 to 6d32d3f Compare May 22, 2026 11:51
@dos1in

dos1in commented May 24, 2026

Copy link
Copy Markdown
Member

建议改成:service 初始化时把这些 API 注册成 api 对象上的真实 own enumerable property。

建议实现类似:

export function registerEnumerableApiNames(names = []) {
	for (const name of names) {
		if (
			typeof name !== 'string'
			|| Object.prototype.hasOwnProperty.call(api, name)
			|| name in Object.prototype
		) {
			continue
		}

		Object.defineProperty(api, name, {
			enumerable: true,
			configurable: true,
			writable: true,
			value: (...args) => invokeAPI(name, ...args),
		})
	}
}

另外一点: native 注入 __diminaRegisteredApis 时现在是手拼 JS 数组字符串,比如 "${name}"。建议改成统一 JSON 序列化,和 Web worker 保持同一策略。

@lbb00

lbb00 commented May 25, 2026

Copy link
Copy Markdown
Contributor Author

@dos1in 随手把 namespace 的 JSON 序列化也改了

@lbb00 lbb00 changed the title feat: make registerApi-registered APIs enumerable on the wx Proxy feat: list custom APIs from registerApi in Object.keys(wx) May 25, 2026
@dos1in dos1in merged commit bd2f019 into didi:main May 25, 2026
3 checks passed
@lbb00 lbb00 deleted the feat/enumerable-registered-apis branch June 15, 2026 08:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants