@live-game/sdk 0.4.0 → 2.0.0-dev.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +24 -0
- package/README.md +101 -10
- package/UPGRADING.md +36 -0
- package/dist/app/client.d.ts +112 -0
- package/dist/app/client.js +324 -0
- package/dist/app/contracts.d.ts +180 -0
- package/dist/app/contracts.js +41 -0
- package/dist/app/define-app.d.ts +99 -0
- package/dist/app/define-app.js +19 -0
- package/dist/app/images.d.ts +7 -0
- package/dist/app/images.js +61 -0
- package/dist/app/index.d.ts +7 -0
- package/dist/app/index.js +6 -0
- package/dist/app/live-events.d.ts +161 -0
- package/dist/app/live-events.js +15 -0
- package/dist/app/react.d.ts +101 -0
- package/dist/app/react.js +39 -0
- package/dist/app/types.d.ts +55 -0
- package/dist/app/types.js +1 -0
- package/dist/index.d.ts +1 -5
- package/dist/index.js +1 -5
- package/dist/room-snapshot.d.ts +33 -0
- package/dist/room-snapshot.js +1 -0
- package/package.json +50 -50
- package/dist/createSDK.d.ts +0 -9
- package/dist/createSDK.js +0 -17
- package/dist/mock/command.d.ts +0 -2
- package/dist/mock/command.js +0 -8
- package/dist/mock/config.d.ts +0 -3
- package/dist/mock/config.js +0 -17
- package/dist/mock/events.d.ts +0 -6
- package/dist/mock/events.js +0 -79
- package/dist/mock/index.d.ts +0 -3
- package/dist/mock/index.js +0 -64
- package/dist/mock/platform.d.ts +0 -6
- package/dist/mock/platform.js +0 -49
- package/dist/mock/report.d.ts +0 -2
- package/dist/mock/report.js +0 -12
- package/dist/mock/storage.d.ts +0 -2
- package/dist/mock/storage.js +0 -14
- package/dist/react/index.d.ts +0 -6
- package/dist/react/index.js +0 -40
- package/dist/types.d.ts +0 -141
- package/dist/types.js +0 -11
- package/dist/utils.d.ts +0 -24
- package/dist/utils.js +0 -151
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 2.0.0-dev.8 — beta
|
|
4
|
+
|
|
5
|
+
- Added runtime-only `guide.publish` and typed `sdk.guide.publish({items, footer?})`. Content contains text and gift references; the host owns placement, typography, outline, background and OBS rendering. Publish on rule changes rather than every game tick.
|
|
6
|
+
- The built-in `APP_GUIDE_VIEW` output needs no application HTML and receives no game state/config/capabilities. Stopping a run clears its content; host presentation settings persist per instance.
|
|
7
|
+
- Removed the unpublished UI guide renderer in favor of this host capability. Existing generic manifest output views remain available for other application displays.
|
|
8
|
+
|
|
9
|
+
## 2.0.0-dev.7 — unpublished local candidate
|
|
10
|
+
|
|
11
|
+
- Added permission-gated `sdk.catalog.gifts({platform:'douyin', query?, ids?})` for the host's offline catalog and controlled icon URLs. Persist platform/ID, not the temporary URL; check `sdk.supports()` first.
|
|
12
|
+
- Added manifest `outputViews` for named HTML outputs sharing the same runtime. Optional `stateKey` projects a top-level state field for lightweight overlays; unchanged projections are not pushed repeatedly.
|
|
13
|
+
- No protocol or application version migration. New capabilities require a supporting host; this candidate is not an npm release.
|
|
14
|
+
|
|
15
|
+
## 2.0.0-dev.6 — unpublished local candidate
|
|
16
|
+
|
|
17
|
+
This candidate is bundled with the desktop templates. It is not an npm release. These notes describe the current local candidate, not a promise that an earlier dev.6 archive contains every change. Keep local candidate archives under distinct filenames when replacing them; published versions must use immutable archives and a new version for changes.
|
|
18
|
+
|
|
19
|
+
- Added event-name inference for live payloads/envelopes, State/Config/Command generics, room/audio/timer/source contracts and `timers.on`.
|
|
20
|
+
- Tightened inferred listener and command payload checks. Explicit generic listeners remain supported. `state.get()` can return null before the runtime publishes; handle it in consumers.
|
|
21
|
+
- Fixed output commands sent before bootstrap selecting the control capability. The SDK now waits for its role before choosing the normal permission gateway.
|
|
22
|
+
- Added consumer type checks against the packed SDK and documented actual sandbox/host limits.
|
|
23
|
+
|
|
24
|
+
No application protocol change: manifestVersion 2 and apiVersion 2.0. Your application version, the SDK package version and the desktop version are independent. See [UPGRADING.md](UPGRADING.md) before changing an existing project.
|
package/README.md
CHANGED
|
@@ -1,23 +1,114 @@
|
|
|
1
1
|
# @live-game/sdk
|
|
2
2
|
|
|
3
|
-
SDK for
|
|
3
|
+
Local application SDK 2.0 for browser workers, controls and outputs. SDK1, mock-host and cloud session APIs are removed.
|
|
4
|
+
|
|
5
|
+
Maintaining an existing project? Read [upgrade and rollback guidance](UPGRADING.md) and the [changelog](CHANGELOG.md). Updating the desktop does not silently upgrade project dependencies or change your application version.
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { defineApp } from "@live-game/sdk/app";
|
|
9
|
+
|
|
10
|
+
void defineApp(async (sdk) => {
|
|
11
|
+
let count = 0;
|
|
12
|
+
sdk.live.on("comment", async () => {
|
|
13
|
+
count++;
|
|
14
|
+
await sdk.state.publish({ count });
|
|
15
|
+
});
|
|
16
|
+
await sdk.state.publish({ count });
|
|
17
|
+
});
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Declare every capability in manifest v2. Runtime owns rules and side effects; control sends commands and output renders state. Reconnecting a view does not restart rules or repeat sound. No Node, Electron IPC, filesystem or platform credentials are exposed.
|
|
21
|
+
|
|
22
|
+
```json
|
|
23
|
+
{
|
|
24
|
+
"manifestVersion": 2,
|
|
25
|
+
"apiVersion": "2.0",
|
|
26
|
+
"id": "sample-tool",
|
|
27
|
+
"name": "Sample",
|
|
28
|
+
"version": "1.0.0",
|
|
29
|
+
"kind": "tool",
|
|
30
|
+
"entries": { "runtime": "dist/runtime.js" },
|
|
31
|
+
"permissions": ["events.comment", "state.publish"]
|
|
32
|
+
}
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
`entries.control` and `entries.output` are optional. Output is required for a game. Package scripts, styles, models and required media under `dist`. The current manifest has no `externalResources` field; external static URLs, remote scripts, arbitrary API calls and WebSockets are blocked. Use `sdk.assets.image()` for supported source-observed images.
|
|
36
|
+
|
|
37
|
+
Use `@live-game/sdk/app` for the SDK and `@live-game/sdk/app/react` for React bindings. The root entry reexports the v2 SDK. Methods cover live events/room, config, private JSON storage, state, commands, view messages, images, audio, timers and local text similarity; support depends on the role, declared/granted permissions and host implementation. Use `sdk.supports()` and handle explicit capability errors.
|
|
38
|
+
|
|
39
|
+
Create/open projects in the desktop developer workbench. Edit source in your editor or AI tool; the client installs dependencies, watches/builds source, previews runtime/control/output, exports the verified ZIP and submits versions for review. Projects keep standard build/check/test scripts and do not install a platform CLI.
|
|
40
|
+
|
|
41
|
+
The SDK contains the wire protocol/types, MessagePort client and capability calls. Host manifest/package validation and native capabilities stay in the host; project/build/watch/export/publishing tools stay inside the desktop client. Local simulation needs no platform account; real live debugging and publishing validate ownership.
|
|
42
|
+
|
|
43
|
+
Official applications and third-party applications share these APIs and sandbox. Platform publishing, signing and commerce APIs are not application SDK capabilities.
|
|
44
|
+
|
|
45
|
+
## Gift catalog and named outputs
|
|
46
|
+
|
|
47
|
+
Declare `catalog.gifts` and check `sdk.supports('catalog.gifts')` before reading `sdk.catalog.gifts({platform:'douyin', query?: string, ids?: string[]})`. The host supplies its offline list, optional cached updates and controlled icon URLs. Results contain `version` and `items` with platform, giftId, giftName, optional iconUrl/diamondValue and source. Names can repeat; persist platform/ID and an optional display name, then resolve icons again in each view. A failed reference update does not remove bundled gifts. IDs refer to the host's numeric live-event gift IDs, not encrypted open-platform sec_gift_id values.
|
|
48
|
+
|
|
49
|
+
Optional manifest `outputViews` declares up to eight named HTML outputs, for example `{"guide":{"name":"玩法提示牌","entry":"dist/guide/index.html","stateKey":"interactionGuide"}}`. The host exposes separate local OBS addresses using the same instance and runtime. `stateKey` optionally selects a top-level state field for bootstrap, state reads and change notifications; identical projections are suppressed. It reduces transport work, not the application's granted capabilities. A view without stateKey receives normal full state. Keep lightweight overlays independent of the game's 3D bundle and generate their text from the same rules that settle events.
|
|
50
|
+
|
|
51
|
+
## Types
|
|
4
52
|
|
|
5
53
|
```ts
|
|
6
|
-
import {
|
|
7
|
-
|
|
54
|
+
import { createAppSDK, defineApp, type GiftEvent } from "@live-game/sdk/app";
|
|
55
|
+
type State = { count: number };
|
|
56
|
+
type Config = { title: string };
|
|
57
|
+
type Command = { type: "reset" } | { type: "add"; payload: { amount: number } };
|
|
58
|
+
const sdk = createAppSDK<State, Config, Command>();
|
|
59
|
+
sdk.live.on("comment", (event) => console.log(event.text));
|
|
60
|
+
sdk.commands.on((command) => {
|
|
61
|
+
if (command.type === "add") console.log(command.payload.amount);
|
|
62
|
+
});
|
|
63
|
+
await sdk.commands.send("add", { amount: 1 }); // control only
|
|
8
64
|
```
|
|
9
65
|
|
|
10
|
-
|
|
66
|
+
Use the same generics on `defineApp<State, Config, Command>()` and React `useAppSDK` / `useAppContext`; `useAppState<State>()` and `useAppConfig<Config>()` subscribe to snapshots. JavaScript projects can use JSDoc `AppSDK<State, Config, Command>` with `checkJs`, as in the built-in template. Generics describe your contract; validate stored JSON and command payloads at runtime. Explicit generic event listeners from existing applications remain supported. Commands without a payload field accept only their name; declared required and optional payloads retain that distinction.
|
|
67
|
+
|
|
68
|
+
Live event names infer their payload and envelope. Exported contracts include `LiveEvent`, individual event types, `AppLiveEventMap`, `LiveRoomSnapshot`, `AppTimerEvent`, `SpeechOptions`, `AudioPlayOptions`, `AudioVoice` and `AudioJobEvent`. Optional source fields mean unknown when absent. Gift `count` is the newly observed increment (possibly zero at combo completion); never add `comboTotal` again. Like `total` is an optional platform total, separate from local increments.
|
|
69
|
+
|
|
70
|
+
## Timers, audio and limits
|
|
11
71
|
|
|
12
72
|
```ts
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
73
|
+
sdk.timers.on(({ key, deadline, lateBy }) => {
|
|
74
|
+
/* runtime handler */
|
|
75
|
+
});
|
|
76
|
+
// sdk.on('timer', handler) remains supported.
|
|
77
|
+
await sdk.timers.set("round", 3000);
|
|
78
|
+
await sdk.timers.cancel("round");
|
|
79
|
+
sdk.audio.onJob(({ jobId, status, error }) => {
|
|
80
|
+
/* track completion */
|
|
81
|
+
});
|
|
82
|
+
const { jobId } = await sdk.audio.speak("Hello", { volume: 1, rate: 1, pitch: 1 });
|
|
17
83
|
```
|
|
18
84
|
|
|
19
|
-
|
|
85
|
+
Timers accept 0–86,400,000 ms; reusing a key replaces its deadline. `deadline` is epoch milliseconds and `lateBy` is delivery delay in milliseconds. Stopping the run cancels timers and audio. Audio returns an admitted `jobId`, not playback completion; statuses are queued, playing, completed, cancelled and failed. Subscribe before starting audio. Speech text is 1–500 characters, volume 0–1, rate/pitch 0.5–2, priority normal/high and optional voice ID from `voices()`. Playback accepts package WAV/MP3 assets, volume 0–1, rate 0.5–2 and optional loop.
|
|
86
|
+
|
|
87
|
+
JSON state is limited to 1 MiB, config to 256 KiB, each storage value to 64 KiB and total instance storage to 1 MiB. Runtime input queue: 1,000. Speech queue: 20 per instance / 80 global; media jobs: 4 per instance / 32 global. Handle `QUEUE_FULL`, `INVALID_ARGUMENT`, `CAPABILITY_DISABLED`, `APP_HANDLER_FAILED`, `TIMEOUT`, `DISCONNECTED` and `STALE_RUN`; do not automatically repeat side effects after a timeout. SDK calls that only acknowledge an action return `null`.
|
|
88
|
+
|
|
89
|
+
The built-in interaction-counter project includes runtime/control/output, typed JavaScript, configuration, validated storage, timers, unit tests and a local verification scenario. Install Node.js 22+ with npm on PATH and reopen the client. Run `npm install` once to create a lockfile (requires npm registry access), then use `npm ci`, `npm run check`, `npm test` and `npm run build`. The SDK archive is included under vendor. With the client running, `npm run verify -- --trust` demonstrates its authenticated HTTP open/status/verify flow; add `--stop` to stop that session afterward. The client does not install dependencies during HTTP `/open`. The desktop owns preview/export; the SDK does not provide a second host or publishing client.
|
|
90
|
+
|
|
91
|
+
## Platform gameplay hints
|
|
92
|
+
|
|
93
|
+
Declare `guide.publish` for the runtime. Publish once after loading the rules and again when their effective descriptions change:
|
|
20
94
|
|
|
21
95
|
```ts
|
|
22
|
-
await sdk.
|
|
96
|
+
await sdk.guide.publish({
|
|
97
|
+
items: [
|
|
98
|
+
{
|
|
99
|
+
id: "heart",
|
|
100
|
+
label: "小心心 ×1",
|
|
101
|
+
effect: "头像 1 张",
|
|
102
|
+
gift: { platform: "douyin", giftId: "463" },
|
|
103
|
+
},
|
|
104
|
+
],
|
|
105
|
+
});
|
|
106
|
+
// Hide/clear the content explicitly:
|
|
107
|
+
await sdk.guide.publish({ items: [] });
|
|
23
108
|
```
|
|
109
|
+
|
|
110
|
+
`AppGuideItem` contains a unique id (1–96 characters), label (1–120), effect (1–160), optional detail (1–240), and optional gift reference. Optional footer is 1–240 characters. Limit: 48 items and 24 KiB of content. No HTML, CSS, image URLs, or presentation settings. Icons come from the host catalog. The streamer configures placement, size, outline and background in the client. The host overlays default output outside the sandbox frame and offers a built-in transparent OBS output, without another game runtime. Content is discarded on stop/restart/failure and repeated identical content is suppressed. Host display settings survive application updates and restarts, separate from application config and KV. Applications need no hint component, CSS, `outputViews` entry or high-frequency state field.
|
|
111
|
+
|
|
112
|
+
## Permanent gameplay settings entry
|
|
113
|
+
|
|
114
|
+
The desktop control header opens gameplay settings using a fragment such as `#livegame=settings&request=1`. Control pages can read the initial `location.hash` and listen for `hashchange`. Parse the fragment with `URLSearchParams` and open the settings when `livegame` is `settings`. The host increments `request` on each click so the control can handle repeated requests. Preserve drafts and keep the runtime running when switching sections.
|
package/UPGRADING.md
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# Upgrading the SDK
|
|
2
|
+
|
|
3
|
+
## Check the contract first
|
|
4
|
+
|
|
5
|
+
| Version | Where it lives | What changes it |
|
|
6
|
+
|---|---|---|
|
|
7
|
+
| SDK package | package.json / package-lock.json / installed SDK | Deliberate dependency update |
|
|
8
|
+
| Application | manifest.json and project package.json | Your application's release |
|
|
9
|
+
| Protocol | manifestVersion 2 / apiVersion 2.0 | Host protocol contract; do not copy the SDK version here |
|
|
10
|
+
| Desktop | Installed client and release admission | Client update; does not rewrite project source |
|
|
11
|
+
|
|
12
|
+
The SDK 2.0 prerelease uses npm’s `beta` tag. Pin the exact reviewed version in the project manifest and lockfile. The bundled vendor archive works without the monorepo. TypeScript consumers need TypeScript 5.4+ for NoInfer; the template pins 5.5.4. Node.js 22+ and npm are project-tool requirements; the application runtime is still a browser Worker.
|
|
13
|
+
|
|
14
|
+
Before switching SDKs, read [CHANGELOG.md](CHANGELOG.md), record the current declared and installed versions with `npm ls @live-game/sdk --depth=0`, and save the project/lockfile in Git or a separate backup. Stop preview before dependency changes. Check `sdk.supports()` after `sdk.ready`; matching protocol versions do not promise every capability exists or is granted on every client.
|
|
15
|
+
|
|
16
|
+
## Bundled archive projects
|
|
17
|
+
|
|
18
|
+
1. Create a temporary project with the target client. Read its SDK changelog, then copy only the desired vendor SDK archive into the existing project's vendor directory. Keep the previous archive; do not replace the project's source with the new template.
|
|
19
|
+
2. Give changed local candidate archives distinct filenames, even when their internal unpublished version is the same. Never overwrite an archive referred to by the old lockfile.
|
|
20
|
+
3. Install the actual copied filename explicitly, for example `npm install --save-exact ./vendor/live-game-sdk-2.0.0-dev.8-local-review.tgz`. The example name is a local filename you assign, not a published release. npm updates the file reference and integrity; do not hand-edit integrity fields.
|
|
21
|
+
4. Review package.json/package-lock.json, run `npm ls @live-game/sdk --depth=0`, then `npm run check`, `npm test` and the client's scenario/ZIP preview. A script-based project can use `npm run verify -- --trust`.
|
|
22
|
+
|
|
23
|
+
The client's “依赖” → “同步依赖变更” runs npm install after you edit declarations. Normal “安装依赖” uses npm ci when a lockfile exists and keeps the recorded dependency choices. Updating the client or template never silently upgrades an existing project's SDK.
|
|
24
|
+
|
|
25
|
+
## Published registry versions
|
|
26
|
+
|
|
27
|
+
After a target version is actually published, choose that exact reviewed version using `npm install --save-exact @live-game/sdk@<target-version>`. Replace the placeholder with a real version; avoid a floating latest/next tag in reproducible application projects. Stable, prerelease and major upgrades require their own review; read the target release's migration notes and test on the oldest client you intend to support. SDK 2.0 removes the SDK1 APIs.
|
|
28
|
+
|
|
29
|
+
## Verify and recover
|
|
30
|
+
|
|
31
|
+
- Explicit command unions now reject payloads for commands without a payload field, missing required payloads and mismatched inferred handlers. Fix the contract or handler instead of casting to any. Keep explicit old listener generics only when you intentionally own the payload contract.
|
|
32
|
+
- Handle null initial state. Audio acknowledgements are job admission, not playback completion; do not blindly retry side effects on timeouts.
|
|
33
|
+
- Dependency changes require a new build/ZIP and review. Application id and stored keys remain stable across application releases; the SDK does not migrate your business data. Version and validate persisted JSON in runtime startup, make migration repeatable, and test both fresh and existing data.
|
|
34
|
+
- To undo a dependency attempt, restore the saved declarations, lockfile, vendor archive and any changed source together, then run npm ci. Check/test/verify again. A failed or cancelled npm install may leave node_modules incomplete; restoring files alone does not restore installed dependencies. Keep the prior approved ZIP for users; do not overwrite a released version.
|
|
35
|
+
|
|
36
|
+
For npm's underlying behavior see [npm ci](https://docs.npmjs.com/cli/v11/commands/npm-ci/), [npm install](https://docs.npmjs.com/cli/v11/commands/npm-install/) and [npm update](https://docs.npmjs.com/cli/v11/commands/npm-update/).
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { type AppBootstrap, type AppCapability, type AppLiveEnvelope, type AppGiftCatalog, type AppGiftQuery, type AppGuide } from "./contracts.js";
|
|
2
|
+
import type { LiveEventType } from "./live-events.js";
|
|
3
|
+
import type { LiveRoomSnapshot } from "../room-snapshot.js";
|
|
4
|
+
import type { AppCommand, AppCommandArgs, AppContext, AppLiveEventMap, AppSourceStatus, AppTimerEvent, AudioJobEvent, AudioPlayOptions, AudioVoice, SpeechOptions } from "./types.js";
|
|
5
|
+
export declare class AppSDKError extends Error {
|
|
6
|
+
readonly code: string;
|
|
7
|
+
constructor(code: string, message: string);
|
|
8
|
+
}
|
|
9
|
+
export type AppSDKConnection = {
|
|
10
|
+
port: MessagePort;
|
|
11
|
+
context: AppBootstrap;
|
|
12
|
+
};
|
|
13
|
+
/** The same implementation runs in application workers, panels and output views. */
|
|
14
|
+
declare function createClient<State = unknown, Config extends object = Record<string, unknown>, Command extends AppCommand = AppCommand>(connection?: AppSDKConnection): {
|
|
15
|
+
ready: Promise<AppContext<State, Config>>;
|
|
16
|
+
dispose: (error?: AppSDKError) => void;
|
|
17
|
+
call: <T = unknown>(method: AppCapability, ...args: unknown[]) => Promise<T>;
|
|
18
|
+
on: {
|
|
19
|
+
<K extends keyof {
|
|
20
|
+
"app.context": AppContext<State, Config>;
|
|
21
|
+
"app.stop": null;
|
|
22
|
+
state: State | null;
|
|
23
|
+
config: Config;
|
|
24
|
+
timer: AppTimerEvent;
|
|
25
|
+
"audio.job": AudioJobEvent;
|
|
26
|
+
command: Command;
|
|
27
|
+
"app.message": AppCommand;
|
|
28
|
+
"live.status": AppSourceStatus;
|
|
29
|
+
}>(event: K, handler: (value: {
|
|
30
|
+
"app.context": AppContext<State, Config>;
|
|
31
|
+
"app.stop": null;
|
|
32
|
+
state: State | null;
|
|
33
|
+
config: Config;
|
|
34
|
+
timer: AppTimerEvent;
|
|
35
|
+
"audio.job": AudioJobEvent;
|
|
36
|
+
command: Command;
|
|
37
|
+
"app.message": AppCommand;
|
|
38
|
+
"live.status": AppSourceStatus;
|
|
39
|
+
}[K]) => unknown): () => void;
|
|
40
|
+
<T = unknown>(event: string, handler: (value: NoInfer<T>) => unknown): () => void;
|
|
41
|
+
};
|
|
42
|
+
readonly disposed: boolean;
|
|
43
|
+
lifecycle: {
|
|
44
|
+
ready: () => Promise<void>;
|
|
45
|
+
fail: (message: string) => Promise<void>;
|
|
46
|
+
onStop: (handler: () => unknown) => () => void;
|
|
47
|
+
};
|
|
48
|
+
readonly context: AppContext<State, Config> | undefined;
|
|
49
|
+
supports: (capability: AppCapability) => boolean;
|
|
50
|
+
config: {
|
|
51
|
+
get: () => Promise<Config>;
|
|
52
|
+
update: (values: Partial<Config>) => Promise<Config>;
|
|
53
|
+
onChange: (handler: (value: Config) => unknown) => () => void;
|
|
54
|
+
};
|
|
55
|
+
storage: {
|
|
56
|
+
get: <T = unknown>(key: string) => Promise<T | null>;
|
|
57
|
+
set: (key: string, value: unknown) => Promise<null>;
|
|
58
|
+
delete: (key: string) => Promise<null>;
|
|
59
|
+
};
|
|
60
|
+
state: {
|
|
61
|
+
get: <T = State>() => Promise<T | null>;
|
|
62
|
+
publish: (value: State) => Promise<null>;
|
|
63
|
+
onChange: (handler: (value: State | null) => unknown) => () => void;
|
|
64
|
+
};
|
|
65
|
+
commands: {
|
|
66
|
+
send: (...[type, payload]: AppCommandArgs<Command>) => Promise<null>;
|
|
67
|
+
on: <T = Command>(handler: (value: NoInfer<T>) => unknown) => () => void;
|
|
68
|
+
};
|
|
69
|
+
views: {
|
|
70
|
+
notify: (type: string, payload?: unknown) => Promise<null>;
|
|
71
|
+
on: <T = AppCommand>(handler: (value: T) => unknown) => () => void;
|
|
72
|
+
};
|
|
73
|
+
live: {
|
|
74
|
+
room: () => Promise<LiveRoomSnapshot | null>;
|
|
75
|
+
on: {
|
|
76
|
+
<K extends LiveEventType>(type: K, handler: (event: AppLiveEventMap[K], envelope: AppLiveEnvelope<AppLiveEventMap[K]>) => unknown): () => void;
|
|
77
|
+
<T>(type: LiveEventType, handler: (event: NoInfer<T>, envelope: AppLiveEnvelope<NoInfer<T>>) => unknown): () => void;
|
|
78
|
+
};
|
|
79
|
+
};
|
|
80
|
+
catalog: {
|
|
81
|
+
gifts: (query: AppGiftQuery) => Promise<AppGiftCatalog>;
|
|
82
|
+
};
|
|
83
|
+
guide: {
|
|
84
|
+
publish: (content: AppGuide) => Promise<void>;
|
|
85
|
+
};
|
|
86
|
+
audio: {
|
|
87
|
+
speak: (text: string, options?: SpeechOptions) => Promise<{
|
|
88
|
+
jobId: string;
|
|
89
|
+
}>;
|
|
90
|
+
play: (asset: string, options?: AudioPlayOptions) => Promise<{
|
|
91
|
+
jobId: string;
|
|
92
|
+
}>;
|
|
93
|
+
cancel: (jobId: string) => Promise<null>;
|
|
94
|
+
voices: () => Promise<AudioVoice[]>;
|
|
95
|
+
onJob: (handler: (event: AudioJobEvent) => unknown) => () => void;
|
|
96
|
+
};
|
|
97
|
+
timers: {
|
|
98
|
+
set: (key: string, durationMs: number) => Promise<null>;
|
|
99
|
+
cancel: (key: string) => Promise<null>;
|
|
100
|
+
on: (handler: (event: AppTimerEvent) => unknown) => () => void;
|
|
101
|
+
};
|
|
102
|
+
text: {
|
|
103
|
+
similarity: (first: string, second: string) => Promise<number>;
|
|
104
|
+
};
|
|
105
|
+
assets: {
|
|
106
|
+
image: (url: string) => Promise<string>;
|
|
107
|
+
};
|
|
108
|
+
log: (level: "info" | "warn" | "error", message: string) => Promise<null>;
|
|
109
|
+
};
|
|
110
|
+
export type AppSDK<State = unknown, Config extends object = Record<string, unknown>, Command extends AppCommand = AppCommand> = ReturnType<typeof createClient<State, Config, Command>>;
|
|
111
|
+
export declare function createAppSDK<State = unknown, Config extends object = Record<string, unknown>, Command extends AppCommand = AppCommand>(connection?: AppSDKConnection): AppSDK<State, Config, Command>;
|
|
112
|
+
export {};
|
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
import { APP_PROTOCOL, } from "./contracts.js";
|
|
2
|
+
export class AppSDKError extends Error {
|
|
3
|
+
constructor(code, message) {
|
|
4
|
+
super(message);
|
|
5
|
+
this.code = code;
|
|
6
|
+
this.name = "AppSDKError";
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
/** The same implementation runs in application workers, panels and output views. */
|
|
10
|
+
function createClient(connection) {
|
|
11
|
+
let context;
|
|
12
|
+
let port;
|
|
13
|
+
let disposed = false;
|
|
14
|
+
let sequence = 0;
|
|
15
|
+
let stateRevision = 0, configRevision = 0;
|
|
16
|
+
const clientId = Array.from(globalThis.crypto.getRandomValues(new Uint32Array(4)), (value) => value.toString(16)).join("");
|
|
17
|
+
const handlers = new Map();
|
|
18
|
+
const pending = new Map();
|
|
19
|
+
let resolveReady;
|
|
20
|
+
let rejectReady;
|
|
21
|
+
const ready = new Promise((resolve, reject) => {
|
|
22
|
+
resolveReady = resolve;
|
|
23
|
+
rejectReady = reject;
|
|
24
|
+
});
|
|
25
|
+
// Consumers can attach their error handling after module initialization.
|
|
26
|
+
void ready.catch(() => { });
|
|
27
|
+
const readyTimeout = setTimeout(() => dispose(new AppSDKError("TIMEOUT", "应用宿主连接超时")), 15000);
|
|
28
|
+
function rejectCalls(error) {
|
|
29
|
+
for (const call of pending.values()) {
|
|
30
|
+
clearTimeout(call.timeout);
|
|
31
|
+
call.reject(error);
|
|
32
|
+
}
|
|
33
|
+
pending.clear();
|
|
34
|
+
}
|
|
35
|
+
async function receive(event) {
|
|
36
|
+
const value = event.data;
|
|
37
|
+
if (!value || value.protocol !== APP_PROTOCOL || disposed)
|
|
38
|
+
return;
|
|
39
|
+
if (value.type === "response") {
|
|
40
|
+
const call = pending.get(value.id);
|
|
41
|
+
if (!call)
|
|
42
|
+
return;
|
|
43
|
+
clearTimeout(call.timeout);
|
|
44
|
+
pending.delete(value.id);
|
|
45
|
+
if (value.error)
|
|
46
|
+
call.reject(new AppSDKError(value.error.code, value.error.message));
|
|
47
|
+
else
|
|
48
|
+
call.resolve(value.result);
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
if (value.type !== "event")
|
|
52
|
+
return;
|
|
53
|
+
if (value.event === "app.disconnected") {
|
|
54
|
+
if (context)
|
|
55
|
+
context = { ...context, status: "failed", error: "本地应用连接已断开" };
|
|
56
|
+
for (const listener of [...(handlers.get("app.context") ?? [])]) {
|
|
57
|
+
try {
|
|
58
|
+
await listener(context);
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
// A failing disposal listener must not prevent the remaining listeners from releasing resources.
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
dispose();
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
if (value.event === "app.context") {
|
|
68
|
+
const next = value.data;
|
|
69
|
+
if (!next ||
|
|
70
|
+
typeof next !== "object" ||
|
|
71
|
+
next.protocol !== APP_PROTOCOL ||
|
|
72
|
+
next.instanceId !== context?.instanceId ||
|
|
73
|
+
next.role !== context.role)
|
|
74
|
+
return;
|
|
75
|
+
if (next.runId !== context.runId)
|
|
76
|
+
rejectCalls(new AppSDKError("STALE_RUN", "应用运行已变化"));
|
|
77
|
+
context = next;
|
|
78
|
+
++stateRevision;
|
|
79
|
+
++configRevision;
|
|
80
|
+
}
|
|
81
|
+
else if (value.runId !== context?.runId)
|
|
82
|
+
return;
|
|
83
|
+
else if (value.event === "state" && context) {
|
|
84
|
+
context = { ...context, state: value.data };
|
|
85
|
+
++stateRevision;
|
|
86
|
+
}
|
|
87
|
+
else if (value.event === "config" && context) {
|
|
88
|
+
context = { ...context, config: value.data };
|
|
89
|
+
++configRevision;
|
|
90
|
+
}
|
|
91
|
+
let failure;
|
|
92
|
+
for (const listener of [...(handlers.get(value.event) ?? [])]) {
|
|
93
|
+
try {
|
|
94
|
+
await listener(value.data);
|
|
95
|
+
}
|
|
96
|
+
catch (error) {
|
|
97
|
+
failure = {
|
|
98
|
+
code: "APP_HANDLER_FAILED",
|
|
99
|
+
message: error instanceof Error && error.message ? error.message.slice(0, 500) : "应用事件处理失败",
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
if (value.deliveryId && !disposed) {
|
|
104
|
+
const ack = {
|
|
105
|
+
protocol: APP_PROTOCOL,
|
|
106
|
+
type: "ack",
|
|
107
|
+
id: value.deliveryId,
|
|
108
|
+
...(failure ? { error: failure } : {}),
|
|
109
|
+
};
|
|
110
|
+
port?.postMessage(ack);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
function attach(value) {
|
|
114
|
+
if (disposed || port)
|
|
115
|
+
return;
|
|
116
|
+
if (value.context.protocol !== APP_PROTOCOL) {
|
|
117
|
+
dispose(new AppSDKError("PROTOCOL", "应用协议版本不匹配"));
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
context = value.context;
|
|
121
|
+
port = value.port;
|
|
122
|
+
clearTimeout(readyTimeout);
|
|
123
|
+
port.addEventListener("message", receive);
|
|
124
|
+
port.start();
|
|
125
|
+
resolveReady(context);
|
|
126
|
+
}
|
|
127
|
+
function bootstrap(event) {
|
|
128
|
+
if (typeof window !== "undefined" && event.source !== window.parent)
|
|
129
|
+
return;
|
|
130
|
+
if (event.data?.protocol !== APP_PROTOCOL || event.data.type !== "bootstrap" || !event.ports[0])
|
|
131
|
+
return;
|
|
132
|
+
globalThis.removeEventListener("message", bootstrap);
|
|
133
|
+
attach({ context: event.data.context, port: event.ports[0] });
|
|
134
|
+
}
|
|
135
|
+
function dispose(error = new AppSDKError("DISCONNECTED", "应用连接已关闭")) {
|
|
136
|
+
if (disposed)
|
|
137
|
+
return;
|
|
138
|
+
disposed = true;
|
|
139
|
+
clearTimeout(readyTimeout);
|
|
140
|
+
globalThis.removeEventListener?.("message", bootstrap);
|
|
141
|
+
port?.removeEventListener("message", receive);
|
|
142
|
+
port?.close();
|
|
143
|
+
rejectCalls(error);
|
|
144
|
+
rejectReady(error);
|
|
145
|
+
handlers.clear();
|
|
146
|
+
}
|
|
147
|
+
function on(event, handler) {
|
|
148
|
+
let set = handlers.get(event);
|
|
149
|
+
if (!set) {
|
|
150
|
+
set = new Set();
|
|
151
|
+
handlers.set(event, set);
|
|
152
|
+
}
|
|
153
|
+
set.add(handler);
|
|
154
|
+
return () => {
|
|
155
|
+
set.delete(handler);
|
|
156
|
+
if (!set.size)
|
|
157
|
+
handlers.delete(event);
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
function onState(handler) {
|
|
161
|
+
const remove = [on("state", handler), on("app.context", (value) => handler(value.state))];
|
|
162
|
+
return () => {
|
|
163
|
+
for (const off of remove)
|
|
164
|
+
off();
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
function onConfig(handler) {
|
|
168
|
+
let previous = JSON.stringify(context?.config);
|
|
169
|
+
const changed = (value) => {
|
|
170
|
+
const encoded = JSON.stringify(value);
|
|
171
|
+
if (encoded === previous)
|
|
172
|
+
return;
|
|
173
|
+
previous = encoded;
|
|
174
|
+
return handler(value);
|
|
175
|
+
};
|
|
176
|
+
const remove = [on("config", changed), on("app.context", (value) => changed(value.config))];
|
|
177
|
+
return () => {
|
|
178
|
+
for (const off of remove)
|
|
179
|
+
off();
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
async function call(method, ...args) {
|
|
183
|
+
await ready;
|
|
184
|
+
if (disposed || !port)
|
|
185
|
+
throw new AppSDKError("DISCONNECTED", "应用连接已关闭");
|
|
186
|
+
if (!context?.capabilities.includes(method))
|
|
187
|
+
throw new AppSDKError("CAPABILITY_DISABLED", `应用未获准使用 ${method}`);
|
|
188
|
+
const id = `${clientId}:${++sequence}`;
|
|
189
|
+
return new Promise((resolve, reject) => {
|
|
190
|
+
const timeout = setTimeout(() => {
|
|
191
|
+
pending.delete(id);
|
|
192
|
+
reject(new AppSDKError("TIMEOUT", `能力调用超时:${method}`));
|
|
193
|
+
}, 30000);
|
|
194
|
+
pending.set(id, { resolve: (value) => resolve(value), reject, timeout });
|
|
195
|
+
const request = {
|
|
196
|
+
protocol: APP_PROTOCOL,
|
|
197
|
+
type: "request",
|
|
198
|
+
id,
|
|
199
|
+
runId: context.runId,
|
|
200
|
+
method,
|
|
201
|
+
args,
|
|
202
|
+
};
|
|
203
|
+
try {
|
|
204
|
+
port.postMessage(request);
|
|
205
|
+
}
|
|
206
|
+
catch {
|
|
207
|
+
clearTimeout(timeout);
|
|
208
|
+
pending.delete(id);
|
|
209
|
+
reject(new AppSDKError("DISCONNECTED", "能力请求发送失败"));
|
|
210
|
+
}
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
async function signal(type, message) {
|
|
214
|
+
await ready;
|
|
215
|
+
if (disposed || !port)
|
|
216
|
+
throw new AppSDKError("DISCONNECTED", "应用连接已关闭");
|
|
217
|
+
if (context?.role !== "runtime")
|
|
218
|
+
throw new AppSDKError("ROLE_DISABLED", "仅运行逻辑可报告启动状态");
|
|
219
|
+
port.postMessage({ protocol: APP_PROTOCOL, type, message });
|
|
220
|
+
}
|
|
221
|
+
async function getState() {
|
|
222
|
+
const revision = stateRevision;
|
|
223
|
+
const state = await call("state.read");
|
|
224
|
+
if (revision === stateRevision && context)
|
|
225
|
+
context = { ...context, state };
|
|
226
|
+
return context?.state;
|
|
227
|
+
}
|
|
228
|
+
async function getConfig() {
|
|
229
|
+
const revision = configRevision;
|
|
230
|
+
const config = await call("config.read");
|
|
231
|
+
if (revision === configRevision && context)
|
|
232
|
+
context = { ...context, config };
|
|
233
|
+
return context.config;
|
|
234
|
+
}
|
|
235
|
+
function onLive(type, handler) {
|
|
236
|
+
return on("live.event", (event) => {
|
|
237
|
+
if (event.type === type)
|
|
238
|
+
return handler(event.payload, event);
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
async function sendCommand(...[type, payload]) {
|
|
242
|
+
await ready;
|
|
243
|
+
return call(context?.role === "output" ? "commands.interact" : "commands.send", { type, payload });
|
|
244
|
+
}
|
|
245
|
+
if (connection)
|
|
246
|
+
attach(connection);
|
|
247
|
+
else {
|
|
248
|
+
globalThis.addEventListener("message", bootstrap);
|
|
249
|
+
if (typeof window !== "undefined" && window.parent !== window)
|
|
250
|
+
window.parent.postMessage({ protocol: APP_PROTOCOL, type: "connect" }, "*");
|
|
251
|
+
else if (typeof window === "undefined" && typeof globalThis.postMessage === "function")
|
|
252
|
+
globalThis.postMessage({ protocol: APP_PROTOCOL, type: "connect" });
|
|
253
|
+
}
|
|
254
|
+
return {
|
|
255
|
+
ready: ready,
|
|
256
|
+
dispose,
|
|
257
|
+
call,
|
|
258
|
+
on,
|
|
259
|
+
get disposed() {
|
|
260
|
+
return disposed;
|
|
261
|
+
},
|
|
262
|
+
lifecycle: {
|
|
263
|
+
ready: () => signal("ready"),
|
|
264
|
+
fail: (message) => signal("fault", message),
|
|
265
|
+
onStop: (handler) => on("app.stop", handler),
|
|
266
|
+
},
|
|
267
|
+
get context() {
|
|
268
|
+
return context;
|
|
269
|
+
},
|
|
270
|
+
supports: (capability) => !disposed && context?.capabilities.includes(capability) === true,
|
|
271
|
+
config: {
|
|
272
|
+
get: getConfig,
|
|
273
|
+
update: (values) => call("config.write", values),
|
|
274
|
+
onChange: (handler) => onConfig(handler),
|
|
275
|
+
},
|
|
276
|
+
storage: {
|
|
277
|
+
get: (key) => call("storage.read", key),
|
|
278
|
+
set: (key, value) => call("storage.write", "set", key, value),
|
|
279
|
+
delete: (key) => call("storage.write", "delete", key),
|
|
280
|
+
},
|
|
281
|
+
state: {
|
|
282
|
+
get: () => getState(),
|
|
283
|
+
publish: (value) => call("state.publish", value),
|
|
284
|
+
onChange: (handler) => onState(handler),
|
|
285
|
+
},
|
|
286
|
+
commands: {
|
|
287
|
+
send: sendCommand,
|
|
288
|
+
on: (handler) => on("command", handler),
|
|
289
|
+
},
|
|
290
|
+
views: {
|
|
291
|
+
notify: (type, payload) => call("views.notify", { type, payload }),
|
|
292
|
+
on: (handler) => on("app.message", handler),
|
|
293
|
+
},
|
|
294
|
+
live: {
|
|
295
|
+
room: () => call("room.read"),
|
|
296
|
+
on: onLive,
|
|
297
|
+
},
|
|
298
|
+
catalog: { gifts: (query) => call("catalog.gifts", query) },
|
|
299
|
+
guide: { publish: (content) => call("guide.publish", content) },
|
|
300
|
+
audio: {
|
|
301
|
+
speak: (text, options) => call("audio.speak", text, options),
|
|
302
|
+
play: (asset, options) => call("audio.play", asset, options),
|
|
303
|
+
cancel: (jobId) => call("audio.control", "cancel", jobId),
|
|
304
|
+
voices: () => call("audio.voices"),
|
|
305
|
+
onJob: (handler) => on("audio.job", handler),
|
|
306
|
+
},
|
|
307
|
+
timers: {
|
|
308
|
+
set: (key, durationMs) => call("timers.schedule", key, durationMs),
|
|
309
|
+
cancel: (key) => call("timers.schedule", key, null),
|
|
310
|
+
on: (handler) => on("timer", handler),
|
|
311
|
+
},
|
|
312
|
+
text: { similarity: (first, second) => call("text.similarity", first, second) },
|
|
313
|
+
assets: { image: (url) => call("assets.image", url) },
|
|
314
|
+
log: (level, message) => call("log.write", level, message),
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
let defaultClient;
|
|
318
|
+
export function createAppSDK(connection) {
|
|
319
|
+
if (connection)
|
|
320
|
+
return createClient(connection);
|
|
321
|
+
if (!defaultClient || defaultClient.disposed)
|
|
322
|
+
defaultClient = createClient();
|
|
323
|
+
return defaultClient;
|
|
324
|
+
}
|