A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(services): a game can record a run and share the clip
esengine11b057faa8f7
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bc265f7e8..ee218b733 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,10 @@ published separately; it ships inside the editor.## [Unreleased]+### Added++- **A game can record a run and share the clip.** `Recorder` in `estella-plugin-minigame-services` starts, pauses, resumes and stops the host's screen recorder, and `highlight(before, after)` keeps the moment that just happened; `share()` then publishes the highlights, or the whole recording without any. WeChat keeps the video and shares it through its own call (at most 60 s of highlights); Douyin hands over a temp file and cuts the highlights on its side. `available` and `canShare` are separate answers, so a record button and a share button can each hide where the host lacks one. Every call resolves when the host says the thing happened, and a host that never answers is reported after 5 s rather than awaited forever. In the editor's play mode the recording is real — the canvas as WebM — and `canShare` is false there.+### Fixed- The agent drawer's History button shows it is open with a grey press again, not the accent colour 0.71 gave it.diff --git a/docs/astro/src/content/docs/publishing/ads-sharing.mdx b/docs/astro/src/content/docs/publishing/ads-sharing.mdxindex 4c276fadb..5584bf146 100644--- a/docs/astro/src/content/docs/publishing/ads-sharing.mdx+++ b/docs/astro/src/content/docs/publishing/ads-sharing.mdx@@ -111,6 +111,54 @@ whether the player actually shared, so there is nothing to await. Off-platform(web, native, the editor) `Share.available` is `false` and `share()` returns`false` — hide the button rather than promise a sheet that cannot open.+## Recording a clip++A short clip of a run is how a mini-game spreads on Douyin, and WeChat can+share one too. `Recorder` ships in the same package as `Share`:++```typescript+import { Recorder } from 'estella-plugin-minigame-services';++// When the run starts (recorder is Res(Recorder)):+if (recorder.available) await recorder.start();++// When something worth keeping just happened — a kill, a near miss:+recorder.highlight(3, 2); // keep 3s before now and 2s after++// When the run ends:+await recorder.stop();++// In the "share my run" button's tap handler — both hosts refuse a share+// the player did not tap for:+if (recorder.canShare) await recorder.share({ title: 'Look at this run' });+```++With highlights, the shared clip is the highlights, in order; without, it is+the whole recording. Every call resolves when the host says the thing+happened, and rejects with the host's own reason (and `code`, where it gave+one). A recording the host ends with an error is heard through+`recorder.onFailure(...)`, and `state` is back to `'idle'`.++| | WeChat | Douyin | Editor / web |+|---|---|---|---|+| Length (`maxSeconds`) | 5 – 7200 s | 4 – 300 s | any |+| What `stop()` gives | the duration; WeChat keeps the video | a temp file (`path`) | a WebM preview (`blob`) |+| Shared clip | at most 60 s of highlights, at least 2 s | the highlights, merged | cannot share |++`maxSeconds` defaults to 300 and is kept inside the host's range. Only the+game canvas is recorded — an ad or a host dialog on top of it is not.++<Aside type="caution">+Douyin's developer tools do not record: "开发者工具不支持录屏调试,请在真机上调试录屏相关功能".+WeChat shares a recording from WeChat 8.0.28 on Android and 8.0.30 on iOS;+where the host has no share call, `canShare` is `false`.+</Aside>++In the editor's play mode the recording is real: `stop()` hands back the+canvas as WebM, so a record button can be built and tried at your desk.+`canShare` is `false` there, so the share button hides itself exactly as it+would on a host that cannot share.+## Friends leaderboardA mini-game leaderboard is not a list you fetch. The player's friends can bediff --git a/docs/astro/src/content/docs/zh-cn/publishing/ads-sharing.mdx b/docs/astro/src/content/docs/zh-cn/publishing/ads-sharing.mdxindex cea4764a9..d39c6ff74 100644--- a/docs/astro/src/content/docs/zh-cn/publishing/ads-sharing.mdx+++ b/docs/astro/src/content/docs/zh-cn/publishing/ads-sharing.mdx@@ -101,6 +101,48 @@ share.share({ title: '来加入我的游戏' }); // 或一次性卡片所以没有可等待的结果。平台之外(web、原生、编辑器)`Share.available` 为 false 且`share()` 返回 false——把按钮藏起来,而不是承诺一张打不开的分享面板。+## 录屏++录一段对局来分享,是小游戏在抖音上传播的主要方式,微信也能分享对局回放。`Recorder`+和 `Share` 在同一个包里:++```typescript+import { Recorder } from 'estella-plugin-minigame-services';++// 一局开始时(recorder 来自 Res(Recorder)):+if (recorder.available) await recorder.start();++// 刚发生了值得留下的事——击杀、险些翻车:+recorder.highlight(3, 2); // 保留此刻之前 3 秒、之后 2 秒++// 一局结束时:+await recorder.stop();++// 在「分享这一局」按钮的点击回调里——两家宿主都拒绝不是玩家点出来的分享:+if (recorder.canShare) await recorder.share({ title: '看我这一局' });+```++标过精彩片段时,分享出去的是这些片段(按顺序);没标过就是整段录像。每个调用都在宿主+确认之后才 resolve,失败时带着宿主自己的原因(有错误码时也带上 `code`)。录制中途被宿主+报错终止的,通过 `recorder.onFailure(...)` 通知,`state` 回到 `'idle'`。++| | 微信 | 抖音 | 编辑器 / web |+|---|---|---|---|+| 时长(`maxSeconds`) | 5 – 7200 秒 | 4 – 300 秒 | 不限 |+| `stop()` 给出 | 时长;视频由微信保管 | 临时文件(`path`) | WebM 预览(`blob`) |+| 分享的片段 | 精彩片段最多 60 秒、至少 2 秒 | 精彩片段合并 | 不能分享 |++`maxSeconds` 默认 300,并被收进宿主接受的范围。只录游戏画布——盖在上面的广告和宿主+弹窗不会被录进去。++<Aside type="caution">+抖音开发者工具不录屏:「开发者工具不支持录屏调试,请在真机上调试录屏相关功能」。+微信从安卓 8.0.28、iOS 8.0.30 起支持分享对局回放;宿主没有分享接口时 `canShare` 为 `false`。+</Aside>++编辑器 Play 里的录屏是真的:`stop()` 把画布录成 WebM 交回来,录屏按钮在自己桌面上就能+做和试。那里 `canShare` 为 `false`,分享按钮会像在不能分享的宿主上一样自己藏起来。+## 好友排行榜小游戏的排行榜不是一个「拉回来的列表」。玩家的好友数据**只能在开放数据域里读**diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex 06aa7fa31..9ea18e4bf 100644--- a/docs/astro/src/data/apiStability.generated.json+++ b/docs/astro/src/data/apiStability.generated.json@@ -3,10 +3,10 @@"counts": {"public": 115,"beta": 103,- "experimental": 2091,+ "experimental": 2095,"deprecated": 3},- "total": 2309,+ "total": 2313,"subsystems": [{"id": "ecs",diff --git a/plugins/minigame-services/README.md b/plugins/minigame-services/README.mdindex 1da6ac693..99259d2dc 100644--- a/plugins/minigame-services/README.md+++ b/plugins/minigame-services/README.md@@ -1,8 +1,8 @@# estella-plugin-minigame-services-The mini-game host's **share sheet**, **in-game purchase** and **friends-leaderboard**, as Estella services. All three used to ship inside the engine;-they live here because most games open none of them, and because a service is+The mini-game host's **share sheet**, **in-game purchase**, **friends+leaderboard** and **screen recorder**, as Estella services. The first three+used to ship inside the engine; they live here because most games open none of them, and because a service isexactly the shape a plugin should be.```bash@@ -11,7 +11,7 @@ npm install estella-plugin-minigame-services```ts title="src/main.ts"import { addPlugin } from 'esengine';-import { miniGameServicesPlugin, Share, Payment, Leaderboard } from 'estella-plugin-minigame-services';+import { miniGameServicesPlugin, Share, Payment, Leaderboard, Recorder } from 'estella-plugin-minigame-services';addPlugin(miniGameServicesPlugin);```@@ -84,6 +84,25 @@ runs **that same file** against an offscreen canvas and invented friends. So theboard you look at while building the panel is the one that ships, and nothinghere needs a rehearsal mode of its own.+## Recorder++```ts+const recorder = app.getResource(Recorder);++if (recorder.available) await recorder.start(); // at the start of a run+recorder.highlight(3, 2); // keep 3s before, 2s after+await recorder.stop(); // at the end++// From the player's tap — both hosts refuse a share nobody asked for.+if (recorder.canShare) await recorder.share({ title: 'Look at this run' });+```++With highlights the shared clip is the highlights; without, the whole+recording. WeChat keeps the video and shares it itself (at most 60s of+highlights), Douyin hands over a temp file and cuts the highlights on its side,+and a browser — the editor's play mode — records a WebM preview it cannot+share, so `canShare` is `false` there.+## Built on the public APIOnly `esengine`'s public surface: `defineResource`, the `Plugin` interface,@@ -91,7 +110,7 @@ Only `esengine`'s public surface: `defineResource`, the `Plugin` interface,`platformCanShare`, `platformOnShareRequest`, `platformCanPay`,`platformRequestPayment`, `platformCanOpenData`, `platformOpenDataPostMessage`,`platformOpenDataCanvas`, `platformSetCloudKeyValues`, `platformCreateCanvas`,-`platformDevicePixelRatio`). Declare `esengine` a **peer** dependency if you+`platformDevicePixelRatio`, `platformScreenRecorder`). Declare `esengine` a **peer** dependency if youwrite one of these — a copy vendored inside the package would be a second enginewhose resources nothing can read.diff --git a/plugins/minigame-services/src/index.ts b/plugins/minigame-services/src/index.tsindex e32e17062..e6a7e74fd 100644--- a/plugins/minigame-services/src/index.ts+++ b/plugins/minigame-services/src/index.ts@@ -1,9 +1,9 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/**- * @file index.ts — the share sheet, the purchase and the friends board.+ * @file index.ts — the share sheet, the purchase, the friends board and the recorder.*- * Share and payment are façades over host capabilities and cost nothing per+ * Share, payment and the recorder are façades over host capabilities and cost nothing per* frame. The leaderboard costs one boolean: the canvas it shows is drawn by* another runtime on its own schedule, so while a board is up it has to be* re-taken, and nothing can tell us when it changed.@@ -12,6 +12,7 @@ import { Schedule, defineSystem, type App, type Plugin } from 'esengine';import { Share, ShareAPI } from './share';import { Payment, PaymentAPI } from './payment';import { Leaderboard, LeaderboardAPI } from './leaderboard';+import { Recorder, RecorderAPI } from './recorder';export { Share, ShareAPI, type ShareCard } from './share';export { Payment, PaymentAPI, type PaymentRequest, type PaymentFailure } from './payment';@@ -19,6 +20,10 @@ export {Leaderboard, LeaderboardAPI,type LeaderboardOptions, type LeaderboardScope, type LeaderboardStyle,} from './leaderboard';+export {+ Recorder, RecorderAPI,+ type Recording, type RecordingShareCard, type RecorderState, type RecordOptions,+} from './recorder';export class MiniGameServicesPlugin implements Plugin {name = 'MiniGameServices';@@ -26,6 +31,7 @@ export class MiniGameServicesPlugin implements Plugin {build(app: App): void {app.insertResource(Share, new ShareAPI());app.insertResource(Payment, new PaymentAPI());+ app.insertResource(Recorder, new RecorderAPI());// The App is resolved per call, not captured: the wasm module is attached// after the plugins have built.const board = new LeaderboardAPI(() => app);diff --git a/plugins/minigame-services/src/recorder.ts b/plugins/minigame-services/src/recorder.tsnew file mode 100644index 000000000..7004b95c8--- /dev/null+++ b/plugins/minigame-services/src/recorder.ts@@ -0,0 +1,159 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file recorder.ts+ * @brief Screen recording and clip sharing as an engine service.+ *+ * One call starts a recording, one stops it, `highlight()` keeps the moment+ * that just happened, and `share()` publishes the clip. WeChat keeps the video+ * and shares it itself, Douyin hands over a file, a browser (the editor's play+ * mode, a web dev build) records a preview it cannot publish — which is why+ * `available` and `canShare` are separate questions.+ */+import {+ defineResource, platformScreenRecorder,+ type PlatformRecording, type PlatformRecordingShareOptions, type PlatformScreenRecorder,+} from 'esengine';++export type Recording = PlatformRecording;+export type RecordingShareCard = PlatformRecordingShareOptions;+export type RecorderState = 'idle' | 'starting' | 'recording' | 'paused' | 'stopping';++export interface RecordOptions {+ /** Nothing past this is recorded; the recording still waits for `stop()`.+ * Default 300 — the most Douyin allows. Kept inside the host's `limits`. */+ maxSeconds?: number;+}++const DEFAULT_MAX_SECONDS = 300;++export class RecorderAPI {+ private state_: RecorderState = 'idle';+ private last_: Recording | null = null;+ private readonly failureListeners_ = new Set<(error: Error) => void>();++ /** Whether this host can record at all — what a game reads to hide its+ * record button rather than show one that fails. */+ get available(): boolean {+ return this.host_() !== null;+ }++ /** Whether a finished recording can be published from here. False in a+ * browser, which records a preview and has nowhere to send it. */+ get canShare(): boolean {+ return this.host_()?.canShare ?? false;+ }++ get state(): RecorderState {+ return this.state_;+ }++ /** The recording length this host accepts, in seconds; null where there is no recorder. */+ get limits(): PlatformScreenRecorder['limits'] | null {+ return this.host_()?.limits ?? null;+ }++ /** The most recent finished recording — what `share()` sends by default. */+ get last(): Recording | null {+ return this.last_;+ }++ /** Hear a recording that ended on its own (the host failed, the device+ * refused). Returns the unsubscribe. */+ onFailure(listener: (error: Error) => void): () => void {+ this.failureListeners_.add(listener);+ return () => { this.failureListeners_.delete(listener); };+ }++ async start(options: RecordOptions = {}): Promise<void> {+ const host = this.require_();+ if (this.state_ !== 'idle') throw new Error(`cannot start while ${this.state_}`);+ const { minSeconds, maxSeconds } = host.limits;+ const seconds = Math.min(maxSeconds, Math.max(minSeconds, options.maxSeconds ?? DEFAULT_MAX_SECONDS));+ this.state_ = 'starting';+ try {+ await host.start(seconds, (error) => this.failed_(error));+ this.state_ = 'recording';+ } catch (e) {+ this.state_ = 'idle';+ throw e;+ }+ }++ async pause(): Promise<void> {+ if (this.state_ !== 'recording') throw new Error(`cannot pause while ${this.state_}`);+ await this.require_().pause();+ this.state_ = 'paused';+ }++ async resume(): Promise<void> {+ if (this.state_ !== 'paused') throw new Error(`cannot resume while ${this.state_}`);+ await this.require_().resume();+ this.state_ = 'recording';+ }++ /** Finish the recording. It becomes `last`, and `share()` can send it. */+ async stop(): Promise<Recording> {+ if (this.state_ !== 'recording' && this.state_ !== 'paused') {+ throw new Error(`cannot stop while ${this.state_}`);+ }+ this.state_ = 'stopping';+ try {+ const recording = await this.require_().stop();+ this.last_ = recording;+ return recording;+ } finally {+ this.state_ = 'idle';+ }+ }++ /** Drop the recording in progress; `last` is left as it was. */+ async abort(): Promise<void> {+ if (this.state_ !== 'recording' && this.state_ !== 'paused') return;+ this.state_ = 'stopping';+ try {+ await this.require_().abort();+ } finally {+ this.state_ = 'idle';+ }+ }++ /**+ * Keep the moment that just happened: `beforeSeconds` before now and+ * `afterSeconds` after it. With any highlights, `share()` sends only them,+ * in order; without, the whole recording. Ignored when not recording.+ */+ highlight(beforeSeconds = 3, afterSeconds = 3): void {+ if (this.state_ !== 'recording') return;+ this.host_()?.highlight(beforeSeconds, afterSeconds);+ }++ /**+ * Publish a recording (default: `last`). Call it from the player's tap —+ * both hosts refuse a share nobody asked for. Rejects with the host's own+ * reason, `code` included where the host gave one.+ */+ share(card: RecordingShareCard = {}, recording: Recording | null = this.last_): Promise<void> {+ const host = this.host_();+ if (!host?.canShare) return Promise.reject(new Error('this platform cannot share a recording — check Recorder.canShare'));+ if (!recording) return Promise.reject(new Error('nothing has been recorded yet'));+ return host.share(recording, card);+ }++ private host_(): PlatformScreenRecorder | null {+ return platformScreenRecorder();+ }++ private require_(): PlatformScreenRecorder {+ const host = this.host_();+ if (!host) throw new Error('this platform cannot record — check Recorder.available');+ return host;+ }++ private failed_(error: Error): void {+ this.state_ = 'idle';+ for (const listener of this.failureListeners_) listener(error);+ }+}++export const Recorder = defineResource<RecorderAPI>(null!, 'Recorder');diff --git a/plugins/minigame-services/tests/recorder.test.ts b/plugins/minigame-services/tests/recorder.test.tsnew file mode 100644index 000000000..e608ed29f--- /dev/null+++ b/plugins/minigame-services/tests/recorder.test.ts@@ -0,0 +1,131 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file What the Recorder service adds over the host's recorder: honest+ * capability answers for a menu, a state a button can show, lengths+ * kept inside the host's limits, and `last` as the default thing shared.+ */+import { describe, it, expect, vi, beforeEach } from 'vitest';++const host = {+ recorder: null as null | Record<string, unknown>,+};++vi.mock('esengine', () => ({+ defineResource: (value: unknown, name: string) => ({ value, name }),+ platformScreenRecorder: () => host.recorder,+}));++const { RecorderAPI } = await import('../src/recorder');++function fakeRecorder(over: Record<string, unknown> = {}) {+ let onFailure: ((e: Error) => void) | null = null;+ const r = {+ limits: { minSeconds: 4, maxSeconds: 300 },+ canShare: true,+ start: vi.fn(async (_s: number, fail: (e: Error) => void) => { onFailure = fail; }),+ pause: vi.fn(async () => {}),+ resume: vi.fn(async () => {}),+ stop: vi.fn(async () => ({ durationMs: 1234, path: 'ttfile://run.mp4', highlights: [] })),+ abort: vi.fn(async () => {}),+ highlight: vi.fn(),+ share: vi.fn(async () => {}),+ fail: (e: Error) => onFailure?.(e),+ ...over,+ };+ host.recorder = r;+ return r;+}++beforeEach(() => { host.recorder = null; });++describe('the recorder service', () => {+ it('answers whether it can record and whether it can share, separately', () => {+ const recorder = new RecorderAPI();+ expect(recorder.available).toBe(false);+ expect(recorder.canShare).toBe(false);+ fakeRecorder({ canShare: false });+ expect(recorder.available).toBe(true);+ expect(recorder.canShare).toBe(false);+ });++ it('refuses to start where there is no recorder, naming what to check', async () => {+ await expect(new RecorderAPI().start()).rejects.toThrow('Recorder.available');+ });++ it('asks the host for a length inside its limits', async () => {+ const r = fakeRecorder();+ const recorder = new RecorderAPI();+ await recorder.start();+ await recorder.stop();+ await recorder.start({ maxSeconds: 1 });+ expect(r.start.mock.calls.map((c) => c[0])).toEqual([300, 4]);+ });++ it('walks idle → recording → paused → recording → idle', async () => {+ fakeRecorder();+ const recorder = new RecorderAPI();+ const seen: string[] = [recorder.state];+ await recorder.start(); seen.push(recorder.state);+ await recorder.pause(); seen.push(recorder.state);+ await recorder.resume(); seen.push(recorder.state);+ await recorder.stop(); seen.push(recorder.state);+ expect(seen).toEqual(['idle', 'recording', 'paused', 'recording', 'idle']);+ });++ it('goes back to idle when the host refuses to start', async () => {+ fakeRecorder({ start: async () => { throw new Error('no permission to record screen'); } });+ const recorder = new RecorderAPI();+ await expect(recorder.start()).rejects.toThrow('no permission');+ expect(recorder.state).toBe('idle');+ });++ it('refuses a second start rather than asking the host twice', async () => {+ const r = fakeRecorder();+ const recorder = new RecorderAPI();+ await recorder.start();+ await expect(recorder.start()).rejects.toThrow('while recording');+ expect(r.start).toHaveBeenCalledTimes(1);+ });++ it('tells its listeners when a recording dies on its own, and is idle again', async () => {+ const r = fakeRecorder();+ const recorder = new RecorderAPI();+ const heard = vi.fn();+ recorder.onFailure(heard);+ await recorder.start();+ r.fail(new Error('internal failed'));+ expect(heard).toHaveBeenCalledWith(expect.objectContaining({ message: 'internal failed' }));+ expect(recorder.state).toBe('idle');+ });++ it('passes a highlight only while recording', async () => {+ const r = fakeRecorder();+ const recorder = new RecorderAPI();+ recorder.highlight();+ await recorder.start();+ recorder.highlight(5, 2);+ await recorder.pause();+ recorder.highlight();+ expect(r.highlight.mock.calls).toEqual([[5, 2]]);+ });++ it('shares the last recording by default', async () => {+ const r = fakeRecorder();+ const recorder = new RecorderAPI();+ await expect(recorder.share()).rejects.toThrow('nothing has been recorded');+ await recorder.start();+ const recording = await recorder.stop();+ expect(recorder.last).toBe(recording);+ await recorder.share({ title: 'my run' });+ expect(r.share).toHaveBeenCalledWith(recording, { title: 'my run' });+ });++ it('refuses to share where the host cannot, naming what to check', async () => {+ fakeRecorder({ canShare: false });+ const recorder = new RecorderAPI();+ await recorder.start();+ await recorder.stop();+ await expect(recorder.share()).rejects.toThrow('Recorder.canShare');+ });+});diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex a800d8aa0..d1b001f11 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 91 beta · 1477 experimental · 3 deprecated+Symbols: 115 public · 91 beta · 1481 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -5661,6 +5661,7 @@ readTextFile: (path: string) => Promise<string>registerFont: ((family: string, bytes: ArrayBuffer) => Promise<void>) | undefinedremoveStorageItem: (key: string) => voidrequestPayment: ((request: PlatformPaymentRequest) => Promise<void>) | undefined+screenRecorder: (() => PlatformScreenRecorder | null) | undefinedsetCloudKeyValues: ((entries: Readonly<Record<string, string>>) => boolean) | undefinedsetStorageItem: (key: string, value: string) => voidsetWindowSize: ((width: number, height: number) => void) | undefined@@ -5727,6 +5728,21 @@ sandbox: boolean | undefinedzoneId: string | undefined```+## PlatformRecording — interface @experimental+```+blob: Blob | undefined+durationMs: number+highlights: readonly (readonly [number, number])[]+path: string | undefined+```++## PlatformRecordingShareOptions — interface @experimental+```+desc: string | undefined+query: string | undefined+title: string | undefined+```+## PlatformRequestOptions — interface @experimental```body: string | ArrayBuffer | undefined@@ -5747,6 +5763,19 @@ statusText: stringtext: () => Promise<string>```+## PlatformScreenRecorder — interface @experimental+```+abort: () => Promise<void>+canShare: boolean+highlight: (beforeSeconds: number, afterSeconds: number) => void+limits: { readonly minSeconds: number; readonly maxSeconds: number; }+pause: () => Promise<void>+resume: () => Promise<void>+share: (recording: PlatformRecording, options: PlatformRecordingShareOptions) => Promise<void>+start: (maxSeconds: number, onFailure: (error: Error) => void) => Promise<void>+stop: () => Promise<PlatformRecording>+```+## PlatformShareOptions — interface @experimental```imageUrl: string | undefined@@ -11495,6 +11524,11 @@ ParticlePlugin(request: PlatformPaymentRequest): Promise<void>```+## platformScreenRecorder — function @experimental+```+(): PlatformScreenRecorder | null+```+## platformSetCloudKeyValues — function @experimental```(entries: Readonly<Record<string, string>>): booleandiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 433b4f121..254fe6e89 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 96 beta · 1496 experimental · 3 deprecated+Symbols: 115 public · 96 beta · 1500 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -5844,6 +5844,7 @@ readTextFile: (path: string) => Promise<string>registerFont: ((family: string, bytes: ArrayBuffer) => Promise<void>) | undefinedremoveStorageItem: (key: string) => voidrequestPayment: ((request: PlatformPaymentRequest) => Promise<void>) | undefined+screenRecorder: (() => PlatformScreenRecorder | null) | undefinedsetCloudKeyValues: ((entries: Readonly<Record<string, string>>) => boolean) | undefinedsetStorageItem: (key: string, value: string) => voidsetWindowSize: ((width: number, height: number) => void) | undefined@@ -5910,6 +5911,21 @@ sandbox: boolean | undefinedzoneId: string | undefined```+## PlatformRecording — interface @experimental+```+blob: Blob | undefined+durationMs: number+highlights: readonly (readonly [number, number])[]+path: string | undefined+```++## PlatformRecordingShareOptions — interface @experimental+```+desc: string | undefined+query: string | undefined+title: string | undefined+```+## PlatformRequestOptions — interface @experimental```body: string | ArrayBuffer | undefined@@ -5930,6 +5946,19 @@ statusText: stringtext: () => Promise<string>```+## PlatformScreenRecorder — interface @experimental+```+abort: () => Promise<void>+canShare: boolean+highlight: (beforeSeconds: number, afterSeconds: number) => void+limits: { readonly minSeconds: number; readonly maxSeconds: number; }+pause: () => Promise<void>+resume: () => Promise<void>+share: (recording: PlatformRecording, options: PlatformRecordingShareOptions) => Promise<void>+start: (maxSeconds: number, onFailure: (error: Error) => void) => Promise<void>+stop: () => Promise<PlatformRecording>+```+## PlatformShareOptions — interface @experimental```imageUrl: string | undefined@@ -11738,6 +11767,11 @@ ParticlePlugin(request: PlatformPaymentRequest): Promise<void>```+## platformScreenRecorder — function @experimental+```+(): PlatformScreenRecorder | null+```+## platformSetCloudKeyValues — function @experimental```(entries: Readonly<Record<string, string>>): booleandiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex c0d7c7c8f..718060546 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.node<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 93 beta · 1476 experimental · 3 deprecated+Symbols: 115 public · 93 beta · 1480 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -5656,6 +5656,7 @@ readTextFile: (path: string) => Promise<string>registerFont: ((family: string, bytes: ArrayBuffer) => Promise<void>) | undefinedremoveStorageItem: (key: string) => voidrequestPayment: ((request: PlatformPaymentRequest) => Promise<void>) | undefined+screenRecorder: (() => PlatformScreenRecorder | null) | undefinedsetCloudKeyValues: ((entries: Readonly<Record<string, string>>) => boolean) | undefinedsetStorageItem: (key: string, value: string) => voidsetWindowSize: ((width: number, height: number) => void) | undefined@@ -5722,6 +5723,21 @@ sandbox: boolean | undefinedzoneId: string | undefined```+## PlatformRecording — interface @experimental+```+blob: Blob | undefined+durationMs: number+highlights: readonly (readonly [number, number])[]+path: string | undefined+```++## PlatformRecordingShareOptions — interface @experimental+```+desc: string | undefined+query: string | undefined+title: string | undefined+```+## PlatformRequestOptions — interface @experimental```body: string | ArrayBuffer | undefined@@ -5742,6 +5758,19 @@ statusText: stringtext: () => Promise<string>```+## PlatformScreenRecorder — interface @experimental+```+abort: () => Promise<void>+canShare: boolean+highlight: (beforeSeconds: number, afterSeconds: number) => void+limits: { readonly minSeconds: number; readonly maxSeconds: number; }+pause: () => Promise<void>+resume: () => Promise<void>+share: (recording: PlatformRecording, options: PlatformRecordingShareOptions) => Promise<void>+start: (maxSeconds: number, onFailure: (error: Error) => void) => Promise<void>+stop: () => Promise<PlatformRecording>+```+## PlatformShareOptions — interface @experimental```imageUrl: string | undefined@@ -11500,6 +11529,11 @@ ParticlePlugin(request: PlatformPaymentRequest): Promise<void>```+## platformScreenRecorder — function @experimental+```+(): PlatformScreenRecorder | null+```+## platformSetCloudKeyValues — function @experimental```(entries: Readonly<Record<string, string>>): booleandiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 41564a9f7..cd7cddcc9 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1,7 +1,7 @@# API surface — esengine/minigame<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 91 beta · 1498 experimental · 3 deprecated+Symbols: 115 public · 91 beta · 1502 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -5005,6 +5005,8 @@ createInnerAudioContext: () => MiniGameInnerAudioContextcreateInterstitialAd: ((opts: { adUnitId: string; }) => MiniGameInterstitialAd) | undefinedcreateRewardedVideoAd: ((opts: { adUnitId: string; }) => MiniGameRewardedVideoAd) | undefinedgetFileSystemManager: () => MiniGameFileSystemManager+getGameRecorder: (() => MiniGameWxRecorder) | undefined+getGameRecorderManager: (() => MiniGameTtRecorder) | undefinedgetOpenDataContext: (() => MiniGameOpenDataContext) | undefinedgetStorageInfoSync: () => MiniGameStorageInfogetStorageSync: (key: string) => unknown@@ -5034,12 +5036,13 @@ onTouchMove: (cb: (res: MiniGameTouchEvent) => void) => voidonTouchStart: (cb: (res: MiniGameTouchEvent) => void) => voidonUnhandledRejection: ((cb: (res: { reason?: unknown; }) => void) => void) | undefinedonWindowResize: ((cb: (res: { windowWidth: number; windowHeight: number; }) => void) => void) | undefined+operateGameRecorderVideo: ((opts: { title?: string; desc?: string; query?: string; timeRange?: number[][]; success?: () => void; fail?: (err: { errMsg?: string; errCode?: number; }) => void; }) => void) | undefinedremoveStorageSync: (key: string) => voidrequest: (opts: MiniGameRequestOptions) => voidrequestMidasPayment: ((opts: { mode: string; offerId: string; buyQuantity: number; zoneId?: string; currencyType?: string; platform?: string; env?: number; success?: () => void; fail?: (err: { errMsg?: string; errCode?: number; }) => void; }) => void) | undefinedsetStorageSync: (key: string, value: string) => voidsetUserCloudStorage: ((opts: { KVDataList: MiniGameKVData[]; success?: () => void; fail?: (err: unknown) => void; complete?: () => void; }) => void) | undefined-shareAppMessage: ((opts: MiniGameShareOptions) => void) | undefined+shareAppMessage: ((opts: MiniGameShareOptions & { channel?: "video"; desc?: string; extra?: { videoPath: string; }; success?: () => void; fail?: (err: { errMsg?: string; }) => void; }) => void) | undefinedshowLoading: ((opts: { title: string; mask?: boolean; }) => void) | undefined```@@ -5113,6 +5116,7 @@ readFile: (path: string) => Promise<ArrayBuffer>readTextFile: (path: string) => Promise<string>removeStorageItem: (key: string) => voidrequestPayment: (request: PlatformPaymentRequest) => Promise<void>+screenRecorder: () => PlatformScreenRecorder | nullsetCloudKeyValues: (entries: Readonly<Record<string, string>>) => booleansetStorageItem: (key: string, value: string) => voidshare: (options: PlatformShareOptions) => void@@ -5909,6 +5913,7 @@ readTextFile: (path: string) => Promise<string>registerFont: ((family: string, bytes: ArrayBuffer) => Promise<void>) | undefinedremoveStorageItem: (key: string) => voidrequestPayment: ((request: PlatformPaymentRequest) => Promise<void>) | undefined+screenRecorder: (() => PlatformScreenRecorder | null) | undefinedsetCloudKeyValues: ((entries: Readonly<Record<string, string>>) => boolean) | undefinedsetStorageItem: (key: string, value: string) => voidsetWindowSize: ((width: number, height: number) => void) | undefined@@ -5975,6 +5980,21 @@ sandbox: boolean | undefinedzoneId: string | undefined```+## PlatformRecording — interface @experimental+```+blob: Blob | undefined+durationMs: number+highlights: readonly (readonly [number, number])[]+path: string | undefined+```++## PlatformRecordingShareOptions — interface @experimental+```+desc: string | undefined+query: string | undefined+title: string | undefined+```+## PlatformRequestOptions — interface @experimental```body: string | ArrayBuffer | undefined@@ -5995,6 +6015,19 @@ statusText: stringtext: () => Promise<string>```+## PlatformScreenRecorder — interface @experimental+```+abort: () => Promise<void>+canShare: boolean+highlight: (beforeSeconds: number, afterSeconds: number) => void+limits: { readonly minSeconds: number; readonly maxSeconds: number; }+pause: () => Promise<void>+resume: () => Promise<void>+share: (recording: PlatformRecording, options: PlatformRecordingShareOptions) => Promise<void>+start: (maxSeconds: number, onFailure: (error: Error) => void) => Promise<void>+stop: () => Promise<PlatformRecording>+```+## PlatformShareOptions — interface @experimental```imageUrl: string | undefined@@ -11764,6 +11797,11 @@ ParticlePlugin(request: PlatformPaymentRequest): Promise<void>```+## platformScreenRecorder — function @experimental+```+(): PlatformScreenRecorder | null+```+## platformSetCloudKeyValues — function @experimental```(entries: Readonly<Record<string, string>>): booleandiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 46b692f0d..3021f3c8c 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1,7 +1,7 @@# API surface — esengine/wechat<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 91 beta · 1489 experimental · 3 deprecated+Symbols: 115 public · 91 beta · 1493 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -5663,6 +5663,7 @@ readTextFile: (path: string) => Promise<string>registerFont: ((family: string, bytes: ArrayBuffer) => Promise<void>) | undefinedremoveStorageItem: (key: string) => voidrequestPayment: ((request: PlatformPaymentRequest) => Promise<void>) | undefined+screenRecorder: (() => PlatformScreenRecorder | null) | undefinedsetCloudKeyValues: ((entries: Readonly<Record<string, string>>) => boolean) | undefinedsetStorageItem: (key: string, value: string) => voidsetWindowSize: ((width: number, height: number) => void) | undefined@@ -5729,6 +5730,21 @@ sandbox: boolean | undefinedzoneId: string | undefined```+## PlatformRecording — interface @experimental+```+blob: Blob | undefined+durationMs: number+highlights: readonly (readonly [number, number])[]+path: string | undefined+```++## PlatformRecordingShareOptions — interface @experimental+```+desc: string | undefined+query: string | undefined+title: string | undefined+```+## PlatformRequestOptions — interface @experimental```body: string | ArrayBuffer | undefined@@ -5749,6 +5765,19 @@ statusText: stringtext: () => Promise<string>```+## PlatformScreenRecorder — interface @experimental+```+abort: () => Promise<void>+canShare: boolean+highlight: (beforeSeconds: number, afterSeconds: number) => void+limits: { readonly minSeconds: number; readonly maxSeconds: number; }+pause: () => Promise<void>+resume: () => Promise<void>+share: (recording: PlatformRecording, options: PlatformRecordingShareOptions) => Promise<void>+start: (maxSeconds: number, onFailure: (error: Error) => void) => Promise<void>+stop: () => Promise<PlatformRecording>+```+## PlatformShareOptions — interface @experimental```imageUrl: string | undefined@@ -11529,6 +11558,11 @@ ParticlePlugin(request: PlatformPaymentRequest): Promise<void>```+## platformScreenRecorder — function @experimental+```+(): PlatformScreenRecorder | null+```+## platformSetCloudKeyValues — function @experimental```(entries: Readonly<Record<string, string>>): booleandiff --git a/sdk/src/core-sys.ts b/sdk/src/core-sys.tsindex 74b6a3587..7243404f8 100644--- a/sdk/src/core-sys.ts+++ b/sdk/src/core-sys.ts@@ -114,6 +114,7 @@ export {platformShare,platformCanShare,platformOnShareRequest,+ platformScreenRecorder,platformCanPay,platformRequestPayment,// The open data domain: the runtime holding the player's friends, the canvas@@ -126,7 +127,10 @@ export {platformCreateCanvas,platformDevicePixelRatio,} from './platform';-export type { PlatformShareOptions, PlatformPaymentRequest } from './platform/types';+export type {+ PlatformShareOptions, PlatformPaymentRequest,+ PlatformScreenRecorder, PlatformRecording, PlatformRecordingShareOptions,+} from './platform/types';export {getPlatform,diff --git a/sdk/src/platform/base.ts b/sdk/src/platform/base.tsindex ec805b927..c18929d5f 100644--- a/sdk/src/platform/base.ts+++ b/sdk/src/platform/base.ts@@ -335,6 +335,13 @@ export function platformOnShareRequest(provide: () => import('./types').Platformreturn true;}+/** The host's screen recorder, or null where there is none — which a game reads+ * to hide its record button rather than to show one that fails. */+export function platformScreenRecorder(): import('./types').PlatformScreenRecorder | null {+ if (!isPlatformInitialized()) return null;+ return getPlatform().screenRecorder?.() ?? null;+}+/** Whether this platform can sign a player in at all — what a menu reads to* hide its sign-in button honestly (web, native and the editor cannot). */export function platformCanSignIn(): boolean {diff --git a/sdk/src/platform/index.ts b/sdk/src/platform/index.tsindex 1044bd029..f7a016c4f 100644--- a/sdk/src/platform/index.ts+++ b/sdk/src/platform/index.ts@@ -63,6 +63,7 @@ export {platformCanShare,platformShare,platformOnShareRequest,+ platformScreenRecorder,platformCanSignIn,platformCanPay,platformRequestPayment,diff --git a/sdk/src/platform/minigame/adapter.ts b/sdk/src/platform/minigame/adapter.tsindex 3edfa5cba..ed118737f 100644--- a/sdk/src/platform/minigame/adapter.ts+++ b/sdk/src/platform/minigame/adapter.ts@@ -28,6 +28,7 @@ import type {PlatformInterstitialAd,PlatformShareOptions,PlatformPaymentRequest,+ PlatformScreenRecorder,} from '../types';import type { PlatformAudioBackend } from '../../audio/PlatformAudioBackend';import type { PlatformVideoBackend, VideoBackendContext } from '../../video/PlatformVideoBackend';@@ -43,6 +44,7 @@ import { mgFetch } from './fetch';import { MiniGameAudioBackend } from '../../audio/MiniGameAudioBackend';import { MiniGameSocket } from '../../net/MiniGameSocket';import { WasmVideoBackend } from '../../video/WasmVideoBackend';+import { createMiniGameRecorder } from './recorder';export class MiniGamePlatformAdapter implements PlatformAdapter {readonly name: PlatformAdapter['name'];@@ -55,6 +57,7 @@ export class MiniGamePlatformAdapter implements PlatformAdapter {private inputCleanup_: (() => void) | null = null;private openDataCtx_: MiniGameOpenDataContext | null = null;private openDataResolved_ = false;+ private recorder_: PlatformScreenRecorder | null | undefined;constructor(profile: MiniGameProfile) {this.profile_ = profile;@@ -197,6 +200,12 @@ export class MiniGamePlatformAdapter implements PlatformAdapter {this.g_.onShareAppMessage?.call(this.g_, provide);}+ /** The host hands out one recorder, so this does too. */+ screenRecorder(): PlatformScreenRecorder | null {+ if (this.recorder_ === undefined) this.recorder_ = createMiniGameRecorder(this.g_);+ return this.recorder_;+ }+/** This one class serves every vendor, so it defines `login` regardless —* the honest answer is whether the host behind it has one. */canSignIn(): boolean {diff --git a/sdk/src/platform/minigame/api.ts b/sdk/src/platform/minigame/api.tsindex 58ed3de88..5cefadd90 100644--- a/sdk/src/platform/minigame/api.ts+++ b/sdk/src/platform/minigame/api.ts@@ -155,6 +155,44 @@ export interface MiniGameInterstitialAd {offClose(cb: () => void): void;}+/** WeChat's GameRecorder. Control calls return promises; outcomes arrive as+ * events — `stop` carries `{ duration }` in ms and no file, because WeChat+ * keeps the video. */+export interface MiniGameWxRecorder {+ start(opts: { duration?: number }): void;+ pause(): Promise<unknown>;+ resume(): Promise<unknown>;+ stop(): Promise<unknown>;+ abort(): Promise<unknown>;+ isFrameSupported?(): boolean;+ on(event: 'start' | 'stop' | 'pause' | 'resume' | 'abort' | 'error', cb: (res?: unknown) => void): void;+ off(event: 'start' | 'stop' | 'pause' | 'resume' | 'abort' | 'error', cb: (res?: unknown) => void): void;+}++/** Douyin's GameRecorderManager. Calls are synchronous; each outcome has its own+ * listener, and `onStop` hands over the temp file. */+export interface MiniGameTtRecorder {+ start(opts: { duration?: number }): void;+ pause(): void;+ resume(): void;+ stop(): void;+ recordClip(opts: {+ timeRange: [number, number];+ success?: (res: { index: number }) => void;+ fail?: (err: { errMsg?: string }) => void;+ }): void;+ clipVideo(opts: {+ path: string;+ success?: (res: { videoPath: string }) => void;+ fail?: (err: { errMsg?: string }) => void;+ }): void;+ onStart(cb: () => void): void;+ onPause(cb: () => void): void;+ onResume(cb: () => void): void;+ onStop(cb: (res: { videoPath: string }) => void): void;+ onError(cb: (res: { errMsg?: string }) => void): void;+}+/** The share card a host shows for an active or passive share. */export interface MiniGameShareOptions {title?: string;@@ -265,11 +303,31 @@ export interface MiniGameGlobal {* (or a game may not have configured): the adapter probes at use time. */createRewardedVideoAd?(opts: { adUnitId: string }): MiniGameRewardedVideoAd;createInterstitialAd?(opts: { adUnitId: string }): MiniGameInterstitialAd;- shareAppMessage?(opts: MiniGameShareOptions): void;+ shareAppMessage?(opts: MiniGameShareOptions & {+ channel?: 'video';+ desc?: string;+ extra?: { videoPath: string };+ success?: () => void;+ fail?: (err: { errMsg?: string }) => void;+ }): void;/** Passive share: what the card says when the player shares from the host's* own menu. The host calls `cb` at share time, not at registration. */onShareAppMessage?(cb: () => MiniGameShareOptions): void;+ /** WeChat's recorder (base 2.8.0), a singleton. Kuaishou copies the shape. */+ getGameRecorder?(): MiniGameWxRecorder;+ /** Shares WeChat's last recording; must run inside a tap (base 2.26.1). */+ operateGameRecorderVideo?(opts: {+ title?: string;+ desc?: string;+ query?: string;+ timeRange?: number[][];+ success?: () => void;+ fail?: (err: { errMsg?: string; errCode?: number }) => void;+ }): void;+ /** Douyin's recorder (base 1.6.1), a singleton. */+ getGameRecorderManager?(): MiniGameTtRecorder;+/** Begin a sign-in. The result is a one-time code the game's own server* exchanges — see the note on `PlatformAdapter.login`. */login?(opts: {diff --git a/sdk/src/platform/minigame/recorder.ts b/sdk/src/platform/minigame/recorder.tsnew file mode 100644index 000000000..8dc7bfb4d--- /dev/null+++ b/sdk/src/platform/minigame/recorder.ts@@ -0,0 +1,319 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file recorder.ts+ * @brief The mini-game hosts' screen recorders behind one PlatformScreenRecorder.+ *+ * WeChat and Douyin disagree on nearly everything but the verbs. WeChat's+ * control calls return promises, its outcomes are `on(event)` events, and it+ * never hands the game a file: a clip is shared by `operateGameRecorderVideo`+ * with ms ranges. Douyin's calls are synchronous with one listener per outcome,+ * `onStop` hands over a temp file, and a clip is cut live by `recordClip`, then+ * merged by `clipVideo` and published through `shareAppMessage`. Both must share+ * from inside a tap.+ *+ * Sources: developers.weixin.qq.com/minigame/dev/api/game-recorder/ and+ * developer.open-douyin.com/docs/resource/zh-CN/mini-game/develop/api/javascript-api/media/screen-recording/+ */+import type {+ PlatformRecording, PlatformRecordingShareOptions, PlatformScreenRecorder,+} from '../types';+import type { MiniGameGlobal, MiniGameTtRecorder, MiniGameWxRecorder } from './api';+import { RecordingClock } from '../recordingClock';++/** Hosts answer in well under a second; one that has not answered in this long+ * will not, and a caller awaiting it would hang a record button forever. */+const HOST_ANSWER_MS = 5000;++/** WeChat's documented ceiling on a shared clip, and its floor. */+const WX_SHARE_MAX_MS = 60_000;+const WX_SHARE_MIN_MS = 2_000;++/**+ * Turns "call, then wait for the host's event" into one promise. A host error+ * while a call waits is that call's failure; one while nothing waits is the+ * recording's, which the caller hears through `onStray`.+ */+class HostGate {+ private waiting_: {+ event: string;+ resolve: (payload: unknown) => void;+ reject: (error: Error) => void;+ timer: ReturnType<typeof setTimeout>;+ } | null = null;++ constructor(private readonly onStray_: (error: Error) => void) {}++ wait(event: string, act: () => unknown): Promise<unknown> {+ if (this.waiting_) {+ return Promise.reject(new Error(`the recorder is still waiting for "${this.waiting_.event}"`));+ }+ return new Promise((resolve, reject) => {+ const timer = setTimeout(() => {+ this.waiting_ = null;+ reject(new Error(`the host did not report "${event}" within ${HOST_ANSWER_MS / 1000}s`));+ }, HOST_ANSWER_MS);+ this.waiting_ = { event, resolve, reject, timer };+ try {+ const r = act();+ if (r && typeof (r as Promise<unknown>).then === 'function') {+ (r as Promise<unknown>).then(undefined, (e: unknown) => this.fail(toError(e)));+ }+ } catch (e) {+ this.fail(toError(e));+ }+ });+ }++ fire(event: string, payload?: unknown): void {+ const w = this.waiting_;+ if (!w || w.event !== event) return;+ clearTimeout(w.timer);+ this.waiting_ = null;+ w.resolve(payload);+ }++ fail(error: Error): void {+ const w = this.waiting_;+ if (!w) {+ this.onStray_(error);+ return;+ }+ clearTimeout(w.timer);+ this.waiting_ = null;+ w.reject(error);+ }+}++function toError(e: unknown): Error {+ if (e instanceof Error) return e;+ const o = e as { errMsg?: string; message?: string; errCode?: number; code?: number;+ error?: { message?: string; code?: number } } | undefined;+ // WeChat's own docs disagree on the error shape: the table says+ // `{ code, message }`, the sample reads `res.error.code`.+ const inner = o?.error ?? o;+ const err = new Error(inner?.message ?? o?.errMsg ?? String(e)) as Error & { code?: number };+ const code = inner?.code ?? o?.errCode;+ if (code !== undefined) err.code = code;+ return err;+}++function clampSeconds(seconds: number, limits: PlatformScreenRecorder['limits']): number {+ return Math.min(limits.maxSeconds, Math.max(limits.minSeconds, Math.round(seconds)));+}++/** The session state both recorders share: the clock, and who to tell when a+ * started recording dies on its own. */+class Session {+ readonly clock: RecordingClock;+ active = false;+ private onFailure_: ((error: Error) => void) | null = null;++ constructor(now?: () => number) {+ this.clock = new RecordingClock(now);+ }++ begin(onFailure: (error: Error) => void): void {+ this.onFailure_ = onFailure;+ }++ started(): void {+ this.active = true;+ this.clock.start();+ }++ end(): void {+ this.active = false;+ this.onFailure_ = null;+ }++ stray(error: Error): void {+ const report = this.onFailure_;+ if (!this.active || !report) return;+ this.end();+ report(error);+ }+}++export function createWxRecorder(g: MiniGameGlobal, now?: () => number): PlatformScreenRecorder | null {+ const rec: MiniGameWxRecorder | undefined = g.getGameRecorder?.call(g);+ if (!rec) return null;+ if (rec.isFrameSupported && !rec.isFrameSupported.call(rec)) return null;+ const session = new Session(now);+ const gate = new HostGate((e) => session.stray(e));+ for (const event of ['start', 'stop', 'pause', 'resume', 'abort'] as const) {+ rec.on(event, (res) => gate.fire(event, res));+ }+ rec.on('error', (res) => gate.fail(toError(res)));+ const limits = { minSeconds: 5, maxSeconds: 7200 };++ return {+ limits,+ get canShare() { return typeof g.operateGameRecorderVideo === 'function'; },+ async start(maxSeconds, onFailure) {+ session.begin(onFailure);+ await gate.wait('start', () => rec.start({ duration: clampSeconds(maxSeconds, limits) }));+ session.started();+ },+ async pause() {+ await gate.wait('pause', () => rec.pause());+ session.clock.pause();+ },+ async resume() {+ await gate.wait('resume', () => rec.resume());+ session.clock.resume();+ },+ async stop() {+ const res = await gate.wait('stop', () => rec.stop()) as { duration?: number } | undefined;+ const durationMs = res?.duration ?? session.clock.elapsedMs();+ session.end();+ return { durationMs, highlights: session.clock.highlights(durationMs) };+ },+ async abort() {+ await gate.wait('abort', () => rec.abort());+ session.end();+ },+ highlight(before, after) {+ if (session.active) session.clock.mark(before, after);+ },+ share(recording, options) {+ const operate = g.operateGameRecorderVideo;+ if (!operate) return Promise.reject(new Error('this host cannot share a recording'));+ const timeRange = wxTimeRange(recording.highlights);+ if (timeRange && spanOf(timeRange) < WX_SHARE_MIN_MS) {+ return Promise.reject(new Error(+ `the highlights add up to ${spanOf(timeRange)}ms; WeChat shares no clip shorter than ${WX_SHARE_MIN_MS / 1000}s`));+ }+ return new Promise<void>((resolve, reject) => {+ operate.call(g, {+ ...shareText(options),+ ...(timeRange ? { timeRange } : {}),+ success: () => resolve(),+ fail: (err) => reject(toError(err)),+ });+ });+ },+ };+}++function spanOf(ranges: readonly (readonly number[])[]): number {+ return ranges.reduce((sum, [a, b]) => sum + (b - a), 0);+}++/** The newest highlights that fit WeChat's 60s ceiling — the moment a player+ * just had is the one they want to share. Undefined shares the whole video. */+export function wxTimeRange(highlights: readonly (readonly [number, number])[]): number[][] | undefined {+ if (highlights.length === 0) return undefined;+ const kept: number[][] = [];+ let budget = WX_SHARE_MAX_MS;+ for (let i = highlights.length - 1; i >= 0 && budget > 0; i--) {+ const [a, b] = highlights[i];+ const start = Math.max(a, b - budget);+ kept.unshift([start, b]);+ budget -= b - start;+ }+ return kept;+}++function shareText(options: PlatformRecordingShareOptions): PlatformRecordingShareOptions {+ const out: PlatformRecordingShareOptions = {};+ if (options.title !== undefined) out.title = options.title;+ if (options.desc !== undefined) out.desc = options.desc;+ if (options.query !== undefined) out.query = options.query;+ return out;+}++export function createTtRecorder(g: MiniGameGlobal, now?: () => number): PlatformScreenRecorder | null {+ const rec: MiniGameTtRecorder | undefined = g.getGameRecorderManager?.call(g);+ if (!rec) return null;+ const session = new Session(now);+ const gate = new HostGate((e) => session.stray(e));+ rec.onStart(() => gate.fire('start'));+ rec.onPause(() => gate.fire('pause'));+ rec.onResume(() => gate.fire('resume'));+ rec.onStop((res) => gate.fire('stop', res));+ rec.onError((res) => gate.fail(toError(res)));+ // `start` must be longer than 3s; the host counts whole seconds.+ const limits = { minSeconds: 4, maxSeconds: 300 };+ // `clipVideo` cuts a recording once; a second share reuses the first cut.+ const cut = new WeakMap<PlatformRecording, string>();+ // The host's clips decide what is cut, not the local ranges: a highlight+ // whose seconds-after run past stop still exists on the host's side.+ const withClips = new WeakSet<PlatformRecording>();+ let clipsThisRecording = 0;++ const clipped = (recording: PlatformRecording, path: string): Promise<string> => {+ if (!withClips.has(recording)) return Promise.resolve(path);+ const done = cut.get(recording);+ if (done) return Promise.resolve(done);+ return new Promise((resolve, reject) => {+ // No clipRange: the host merges every recordClip of this recording in order.+ rec.clipVideo({+ path,+ success: (res) => { cut.set(recording, res.videoPath); resolve(res.videoPath); },+ fail: (err) => reject(toError(err)),+ });+ });+ };++ return {+ limits,+ get canShare() { return typeof g.shareAppMessage === 'function'; },+ async start(maxSeconds, onFailure) {+ session.begin(onFailure);+ await gate.wait('start', () => rec.start({ duration: clampSeconds(maxSeconds, limits) }));+ session.started();+ clipsThisRecording = 0;+ },+ async pause() {+ await gate.wait('pause', () => rec.pause());+ session.clock.pause();+ },+ async resume() {+ await gate.wait('resume', () => rec.resume());+ session.clock.resume();+ },+ async stop() {+ const res = await gate.wait('stop', () => rec.stop()) as { videoPath?: string } | undefined;+ const durationMs = session.clock.elapsedMs();+ session.end();+ const recording = { durationMs, path: res?.videoPath, highlights: session.clock.highlights(durationMs) };+ if (clipsThisRecording > 0) withClips.add(recording);+ return recording;+ },+ // Douyin has no abort: stopping and dropping the file is the same outcome.+ async abort() {+ await gate.wait('stop', () => rec.stop());+ session.end();+ },+ highlight(before, after) {+ if (!session.active) return;+ session.clock.mark(before, after);+ clipsThisRecording++;+ rec.recordClip({ timeRange: [before, after] });+ },+ async share(recording, options) {+ const shareApp = g.shareAppMessage;+ if (!shareApp) throw new Error('this host cannot share a recording');+ if (!recording.path) throw new Error('this recording has no video file to share');+ const videoPath = await clipped(recording, recording.path);+ await new Promise<void>((resolve, reject) => {+ shareApp.call(g, {+ channel: 'video',+ ...shareText(options),+ extra: { videoPath },+ success: () => resolve(),+ fail: (err) => reject(toError(err)),+ });+ });+ },+ };+}++/** Whichever recorder this host has. Chosen by what the global offers, not by+ * vendor id: a vendor copying WeChat's shape gets WeChat's recorder. */+export function createMiniGameRecorder(g: MiniGameGlobal): PlatformScreenRecorder | null {+ if (g.getGameRecorderManager) return createTtRecorder(g);+ if (g.getGameRecorder) return createWxRecorder(g);+ return null;+}diff --git a/sdk/src/platform/recordingClock.ts b/sdk/src/platform/recordingClock.tsnew file mode 100644index 000000000..d512ac942--- /dev/null+++ b/sdk/src/platform/recordingClock.ts@@ -0,0 +1,57 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file recordingClock.ts+ * @brief The time axis every screen recorder cuts highlights on.+ */+/** Recording time that does not count pauses — the axis both hosts cut clips on. */+export class RecordingClock {+ private startedAt_ = 0;+ private pausedAt_: number | null = null;+ private pausedTotal_ = 0;+ private readonly highlights_: [number, number][] = [];++ constructor(private readonly now_: () => number = Date.now) {}++ start(): void {+ this.startedAt_ = this.now_();+ this.pausedAt_ = null;+ this.pausedTotal_ = 0;+ this.highlights_.length = 0;+ }++ pause(): void {+ if (this.pausedAt_ === null) this.pausedAt_ = this.now_();+ }++ resume(): void {+ if (this.pausedAt_ === null) return;+ this.pausedTotal_ += this.now_() - this.pausedAt_;+ this.pausedAt_ = null;+ }++ elapsedMs(): number {+ const end = this.pausedAt_ ?? this.now_();+ return Math.max(0, end - this.startedAt_ - this.pausedTotal_);+ }++ mark(beforeSeconds: number, afterSeconds: number): void {+ const at = this.elapsedMs();+ this.highlights_.push([Math.max(0, at - beforeSeconds * 1000), at + afterSeconds * 1000]);+ }++ /** Ranges clipped to the recording and merged where they overlap. */+ highlights(durationMs: number): [number, number][] {+ const out: [number, number][] = [];+ const sorted = this.highlights_+ .map(([a, b]): [number, number] => [a, Math.min(b, durationMs)])+ .filter(([a, b]) => b > a)+ .sort((x, y) => x[0] - y[0]);+ for (const r of sorted) {+ const last = out[out.length - 1];+ if (last && r[0] <= last[1]) last[1] = Math.max(last[1], r[1]);+ else out.push([r[0], r[1]]);+ }+ return out.map(([a, b]) => [Math.round(a), Math.round(b)]);+ }+}diff --git a/sdk/src/platform/types.ts b/sdk/src/platform/types.tsindex 7788b8b62..cbba82687 100644--- a/sdk/src/platform/types.ts+++ b/sdk/src/platform/types.ts@@ -594,6 +594,10 @@ export interface PlatformAdapter {* host asks at share time, so the provider can answer with live state. */onShareRequest?(provide: () => PlatformShareOptions): void;+ /** The host's screen recorder, or null where this particular host has none.+ * Absent on platforms that cannot record at all (native, playable). */+ screenRecorder?(): PlatformScreenRecorder | null;+/** Send a message into the open data context — the second JS runtime that* is the only place friend data can be read. ONE WAY by nature: no host* offers a channel back, so this returns nothing and nothing awaits it. */@@ -698,6 +702,50 @@ export interface PlatformShareOptions {query?: string;}+/** A finished recording. What it carries depends on who keeps the video: WeChat+ * keeps it to itself and shares it on the game's behalf, Douyin hands over a+ * temp file, a browser hands over the encoded bytes. */+export interface PlatformRecording {+ readonly durationMs: number;+ /** The host's temp file for the video (Douyin). */+ readonly path?: string;+ /** The encoded video (web) — a debug preview, not something a host can share. */+ readonly blob?: Blob;+ /** Highlight ranges in ms from the start of the recording, merged and in order. */+ readonly highlights: readonly (readonly [number, number])[];+}++/** What a shared clip says when it is opened. `query` rides the launch options+ * of whoever opens it, as a share card's does. */+export interface PlatformRecordingShareOptions {+ title?: string;+ desc?: string;+ query?: string;+}++/**+ * The host's game-screen recorder, one per host (both vendors hand out a+ * singleton). Every call resolves when the host says the thing happened, not+ * when it was asked: otherwise a refused start shows "recording" over nothing.+ */+export interface PlatformScreenRecorder {+ /** The recording length the host accepts, in seconds. */+ readonly limits: { readonly minSeconds: number; readonly maxSeconds: number };+ /** Whether a finished recording can be shared from here at all. */+ readonly canShare: boolean;+ /** `onFailure` hears a failure after the start was accepted — the recording+ * is gone when it is called. */+ start(maxSeconds: number, onFailure: (error: Error) => void): Promise<void>;+ pause(): Promise<void>;+ resume(): Promise<void>;+ stop(): Promise<PlatformRecording>;+ abort(): Promise<void>;+ /** Keep `beforeSeconds` before now and `afterSeconds` after it for sharing. */+ highlight(beforeSeconds: number, afterSeconds: number): void;+ /** Both hosts refuse unless this runs inside the player's tap. */+ share(recording: PlatformRecording, options: PlatformRecordingShareOptions): Promise<void>;+}+// =============================================================================// Platform Detection// =============================================================================diff --git a/sdk/src/platform/web.ts b/sdk/src/platform/web.tsindex 52a9fd87a..2075e650e 100644--- a/sdk/src/platform/web.ts+++ b/sdk/src/platform/web.ts@@ -18,6 +18,7 @@ import type {PlatformSocket,PlatformSocketOptions,PlatformTextEditor,+ PlatformScreenRecorder,} from './types';import { createWebTextEditor } from './webTextEditor';import { WebAudioBackend } from '../audio/WebAudioBackend';@@ -26,6 +27,7 @@ import { WebVideoBackend } from '../video/WebVideoBackend';import type { PlatformVideoBackend } from '../video/PlatformVideoBackend';import { GameSocket } from '../net/GameSocket';import { createPrimaryPointer } from './primaryPointer';+import { createWebRecorder } from './webRecorder';const WHEEL_LINE_HEIGHT = 16;@@ -36,6 +38,13 @@ const WHEEL_LINE_HEIGHT = 16;class WebPlatformAdapter implements PlatformAdapter {readonly name = 'web' as const;private inputCleanup_: (() => void) | null = null;+ private recorder_: PlatformScreenRecorder | null | undefined;++ /** Resolved on first ask: the canvas exists by the time a game records. */+ screenRecorder(): PlatformScreenRecorder | null {+ if (this.recorder_ === undefined) this.recorder_ = createWebRecorder();+ return this.recorder_;+ }hasTouch(): boolean {return typeof navigator !== 'undefined'diff --git a/sdk/src/platform/webRecorder.ts b/sdk/src/platform/webRecorder.tsnew file mode 100644index 000000000..ad0b1dcca--- /dev/null+++ b/sdk/src/platform/webRecorder.ts@@ -0,0 +1,106 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file webRecorder.ts+ * @brief A browser's screen recorder: MediaRecorder over the engine canvas.+ *+ * It exists so a record button can be built and tried where the game is made —+ * the editor's play mode and a web dev build — with the same lifecycle a+ * mini-game host runs. The result is a debug preview (`recording.blob`); a+ * browser has nowhere to publish a clip, so `canShare` is false.+ */+import type { PlatformRecording, PlatformScreenRecorder } from './types';+import { RecordingClock } from './recordingClock';++const FPS = 30;++function engineCanvas(): HTMLCanvasElement | null {+ if (typeof document === 'undefined') return null;+ return (document.getElementById('canvas') as HTMLCanvasElement | null)+ ?? document.querySelector('canvas');+}++export function createWebRecorder(now?: () => number): PlatformScreenRecorder | null {+ if (typeof MediaRecorder === 'undefined') return null;+ const canvas = engineCanvas();+ if (!canvas || typeof canvas.captureStream !== 'function') return null;++ const clock = new RecordingClock(now);+ let recorder: MediaRecorder | null = null;+ let chunks: Blob[] = [];+ let limit: ReturnType<typeof setTimeout> | null = null;+ let maxMs = 0;++ // Like both hosts: at the limit nothing more is recorded, and the recording+ // still waits for stop().+ const armLimit = (): void => {+ limit = setTimeout(() => {+ limit = null;+ if (recorder?.state === 'recording') recorder.pause();+ clock.pause();+ }, Math.max(0, maxMs - clock.elapsedMs()));+ };+ const disarmLimit = (): void => {+ if (limit !== null) clearTimeout(limit);+ limit = null;+ };+ const settle = (event: 'start' | 'pause' | 'resume' | 'stop', act: (r: MediaRecorder) => void): Promise<void> =>+ new Promise((resolve, reject) => {+ const r = recorder;+ if (!r) { reject(new Error('not recording')); return; }+ r.addEventListener(event, () => resolve(), { once: true });+ try { act(r); } catch (e) { reject(e instanceof Error ? e : new Error(String(e))); }+ });++ return {+ limits: { minSeconds: 1, maxSeconds: 7200 },+ canShare: false,+ async start(maxSeconds, onFailure) {+ if (recorder) throw new Error('already recording');+ const r = new MediaRecorder(canvas.captureStream(FPS));+ recorder = r;+ chunks = [];+ r.addEventListener('dataavailable', (e) => { if (e.data.size > 0) chunks.push(e.data); });+ r.addEventListener('error', (e) => {+ disarmLimit();+ recorder = null;+ const err = (e as unknown as { error?: unknown }).error;+ onFailure(err instanceof Error ? err : new Error('the browser stopped recording'));+ });+ await settle('start', (rec) => rec.start());+ clock.start();+ maxMs = maxSeconds * 1000;+ armLimit();+ },+ async pause() {+ disarmLimit();+ if (recorder?.state === 'recording') await settle('pause', (r) => r.pause());+ clock.pause();+ },+ async resume() {+ if (recorder?.state === 'paused') await settle('resume', (r) => r.resume());+ clock.resume();+ armLimit();+ },+ async stop(): Promise<PlatformRecording> {+ disarmLimit();+ const mime = recorder?.mimeType || 'video/webm';+ await settle('stop', (r) => r.stop());+ recorder = null;+ const durationMs = clock.elapsedMs();+ return { durationMs, blob: new Blob(chunks, { type: mime }), highlights: clock.highlights(durationMs) };+ },+ async abort() {+ disarmLimit();+ if (recorder) await settle('stop', (r) => r.stop());+ recorder = null;+ chunks = [];+ },+ highlight(before, after) {+ if (recorder) clock.mark(before, after);+ },+ share() {+ return Promise.reject(new Error('a browser has nowhere to publish a recording'));+ },+ };+}diff --git a/sdk/tests/minigame-recorder.test.ts b/sdk/tests/minigame-recorder.test.tsnew file mode 100644index 000000000..61f91ad7a--- /dev/null+++ b/sdk/tests/minigame-recorder.test.ts@@ -0,0 +1,219 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The mini-game screen recorders over fake WeChat and Douyin hosts.+ *+ * Each fake answers the way its vendor's docs say: WeChat through `on(event)`+ * with a promise per call and no file, Douyin through one listener per outcome+ * with a temp file on stop. The claims are what the engine adds on top — a call+ * resolves when the host says it happened, highlights become each host's own+ * clip request, and a share is refused here when the host would refuse it.+ */+import { describe, it, expect, vi, afterEach } from 'vitest';+import { createMiniGameRecorder, createTtRecorder, createWxRecorder, wxTimeRange } from '../src/platform/minigame/recorder';+import type { MiniGameGlobal } from '../src/platform/minigame/api';++type Listener = (res?: unknown) => void;++function fakeWx(options: { frame?: boolean; share?: boolean; answer?: boolean } = {}) {+ const listeners = new Map<string, Listener[]>();+ const emit = (event: string, res?: unknown): void => { for (const l of listeners.get(event) ?? []) l(res); };+ const answer = options.answer ?? true;+ const calls: { start: unknown[]; share: unknown[] } = { start: [], share: [] };+ let startedAt = 0;+ const clock = { t: 0 };+ const rec = {+ start(o: unknown) { calls.start.push(o); startedAt = clock.t; if (answer) queueMicrotask(() => emit('start')); },+ pause() { queueMicrotask(() => emit('pause')); return Promise.resolve(); },+ resume() { queueMicrotask(() => emit('resume')); return Promise.resolve(); },+ stop() { queueMicrotask(() => emit('stop', { duration: clock.t - startedAt })); return Promise.resolve(); },+ abort() { queueMicrotask(() => emit('abort')); return Promise.resolve(); },+ isFrameSupported: () => options.frame ?? true,+ on(event: string, cb: Listener) { listeners.set(event, [...(listeners.get(event) ?? []), cb]); },+ off() {},+ };+ const g = {+ getGameRecorder: () => rec,+ ...(options.share ?? true ? {+ operateGameRecorderVideo(o: { success?: () => void }) { calls.share.push(o); o.success?.(); },+ } : {}),+ } as unknown as MiniGameGlobal;+ return { g, emit, calls, clock };+}++function fakeTt() {+ const on: Record<string, Listener> = {};+ const clock = { t: 0 };+ const calls = { start: [] as unknown[], clip: [] as unknown[], cut: [] as unknown[], share: [] as unknown[] };+ const rec = {+ start(o: unknown) { calls.start.push(o); queueMicrotask(() => on.start?.()); },+ pause() { queueMicrotask(() => on.pause?.()); },+ resume() { queueMicrotask(() => on.resume?.()); },+ stop() { queueMicrotask(() => on.stop?.({ videoPath: 'ttfile://tmp/run.mp4' })); },+ recordClip(o: unknown) { calls.clip.push(o); },+ clipVideo(o: { path: string; success?: (r: { videoPath: string }) => void }) {+ calls.cut.push(o);+ o.success?.({ videoPath: `ttfile://tmp/cut-${calls.cut.length}.mp4` });+ },+ onStart: (cb: Listener) => { on.start = cb; },+ onPause: (cb: Listener) => { on.pause = cb; },+ onResume: (cb: Listener) => { on.resume = cb; },+ onStop: (cb: Listener) => { on.stop = cb; },+ onError: (cb: Listener) => { on.error = cb; },+ };+ const g = {+ getGameRecorderManager: () => rec,+ shareAppMessage(o: { success?: () => void }) { calls.share.push(o); o.success?.(); },+ } as unknown as MiniGameGlobal;+ return { g, on, calls, clock };+}++afterEach(() => { vi.useRealTimers(); });++describe('WeChat', () => {+ it('is no recorder on a device that cannot record frames', () => {+ expect(createWxRecorder(fakeWx({ frame: false }).g)).toBeNull();+ });++ it('starts when the host says it started, asking for a length it accepts', async () => {+ const host = fakeWx();+ const r = createWxRecorder(host.g)!;+ await r.start(2, () => {});+ expect(host.calls.start).toEqual([{ duration: 5 }]);+ });++ it('carries the host error to the start that caused it, in either documented shape', async () => {+ for (const shape of [{ code: 22022, message: 'frame not supported' },+ { error: { code: 22022, message: 'frame not supported' } }]) {+ const host = fakeWx({ answer: false });+ const r = createWxRecorder(host.g)!;+ const started = r.start(60, () => {});+ host.emit('error', shape);+ await expect(started).rejects.toMatchObject({ message: 'frame not supported', code: 22022 });+ }+ });++ it('gives up on a host that never answers, instead of hanging the button', async () => {+ vi.useFakeTimers();+ const r = createWxRecorder(fakeWx({ answer: false }).g)!;+ const started = r.start(60, () => {});+ const seen = expect(started).rejects.toThrow('did not report "start"');+ await vi.advanceTimersByTimeAsync(5000);+ await seen;+ });++ it('hands a stray host error to whoever started the recording', async () => {+ const host = fakeWx();+ const r = createWxRecorder(host.g)!;+ const onFailure = vi.fn();+ await r.start(60, onFailure);+ host.emit('error', { code: 22012, message: 'internal failed' });+ expect(onFailure).toHaveBeenCalledWith(expect.objectContaining({ code: 22012 }));+ });++ it('stops with the host duration and highlights on the time axis that skips pauses', async () => {+ const host = fakeWx();+ const r = createWxRecorder(host.g, () => host.clock.t)!;+ await r.start(60, () => {});+ host.clock.t = 10_000;+ await r.pause();+ host.clock.t = 25_000;+ await r.resume();+ host.clock.t = 30_000;+ r.highlight(3, 1);+ const recording = await r.stop();+ expect(recording.durationMs).toBe(30_000);+ expect(recording.path).toBeUndefined();+ expect(recording.highlights).toEqual([[12_000, 16_000]]);+ });++ it('shares the highlights as the ms ranges WeChat cuts on', async () => {+ const host = fakeWx();+ const r = createWxRecorder(host.g)!;+ await r.share({ durationMs: 20_000, highlights: [[1000, 4000], [8000, 12_000]] }, { title: 'run' });+ expect(host.calls.share[0]).toMatchObject({ title: 'run', timeRange: [[1000, 4000], [8000, 12_000]] });+ });++ it('shares the whole video when nothing was highlighted', async () => {+ const host = fakeWx();+ await createWxRecorder(host.g)!.share({ durationMs: 20_000, highlights: [] }, {});+ expect(host.calls.share[0]).not.toHaveProperty('timeRange');+ });++ it('refuses a clip shorter than WeChat accepts, before asking the host', async () => {+ const host = fakeWx();+ const r = createWxRecorder(host.g)!;+ await expect(r.share({ durationMs: 9000, highlights: [[0, 1500]] }, {})).rejects.toThrow('shorter than 2s');+ expect(host.calls.share).toEqual([]);+ });++ it('says it cannot share where the host has no share call', () => {+ expect(createWxRecorder(fakeWx({ share: false }).g)!.canShare).toBe(false);+ });+});++describe('the newest highlights that fit WeChat\'s 60s', () => {+ it('keeps the latest and trims the oldest one that straddles the ceiling', () => {+ expect(wxTimeRange([[0, 30_000], [40_000, 70_000], [80_000, 90_000]]))+ .toEqual([[10_000, 30_000], [40_000, 70_000], [80_000, 90_000]]);+ });+});++describe('Douyin', () => {+ it('asks for a length longer than 3s and no longer than 300s', async () => {+ const host = fakeTt();+ const r = createTtRecorder(host.g)!;+ await r.start(1, () => {});+ await r.stop();+ await r.start(3600, () => {});+ expect(host.calls.start).toEqual([{ duration: 4 }, { duration: 300 }]);+ });++ it('stops with the temp file the host hands over', async () => {+ const r = createTtRecorder(fakeTt().g)!;+ await r.start(60, () => {});+ expect((await r.stop()).path).toBe('ttfile://tmp/run.mp4');+ });++ it('cuts a highlight live, then shares the merged cut — once, however often it is shared', async () => {+ const host = fakeTt();+ const r = createTtRecorder(host.g)!;+ await r.start(60, () => {});+ r.highlight(5, 2);+ expect(host.calls.clip).toEqual([{ timeRange: [5, 2] }]);+ const recording = await r.stop();+ await r.share(recording, { title: 'run' });+ await r.share(recording, { title: 'run' });+ expect(host.calls.cut).toHaveLength(1);+ expect(host.calls.share[0]).toMatchObject({+ channel: 'video', title: 'run', extra: { videoPath: 'ttfile://tmp/cut-1.mp4' },+ });+ expect(host.calls.share[1]).toMatchObject({ extra: { videoPath: 'ttfile://tmp/cut-1.mp4' } });+ });++ it('shares the whole file when nothing was highlighted', async () => {+ const host = fakeTt();+ const r = createTtRecorder(host.g)!;+ await r.start(60, () => {});+ await r.share(await r.stop(), {});+ expect(host.calls.cut).toEqual([]);+ expect(host.calls.share[0]).toMatchObject({ extra: { videoPath: 'ttfile://tmp/run.mp4' } });+ });++ it('carries the host refusal to the share', async () => {+ const host = fakeTt();+ (host.g as unknown as { shareAppMessage: unknown }).shareAppMessage =+ (o: { fail?: (e: unknown) => void }) => o.fail?.({ errMsg: 'shareAppMessage:fail video file is too short' });+ const r = createTtRecorder(host.g)!;+ await expect(r.share({ durationMs: 2000, path: 'ttfile://x', highlights: [] }, {}))+ .rejects.toThrow('video file is too short');+ });+});++describe('which recorder a host gets', () => {+ it('follows what the global offers, not the vendor name', () => {+ expect(createMiniGameRecorder({} as MiniGameGlobal)).toBeNull();+ expect(createMiniGameRecorder(fakeTt().g)!.limits.maxSeconds).toBe(300);+ expect(createMiniGameRecorder(fakeWx().g)!.limits.maxSeconds).toBe(7200);+ });+});diff --git a/sdk/tests/web-recorder.test.ts b/sdk/tests/web-recorder.test.tsnew file mode 100644index 000000000..4c8631123--- /dev/null+++ b/sdk/tests/web-recorder.test.ts@@ -0,0 +1,75 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The browser recorder: the lifecycle a mini-game host runs, over+ * MediaRecorder on the engine canvas, ending in a preview it cannot share.+ */+import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest';+import { createWebRecorder } from '../src/platform/webRecorder';++class FakeMediaRecorder extends EventTarget {+ static made: FakeMediaRecorder[] = [];+ state: 'inactive' | 'recording' | 'paused' = 'inactive';+ mimeType = 'video/webm';+ constructor(readonly stream: unknown) { super(); FakeMediaRecorder.made.push(this); }+ start() { this.state = 'recording'; queueMicrotask(() => this.dispatchEvent(new Event('start'))); }+ pause() { this.state = 'paused'; queueMicrotask(() => this.dispatchEvent(new Event('pause'))); }+ resume() { this.state = 'recording'; queueMicrotask(() => this.dispatchEvent(new Event('resume'))); }+ stop() {+ this.state = 'inactive';+ queueMicrotask(() => {+ const data = Object.assign(new Event('dataavailable'), { data: new Blob(['frames']) });+ this.dispatchEvent(data);+ this.dispatchEvent(new Event('stop'));+ });+ }+}++beforeEach(() => {+ FakeMediaRecorder.made = [];+ vi.stubGlobal('MediaRecorder', FakeMediaRecorder);+ const canvas = document.createElement('canvas');+ canvas.id = 'canvas';+ (canvas as unknown as { captureStream: () => unknown }).captureStream = () => ({ fake: 'stream' });+ document.body.appendChild(canvas);+});++afterEach(() => {+ vi.unstubAllGlobals();+ vi.useRealTimers();+ document.getElementById('canvas')?.remove();+});++describe('recording in a browser', () => {+ it('is no recorder where the browser has no MediaRecorder', () => {+ vi.stubGlobal('MediaRecorder', undefined);+ expect(createWebRecorder()).toBeNull();+ });++ it('records the engine canvas and hands back a preview', async () => {+ const r = createWebRecorder()!;+ await r.start(60, () => {});+ const recording = await r.stop();+ expect(FakeMediaRecorder.made[0].stream).toEqual({ fake: 'stream' });+ expect(recording.blob?.type).toBe('video/webm');+ expect(await recording.blob?.text()).toBe('frames');+ });++ it('stops taking frames at the limit and still waits for stop, as the hosts do', async () => {+ vi.useFakeTimers();+ let t = 0;+ const r = createWebRecorder(() => t)!;+ await r.start(5, () => {});+ t = 5000;+ await vi.advanceTimersByTimeAsync(5000);+ expect(FakeMediaRecorder.made[0].state).toBe('paused');+ t = 9000;+ expect((await r.stop()).durationMs).toBe(5000);+ });++ it('cannot share, and says so', async () => {+ const r = createWebRecorder()!;+ expect(r.canShare).toBe(false);+ await expect(r.share({ durationMs: 1, highlights: [] }, {})).rejects.toThrow('nowhere to publish');+ });+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 914a7698f..385f8e704 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -966,6 +966,8 @@ export const NOTED = {{ internal: 'a working directory of the repo\'s own tooling' },'feat(ui): a HUD can clear the host\'s own menu, not just the notch':{ note: 'A UI node can keep clear of WeChat\'s capsule menu, which the safe area does not cover.' },+ 'feat(services): a game can record a run and share the clip':+ { note: 'A game can record a run and share the clip.' },'fix(agent): the history toggle presses grey again, not the accent':{ note: "The agent drawer's History button shows it is open with a grey press again, not the accent colour 0.71 gave it." },};