openvod-jssdk 0.0.0-stage → 1.2.0

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/dist/index.cjs ADDED
@@ -0,0 +1,1209 @@
1
+ 'use strict';
2
+
3
+ // src/errors.ts
4
+ var ERROR_HINTS = {
5
+ unauthorized: "\u767B\u5F55\u6001\u65E0\u6548\u6216\u5DF2\u8FC7\u671F\uFF1ASDK \u5BF9\u4E1A\u52A1\u8BF7\u6C42\u4F1A\u81EA\u52A8\u91CD\u767B\u4E00\u6B21\u5E76\u91CD\u8BD5\uFF1B\u4E8C\u6B21\u4ECD\u5931\u8D25\u8BF4\u660E\u8D26\u53F7\u88AB\u7981 / \u53E3\u4EE4\u5DF2\u53D8\uFF08static \u6A21\u5F0F\u9700\u91CD\u65B0\u6CE8\u5165 token\uFF09\u3002",
6
+ invalid_credentials: "\u8D26\u53F7\u6216\u53E3\u4EE4\u9519\u8BEF\uFF08SDK \u4E0D\u6E05\u7A7A\u5DF2\u914D\u7F6E\u51ED\u636E\uFF09\uFF1A\u4FEE\u6B63\u540E\u7528 setCredential() \u66F4\u65B0\u51ED\u636E\u518D\u91CD\u8BD5\u3002",
7
+ forbidden: "\u8BF7\u6C42\u88AB\u62D2\u7EDD\uFF1A\u68C0\u67E5\u5206\u53D1\u7AEF CORS \u6765\u6E90\u9650\u5236\u4E0E\u5E73\u53F0\u4FA7\u8BBF\u95EE\u7B56\u7565\u3002",
8
+ bad_request: "\u8BF7\u6C42\u53C2\u6570\u4E0D\u5408\u6CD5\uFF1A\u68C0\u67E5 mediaId / templateId \u662F\u5426\u6765\u81EA\u5206\u53D1\u7AEF\u54CD\u5E94\uFF08templateId \u4E00\u5F8B\u53D6 handle.templates[].id\uFF0C\u4E0D\u8981\u624B\u62FC\uFF09\u3002",
9
+ bad_token: "\u64AD\u653E token \u65E0\u6548 / \u5DF2\u8FC7\u671F / \u4F1A\u8BDD\u5DF2\u540A\u9500\uFF1ASDK \u5BF9\u81EA\u8EAB\u8D44\u6E90\u8BF7\u6C42\uFF08\u5B57\u5E55\uFF09\u4F1A\u81EA\u52A8\u91CD\u7B7E\u4E00\u6B21\uFF1B\u64AD\u653E\u5668\u5185\u90E8\u6E05\u5355 / \u5BC6\u94A5 / \u5206\u7247 403 \u8BF7\u8C03\u7528 handle.refresh() \u6362\u6E90\u3002",
10
+ not_found: "\u8D44\u6E90\u4E0D\u5B58\u5728\uFF08\u5A92\u8D44 / \u5B57\u5E55\u8F68\u9053 / \u6E05\u5355\u5BF9\u8C61\u5DF2\u88AB\u5220\u9664\uFF09\uFF1A\u56DE\u5217\u8868\u6216\u91CD\u65B0\u83B7\u53D6\u3002",
11
+ not_playable: "\u5A92\u8D44\u672A\u5C31\u7EEA\u6216\u6307\u5B9A\u6A21\u677F\u65E0\u4EA7\u7269\uFF1A\u56DE\u5217\u8868\uFF0C\u6216\u4ECE handle.templates \u91CD\u65B0\u9009\u62E9\u6E05\u6670\u5EA6\u3002",
12
+ session_limit: "\u5E76\u53D1\u64AD\u653E\u4F1A\u8BDD\u5DF2\u8FBE\u4E0A\u9650\uFF08force_new \u4E0D\u7ED5\u8FC7\u4E0A\u9650\uFF0C\u4EC5\u65B0\u5EFA\u4F1A\u8BDD\u65F6\u68C0\u67E5\uFF09\uFF1A\u7B49\u5F85\u65E7\u4F1A\u8BDD\u6309 TTL \u81EA\u7136\u8FC7\u671F\uFF0C\u6216\u5728\u7BA1\u7406\u7AEF\u8C03\u5927\u8BE5\u7528\u6237 max_concurrent_sessions\u3002",
13
+ rate_limited: "\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF1A\u9000\u907F\u540E\u91CD\u8BD5\uFF08v1 \u5206\u53D1\u7AEF\u672A\u542F\u7528\u9650\u9891\uFF0C\u4FDD\u7559\u7801\uFF09\u3002",
14
+ not_implemented: "\u8BE5\u7AEF\u70B9\u672A\u5B9E\u73B0 / \u672A\u914D\u7F6E\uFF1A\u68C0\u67E5\u5206\u53D1\u7AEF\u7248\u672C\u4E0E\u7BA1\u7406\u7AEF\u9884\u89C8\u8D26\u53F7\u7B49\u914D\u7F6E\u3002",
15
+ internal: "\u670D\u52A1\u7AEF\u6216\u7F51\u7EDC\u5F02\u5E38\uFF1A\u7A0D\u540E\u91CD\u8BD5\uFF08GET \u7C7B\u8BF7\u6C42\u53EF\u7ECF retries \u81EA\u52A8\u91CD\u8BD5\uFF09\uFF1Bstatus=0 \u8868\u793A\u7F51\u7EDC\u5C42\u5931\u8D25\u2014\u2014\u5E38\u89C1\u4E8E\u5206\u53D1\u7AEF\u672A\u542F\u52A8\u6216 CORS \u672A\u653E\u884C\u5F53\u524D\u6E90\u7AD9\u3002"
16
+ };
17
+ function describeError(code) {
18
+ if (!code) return "\u7F3A\u5C11\u9519\u8BEF\u7801\uFF1A\u8BF7\u68C0\u67E5\u7F51\u7EDC\u4E0E\u5206\u53D1\u7AEF\u65E5\u5FD7\u3002";
19
+ return ERROR_HINTS[code] ?? `\u672A\u77E5\u9519\u8BEF\u7801\uFF1A${code}\uFF08\u53EF\u80FD\u662F\u5206\u53D1\u7AEF\u65B0\u589E\uFF0C\u8BF7\u5BF9\u7167 api.md \xA70.2\uFF09`;
20
+ }
21
+ var DeliveryError = class extends Error {
22
+ /** 服务端错误码(api.md §0.2 全表);网络 / 超时 / 非 JSON 响应统一 "internal" */
23
+ code;
24
+ /** HTTP 状态码;网络层失败 = 0 */
25
+ status;
26
+ /** SDK 附加排查建议(不覆盖服务端 message,见 §8) */
27
+ hint;
28
+ constructor(code, message, status, hint) {
29
+ super(message);
30
+ this.name = "DeliveryError";
31
+ this.code = code;
32
+ this.status = status;
33
+ this.hint = hint ?? describeError(code);
34
+ }
35
+ };
36
+ var PlayerSdkError = class extends Error {
37
+ code;
38
+ constructor(code, message) {
39
+ super(message);
40
+ this.name = "PlayerSdkError";
41
+ this.code = code;
42
+ }
43
+ };
44
+ function toSdkError(error) {
45
+ if (error instanceof DeliveryError || error instanceof PlayerSdkError) return error;
46
+ return new DeliveryError("internal", error instanceof Error ? error.message : String(error), 0);
47
+ }
48
+
49
+ // src/config.ts
50
+ var DEFAULT_TIMEOUT_MS = 1e4;
51
+ var DEFAULT_JWT_REFRESH_LEEWAY_SEC = 300;
52
+ var DEFAULT_REFRESH_LEEWAY_SEC = 300;
53
+ function invalid(message) {
54
+ return new PlayerSdkError("sdk_invalid_config", message);
55
+ }
56
+ function positiveInt(value, fallback, name) {
57
+ if (value === void 0) return fallback;
58
+ if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) {
59
+ throw invalid(`${name} \u5FC5\u987B\u662F\u6B63\u6574\u6570\uFF08\u5F53\u524D\uFF1A${String(value)}\uFF09`);
60
+ }
61
+ return value;
62
+ }
63
+ function nonNegativeInt(value, fallback, name) {
64
+ if (value === void 0) return fallback;
65
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
66
+ throw invalid(`${name} \u5FC5\u987B\u662F\u975E\u8D1F\u6574\u6570\uFF08\u5F53\u524D\uFF1A${String(value)}\uFF09`);
67
+ }
68
+ return value;
69
+ }
70
+ function normalizeBaseUrl(raw) {
71
+ if (typeof raw !== "string" || !raw.trim()) {
72
+ throw invalid("baseUrl \u5FC5\u586B\uFF08delivery \u5730\u5740\uFF0C\u5982 https://vod.example.com\uFF09");
73
+ }
74
+ const value = raw.trim().replace(/\/+$/, "");
75
+ let url;
76
+ try {
77
+ url = new URL(value);
78
+ } catch {
79
+ throw invalid(`baseUrl \u4E0D\u662F\u5408\u6CD5 URL\uFF1A${raw}`);
80
+ }
81
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
82
+ throw invalid(`baseUrl \u4EC5\u652F\u6301 http/https\uFF08\u5F53\u524D\uFF1A${url.protocol}\uFF09`);
83
+ }
84
+ return value;
85
+ }
86
+ function validateCredential(source) {
87
+ if (!source || typeof source !== "object") {
88
+ throw invalid("credential \u5FC5\u987B\u662F\u5BF9\u8C61\uFF08password / tokenProvider / static \u4E09\u9009\u4E00\uFF09");
89
+ }
90
+ switch (source.mode) {
91
+ case "password":
92
+ if (typeof source.username !== "string" || !source.username) throw invalid("password \u6A21\u5F0F\u9700\u8981\u975E\u7A7A username");
93
+ if (typeof source.password !== "string" || !source.password) throw invalid("password \u6A21\u5F0F\u9700\u8981\u975E\u7A7A password");
94
+ return { mode: "password", username: source.username, password: source.password };
95
+ case "tokenProvider":
96
+ if (typeof source.getToken !== "function") throw invalid("tokenProvider \u6A21\u5F0F\u9700\u8981 getToken \u51FD\u6570");
97
+ return { mode: "tokenProvider", getToken: source.getToken };
98
+ case "static":
99
+ if (typeof source.token !== "string" || !source.token) throw invalid("static \u6A21\u5F0F\u9700\u8981\u975E\u7A7A token");
100
+ return { mode: "static", token: source.token, expires_at: source.expires_at };
101
+ default:
102
+ throw invalid(`\u672A\u77E5 credential.mode\uFF1A${String(source.mode)}`);
103
+ }
104
+ }
105
+ function validateStorage(storage) {
106
+ if (storage === void 0) return;
107
+ const candidate = storage;
108
+ if (!storage || typeof storage !== "object" || typeof candidate.get !== "function" || typeof candidate.set !== "function" || typeof candidate.remove !== "function") {
109
+ throw invalid("storage \u5FC5\u987B\u5B9E\u73B0 get / set / remove \u4E09\u4E2A\u65B9\u6CD5\uFF08spec \xA73.4\uFF09");
110
+ }
111
+ }
112
+ function resolveConfig(config) {
113
+ if (!config || typeof config !== "object") {
114
+ throw invalid("createPlayerSdk(config) \u9700\u8981\u914D\u7F6E\u5BF9\u8C61\uFF08\u81F3\u5C11 baseUrl\uFF09");
115
+ }
116
+ const baseUrl = normalizeBaseUrl(config.baseUrl);
117
+ const injectedFetch = config.fetch;
118
+ const globalFetch = typeof globalThis.fetch === "function" ? globalThis.fetch.bind(globalThis) : null;
119
+ const fetchImpl = injectedFetch ?? globalFetch;
120
+ if (!fetchImpl || typeof fetchImpl !== "function") {
121
+ throw invalid("\u627E\u4E0D\u5230 fetch\uFF1A\u8BF7\u6CE8\u5165 config.fetch\uFF08Node <18 / \u975E\u6807\u51C6\u8FD0\u884C\u65F6\uFF09");
122
+ }
123
+ const autoRefresh = config.autoRefresh ?? true;
124
+ if (typeof autoRefresh !== "boolean") throw invalid("autoRefresh \u5FC5\u987B\u662F\u5E03\u5C14\u503C");
125
+ if (config.onEvent !== void 0 && typeof config.onEvent !== "function") {
126
+ throw invalid("onEvent \u5FC5\u987B\u662F\u51FD\u6570\uFF08\u7B49\u4EF7 sdk.on(listener)\uFF09");
127
+ }
128
+ validateStorage(config.storage);
129
+ return {
130
+ baseUrl,
131
+ credential: config.credential == null ? null : validateCredential(config.credential),
132
+ fetch: fetchImpl,
133
+ timeoutMs: positiveInt(config.timeoutMs, DEFAULT_TIMEOUT_MS, "timeoutMs"),
134
+ retries: nonNegativeInt(config.retries, 0, "retries"),
135
+ jwtRefreshLeewaySec: nonNegativeInt(config.jwtRefreshLeewaySec, DEFAULT_JWT_REFRESH_LEEWAY_SEC, "jwtRefreshLeewaySec"),
136
+ refreshLeewaySec: nonNegativeInt(config.refreshLeewaySec, DEFAULT_REFRESH_LEEWAY_SEC, "refreshLeewaySec"),
137
+ autoRefresh,
138
+ storage: config.storage ?? null,
139
+ onEvent: config.onEvent ?? null
140
+ };
141
+ }
142
+
143
+ // src/auth.ts
144
+ var TOKEN_STORAGE_KEY = "openvod.player-sdk.token";
145
+ function parseExpiresAt(value) {
146
+ if (value == null) return null;
147
+ if (typeof value === "number") {
148
+ if (!Number.isFinite(value) || value <= 0) return null;
149
+ return Math.floor(value > 1e12 ? value / 1e3 : value);
150
+ }
151
+ const ms = Date.parse(value);
152
+ return Number.isNaN(ms) ? null : Math.floor(ms / 1e3);
153
+ }
154
+ var AuthManager = class {
155
+ constructor(deps) {
156
+ this.deps = deps;
157
+ this.credential = deps.config.credential;
158
+ }
159
+ deps;
160
+ credential;
161
+ cached = null;
162
+ inflight = null;
163
+ storageLoaded = false;
164
+ loginEmitted = false;
165
+ expiredEmitted = false;
166
+ /** 是否配置了凭据(attach 模式为 false) */
167
+ hasCredential() {
168
+ return this.credential != null;
169
+ }
170
+ /** 当前身份键(缓存键 / storage identity 校验用;同一身份共享缓存) */
171
+ identityKey() {
172
+ const credential = this.credential;
173
+ if (!credential) return null;
174
+ switch (credential.mode) {
175
+ case "password":
176
+ return `password:${credential.username}`;
177
+ case "tokenProvider":
178
+ return "tokenProvider";
179
+ case "static":
180
+ return `static:${credential.token}`;
181
+ }
182
+ }
183
+ /**
184
+ * 运行时切换身份(spec §3.5):清 token / 会话缓存 / 定时器 → 旧句柄 disposed=true → emit auth:changed{switched}。
185
+ * 传 null = 退化为 attach 模式(仅 attachPlayback 可用)。
186
+ */
187
+ setCredential(source) {
188
+ this.credential = source == null ? null : validateCredential(source);
189
+ this.cached = null;
190
+ this.inflight = null;
191
+ this.loginEmitted = false;
192
+ this.expiredEmitted = false;
193
+ void this.clearStored();
194
+ this.deps.onIdentityChange();
195
+ this.deps.emit({ type: "auth:changed", reason: "switched" });
196
+ }
197
+ /**
198
+ * 取有效 JWT(spec §3.2):
199
+ * - 缓存命中且在 leeway 之外 → 零请求返回;
200
+ * - 进入 leeway 窗口 / force → 经凭据源重新获取(single-flight 并发去重);
201
+ * - `static` 模式无重登能力:force / 进入 leeway → 抛 DeliveryError + emit auth:changed{expired}。
202
+ */
203
+ async getAccessToken(options) {
204
+ const credential = this.credential;
205
+ if (!credential) {
206
+ throw new PlayerSdkError(
207
+ "sdk_no_credential",
208
+ "\u672A\u914D\u7F6E\u51ED\u636E\uFF1A\u8BF7\u7528 createPlayerSdk({ credential }) \u6216 auth.setCredential() \u914D\u7F6E\uFF08attach \u6A21\u5F0F\u4EC5\u652F\u6301 attachPlayback\uFF09"
209
+ );
210
+ }
211
+ if (credential.mode === "static") {
212
+ const expiresAtSec = parseExpiresAt(credential.expires_at);
213
+ if (options?.force || this.isExpiring(expiresAtSec)) {
214
+ this.markExpired();
215
+ throw new DeliveryError(
216
+ "unauthorized",
217
+ "\u9759\u6001 token \u5DF2\u5931\u6548\uFF08static \u6A21\u5F0F\u4E0D\u5177\u5907\u91CD\u767B\u80FD\u529B\uFF09\uFF1A\u8BF7\u6CE8\u5165\u65B0 token \u6216\u6539\u7528 tokenProvider",
218
+ 401
219
+ );
220
+ }
221
+ return credential.token;
222
+ }
223
+ await this.ensureStorageLoaded();
224
+ const identity = this.identityKey();
225
+ if (!options?.force && this.cached && this.cached.identity === identity && !this.isExpiring(this.cached.expires_at_sec)) {
226
+ return this.cached.access_token;
227
+ }
228
+ if (this.inflight) return this.inflight;
229
+ const task = this.acquire(credential, identity).finally(() => {
230
+ if (this.inflight === task) this.inflight = null;
231
+ });
232
+ this.inflight = task;
233
+ return task;
234
+ }
235
+ /**
236
+ * 401 兜底(spec §4.4):可重登返回 true(调用方重试一次);`static` 模式标记失效并返回 false。
237
+ * 重登自身失败(invalid_credentials / 网络)时抛错,由调用方透传。
238
+ */
239
+ async recoverUnauthorized() {
240
+ const credential = this.credential;
241
+ if (!credential || credential.mode === "static") {
242
+ this.markExpired();
243
+ return false;
244
+ }
245
+ await this.getAccessToken({ force: true });
246
+ return true;
247
+ }
248
+ /** 标记登录态失效(emit auth:changed{expired},同一失效周期只发一次) */
249
+ markExpired() {
250
+ if (this.expiredEmitted) return;
251
+ this.expiredEmitted = true;
252
+ this.deps.emit({ type: "auth:changed", reason: "expired" });
253
+ }
254
+ // ---- 内部 ----
255
+ isExpiring(expiresAtSec) {
256
+ if (expiresAtSec == null) return false;
257
+ return expiresAtSec - this.deps.config.jwtRefreshLeewaySec <= Math.floor(this.deps.now() / 1e3);
258
+ }
259
+ async acquire(credential, identity) {
260
+ const nowSec = Math.floor(this.deps.now() / 1e3);
261
+ let accessToken;
262
+ let expiresAtSec;
263
+ if (credential.mode === "password") {
264
+ const body = await this.deps.client.json({
265
+ method: "POST",
266
+ path: "/v1/auth/login",
267
+ body: { username: credential.username, password: credential.password }
268
+ });
269
+ if (!body || typeof body.access_token !== "string" || !body.access_token) {
270
+ throw new PlayerSdkError("sdk_bad_response", "login \u54CD\u5E94\u7F3A\u5C11 access_token\uFF08\u68C0\u67E5 baseUrl \u662F\u5426\u6307\u5411\u5206\u53D1\u7AEF\uFF09");
271
+ }
272
+ accessToken = body.access_token;
273
+ expiresAtSec = typeof body.expires_in === "number" && Number.isFinite(body.expires_in) ? nowSec + Math.floor(body.expires_in) : null;
274
+ } else {
275
+ const result = await credential.getToken();
276
+ if (typeof result === "string") {
277
+ if (!result) throw new PlayerSdkError("sdk_bad_response", "tokenProvider.getToken \u8FD4\u56DE\u4E86\u7A7A\u5B57\u7B26\u4E32");
278
+ accessToken = result;
279
+ expiresAtSec = null;
280
+ } else if (result && typeof result === "object" && typeof result.access_token === "string" && result.access_token) {
281
+ accessToken = result.access_token;
282
+ expiresAtSec = parseExpiresAt(result.expires_at);
283
+ } else {
284
+ throw new PlayerSdkError(
285
+ "sdk_bad_response",
286
+ "tokenProvider.getToken \u5FC5\u987B\u8FD4\u56DE token \u5B57\u7B26\u4E32\u6216 { access_token, expires_at }"
287
+ );
288
+ }
289
+ }
290
+ this.cached = { access_token: accessToken, expires_at_sec: expiresAtSec, identity };
291
+ this.expiredEmitted = false;
292
+ void this.persistStored();
293
+ this.deps.emit({ type: "auth:changed", reason: this.loginEmitted ? "refresh" : "login" });
294
+ this.loginEmitted = true;
295
+ return accessToken;
296
+ }
297
+ async ensureStorageLoaded() {
298
+ if (this.storageLoaded) return;
299
+ this.storageLoaded = true;
300
+ const storage = this.deps.config.storage;
301
+ if (!storage) return;
302
+ try {
303
+ const raw = await storage.get(TOKEN_STORAGE_KEY);
304
+ if (!raw) return;
305
+ const parsed = JSON.parse(raw);
306
+ if (!parsed || typeof parsed.access_token !== "string" || !parsed.access_token) return;
307
+ if (typeof parsed.identity !== "string" || parsed.identity !== this.identityKey()) return;
308
+ const expiresAtSec = typeof parsed.expires_at === "string" ? parseExpiresAt(parsed.expires_at) : null;
309
+ if (expiresAtSec != null && expiresAtSec <= Math.floor(this.deps.now() / 1e3)) return;
310
+ this.cached = { access_token: parsed.access_token, expires_at_sec: expiresAtSec, identity: parsed.identity };
311
+ } catch {
312
+ }
313
+ }
314
+ async persistStored() {
315
+ const storage = this.deps.config.storage;
316
+ const cached = this.cached;
317
+ if (!storage || !cached) return;
318
+ try {
319
+ await storage.set(
320
+ TOKEN_STORAGE_KEY,
321
+ JSON.stringify({
322
+ access_token: cached.access_token,
323
+ expires_at: cached.expires_at_sec == null ? null : new Date(cached.expires_at_sec * 1e3).toISOString(),
324
+ identity: cached.identity
325
+ })
326
+ );
327
+ } catch {
328
+ }
329
+ }
330
+ async clearStored() {
331
+ const storage = this.deps.config.storage;
332
+ if (!storage) return;
333
+ try {
334
+ await storage.remove(TOKEN_STORAGE_KEY);
335
+ } catch {
336
+ }
337
+ }
338
+ };
339
+
340
+ // src/client.ts
341
+ function isKnownErrorCode(code) {
342
+ return Object.prototype.hasOwnProperty.call(ERROR_HINTS, code);
343
+ }
344
+ var HttpClient = class {
345
+ constructor(cfg) {
346
+ this.cfg = cfg;
347
+ }
348
+ cfg;
349
+ /** 业务面 JSON 请求(/v1/media*):非 2xx 抛 DeliveryError(错误信封解析,N4 保真) */
350
+ async json(opts) {
351
+ const res = await this.send({
352
+ method: opts.method,
353
+ url: opts.path,
354
+ body: opts.body,
355
+ token: opts.token,
356
+ signal: opts.signal,
357
+ retry: opts.retry ?? opts.method === "GET"
358
+ });
359
+ if (!res.ok) throw await toDeliveryError(res);
360
+ const text = await res.text();
361
+ if (!text) return null;
362
+ try {
363
+ return JSON.parse(text);
364
+ } catch {
365
+ throw new PlayerSdkError(
366
+ "sdk_bad_response",
367
+ `\u5206\u53D1\u7AEF\u54CD\u5E94\u4E0D\u662F\u5408\u6CD5 JSON\uFF1A${opts.method} ${opts.path}\uFF08HTTP ${res.status}\uFF09`
368
+ );
369
+ }
370
+ }
371
+ /** 绝对 URL 文本请求(字幕 VTT,spec §6):非 2xx 抛 DeliveryError */
372
+ async text(url, options = {}) {
373
+ const res = await this.send({
374
+ method: "GET",
375
+ url,
376
+ signal: options.signal,
377
+ retry: options.retry ?? true
378
+ });
379
+ if (!res.ok) throw await toDeliveryError(res);
380
+ return res.text();
381
+ }
382
+ // ---- 内部 ----
383
+ absoluteUrl(url) {
384
+ return /^https?:\/\//i.test(url) ? url : `${this.cfg.baseUrl}${url}`;
385
+ }
386
+ async send(req) {
387
+ const attempts = req.retry ? Math.max(0, this.cfg.retries) + 1 : 1;
388
+ let lastError = null;
389
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
390
+ try {
391
+ const res = await this.fetchOnce(req);
392
+ if (res.status >= 500 && req.retry && attempt < attempts - 1) continue;
393
+ return res;
394
+ } catch (error) {
395
+ if (!(error instanceof DeliveryError)) throw error;
396
+ lastError = error;
397
+ if (attempt >= attempts - 1) throw error;
398
+ }
399
+ }
400
+ throw lastError ?? new DeliveryError("internal", "\u8BF7\u6C42\u5931\u8D25", 0);
401
+ }
402
+ async fetchOnce(req) {
403
+ const controller = new AbortController();
404
+ let timedOut = false;
405
+ const timer = setTimeout(() => {
406
+ timedOut = true;
407
+ controller.abort();
408
+ }, this.cfg.timeoutMs);
409
+ timer.unref?.();
410
+ const onOuterAbort = () => controller.abort();
411
+ if (req.signal) {
412
+ if (req.signal.aborted) {
413
+ clearTimeout(timer);
414
+ throw new DeliveryError("internal", "\u8BF7\u6C42\u5DF2\u53D6\u6D88", 0);
415
+ }
416
+ req.signal.addEventListener("abort", onOuterAbort, { once: true });
417
+ }
418
+ try {
419
+ const headers = {};
420
+ if (req.body !== void 0) headers["content-type"] = "application/json";
421
+ if (req.token) headers["authorization"] = `Bearer ${req.token}`;
422
+ return await this.cfg.fetch(this.absoluteUrl(req.url), {
423
+ method: req.method,
424
+ headers,
425
+ body: req.body === void 0 ? void 0 : JSON.stringify(req.body),
426
+ // m3u8 / 密钥 / 字幕响应恒 no-store(P0);业务 JSON 请求同样避免中间缓存
427
+ cache: "no-store",
428
+ signal: controller.signal
429
+ });
430
+ } catch (error) {
431
+ if (timedOut) {
432
+ throw new DeliveryError("internal", `\u8BF7\u6C42\u8D85\u65F6\uFF08${this.cfg.timeoutMs}ms\uFF09\uFF1A${req.method} ${req.url}`, 0);
433
+ }
434
+ if (req.signal?.aborted) throw new DeliveryError("internal", "\u8BF7\u6C42\u5DF2\u53D6\u6D88", 0);
435
+ throw new DeliveryError(
436
+ "internal",
437
+ `\u65E0\u6CD5\u8FDE\u63A5\u5206\u53D1\u7AEF\uFF08${this.cfg.baseUrl}\uFF09\uFF1A${error instanceof Error ? error.message : String(error)}\uFF08\u68C0\u67E5\u5206\u53D1\u7AEF\u662F\u5426\u5DF2\u542F\u52A8 / CORS \u662F\u5426\u653E\u884C\u5F53\u524D\u6E90\u7AD9\uFF09`,
438
+ 0
439
+ );
440
+ } finally {
441
+ clearTimeout(timer);
442
+ req.signal?.removeEventListener("abort", onOuterAbort);
443
+ }
444
+ }
445
+ };
446
+ async function toDeliveryError(res) {
447
+ let code;
448
+ let message;
449
+ try {
450
+ const body = await res.json();
451
+ if (body && typeof body === "object" && body.error && typeof body.error === "object") {
452
+ if (typeof body.error.code === "string") code = body.error.code;
453
+ if (typeof body.error.message === "string" && body.error.message) message = body.error.message;
454
+ }
455
+ } catch {
456
+ }
457
+ if (code && isKnownErrorCode(code)) {
458
+ return new DeliveryError(code, message ?? `\u5206\u53D1\u7AEF\u8FD4\u56DE HTTP ${res.status}`, res.status);
459
+ }
460
+ return new DeliveryError("internal", message ?? `\u5206\u53D1\u7AEF\u8FD4\u56DE HTTP ${res.status}`, res.status);
461
+ }
462
+
463
+ // src/events.ts
464
+ function createEmitter() {
465
+ const typed = /* @__PURE__ */ new Map();
466
+ const all = /* @__PURE__ */ new Set();
467
+ return {
468
+ on(type, listener) {
469
+ if (type === null) {
470
+ all.add(listener);
471
+ return () => {
472
+ all.delete(listener);
473
+ };
474
+ }
475
+ let set = typed.get(type);
476
+ if (!set) {
477
+ set = /* @__PURE__ */ new Set();
478
+ typed.set(type, set);
479
+ }
480
+ set.add(listener);
481
+ return () => {
482
+ set.delete(listener);
483
+ };
484
+ },
485
+ emit(event) {
486
+ const targets = [...all, ...typed.get(event.type) ?? []];
487
+ for (const listener of targets) {
488
+ try {
489
+ listener(event);
490
+ } catch {
491
+ }
492
+ }
493
+ }
494
+ };
495
+ }
496
+
497
+ // src/media.ts
498
+ function parseCustomMetadata(custom) {
499
+ const out = {};
500
+ if (!custom || typeof custom !== "object" || Array.isArray(custom)) return out;
501
+ const raw = custom;
502
+ const category = raw.category;
503
+ if (category && typeof category === "object" && !Array.isArray(category)) {
504
+ const c = category;
505
+ const id = typeof c.id === "string" ? c.id.trim() : "";
506
+ const path = typeof c.path === "string" ? c.path.trim() : "";
507
+ const name = typeof c.name === "string" ? c.name.trim() : "";
508
+ if (id && path) out.category = { id, name, path };
509
+ }
510
+ if (typeof raw.description === "string" && raw.description.trim()) {
511
+ out.description = raw.description.trim();
512
+ }
513
+ if (Array.isArray(raw.tags)) {
514
+ const tags = [];
515
+ for (const tag of raw.tags) {
516
+ if (typeof tag !== "string") continue;
517
+ const value = tag.trim();
518
+ if (value && !tags.includes(value)) tags.push(value);
519
+ }
520
+ if (tags.length) out.tags = tags;
521
+ }
522
+ return out;
523
+ }
524
+ function templateLabel(template) {
525
+ return template.name ?? `\u6A21\u677F ${template.id.slice(0, 8)}`;
526
+ }
527
+ var MediaApi = class {
528
+ constructor(request) {
529
+ this.request = request;
530
+ }
531
+ request;
532
+ /**
533
+ * 媒资列表(GET /v1/media;恒为 READY;`next_cursor` v1 恒 null 原样透传)。
534
+ * `limit` 原样传给服务端(缺省 50 / 1..200 / 非法静默回退,由服务端裁决,N3)。
535
+ */
536
+ async listMedia(options) {
537
+ const query = options?.limit == null ? "" : `?limit=${encodeURIComponent(String(options.limit))}`;
538
+ return await this.request("list_media", {
539
+ method: "GET",
540
+ path: `/v1/media${query}`,
541
+ signal: options?.signal
542
+ });
543
+ }
544
+ /** 媒资详情(GET /v1/media/{id};非 READY 仍返回详情,`playable=false`) */
545
+ async getMedia(mediaId, options) {
546
+ return await this.request("get_media", {
547
+ method: "GET",
548
+ path: `/v1/media/${encodeURIComponent(mediaId)}`,
549
+ signal: options?.signal
550
+ });
551
+ }
552
+ };
553
+
554
+ // src/subtitles.ts
555
+ function isNonEmptyString(value) {
556
+ return typeof value === "string" && value.length > 0;
557
+ }
558
+ function sanitizeSubtitles(value) {
559
+ if (!Array.isArray(value)) return [];
560
+ const out = [];
561
+ for (const item of value) {
562
+ if (!item || typeof item !== "object") continue;
563
+ const raw = item;
564
+ if (!isNonEmptyString(raw.id) || !isNonEmptyString(raw.url)) continue;
565
+ out.push({
566
+ id: raw.id,
567
+ lang: typeof raw.lang === "string" ? raw.lang : "",
568
+ label: typeof raw.label === "string" ? raw.label : "",
569
+ is_default: raw.is_default === true,
570
+ url: raw.url
571
+ });
572
+ }
573
+ return out;
574
+ }
575
+ function findMatchingTrack(tracks, ref) {
576
+ return tracks.find((t) => t.id === ref.id && t.lang === ref.lang) ?? tracks.find((t) => t.id === ref.id) ?? null;
577
+ }
578
+ async function fetchVttText(client, url, signal) {
579
+ return client.text(url, { signal, retry: true });
580
+ }
581
+
582
+ // src/playback.ts
583
+ var AUTO_REFRESH_RETRY_MS = 3e4;
584
+ var MIN_REFRESH_DELAY_MS = 1e3;
585
+ var B64URL_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
586
+ function unref(timer) {
587
+ timer.unref?.();
588
+ }
589
+ function decodeBase64Url(input) {
590
+ let bits = 0;
591
+ let value = 0;
592
+ let out = "";
593
+ for (const ch of input) {
594
+ const index = B64URL_ALPHABET.indexOf(ch);
595
+ if (index < 0) return null;
596
+ value = value << 6 | index;
597
+ bits += 6;
598
+ if (bits >= 8) {
599
+ bits -= 8;
600
+ out += String.fromCharCode(value >> bits & 255);
601
+ }
602
+ }
603
+ return out;
604
+ }
605
+ function manifestTokenExp(url) {
606
+ try {
607
+ const queryIndex = url.indexOf("?");
608
+ if (queryIndex < 0) return null;
609
+ const token = new URLSearchParams(url.slice(queryIndex + 1)).get("t");
610
+ if (!token) return null;
611
+ const payloadB64 = token.split(".")[0];
612
+ if (!payloadB64) return null;
613
+ const json = decodeBase64Url(payloadB64);
614
+ if (!json) return null;
615
+ const payload = JSON.parse(json);
616
+ return typeof payload?.exp === "number" && Number.isFinite(payload.exp) ? payload.exp : null;
617
+ } catch {
618
+ return null;
619
+ }
620
+ }
621
+ function parseIsoSeconds(value) {
622
+ if (!value) return null;
623
+ const ms = Date.parse(value);
624
+ return Number.isNaN(ms) ? null : Math.floor(ms / 1e3);
625
+ }
626
+ function sanitizeTemplates(value) {
627
+ if (!Array.isArray(value)) return [];
628
+ const out = [];
629
+ for (const item of value) {
630
+ if (!item || typeof item !== "object") continue;
631
+ const raw = item;
632
+ if (typeof raw.id !== "string" || !raw.id) continue;
633
+ out.push({
634
+ id: raw.id,
635
+ name: typeof raw.name === "string" ? raw.name : null,
636
+ is_default: raw.is_default === true
637
+ });
638
+ }
639
+ return out;
640
+ }
641
+ function normalizePlaybackResponse(mediaId, body) {
642
+ if (!body || typeof body !== "object") {
643
+ throw new PlayerSdkError("sdk_bad_response", `play \u54CD\u5E94\u4E0D\u662F\u5BF9\u8C61\uFF08media ${mediaId}\uFF09`);
644
+ }
645
+ const raw = body;
646
+ if (typeof raw.sid !== "string" || typeof raw.manifest_url !== "string" || !raw.manifest_url || typeof raw.expires_at !== "string" || typeof raw.template_id !== "string") {
647
+ throw new PlayerSdkError(
648
+ "sdk_bad_response",
649
+ `play \u54CD\u5E94\u7F3A\u5C11\u5FC5\u9700\u5B57\u6BB5\uFF08sid / manifest_url / expires_at / template_id\uFF0Cmedia ${mediaId}\uFF09`
650
+ );
651
+ }
652
+ return {
653
+ media_id: mediaId,
654
+ sid: raw.sid,
655
+ manifest_url: raw.manifest_url,
656
+ expires_at: raw.expires_at,
657
+ template_id: raw.template_id,
658
+ subtitles: sanitizeSubtitles(raw.subtitles),
659
+ templates: sanitizeTemplates(raw.templates),
660
+ disposed: false,
661
+ requestedTemplateId: null
662
+ };
663
+ }
664
+ var PlaybackHandleImpl = class {
665
+ constructor(manager, state) {
666
+ this.manager = manager;
667
+ this.state = state;
668
+ }
669
+ manager;
670
+ state;
671
+ get media_id() {
672
+ return this.state.media_id;
673
+ }
674
+ get sid() {
675
+ return this.state.sid;
676
+ }
677
+ get manifest_url() {
678
+ return this.state.manifest_url;
679
+ }
680
+ get expires_at() {
681
+ return this.state.expires_at;
682
+ }
683
+ get template_id() {
684
+ return this.state.template_id;
685
+ }
686
+ get subtitles() {
687
+ return this.state.subtitles;
688
+ }
689
+ get templates() {
690
+ return this.state.templates;
691
+ }
692
+ get disposed() {
693
+ return this.state.disposed;
694
+ }
695
+ async switchTemplate(templateId, options) {
696
+ this.assertUsable();
697
+ this.manager.requireCredential();
698
+ if (templateId === this.state.template_id) return this;
699
+ try {
700
+ await this.manager.switchTemplate(this, templateId, options?.signal);
701
+ } catch (error) {
702
+ if (!options?.signal?.aborted) this.manager.emitError("switch_template", error);
703
+ throw error;
704
+ }
705
+ return this;
706
+ }
707
+ async refresh(options) {
708
+ this.assertUsable();
709
+ this.manager.requireCredential();
710
+ try {
711
+ const requested = await this.manager.refresh(this, {
712
+ force: options?.force ?? false,
713
+ signal: options?.signal
714
+ });
715
+ if (requested) this.manager.emitRefreshed(this, "manual");
716
+ } catch (error) {
717
+ if (!options?.signal?.aborted) this.manager.emitError("refresh", error);
718
+ throw error;
719
+ }
720
+ return this;
721
+ }
722
+ async fetchSubtitleText(track, options) {
723
+ this.assertUsable();
724
+ try {
725
+ return await fetchVttText(this.manager.client, track.url, options?.signal);
726
+ } catch (error) {
727
+ const transient = error instanceof DeliveryError && error.code === "bad_token" && !options?.signal?.aborted;
728
+ if (!transient) {
729
+ if (!options?.signal?.aborted) this.manager.emitError("subtitle", error);
730
+ throw error;
731
+ }
732
+ try {
733
+ await this.manager.refresh(this, { force: true, signal: options?.signal });
734
+ const fresh = findMatchingTrack(this.state.subtitles, track);
735
+ if (!fresh || fresh.url === track.url) throw error;
736
+ return await fetchVttText(this.manager.client, fresh.url, options?.signal);
737
+ } catch (retryError) {
738
+ if (!options?.signal?.aborted) this.manager.emitError("subtitle", retryError);
739
+ throw retryError;
740
+ }
741
+ }
742
+ }
743
+ dispose() {
744
+ this.manager.disposeHandle(this);
745
+ }
746
+ assertUsable() {
747
+ if (this.state.disposed) {
748
+ throw new PlayerSdkError(
749
+ "sdk_disposed",
750
+ `\u64AD\u653E\u53E5\u67C4\u5DF2\u91CA\u653E\uFF08media ${this.state.media_id}\uFF09\uFF1A\u8BF7\u91CD\u65B0 play()\uFF1B\u8EAB\u4EFD\u5207\u6362 / sdk.dispose() \u4E5F\u4F1A\u4F7F\u65E7\u53E5\u67C4\u5931\u6548`
751
+ );
752
+ }
753
+ }
754
+ /** 内部:原位更新(不对外暴露;manager 在请求成功后调用) */
755
+ _update(next) {
756
+ Object.assign(this.state, next);
757
+ }
758
+ _state() {
759
+ return this.state;
760
+ }
761
+ };
762
+ var PlaybackManager = class {
763
+ constructor(deps) {
764
+ this.deps = deps;
765
+ }
766
+ deps;
767
+ entries = /* @__PURE__ */ new Map();
768
+ /** 同媒资同语义请求的 single-flight(§4.2 并发去重) */
769
+ inflight = /* @__PURE__ */ new Map();
770
+ disposed = false;
771
+ get client() {
772
+ return this.deps.client;
773
+ }
774
+ // ---- 公共入口(接口语义见 spec §2.3 / §4 / §5) ----
775
+ async play(mediaId, options = {}) {
776
+ this.assertNotDisposed();
777
+ const templateId = options.templateId ?? null;
778
+ const forceNew = options.forceNew ?? false;
779
+ const key = `play|${templateId ?? "*"}|${forceNew ? 1 : 0}`;
780
+ const running = this.inflight.get(mediaId);
781
+ if (running && running.key === key) return running.promise;
782
+ const promise = this.serialize(mediaId, async () => {
783
+ const entry = this.entryFor(mediaId);
784
+ const current = entry.handle;
785
+ const previousTemplateId = current && !current.disposed ? current.template_id : null;
786
+ if (current && !current.disposed) {
787
+ if (!forceNew && templateId != null && templateId === current.template_id) return current;
788
+ if (!forceNew && templateId == null && !this.isStale(current)) return current;
789
+ }
790
+ const handle = await this.requestPlay(entry, { templateId, forceNew, signal: options.signal });
791
+ if (previousTemplateId != null && templateId != null && !forceNew && handle.template_id !== previousTemplateId) {
792
+ this.deps.emitter.emit({
793
+ type: "playback:template_changed",
794
+ media_id: handle.media_id,
795
+ template_id: handle.template_id,
796
+ manifest_url: handle.manifest_url
797
+ });
798
+ }
799
+ return handle;
800
+ });
801
+ this.inflight.set(mediaId, { key, promise });
802
+ const clear = () => {
803
+ const current = this.inflight.get(mediaId);
804
+ if (current && current.promise === promise) this.inflight.delete(mediaId);
805
+ };
806
+ void promise.then(clear, clear);
807
+ return promise;
808
+ }
809
+ /** attach 接管(§5.4):零请求注册已有签名 URL */
810
+ attach(descriptor) {
811
+ this.assertNotDisposed();
812
+ if (!descriptor || typeof descriptor.media_id !== "string" || !descriptor.media_id) {
813
+ throw new PlayerSdkError("sdk_bad_response", "attachPlayback \u9700\u8981 descriptor.media_id");
814
+ }
815
+ if (typeof descriptor.manifest_url !== "string" || !descriptor.manifest_url) {
816
+ throw new PlayerSdkError("sdk_bad_response", "attachPlayback \u9700\u8981 descriptor.manifest_url\uFF08\u5DF2\u6709\u7B7E\u540D URL\uFF09");
817
+ }
818
+ const entry = this.entryFor(descriptor.media_id);
819
+ this.clearTimers(entry);
820
+ entry.autoStopped = false;
821
+ const handle = new PlaybackHandleImpl(this, {
822
+ media_id: descriptor.media_id,
823
+ sid: descriptor.sid ?? "",
824
+ manifest_url: descriptor.manifest_url,
825
+ expires_at: descriptor.expires_at ?? "",
826
+ template_id: descriptor.template_id ?? "",
827
+ subtitles: sanitizeSubtitles(descriptor.subtitles),
828
+ templates: sanitizeTemplates(descriptor.templates),
829
+ disposed: false,
830
+ requestedTemplateId: descriptor.template_id ?? null
831
+ });
832
+ entry.handle = handle;
833
+ if (descriptor.expires_at) {
834
+ this.scheduleAutoRefresh(entry);
835
+ } else {
836
+ this.clearTimers(entry);
837
+ }
838
+ return handle;
839
+ }
840
+ /** 重新签发(复用会话,§4.2):返回是否真的发起了请求(false = 本地缓存新鲜,零请求) */
841
+ async refresh(handle, options) {
842
+ this.assertNotDisposed();
843
+ return this.serialize(handle.media_id, async () => {
844
+ this.assertHandleAlive(handle);
845
+ const entry = this.entryFor(handle.media_id);
846
+ if (!options.force && !this.isStale(handle._state())) return false;
847
+ await this.requestPlay(entry, {
848
+ templateId: handle._state().requestedTemplateId,
849
+ forceNew: false,
850
+ signal: options.signal
851
+ });
852
+ return true;
853
+ });
854
+ }
855
+ /** 复用会话换源(§5.2):成功后句柄原位更新 + emit playback:template_changed */
856
+ async switchTemplate(handle, templateId, signal) {
857
+ this.assertNotDisposed();
858
+ await this.serialize(handle.media_id, async () => {
859
+ this.assertHandleAlive(handle);
860
+ const entry = this.entryFor(handle.media_id);
861
+ await this.requestPlay(entry, { templateId, forceNew: false, signal });
862
+ this.deps.emitter.emit({
863
+ type: "playback:template_changed",
864
+ media_id: handle.media_id,
865
+ template_id: handle.template_id,
866
+ manifest_url: handle.manifest_url
867
+ });
868
+ });
869
+ }
870
+ /** 无凭据(attach 模式)时 refresh / switchTemplate 的显式拒绝(spec §5.4) */
871
+ requireCredential() {
872
+ if (!this.deps.auth.hasCredential()) {
873
+ throw new PlayerSdkError(
874
+ "sdk_no_credential",
875
+ "\u672A\u914D\u7F6E\u51ED\u636E\uFF08attach \u6A21\u5F0F\u4EC5\u900F\u4F20\u5DF2\u6709\u7B7E\u540D URL\uFF09\uFF1Arefresh / switchTemplate \u9700\u8981 credential\uFF08password / tokenProvider / static\uFF09"
876
+ );
877
+ }
878
+ }
879
+ /** 按轨道定位所属句柄(sdk.fetchSubtitleText 便利入口用;匹配不到返回 null) */
880
+ findByTrack(track) {
881
+ let byId = null;
882
+ for (const entry of this.entries.values()) {
883
+ const handle = entry.handle;
884
+ if (!handle || handle.disposed) continue;
885
+ if (handle.subtitles.some((t) => t.id === track.id && t.url === track.url)) return handle;
886
+ if (!byId && handle.subtitles.some((t) => t.id === track.id)) byId = handle;
887
+ }
888
+ return byId;
889
+ }
890
+ // ---- 释放语义(§4.6:服务端无释放端点,仅停定时器 + 本地失效) ----
891
+ disposeHandle(handle) {
892
+ if (handle.disposed) return;
893
+ handle._update({ disposed: true });
894
+ const entry = this.entries.get(handle.media_id);
895
+ if (entry && entry.handle === handle) {
896
+ this.clearTimers(entry);
897
+ this.entries.delete(handle.media_id);
898
+ }
899
+ this.inflight.delete(handle.media_id);
900
+ }
901
+ /** 身份切换(spec §3.5):停全部定时器 + 清会话缓存 + 旧句柄 disposed=true */
902
+ handleIdentityChange() {
903
+ this.disposeAll();
904
+ }
905
+ disposeAll() {
906
+ for (const entry of this.entries.values()) {
907
+ this.clearTimers(entry);
908
+ if (entry.handle) entry.handle._update({ disposed: true });
909
+ }
910
+ this.entries.clear();
911
+ this.inflight.clear();
912
+ }
913
+ dispose() {
914
+ this.disposed = true;
915
+ this.disposeAll();
916
+ }
917
+ // ---- 事件辅助(handle 与内部流程共用) ----
918
+ emitRefreshed(handle, reason) {
919
+ this.deps.emitter.emit({
920
+ type: "playback:refreshed",
921
+ media_id: handle.media_id,
922
+ manifest_url: handle.manifest_url,
923
+ expires_at: handle.expires_at,
924
+ reason
925
+ });
926
+ }
927
+ emitError(operation, error) {
928
+ this.deps.emitter.emit({ type: "error", operation, error: toSdkError(error) });
929
+ }
930
+ // ---- 内部实现 ----
931
+ assertNotDisposed() {
932
+ if (this.disposed) {
933
+ throw new PlayerSdkError("sdk_disposed", "SDK \u5B9E\u4F8B\u5DF2 dispose()\uFF1A\u8BF7\u91CD\u65B0 createPlayerSdk()");
934
+ }
935
+ }
936
+ assertHandleAlive(handle) {
937
+ handle.assertUsable();
938
+ }
939
+ entryFor(mediaId) {
940
+ let entry = this.entries.get(mediaId);
941
+ if (!entry) {
942
+ entry = {
943
+ mediaId,
944
+ handle: null,
945
+ queue: Promise.resolve(),
946
+ refreshTimer: null,
947
+ retryTimer: null,
948
+ autoStopped: false
949
+ };
950
+ this.entries.set(mediaId, entry);
951
+ }
952
+ return entry;
953
+ }
954
+ /** 同媒资操作串行化(§5.3):队列按提交顺序执行,不同媒资可并发 */
955
+ serialize(mediaId, task) {
956
+ const entry = this.entryFor(mediaId);
957
+ const previous = entry.queue;
958
+ let release;
959
+ entry.queue = new Promise((resolve) => {
960
+ release = resolve;
961
+ });
962
+ return (async () => {
963
+ await previous.catch(() => void 0);
964
+ try {
965
+ return await task();
966
+ } finally {
967
+ release();
968
+ }
969
+ })();
970
+ }
971
+ /** 发起 play 请求并在成功后原位更新句柄 + 重排自动续签 */
972
+ async requestPlay(entry, opts) {
973
+ const body = {};
974
+ if (opts.forceNew) body.force_new = true;
975
+ if (opts.templateId != null) body.template_id = opts.templateId;
976
+ const response = await this.deps.authedRequest("play", {
977
+ method: "POST",
978
+ path: `/v1/media/${encodeURIComponent(entry.mediaId)}/play`,
979
+ body,
980
+ signal: opts.signal
981
+ });
982
+ const next = normalizePlaybackResponse(entry.mediaId, response);
983
+ next.requestedTemplateId = opts.templateId;
984
+ let handle = entry.handle;
985
+ if (!handle || handle.disposed) {
986
+ handle = new PlaybackHandleImpl(this, next);
987
+ entry.handle = handle;
988
+ } else {
989
+ handle._update(next);
990
+ }
991
+ entry.autoStopped = false;
992
+ this.scheduleAutoRefresh(entry);
993
+ return handle;
994
+ }
995
+ /** 到期时刻(Unix 秒)= min(会话 exp, 清单 token exp) - refreshLeewaySec;无信息 → null */
996
+ nextRefreshAtSec(handle) {
997
+ const sessionExp = parseIsoSeconds(handle.expires_at);
998
+ const tokenExp = manifestTokenExp(handle.manifest_url);
999
+ const candidates = [sessionExp, tokenExp].filter((v) => v != null);
1000
+ if (!candidates.length) return null;
1001
+ return Math.min(...candidates) - this.deps.config.refreshLeewaySec;
1002
+ }
1003
+ /** 缓存是否已进入 leeway / 缺失到期信息(§4.2) */
1004
+ isStale(handle) {
1005
+ const at = this.nextRefreshAtSec(handle);
1006
+ if (at == null) return true;
1007
+ return at * 1e3 <= this.deps.now();
1008
+ }
1009
+ scheduleAutoRefresh(entry) {
1010
+ this.clearTimers(entry);
1011
+ if (this.disposed || !this.deps.config.autoRefresh || entry.autoStopped) return;
1012
+ const handle = entry.handle;
1013
+ if (!handle || handle.disposed) return;
1014
+ if (!this.deps.auth.hasCredential()) return;
1015
+ const at = this.nextRefreshAtSec(handle);
1016
+ if (at == null) return;
1017
+ const delay = Math.max(MIN_REFRESH_DELAY_MS, at * 1e3 - this.deps.now());
1018
+ entry.refreshTimer = setTimeout(() => {
1019
+ void this.runAutoRefresh(entry);
1020
+ }, delay);
1021
+ unref(entry.refreshTimer);
1022
+ }
1023
+ /** 自动续签(§4.3):成功 → emit refreshed{auto} + 重新排程;失败 → 30s 后重试一次 */
1024
+ async runAutoRefresh(entry) {
1025
+ entry.refreshTimer = null;
1026
+ const handle = entry.handle;
1027
+ if (this.disposed || !handle || handle.disposed || entry.autoStopped) return;
1028
+ const requestedTemplateId = handle._state().requestedTemplateId;
1029
+ const attempt = () => this.serialize(entry.mediaId, async () => {
1030
+ const current = entry.handle;
1031
+ if (!current || current.disposed) throw new PlayerSdkError("sdk_disposed", "\u64AD\u653E\u53E5\u67C4\u5DF2\u91CA\u653E\uFF0C\u81EA\u52A8\u7EED\u7B7E\u4E2D\u6B62");
1032
+ await this.requestPlay(entry, { templateId: requestedTemplateId, forceNew: false });
1033
+ });
1034
+ try {
1035
+ await attempt();
1036
+ const refreshed = entry.handle;
1037
+ if (refreshed && !refreshed.disposed) this.emitRefreshed(refreshed, "auto");
1038
+ } catch {
1039
+ entry.retryTimer = setTimeout(() => {
1040
+ void this.retryAutoRefresh(entry, requestedTemplateId);
1041
+ }, AUTO_REFRESH_RETRY_MS);
1042
+ unref(entry.retryTimer);
1043
+ }
1044
+ }
1045
+ async retryAutoRefresh(entry, requestedTemplateId) {
1046
+ entry.retryTimer = null;
1047
+ if (this.disposed) return;
1048
+ try {
1049
+ await this.serialize(entry.mediaId, async () => {
1050
+ const current = entry.handle;
1051
+ if (!current || current.disposed) throw new PlayerSdkError("sdk_disposed", "\u64AD\u653E\u53E5\u67C4\u5DF2\u91CA\u653E\uFF0C\u81EA\u52A8\u7EED\u7B7E\u4E2D\u6B62");
1052
+ await this.requestPlay(entry, { templateId: requestedTemplateId, forceNew: false });
1053
+ });
1054
+ const refreshed = entry.handle;
1055
+ if (refreshed && !refreshed.disposed) this.emitRefreshed(refreshed, "retry");
1056
+ } catch (error) {
1057
+ entry.autoStopped = true;
1058
+ this.emitError("auto_refresh", error);
1059
+ }
1060
+ }
1061
+ clearTimers(entry) {
1062
+ if (entry.refreshTimer) {
1063
+ clearTimeout(entry.refreshTimer);
1064
+ entry.refreshTimer = null;
1065
+ }
1066
+ if (entry.retryTimer) {
1067
+ clearTimeout(entry.retryTimer);
1068
+ entry.retryTimer = null;
1069
+ }
1070
+ }
1071
+ };
1072
+
1073
+ // src/index.ts
1074
+ function createPlayerSdk(config) {
1075
+ const cfg = resolveConfig(config);
1076
+ const emitter = createEmitter();
1077
+ if (cfg.onEvent) emitter.on(null, cfg.onEvent);
1078
+ const client = new HttpClient({
1079
+ baseUrl: cfg.baseUrl,
1080
+ fetch: cfg.fetch,
1081
+ timeoutMs: cfg.timeoutMs,
1082
+ retries: cfg.retries
1083
+ });
1084
+ let playbackRef = null;
1085
+ const auth = new AuthManager({
1086
+ client,
1087
+ config: cfg,
1088
+ now: () => Date.now(),
1089
+ emit: (event) => emitter.emit(event),
1090
+ onIdentityChange: () => playbackRef?.handleIdentityChange()
1091
+ });
1092
+ async function authedRequest(_operation, opts) {
1093
+ const token = await auth.getAccessToken();
1094
+ try {
1095
+ return await client.json({ ...opts, token });
1096
+ } catch (error) {
1097
+ if (!(error instanceof DeliveryError) || error.code !== "unauthorized") throw error;
1098
+ const recovered = await auth.recoverUnauthorized();
1099
+ if (!recovered) throw error;
1100
+ const retryToken = await auth.getAccessToken();
1101
+ try {
1102
+ return await client.json({ ...opts, token: retryToken });
1103
+ } catch (retryError) {
1104
+ if (retryError instanceof DeliveryError && retryError.code === "unauthorized") auth.markExpired();
1105
+ throw retryError;
1106
+ }
1107
+ }
1108
+ }
1109
+ const media = new MediaApi(authedRequest);
1110
+ const playback = new PlaybackManager({
1111
+ client,
1112
+ auth,
1113
+ config: cfg,
1114
+ emitter,
1115
+ authedRequest,
1116
+ now: () => Date.now()
1117
+ });
1118
+ playbackRef = playback;
1119
+ let disposed = false;
1120
+ const assertNotDisposed = () => {
1121
+ if (disposed) throw new PlayerSdkError("sdk_disposed", "SDK \u5B9E\u4F8B\u5DF2 dispose()\uFF1A\u8BF7\u91CD\u65B0 createPlayerSdk()");
1122
+ };
1123
+ const emitError = (operation, error, signal) => {
1124
+ if (signal?.aborted) return;
1125
+ emitter.emit({ type: "error", operation, error: toSdkError(error) });
1126
+ };
1127
+ function on(rawType, maybeListener) {
1128
+ if (typeof rawType === "function") return emitter.on(null, rawType);
1129
+ if (typeof maybeListener !== "function") {
1130
+ throw new PlayerSdkError("sdk_invalid_config", "on(type, listener) \u9700\u8981 listener \u51FD\u6570");
1131
+ }
1132
+ return emitter.on(rawType, maybeListener);
1133
+ }
1134
+ const sdk = {
1135
+ auth: {
1136
+ getAccessToken: async (options) => {
1137
+ assertNotDisposed();
1138
+ try {
1139
+ return await auth.getAccessToken(options);
1140
+ } catch (error) {
1141
+ emitter.emit({ type: "error", operation: "login", error: toSdkError(error) });
1142
+ throw error;
1143
+ }
1144
+ },
1145
+ setCredential: (source) => {
1146
+ assertNotDisposed();
1147
+ auth.setCredential(source);
1148
+ }
1149
+ },
1150
+ listMedia: async (options) => {
1151
+ assertNotDisposed();
1152
+ try {
1153
+ return await media.listMedia(options);
1154
+ } catch (error) {
1155
+ emitError("list_media", error, options?.signal);
1156
+ throw error;
1157
+ }
1158
+ },
1159
+ getMedia: async (mediaId, options) => {
1160
+ assertNotDisposed();
1161
+ try {
1162
+ return await media.getMedia(mediaId, options);
1163
+ } catch (error) {
1164
+ emitError("get_media", error, options?.signal);
1165
+ throw error;
1166
+ }
1167
+ },
1168
+ play: async (mediaId, options) => {
1169
+ assertNotDisposed();
1170
+ try {
1171
+ return await playback.play(mediaId, options ?? {});
1172
+ } catch (error) {
1173
+ emitError("play", error, options?.signal);
1174
+ throw error;
1175
+ }
1176
+ },
1177
+ attachPlayback: (descriptor) => {
1178
+ assertNotDisposed();
1179
+ return playback.attach(descriptor);
1180
+ },
1181
+ fetchSubtitleText: async (track, options) => {
1182
+ assertNotDisposed();
1183
+ const handle = playback.findByTrack(track);
1184
+ if (handle && !handle.disposed) return handle.fetchSubtitleText(track, options);
1185
+ try {
1186
+ return await fetchVttText(client, track.url, options?.signal);
1187
+ } catch (error) {
1188
+ emitError("subtitle", error, options?.signal);
1189
+ throw error;
1190
+ }
1191
+ },
1192
+ on,
1193
+ dispose: () => {
1194
+ if (disposed) return;
1195
+ disposed = true;
1196
+ playback.dispose();
1197
+ }
1198
+ };
1199
+ return sdk;
1200
+ }
1201
+
1202
+ exports.DeliveryError = DeliveryError;
1203
+ exports.PlayerSdkError = PlayerSdkError;
1204
+ exports.createPlayerSdk = createPlayerSdk;
1205
+ exports.describeError = describeError;
1206
+ exports.parseCustomMetadata = parseCustomMetadata;
1207
+ exports.templateLabel = templateLabel;
1208
+ //# sourceMappingURL=index.cjs.map
1209
+ //# sourceMappingURL=index.cjs.map