krillplayer-plugin 0.3.0 → 0.4.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/README.md CHANGED
@@ -104,5 +104,6 @@ npx krillplayer-plugin skill
104
104
 
105
105
  ## 更新记录
106
106
 
107
+ - **0.4.0**:`danmaku.send` 可以返回发送会话(WebSocket),App 替插件连、发、等,收到的帧交给新的 `danmaku.sendDecode` 判;导出它的插件能力是 `danmakuSendSession`。用例多了假服务器 `socket`。契约修订号不变。完整记录见 `CHANGELOG.md`。
107
108
  - **0.1.2**:契约去掉资料库槽位 `library`(`list`、`read`、`changes`、`ids`)与能力 `library`、`libraryChanges`,App 不再整库扫描来源。还导出 `library` 的插件打包失败,删掉这个导出即可;已经装着的旧版本照常运行,App 不调它。契约修订号不变。
108
109
  - **0.1.1**:契约加上在直播间发弹幕的 `danmaku.send`(能力 `danmakuSend`)。
package/dist/cli.js CHANGED
@@ -80,7 +80,8 @@ var Capability = enumeration("Capability", [
80
80
  "danmakuSend",
81
81
  "browseLists",
82
82
  "playerPanels",
83
- "cardActions"
83
+ "cardActions",
84
+ "danmakuSendSession"
84
85
  ]);
85
86
  var Media = enumeration("Media", ["video", "audio"]);
86
87
  var ChannelKind = enumeration("ChannelKind", ["creator", "station", "podcast"]);
@@ -484,6 +485,24 @@ var LiveDanmakuConnection = object("LiveDanmakuConnection", {
484
485
  heartbeat: optional(object("DanmakuHeartbeat", { frame: DanmakuFrame, interval: number })),
485
486
  recent: optional(array(DanmakuComment))
486
487
  });
488
+ var DANMAKU_SEND_LIMITS = { waitSeconds: 10, sessionSeconds: 20 };
489
+ var DanmakuSendWait = object("DanmakuSendWait", {
490
+ seconds: number,
491
+ outcome: enumeration("DanmakuSendOutcome", ["sent", "failed"], "failed")
492
+ });
493
+ var DanmakuSendSession = object("DanmakuSendSession", {
494
+ url: string,
495
+ headers: optional(map(string)),
496
+ handshake: array(DanmakuFrame),
497
+ wait: DanmakuSendWait,
498
+ state: optional(string)
499
+ });
500
+ var DanmakuSendStep = object("DanmakuSendStep", {
501
+ replies: optional(array(DanmakuFrame)),
502
+ sent: optional(boolean),
503
+ wait: optional(DanmakuSendWait),
504
+ state: optional(string)
505
+ });
487
506
  var DanmakuBatch = object("DanmakuBatch", {
488
507
  messages: array(DanmakuComment),
489
508
  replies: optional(array(DanmakuFrame)),
@@ -779,11 +798,15 @@ var SLOT_RULES = {
779
798
  capabilities: { subtitles: ["list"], subtitleSearch: ["search"] }
780
799
  },
781
800
  // send 是在直播间里发一条弹幕(contract.md 2.7),单独一项能力:只认 danmaku 的旧内核不认识 danmakuSend,跳过,不会去调它。
801
+ // 导出 sendDecode 的插件的 send 可以返回发送会话,能力是 danmakuSendSession 而不是 danmakuSend:只认 danmakuSend 的旧内核
802
+ // 不会去调它、把会话当成发出去了。
782
803
  danmaku: {
783
- functions: ["connect", "decode", "segment", "match", "comments", "send"],
804
+ functions: ["connect", "decode", "segment", "match", "comments", "send", "sendDecode"],
784
805
  required: [],
785
806
  pairs: [["connect", "decode"], ["match", "comments"]],
786
- capabilities: { danmaku: ["connect", "segment"], danmakuMatch: ["match"], danmakuSend: ["send"] }
807
+ needs: { sendDecode: "send" },
808
+ capabilities: { danmaku: ["connect", "segment"], danmakuMatch: ["match"], danmakuSend: ["send"], danmakuSendSession: ["sendDecode"] },
809
+ supersedes: { danmakuSendSession: "danmakuSend" }
787
810
  },
788
811
  status: { functions: ["check", "images"], required: ["check"], pairs: [], capabilities: { status: ["check"] } },
789
812
  login: {
@@ -829,7 +852,9 @@ var SLOT_RETURNS = {
829
852
  decode: { schema: DanmakuBatch },
830
853
  segment: { schema: DanmakuSegment },
831
854
  match: { schema: array(DanmakuMatch) },
832
- comments: { schema: DanmakuSegment }
855
+ comments: { schema: DanmakuSegment },
856
+ send: { schema: DanmakuSendSession, nullable: true },
857
+ sendDecode: { schema: DanmakuSendStep }
833
858
  },
834
859
  status: { check: { schema: array(ChannelStatus) }, images: { schema: array(ChannelImage) } },
835
860
  login: {
@@ -3337,6 +3362,91 @@ async function decompress(format2, data, limit = FORMAT_LIMITS.decompressedBytes
3337
3362
  return output;
3338
3363
  }
3339
3364
 
3365
+ // host/danmaku-send.ts
3366
+ var DanmakuSendFailure = class extends Error {
3367
+ };
3368
+ async function runSendSession({
3369
+ session,
3370
+ grants,
3371
+ open,
3372
+ decode: decode2,
3373
+ lookup: lookup2
3374
+ }) {
3375
+ const secrets = (grants.secrets ?? []).filter((secret) => secret !== "");
3376
+ const texts = (frames) => frames.map(frameText);
3377
+ const headers2 = session.headers ?? {};
3378
+ let pass;
3379
+ try {
3380
+ const chain = new Chain("danmaku", grants);
3381
+ pass = chain.first({ url: session.url, headers: headers2, frames: texts(session.handshake) });
3382
+ const looked = pass.publicOnly === null ? void 0 : lookup2?.(pass.address.host);
3383
+ if (looked !== void 0) chain.resolved(looked.addresses);
3384
+ } catch (error) {
3385
+ throw new DanmakuSendFailure(`danmaku send: ${error.message}`);
3386
+ }
3387
+ const inFrame = (frame2, secret) => frame2.data === void 0 ? (frame2.text ?? "").includes(secret) : Buffer.from(frame2.data).includes(Buffer.from(secret, "utf8"));
3388
+ const carrying = (strings, frames) => secrets.some((secret) => strings.some((text) => text.includes(secret)) || frames.some((frame2) => inFrame(frame2, secret)));
3389
+ const mayCarry = carrying([session.url, ...Object.keys(headers2), ...Object.values(headers2)], session.handshake);
3390
+ const socket = open(pass.address.href, pass.headers);
3391
+ let expired = null;
3392
+ let shookHands = false;
3393
+ let timer;
3394
+ const end = (outcome) => {
3395
+ expired ??= outcome;
3396
+ socket.close();
3397
+ };
3398
+ const arm = (wait) => {
3399
+ clearTimeout(timer);
3400
+ const seconds = Math.min(Math.max(wait.seconds, 0), DANMAKU_SEND_LIMITS.waitSeconds);
3401
+ timer = setTimeout(() => end(shookHands ? wait.outcome : "failed"), seconds * 1e3);
3402
+ };
3403
+ const cap = setTimeout(() => end("failed"), DANMAKU_SEND_LIMITS.sessionSeconds * 1e3);
3404
+ const closed = () => {
3405
+ if (expired === "sent") return;
3406
+ throw new DanmakuSendFailure(expired === null ? "danmaku send: the connection closed before the plugin decided" : "danmaku send: no decision before the deadline");
3407
+ };
3408
+ try {
3409
+ arm(session.wait);
3410
+ try {
3411
+ for (const frame2 of session.handshake) await socket.send(frame2);
3412
+ } catch {
3413
+ return closed();
3414
+ }
3415
+ shookHands = true;
3416
+ arm(session.wait);
3417
+ let state = session.state ?? null;
3418
+ for (; ; ) {
3419
+ let frame2;
3420
+ try {
3421
+ frame2 = await socket.receive();
3422
+ } catch {
3423
+ return closed();
3424
+ }
3425
+ const step = await decode2(frame2, state);
3426
+ if (step.state !== void 0) state = step.state;
3427
+ for (const reply of step.replies ?? []) {
3428
+ if (!mayCarry && carrying([], [reply])) {
3429
+ throw new DanmakuSendFailure("danmaku send: a reply carries credentials the handshake did not");
3430
+ }
3431
+ try {
3432
+ await socket.send(reply);
3433
+ } catch {
3434
+ return closed();
3435
+ }
3436
+ }
3437
+ if (step.sent === true) return;
3438
+ if (step.wait !== void 0) arm(step.wait);
3439
+ }
3440
+ } finally {
3441
+ clearTimeout(timer);
3442
+ clearTimeout(cap);
3443
+ socket.close();
3444
+ }
3445
+ }
3446
+ function frameText(frame2) {
3447
+ return frame2.data === void 0 ? frame2.text ?? "" : Buffer.from(frame2.data).toString("latin1");
3448
+ }
3449
+
3340
3450
  // contract/validate.ts
3341
3451
  var UNKNOWN_KIND_HINTS = [
3342
3452
  [/^(video|vod|clip|short)s?$/i, "\u5E73\u53F0\u4E0A\u4E00\u4E2A\u666E\u901A\u7684\u89C6\u9891\u5199 onDemand\uFF0C\u4E0D\u8981\u5199\u6210 movie \u6216 file"],
@@ -4047,6 +4157,76 @@ async function readCases(directory) {
4047
4157
  return { name: relative(directory, file), data: JSON.parse(raw), byteOrderMark: holdsByteOrderMark(raw) };
4048
4158
  }));
4049
4159
  }
4160
+ var frameJSON = (frame2) => frame2.data === void 0 ? { text: frame2.text ?? "" } : { data: bytesToJSON(frame2.data) };
4161
+ var frameOf = (json) => "data" in json ? { data: new Uint8Array(Buffer.from(json.data.$bytes, "base64")) } : { text: json.text };
4162
+ function scriptedSockets(script) {
4163
+ const problems = [];
4164
+ let opened = false;
4165
+ let step = 0;
4166
+ const open = (url, headers2) => {
4167
+ if (opened) problems.push(`a second socket to ${url}`);
4168
+ opened = true;
4169
+ if (script === void 0) problems.push(`unscripted socket to ${url}`);
4170
+ else if (url !== script.url) problems.push(`socket to ${url}, scripted ${script.url}`);
4171
+ else if (script.headers !== void 0 && canonicalHeaders(script.headers) !== canonicalHeaders(headers2)) {
4172
+ problems.push(`socket headers ${canonicalHeaders(headers2)}, scripted ${canonicalHeaders(script.headers)}`);
4173
+ }
4174
+ const steps = problems.length === 0 && script !== void 0 ? script.script : [];
4175
+ const inbox = [];
4176
+ const waiting = [];
4177
+ let closed = problems.length > 0;
4178
+ const shut = () => {
4179
+ closed = true;
4180
+ for (const waiter of waiting.splice(0)) waiter.reject(new Error("socket closed"));
4181
+ };
4182
+ const advance = () => {
4183
+ while (!closed && step < steps.length) {
4184
+ const current = steps[step];
4185
+ if ("client" in current) return;
4186
+ step += 1;
4187
+ if ("close" in current) return shut();
4188
+ const frame2 = frameOf(current.server);
4189
+ const waiter = waiting.shift();
4190
+ if (waiter === void 0) inbox.push(frame2);
4191
+ else waiter.resolve(frame2);
4192
+ }
4193
+ };
4194
+ advance();
4195
+ return {
4196
+ async send(frame2) {
4197
+ if (closed) throw new Error("socket closed");
4198
+ const current = steps[step];
4199
+ if (current === void 0 || !("client" in current)) {
4200
+ problems.push(`unscripted frame ${canonical(frameJSON(frame2))}`);
4201
+ return shut();
4202
+ }
4203
+ if (canonical(frameJSON(frame2)) !== canonical(current.client)) {
4204
+ problems.push(`frame differs at socket step ${step + 1}
4205
+ expected ${canonical(current.client)}
4206
+ actual ${canonical(frameJSON(frame2))}`);
4207
+ return shut();
4208
+ }
4209
+ step += 1;
4210
+ advance();
4211
+ },
4212
+ receive() {
4213
+ const frame2 = inbox.shift();
4214
+ if (frame2 !== void 0) return Promise.resolve(frame2);
4215
+ if (closed) return Promise.reject(new Error("socket closed"));
4216
+ return new Promise((resolve4, reject) => waiting.push({ resolve: resolve4, reject }));
4217
+ },
4218
+ close: shut
4219
+ };
4220
+ };
4221
+ return {
4222
+ open,
4223
+ problems: () => [
4224
+ ...problems,
4225
+ ...script !== void 0 && !opened ? [`scripted socket to ${script.url} was not opened`] : [],
4226
+ ...opened && script !== void 0 && problems.length === 0 && step < script.script.length ? [`socket script stopped at step ${step + 1} of ${script.script.length}`] : []
4227
+ ]
4228
+ };
4229
+ }
4050
4230
 
4051
4231
  // trial-runner/engine.ts
4052
4232
  import { execFile, spawn } from "node:child_process";
@@ -4784,6 +4964,9 @@ function capabilitiesOf(namespace) {
4784
4964
  problems.push(`${name2}.${present} needs ${name2}.${missing}`);
4785
4965
  }
4786
4966
  }
4967
+ for (const [member, needed] of Object.entries(rule.needs ?? {})) {
4968
+ if (has(member) && !has(needed)) problems.push(`${name2}.${member} needs ${name2}.${needed}`);
4969
+ }
4787
4970
  const matched = Object.entries(rule.capabilities).filter(([, any]) => any.some(has)).map(([capability]) => capability);
4788
4971
  const superseded = new Set(matched.flatMap((capability) => rule.supersedes?.[capability] ?? []));
4789
4972
  const generated = matched.filter((capability) => !superseded.has(capability));
@@ -4944,6 +5127,7 @@ async function readPlugin(path) {
4944
5127
  language: manifest.language,
4945
5128
  dictionaries: dictionariesIn(files2),
4946
5129
  exports: checked.exports,
5130
+ capabilities: capabilities ?? [],
4947
5131
  // 清单用了内核留用的参数名(contract.md 6.1)和静态检查拦下的一样判红。
4948
5132
  violations: [...checked.violations, ...checkManifest({ ...manifest, capabilities }).map((problem) => ` manifest.json: ${problem}`)]
4949
5133
  };
@@ -5008,15 +5192,38 @@ async function runSlotCase(plugin2, testCase) {
5008
5192
  let outcome;
5009
5193
  let written;
5010
5194
  const problems = [];
5195
+ const sockets = scriptedSockets(testCase.socket);
5011
5196
  const context = await openSlot(plugin2, testCase, replay.fetch, testCase.credentials ?? null, (write) => {
5012
5197
  written = write;
5013
5198
  }, metadata, files2);
5014
5199
  try {
5015
5200
  const value = await context.call(testCase.slot, testCase.call ?? "", testCase.args.map(fromJSON));
5016
- problems.push(...contractProblems(testCase, value));
5017
- outcome = { output: toJSON(value) };
5201
+ const contract = contractProblems(testCase, value);
5202
+ problems.push(...contract);
5203
+ if (isSendSession(testCase, value) && contract.length === 0) {
5204
+ if (!plugin2.capabilities.includes("danmakuSendSession")) {
5205
+ throw new DanmakuSendFailure("danmaku send: the plugin returned a send session but does not export danmaku.sendDecode");
5206
+ }
5207
+ await runSendSession({
5208
+ session: value,
5209
+ grants: sendGrants(plugin2, testCase),
5210
+ open: sockets.open,
5211
+ decode: async (frame2, state) => {
5212
+ const step = await context.call("danmaku", "sendDecode", [frame2, state]);
5213
+ const stepProblems = contractProblems({ slot: "danmaku", call: "sendDecode" }, step);
5214
+ if (stepProblems.length > 0) {
5215
+ problems.push(...stepProblems);
5216
+ throw new DanmakuSendFailure("danmaku send: sendDecode returned a step outside the contract");
5217
+ }
5218
+ return step;
5219
+ }
5220
+ });
5221
+ outcome = { output: null };
5222
+ } else {
5223
+ outcome = { output: toJSON(value) };
5224
+ }
5018
5225
  } catch (error) {
5019
- if (!isCallFailure(error)) throw error;
5226
+ if (!isCallFailure(error) && !(error instanceof DanmakuSendFailure)) throw error;
5020
5227
  outcome = { error: structuredError(error), message: describeError(error) };
5021
5228
  } finally {
5022
5229
  context.close();
@@ -5025,7 +5232,8 @@ async function runSlotCase(plugin2, testCase) {
5025
5232
  ...replay.unrecorded.map((request) => `unrecorded request ${request}`),
5026
5233
  ...replay.pending.map(({ request }) => `recorded request not sent ${request.method} ${request.url}`),
5027
5234
  ...metadata.problems(),
5028
- ...files2.problems()
5235
+ ...files2.problems(),
5236
+ ...sockets.problems()
5029
5237
  );
5030
5238
  if ("output" in outcome) {
5031
5239
  if (testCase.error !== void 0) problems.push(`should throw ${canonical(testCase.error)}, returned ${canonical(outcome.output)}`);
@@ -5048,6 +5256,22 @@ async function runSlotCase(plugin2, testCase) {
5048
5256
  }
5049
5257
  return problems.length === 0 ? { status: "passed" } : { status: "failed", reason: problems.join("\n ") };
5050
5258
  }
5259
+ function isSendSession(testCase, value) {
5260
+ return testCase.slot === "danmaku" && testCase.call === "send" && value !== null && value !== void 0;
5261
+ }
5262
+ function sendGrants(plugin2, testCase) {
5263
+ const parameters = testCase.parameters ?? null;
5264
+ const user = plugin2.network.userProvidedURLs === true && parameters !== null;
5265
+ return {
5266
+ declared: plugin2.network.hosts,
5267
+ user: user ? userHostsOf(plugin2, parameters) : [],
5268
+ userAddresses: user ? userAddressesOf(plugin2, parameters) : [],
5269
+ secrets: [
5270
+ ...credentialValues(testCase.credentials ?? null),
5271
+ ...plugin2.parameters.filter((parameter) => parameter.secret).flatMap((parameter) => parameters !== null && Object.hasOwn(parameters, parameter.name) && parameters[parameter.name] !== "" ? [parameters[parameter.name]] : [])
5272
+ ]
5273
+ };
5274
+ }
5051
5275
  function report(results, log) {
5052
5276
  const counts = { passed: 0, skipped: 0, failed: 0 };
5053
5277
  for (const { name: name2, outcome } of results) {
@@ -5086,6 +5310,9 @@ async function recordCommand(pluginDirectory, { slot, call: callName, args, cred
5086
5310
  const problems = contractProblems({ slot, call: callName }, value);
5087
5311
  if (problems.length > 0) throw new RecordRefused(`the plugin's output does not match the contract, nothing was recorded:
5088
5312
  ${problems.join("\n ")}`);
5313
+ if (isSendSession({ slot, call: callName }, value)) {
5314
+ throw new RecordRefused("danmaku.send returned a send session; record does not open sockets, write the case's socket script by hand (see the skill's references/cases.md, section socket)");
5315
+ }
5089
5316
  return { output: toJSON(value) };
5090
5317
  };
5091
5318
  await settle(invokeSlot(plugin2, { slot, call: callName, args, parameters, appKeys, output: null }, recording.fetch, credentials));
package/dist/crypto.js CHANGED
@@ -69,7 +69,8 @@ var Capability = enumeration("Capability", [
69
69
  "danmakuSend",
70
70
  "browseLists",
71
71
  "playerPanels",
72
- "cardActions"
72
+ "cardActions",
73
+ "danmakuSendSession"
73
74
  ]);
74
75
  var Media = enumeration("Media", ["video", "audio"]);
75
76
  var ChannelKind = enumeration("ChannelKind", ["creator", "station", "podcast"]);
@@ -473,6 +474,23 @@ var LiveDanmakuConnection = object("LiveDanmakuConnection", {
473
474
  heartbeat: optional(object("DanmakuHeartbeat", { frame: DanmakuFrame, interval: number })),
474
475
  recent: optional(array(DanmakuComment))
475
476
  });
477
+ var DanmakuSendWait = object("DanmakuSendWait", {
478
+ seconds: number,
479
+ outcome: enumeration("DanmakuSendOutcome", ["sent", "failed"], "failed")
480
+ });
481
+ var DanmakuSendSession = object("DanmakuSendSession", {
482
+ url: string,
483
+ headers: optional(map(string)),
484
+ handshake: array(DanmakuFrame),
485
+ wait: DanmakuSendWait,
486
+ state: optional(string)
487
+ });
488
+ var DanmakuSendStep = object("DanmakuSendStep", {
489
+ replies: optional(array(DanmakuFrame)),
490
+ sent: optional(boolean),
491
+ wait: optional(DanmakuSendWait),
492
+ state: optional(string)
493
+ });
476
494
  var DanmakuBatch = object("DanmakuBatch", {
477
495
  messages: array(DanmakuComment),
478
496
  replies: optional(array(DanmakuFrame)),
@@ -770,7 +788,9 @@ var SLOT_RETURNS = {
770
788
  decode: { schema: DanmakuBatch },
771
789
  segment: { schema: DanmakuSegment },
772
790
  match: { schema: array(DanmakuMatch) },
773
- comments: { schema: DanmakuSegment }
791
+ comments: { schema: DanmakuSegment },
792
+ send: { schema: DanmakuSendSession, nullable: true },
793
+ sendDecode: { schema: DanmakuSendStep }
774
794
  },
775
795
  status: { check: { schema: array(ChannelStatus) }, images: { schema: array(ChannelImage) } },
776
796
  login: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "krillplayer-plugin",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Write, pack, record and test KrillPlayer source plugins on the App's own QuickJS-ng engine, with an AI skill.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://krillplayer.kami.asia",
@@ -41,6 +41,6 @@
41
41
  "eslint": "9.39.5"
42
42
  },
43
43
  "optionalDependencies": {
44
- "@krillplayer/plugin-engine-darwin-arm64": "0.3.0"
44
+ "@krillplayer/plugin-engine-darwin-arm64": "0.4.0"
45
45
  }
46
46
  }
@@ -19,6 +19,7 @@ metadata:
19
19
  | 一样内容该写成哪个种类 | [references/choosing-a-kind.md](references/choosing-a-kind.md) |
20
20
  | 某条报错什么意思、怎么改 | [references/errors-and-fixes.md](references/errors-and-fixes.md) |
21
21
  | 用例文件怎么写、怎么录、失败情形怎么造 | [references/cases.md](references/cases.md) |
22
+ | 平台只在 WebSocket 上收弹幕:`danmaku.send` 返回发送会话、`sendDecode` 判收到的帧,用例里写假服务器 `socket` | [references/contract.d.ts](references/contract.d.ts) 的 `DanmakuSlot`,[references/cases.md](references/cases.md)「socket」 |
22
23
  | 照着改的样例:媒体服务器、文件类来源(`file-share` 用 `krillplayer.formats.xml` 解 WebDAV 的目录,`network-share` 经 `krillplayer.files` 让 App 替它读 SMB 共享)、既直播又发视频的平台、电视、播客、弹幕工具(`danmaku.match` 与 `comments`)、字幕工具(`subtitles.search` 与 `fetch`)、资源插件(`resources.find`:按作品回答有没有可播的版本)、目录插件(只导出 `browse`,作品清单经 `krillplayer.metadata` 查),数据都写在插件里、不出网 | `assets/samples/<样例>/`:`plugin.ts`、`manifest.ts`、`cases/` |
23
24
  | 出网的样例:`krillplayer.http.request`、解 JSON、HTTP 状态到错误种类、录下来的 `exchanges`、手工造的失败用例 | `assets/samples/internet-archive/` |
24
25
 
@@ -36,6 +36,7 @@
36
36
  | `error` | 期望抛出的错误,代替 `output`:`{ "kind": "ended", "message": "…" }`,与 `krillplayer.error(kind, message)` 逐字段比对。不是经 `krillplayer.error` 抛出的错误记为 `{ "kind": "other" }` |
37
37
  | `written` | 这次调用经 `krillplayer.credentials.set` 最后写入的凭证:`{ "values": { "token": "REDACTED" }, "expiresAt": 1767225600 }`。写了凭证而用例没写这个键判失败 |
38
38
  | `requires` | 试跑器没有的能力(例如 `webview`),写了就跳过这条,只在 App 里测 |
39
+ | `socket` | `danmaku.send` 返回发送会话时连的假服务器,见下 |
39
40
 
40
41
  状态槽位带凭证的用例在试跑器里跳过。
41
42
 
@@ -72,6 +73,26 @@ npx krillplayer-plugin record --slot <槽位> [--call <函数>] --args '<JSON
72
73
 
73
74
  来源能稳定触发的失败照上面直接录。其余的(限流、服务器出错、改了格式)录不到:复制一条录好的用例,改 `exchanges` 里的应答(HTTP 状态、来源的错误码、空列表、缺字段),删掉 `output`,写上期望的 `error`。插件代码里每一处 `throw krillplayer.error(…)` 都该有一条用例走到它。
74
75
 
76
+ ## socket
77
+
78
+ `danmaku.send` 返回发送会话(contract.d.ts 的 `DanmakuSendSession`)时,`trial` 与 App 一样替插件连、发握手、按 `wait` 计时,收到的帧交给 `sendDecode`。用例的结果是会话的结果:发出去了 `output` 写 `null`;`sendDecode` 抛了 `krillplayer.error` 就写那个 `error`;地址被拒、连不上、断开、到期没有定论都是 `{ "kind": "other" }`。连的是 `socket` 写的假服务器:
79
+
80
+ ```json
81
+ "socket": {
82
+ "url": "wss://chat.example/room/room-1",
83
+ "script": [
84
+ { "client": { "text": "login REDACTED" } },
85
+ { "server": { "text": "login-ok" } },
86
+ { "client": { "text": "say good evening" } },
87
+ { "server": { "text": "error muted you are muted in this room" } }
88
+ ]
89
+ }
90
+ ```
91
+
92
+ `url` 是插件给的地址(规范写法);写了 `headers` 时连接带的请求头要与它完全相同。`script` 按顺序走:`client` 是插件这时要发出的帧(握手或 `replies`),逐字段比对;`server` 是服务器推过来的帧;`{ "close": true }` 是服务器断开。走完之后服务器不再说话,会话按 `wait` 收尾。字节帧写成 `{ "data": { "$bytes": "<base64>" } }`。每种结果都写一条:接受、回错误帧、一直不回话、定论之前断开。
93
+
94
+ `record` 不替会话连真的平台,遇到会话不写文件:先录 `send` 之前的请求(取网关、取令牌),会话这一段照平台的协议手写。
95
+
75
96
  ## metadata
76
97
 
77
98
  ```json
@@ -23,7 +23,7 @@ export interface Paged<T> {
23
23
  export type Ids = Record<string, string>;
24
24
 
25
25
  // 能力由打包器按导出的函数生成(SLOT_RULES),插件不手写。
26
- export type Capability = "browse" | "music" | "play" | "resolve" | "resources" | "subtitles" | "subtitleSearch" | "danmaku" | "danmakuMatch" | "status" | "login" | "playbackReport" | "danmakuSend" | "browseLists" | "playerPanels" | "cardActions";
26
+ export type Capability = "browse" | "music" | "play" | "resolve" | "resources" | "subtitles" | "subtitleSearch" | "danmaku" | "danmakuMatch" | "status" | "login" | "playbackReport" | "danmakuSend" | "browseLists" | "playerPanels" | "cardActions" | "danmakuSendSession";
27
27
 
28
28
  // 内容对象。通用域三样结构:频道、合集、条目,每个种类一个类型,只带属于它的字段。
29
29
  // 种类的取值是内核定死的词表,插件不能自造。比插件旧的 App 遇到不认识的种类时跳过数组里的那一项、把可选字段当作没给;
@@ -804,6 +804,35 @@ export interface DanmakuHeartbeat {
804
804
  interval: number;
805
805
  }
806
806
 
807
+ // 期限到了还没有定论时怎么收尾:sent 算发出去了,failed 按 other 失败。不认识的值按 failed。
808
+ export interface DanmakuSendWait {
809
+ seconds: number;
810
+ outcome: DanmakuSendOutcome;
811
+ }
812
+
813
+ // App 不认识的取值当作 "failed"。
814
+ export type DanmakuSendOutcome = "sent" | "failed";
815
+
816
+ // 发送会话:send 不自己发时返回它,内核连 url(ws 或 wss),带 headers,依次发 handshake,按 wait 计时;
817
+ // 收到的每一帧连同 state 交给 sendDecode。url、headers、handshake 与 LiveDanmakuConnection 同名同义,凭证的规矩也一样。
818
+ // 连接只为这一次发送存在。
819
+ export interface DanmakuSendSession {
820
+ url: string;
821
+ headers?: Record<string, string>;
822
+ handshake: DanmakuFrame[];
823
+ wait: DanmakuSendWait;
824
+ state?: string;
825
+ }
826
+
827
+ // sendDecode 解出一帧后的一步:replies 依次发出(同 DanmakuBatch.replies);sent 为 true 是发出去了,会话结束;
828
+ // wait 换一个从现在起算的期限;state 有就换掉。被拒绝时不返回,抛 krillplayer.error。
829
+ export interface DanmakuSendStep {
830
+ replies?: DanmakuFrame[];
831
+ sent?: boolean;
832
+ wait?: DanmakuSendWait;
833
+ state?: string;
834
+ }
835
+
807
836
  // 一帧解出的结果:按顺序上屏的弹幕、要回发的帧、续接令牌。续接令牌由内核保存,重连时交给 connect。
808
837
  export interface DanmakuBatch {
809
838
  messages: DanmakuComment[];
@@ -1406,13 +1435,19 @@ export interface LoginSlot {
1406
1435
  // 之后连接里推回来的同一条由内核去掉。被拒绝时抛 krillplayer.error:没登录或登录失效 loginRequired、被禁言 muted、
1407
1436
  // 发得太快 rateLimited、内容不让发 contentRejected,别的原因 other,message 是来源给的说明(内核原样显示)。
1408
1437
  // 内核不自动重发,同一条内容不连发,两次发送之间留几秒;插件也不要替用户重发。
1438
+ // 平台只在 WebSocket 上收发弹幕时,send 不自己发,返回一个发送会话(DanmakuSendSession):内核连 url、依次发 handshake、按 wait 计时,
1439
+ // 收到的每一帧连同 state 交给 sendDecode。sendDecode 返回 { sent: true } 是发出去了,抛 krillplayer.error 是被拒绝(种类同上),
1440
+ // 别的就接着等:replies 依次发出,wait 换一个从现在起算的期限,state 换掉。期限到了还没有定论时按 wait.outcome 收尾:
1441
+ // 平台被拒才回话、接受时不回话的,最后一步写 { seconds: 3, outcome: "sent" }。连接只为这一次发送存在,插件不持有、不计时。
1442
+ // wait.seconds 最多 10,整个会话最多 20 秒(DANMAKU_SEND_LIMITS)。返回会话的插件要导出 sendDecode,只导出 sendDecode 打包器报错。
1409
1443
  export interface DanmakuSlot {
1410
1444
  connect?(krillplayer: KrillPlayer, itemId: string, resume: string | null): Promise<LiveDanmakuConnection>;
1411
1445
  decode?(krillplayer: KrillPlayer, frame: DanmakuFrame): DanmakuBatch | Promise<DanmakuBatch>;
1412
1446
  segment?(krillplayer: KrillPlayer, itemId: string, position: number): Promise<DanmakuSegment>;
1413
1447
  match?(krillplayer: KrillPlayer, media: MediaQuery): Promise<DanmakuMatch[]>;
1414
1448
  comments?(krillplayer: KrillPlayer, matchId: string, position: number): Promise<DanmakuSegment>;
1415
- send?(krillplayer: KrillPlayer, itemId: string, text: string): Promise<void>;
1449
+ send?(krillplayer: KrillPlayer, itemId: string, text: string): Promise<void | DanmakuSendSession>;
1450
+ sendDecode?(krillplayer: KrillPlayer, frame: DanmakuFrame, state: string | null): DanmakuSendStep | Promise<DanmakuSendStep>;
1416
1451
  }
1417
1452
 
1418
1453
  // 播放回报槽位(可选):插件把这次播放报给来源。失败不影响播放,内核不重试。