@nyte-ai/protocol 0.0.29-nightly.20261120.113 → 0.3.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.
Files changed (61) hide show
  1. package/README.md +1 -1
  2. package/THIRD-PARTY-NOTICES.md +61 -3
  3. package/dist/chunks/{client-ha6yznqf.js → index-0q4bw06r.js} +12 -5
  4. package/dist/chunks/{client-wn6q96dq.js → index-1gda64ex.js} +27 -9
  5. package/dist/chunks/{client-4fq758q8.js → index-362qtcjf.js} +43 -20
  6. package/dist/chunks/index-7v2tp03w.js +224 -0
  7. package/dist/chunks/{client-wqkvb55q.js → index-gw4eefqr.js} +72 -37
  8. package/dist/chunks/{client-3sbyne3r.js → index-h14s9gt3.js} +1 -1
  9. package/dist/chunks/{client-eggvt9rc.js → index-ht11mtxs.js} +1 -1
  10. package/dist/chunks/{client-sw8vswjs.js → index-k7th682a.js} +53 -15
  11. package/dist/chunks/{client-xscg1xbf.js → index-kr00kac7.js} +1 -1
  12. package/dist/chunks/{client-j4157t87.js → index-q0t950kb.js} +10 -4
  13. package/dist/chunks/{client-101w6sd1.js → index-ra9p4jfx.js} +1 -1
  14. package/dist/chunks/{client-b8brz84x.js → index-rzv8zrzf.js} +3 -1
  15. package/dist/chunks/index-t6hyhcet.js +36 -0
  16. package/dist/chunks/{client-kqr7p5nh.js → index-vbt1c8yx.js} +3 -2
  17. package/dist/src/client/directory-store.d.ts +24 -0
  18. package/dist/src/{directory-store.js → client/directory-store.js} +1 -1
  19. package/dist/src/{session-store.d.ts → client/session-store.d.ts} +3 -1
  20. package/dist/src/{session-store.js → client/session-store.js} +1 -1
  21. package/dist/src/{socket-client.d.ts → client/socket-client.d.ts} +5 -0
  22. package/dist/src/client/socket-client.js +9 -0
  23. package/dist/src/client/stream-client.d.ts +11 -0
  24. package/dist/src/client/stream-client.js +14 -0
  25. package/dist/src/{client.d.ts → client/transport.d.ts} +2 -3
  26. package/dist/src/client/transport.js +11 -0
  27. package/dist/src/index.d.ts +13 -13
  28. package/dist/src/index.js +20 -16
  29. package/dist/src/{codec.js → operations/codec.js} +3 -2
  30. package/dist/src/operations/declarations.js +1 -0
  31. package/dist/src/{digest.js → operations/digest.js} +1 -1
  32. package/dist/src/{raw-parts.js → operations/raw-parts.js} +1 -1
  33. package/dist/src/wire/frame-checks.d.ts +247 -0
  34. package/dist/src/{frame-checks.js → wire/frame-checks.js} +1 -1
  35. package/dist/src/wire/json.d.ts +6 -0
  36. package/dist/src/wire/json.js +10 -0
  37. package/dist/src/{stream-buffer.js → wire/stream-buffer.js} +1 -1
  38. package/dist/src/{stream-channel.js → wire/stream-channel.js} +1 -1
  39. package/dist/src/{streams.js → wire/streams.js} +1 -1
  40. package/dist/src/{wire.d.ts → wire/wire.d.ts} +2 -1
  41. package/dist/src/{wire.js → wire/wire.js} +2 -2
  42. package/package.json +9 -9
  43. package/dist/chunks/client-6vn29412.js +0 -138
  44. package/dist/chunks/client-rk08pxm6.js +0 -12
  45. package/dist/src/client.js +0 -11
  46. package/dist/src/declarations.js +0 -1
  47. package/dist/src/directory-store.d.ts +0 -16
  48. package/dist/src/frame-checks.d.ts +0 -246
  49. package/dist/src/json.d.ts +0 -2
  50. package/dist/src/json.js +0 -6
  51. package/dist/src/socket-client.js +0 -9
  52. package/dist/src/stream-client.d.ts +0 -7
  53. package/dist/src/stream-client.js +0 -10
  54. /package/dist/chunks/{client-x7k53ygp.js → index-r3zsnw1t.js} +0 -0
  55. /package/dist/src/{codec.d.ts → operations/codec.d.ts} +0 -0
  56. /package/dist/src/{declarations.d.ts → operations/declarations.d.ts} +0 -0
  57. /package/dist/src/{digest.d.ts → operations/digest.d.ts} +0 -0
  58. /package/dist/src/{raw-parts.d.ts → operations/raw-parts.d.ts} +0 -0
  59. /package/dist/src/{stream-buffer.d.ts → wire/stream-buffer.d.ts} +0 -0
  60. /package/dist/src/{stream-channel.d.ts → wire/stream-channel.d.ts} +0 -0
  61. /package/dist/src/{streams.d.ts → wire/streams.d.ts} +0 -0
package/README.md CHANGED
@@ -40,7 +40,7 @@ const operations = await transport.invoke("operations.describe", {});
40
40
 
41
41
  `decodeOutput` decodes an answer leniently. It ignores unknown fields and skips array records of an unknown kind. The sdk then rebuilds `Set`s and `Map`s from their wire forms.
42
42
 
43
- `openHostSocket` opens the host's WebSocket, which carries events and streamed text. The [host protocol](../../docs/host-protocol/README.md) describes it.
43
+ `openHostSocket` opens the host's WebSocket, which carries events and streamed text.
44
44
 
45
45
  ## Development
46
46
 
@@ -146,6 +146,11 @@ Silvia O'Dwyer.
146
146
  `@pierre/diffs`' stylesheet. Nyte core remains the source of change, VCS,
147
147
  file, and session identity; Pierre does not own application state or the
148
148
  workbench composition.
149
+ - Ported: the chat panes' size rules (`packages/app/src/panes/piecewise.ts`,
150
+ `packages/app/src/panes/divide.ts`) and their separator drag, which pushes
151
+ past a pane at its minimum size, are adapted from the unreleased
152
+ `@pierre/layouts` on the `necolas/layout` branch at commit
153
+ `a745a6171d256822f895a06d5a3f0fdafda77d58`.
149
154
 
150
155
  License: Apache License 2.0, reproduced in the appendix below. Copyright 2025
151
156
  Pierre Computer Company. The license text is also distributed in each package.
@@ -400,7 +405,7 @@ SOFTWARE.
400
405
 
401
406
  - Repository: https://github.com/pingdotgg/t3code
402
407
  - The SQLite reader and checkpoint workers, large-parameter statement cache
403
- bypass, and connection tuning in `packages/host/src/sqlite*.ts` are adapted
408
+ bypass, and connection tuning in `packages/host/src/store/sqlite*.ts` are adapted
404
409
  from `bf8ffe81a63c82d3de5fbaa9991fd5f30034a452`.
405
410
  - Homepage: https://t3.codes
406
411
 
@@ -487,7 +492,7 @@ SOFTWARE.
487
492
  ## Visual Studio Code (`microsoft/vscode`)
488
493
 
489
494
  - Repository: https://github.com/microsoft/vscode
490
- - What: the zsh and bash startup scripts in `packages/host/src/local/shell-integration`
495
+ - What: the zsh and bash startup scripts in `packages/host/src/local/process/shell-integration`
491
496
  adapt portions of VS Code's shell integration scripts at tag `1.105.1`; the
492
497
  folder's `UPSTREAM.md` lists them.
493
498
 
@@ -548,7 +553,7 @@ text ships alongside each package as `LICENSE`.
548
553
 
549
554
  - Repository: https://github.com/fuma-nama/fumadocs
550
555
  - What: the docs site's Mermaid MDX component
551
- (`packages/docs/src/components/mdx/mermaid.tsx`) is ported from the Fumadocs
556
+ (`services/web/src/components/mdx/mermaid.tsx`) is ported from the Fumadocs
552
557
  docs app, adapted to render through `beautiful-mermaid` and to follow the
553
558
  active light or dark theme without a client-side re-render.
554
559
 
@@ -696,6 +701,40 @@ wherever the gameplay is used: "Gameplay – youtube.com/@Naybr".
696
701
 
697
702
  License: every one is public domain or CC0. None requires attribution.
698
703
 
704
+ ## Yoga (`facebook/yoga`)
705
+
706
+ - Repository: https://github.com/facebook/yoga
707
+ - What: the flexbox layout engine. Nyte Studio builds version 3.2.2 from source
708
+ as a Swift package and links it into `NyteStudio` and `lune`, where it lays
709
+ out the frames of a Lune design. Nyte Studio also bundles Inter, under the
710
+ entry above, and ships both licenses in its app bundle.
711
+
712
+ License: MIT, with the following notice:
713
+
714
+ ```text
715
+ MIT License
716
+
717
+ Copyright (c) Facebook, Inc. and its affiliates.
718
+
719
+ Permission is hereby granted, free of charge, to any person obtaining a copy
720
+ of this software and associated documentation files (the "Software"), to deal
721
+ in the Software without restriction, including without limitation the rights
722
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
723
+ copies of the Software, and to permit persons to whom the Software is
724
+ furnished to do so, subject to the following conditions:
725
+
726
+ The above copyright notice and this permission notice shall be included in all
727
+ copies or substantial portions of the Software.
728
+
729
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
730
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
731
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
732
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
733
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
734
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
735
+ SOFTWARE.
736
+ ```
737
+
699
738
  ## Appendix: Apache License 2.0
700
739
 
701
740
  This is the license for Pierre, Grok Build, and OpenAI Codex above. Section 4
@@ -910,3 +949,22 @@ here.
910
949
  See the License for the specific language governing permissions and
911
950
  limitations under the License.
912
951
  ```
952
+
953
+ ## BeautifulMermaid (`lukilabs/beautiful-mermaid-swift`)
954
+
955
+ - Repository: https://github.com/lukilabs/beautiful-mermaid-swift
956
+ - What: draws Mermaid diagrams with Core Graphics. Nyte Studio builds version
957
+ 1.0.4 from source as a Swift package and links it into `NyteStudio`, where it
958
+ draws the diagrams in a chat reply. Its license ships in the app bundle.
959
+
960
+ License: MIT, Copyright (c) 2026 Craft Docs.
961
+
962
+ ## ElkSwift (`lukilabs/elk-swift`)
963
+
964
+ - Repository: https://github.com/lukilabs/elk-swift
965
+ - What: a Swift port of the Eclipse Layout Kernel's layered layout, which
966
+ BeautifulMermaid depends on. Nyte Studio builds version 1.0.2 from source,
967
+ unmodified, and links it into `NyteStudio`. The source is available at the
968
+ repository above, and the full license ships in the app bundle.
969
+
970
+ License: Eclipse Public License 2.0, https://www.eclipse.org/legal/epl-2.0/.
@@ -1,16 +1,19 @@
1
- // src/directory-store.ts
2
- import { SESSIONS_LIMIT } from "@nyte-ai/schema";
1
+ // src/client/directory-store.ts
2
+ import { digestIdSet, SESSIONS_LIMIT } from "@nyte-ai/schema";
3
3
  function openDirectoryStore2(read, window = {}) {
4
4
  const parents = window.parents ?? { kind: "all" };
5
+ const pinned = window.pinned;
6
+ const query = window.query?.toLowerCase();
5
7
  const limit = Math.max(1, window.limit ?? SESSIONS_LIMIT);
6
8
  const rows = new Map;
7
9
  let ids = [];
10
+ let described = [];
8
11
  let seq = 0;
9
12
  const order = () => {
10
13
  ids = [...rows.values()].toSorted((left, right) => right.lastActivityAt - left.lastActivityAt || compareIds(left.id, right.id)).slice(0, limit).map((row) => row.id);
11
14
  };
12
15
  const keep = (row) => {
13
- if (parents.kind === "all" || row.parent === (parents.kind === "roots" ? null : parents.session))
16
+ if ((parents.kind === "all" || row.parent === (parents.kind === "roots" ? null : parents.session)) && (pinned === undefined || row.pinned === pinned) && (query === undefined || (row.name?.toLowerCase().includes(query) ?? false)))
14
17
  rows.set(row.id, row);
15
18
  else
16
19
  rows.delete(row.id);
@@ -19,7 +22,7 @@ function openDirectoryStore2(read, window = {}) {
19
22
  seq = next.seq;
20
23
  for (const row of next.rows)
21
24
  keep(row);
22
- const kept = new Set(next.ids);
25
+ const kept = new Set(next.kept === undefined ? next.ids : [...described, ...next.ids]);
23
26
  for (const id of rows.keys())
24
27
  if (!kept.has(id))
25
28
  rows.delete(id);
@@ -31,7 +34,7 @@ function openDirectoryStore2(read, window = {}) {
31
34
  return seq;
32
35
  },
33
36
  apply(change) {
34
- if (change.seq <= seq)
37
+ if (change.seq < seq)
35
38
  return;
36
39
  seq = change.seq;
37
40
  const table = change.tables.sessions;
@@ -43,6 +46,10 @@ function openDirectoryStore2(read, window = {}) {
43
46
  rows.delete(id);
44
47
  order();
45
48
  },
49
+ describe() {
50
+ described = ids;
51
+ return { seq, held: { count: ids.length, digest: digestIdSet(ids) } };
52
+ },
46
53
  resume,
47
54
  snapshot: () => ({ ids, rows })
48
55
  };
@@ -5,21 +5,31 @@ import {
5
5
  STREAM_HEADER2,
6
6
  DEFLATE_REQUEST2,
7
7
  readStreamFrame2
8
- } from "./client-3sbyne3r.js";
8
+ } from "./index-h14s9gt3.js";
9
9
  import {
10
10
  streamBuffer2
11
- } from "./client-b8brz84x.js";
11
+ } from "./index-rzv8zrzf.js";
12
12
  import {
13
13
  parseJson2
14
- } from "./client-rk08pxm6.js";
14
+ } from "./index-t6hyhcet.js";
15
15
  import {
16
16
  decodeError2,
17
17
  parseSse2
18
- } from "./client-4fq758q8.js";
18
+ } from "./index-362qtcjf.js";
19
19
 
20
- // src/stream-client.ts
20
+ // src/client/stream-client.ts
21
21
  import { inflateSync } from "fflate";
22
22
  import { SdkError } from "@nyte-ai/schema";
23
+ var answers = new WeakSet;
24
+ function hostAnswer2(error) {
25
+ if (!error.retry)
26
+ answers.add(error);
27
+ return error;
28
+ }
29
+ function linkLost2(error) {
30
+ return error instanceof SdkError && error.code === "unavailable" && !answers.has(error);
31
+ }
32
+ var QUIET_MS = 45000;
23
33
  function createStreamClient2(post, deflate) {
24
34
  let channel;
25
35
  const json = (value) => ({
@@ -56,6 +66,12 @@ function createStreamClient2(post, deflate) {
56
66
  const ready = Promise.withResolvers();
57
67
  const current = { ready: ready.promise, controller, streams: new Map };
58
68
  channel = current;
69
+ const quiet = () => setTimeout(() => controller.abort(new SdkError("unavailable", "The stream channel went quiet.")), QUIET_MS);
70
+ let silence = quiet();
71
+ const heard = () => {
72
+ clearTimeout(silence);
73
+ silence = quiet();
74
+ };
59
75
  (async () => {
60
76
  try {
61
77
  const response = await post(CHANNEL_PATH2, {
@@ -66,7 +82,7 @@ function createStreamClient2(post, deflate) {
66
82
  if (id === null || response.body === null)
67
83
  throw new SdkError("invalid", "The host did not open a stream channel.");
68
84
  ready.resolve(id);
69
- for await (const envelope of parseSse2(networkBody(response.body))) {
85
+ for await (const envelope of parseSse2(networkBody(response.body, heard))) {
70
86
  const frame = readStreamFrame2(envelope);
71
87
  const stream = current.streams.get(frame.stream);
72
88
  if (stream === undefined)
@@ -76,7 +92,7 @@ function createStreamClient2(post, deflate) {
76
92
  buffer.end();
77
93
  forget(current, frame.stream);
78
94
  } else if (frame.kind === "error") {
79
- buffer.fail(decodeError2(parseJson2(frame.error)));
95
+ buffer.fail(hostAnswer2(decodeError2(parseJson2(frame.error))));
80
96
  forget(current, frame.stream);
81
97
  } else {
82
98
  let chunk;
@@ -100,6 +116,7 @@ function createStreamClient2(post, deflate) {
100
116
  for (const stream of current.streams.values())
101
117
  stream.buffer.fail(error);
102
118
  } finally {
119
+ clearTimeout(silence);
103
120
  for (const stream of current.streams.values())
104
121
  stream.dispose();
105
122
  current.streams.clear();
@@ -146,13 +163,14 @@ function createStreamClient2(post, deflate) {
146
163
  }
147
164
  };
148
165
  }
149
- function networkBody(body) {
166
+ function networkBody(body, heard) {
150
167
  const reader = body.getReader();
151
168
  return new ReadableStream({
152
169
  async pull(controller) {
153
170
  const next = await reader.read().catch((cause) => {
154
171
  throw new SdkError("unavailable", cause instanceof Error ? cause.message : String(cause));
155
172
  });
173
+ heard();
156
174
  if (next.done)
157
175
  controller.close();
158
176
  else
@@ -162,4 +180,4 @@ function networkBody(body) {
162
180
  });
163
181
  }
164
182
 
165
- export { createStreamClient2 };
183
+ export { hostAnswer2, linkLost2, createStreamClient2 };
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  parseJson2
3
- } from "./client-rk08pxm6.js";
3
+ } from "./index-t6hyhcet.js";
4
4
 
5
- // src/wire.ts
5
+ // src/wire/wire.ts
6
6
  import { isJsonObject, SdkError, SdkErrorWireSchema, SdkErrorWireType } from "@nyte-ai/schema";
7
7
  import { dev } from "@nyte-ai/core/client";
8
8
  var errorStatus2 = {
@@ -22,13 +22,16 @@ var OPERATIONS_HEADER2 = "X-Nyte-Operations";
22
22
  var DATA = 0;
23
23
  var CONTROL = 1;
24
24
  function encodeError2(error) {
25
- return {
25
+ const wire = {
26
26
  code: error.code,
27
27
  message: error.message,
28
28
  hostId: error.hostId,
29
29
  issues: error.issues,
30
30
  correlation: error.correlation
31
31
  };
32
+ if (!error.retry)
33
+ return wire;
34
+ return { ...wire, retry: true };
32
35
  }
33
36
  function decodeError2(value, status) {
34
37
  const result = SdkErrorWireSchema["~standard"].validate(value);
@@ -38,7 +41,8 @@ function decodeError2(value, status) {
38
41
  return new SdkError(wire.code, wire.message, {
39
42
  hostId: wire.hostId,
40
43
  issues: wire.issues,
41
- correlation: wire.correlation
44
+ correlation: wire.correlation,
45
+ retry: wire.retry === true
42
46
  });
43
47
  }
44
48
  function statusCode2(status) {
@@ -88,17 +92,34 @@ data: ${wire}
88
92
  async function* parseSse2(stream) {
89
93
  const reader = stream.getReader();
90
94
  const decoder = new TextDecoder;
91
- let buffer = "";
95
+ const pending = [];
96
+ let afterReturn = false;
97
+ let held = "";
92
98
  try {
93
99
  for (;; ) {
94
100
  const read = await reader.read();
95
- buffer += read.done ? decoder.decode() : decoder.decode(read.value, { stream: true });
96
- const blocks = buffer.replace(/\r\n?/g, `
97
- `).split(`
101
+ const decoded = read.done ? decoder.decode() : decoder.decode(read.value, { stream: true });
102
+ const text = held + (afterReturn && decoded.startsWith(`
103
+ `) ? decoded.slice(1) : decoded).replace(/\r\n?/g, `
104
+ `);
105
+ if (decoded !== "")
106
+ afterReturn = decoded.endsWith("\r");
107
+ held = !read.done && text.endsWith(`
108
+ `) && !text.endsWith(`
109
+
110
+ `) ? `
111
+ ` : "";
112
+ const blocks = text.slice(0, text.length - held.length).split(`
98
113
 
99
114
  `);
100
- buffer = read.done ? "" : blocks.pop() ?? "";
101
- for (const block of blocks) {
115
+ pending.push(blocks.shift() ?? "");
116
+ if (blocks.length === 0 && !read.done)
117
+ continue;
118
+ const complete = [pending.join(""), ...blocks];
119
+ pending.length = 0;
120
+ if (!read.done)
121
+ pending.push(complete.pop() ?? "");
122
+ for (const block of complete) {
102
123
  const frame = parseEventBlock(block);
103
124
  if (frame !== null)
104
125
  yield frame.data;
@@ -193,27 +214,29 @@ async function* parseOutputFrames2(stream) {
193
214
  const reader = stream.getReader();
194
215
  const decoder = new TextDecoder;
195
216
  let buffer = new Uint8Array(0);
217
+ let offset = 0;
196
218
  try {
197
219
  for (;; ) {
198
220
  const read = await reader.read();
199
221
  if (read.done) {
200
- if (buffer.byteLength > 0)
222
+ if (offset < buffer.byteLength)
201
223
  throw new SdkError("internal", "The output stream ended mid-frame.");
202
224
  return;
203
225
  }
204
- buffer = joined(buffer, read.value);
205
- while (buffer.byteLength >= 5) {
206
- const length = new DataView(buffer.buffer, buffer.byteOffset, 5).getUint32(1);
207
- if (buffer.byteLength < 5 + length)
226
+ buffer = joined(buffer.subarray(offset), read.value);
227
+ offset = 0;
228
+ while (buffer.byteLength - offset >= 5) {
229
+ const length = new DataView(buffer.buffer, buffer.byteOffset + offset, 5).getUint32(1);
230
+ const start = offset + 5;
231
+ if (buffer.byteLength < start + length)
208
232
  break;
209
- const tag = buffer[0];
210
- const payload = buffer.slice(5, 5 + length);
211
- buffer = buffer.slice(5 + length);
233
+ const tag = buffer[offset];
234
+ offset = start + length;
212
235
  if (tag === DATA) {
213
- yield { kind: "bytes", data: payload };
236
+ yield { kind: "bytes", data: buffer.slice(start, offset) };
214
237
  continue;
215
238
  }
216
- const control = decodeControl(parseJson2(decoder.decode(payload)));
239
+ const control = decodeControl(parseJson2(decoder.decode(buffer.subarray(start, offset))));
217
240
  if (control !== null)
218
241
  yield control;
219
242
  }
@@ -0,0 +1,224 @@
1
+ import {
2
+ welcomes2,
3
+ results2,
4
+ errors2,
5
+ events2,
6
+ texts2,
7
+ fragments2
8
+ } from "./index-vbt1c8yx.js";
9
+ import {
10
+ readJson2
11
+ } from "./index-t6hyhcet.js";
12
+ import {
13
+ decodeError2
14
+ } from "./index-362qtcjf.js";
15
+
16
+ // src/client/socket-client.ts
17
+ import {
18
+ API_MIN_REVISION,
19
+ API_REVISION,
20
+ isJsonObject,
21
+ SdkError,
22
+ SOCKET_LIMITS
23
+ } from "@nyte-ai/schema";
24
+ var OPEN_MS = 1e4;
25
+ var IDLE_PROBE_MS = 30000;
26
+ var OWED_PROBE_MS = 5000;
27
+ var PROBE_MS = 1e4;
28
+ var ASKED_PROBE_MS = 2000;
29
+ var PROBE_FRAME = { c: "e", type: "call", op: "events.unsubscribe", input: { scopes: [] } };
30
+ var LOST_REASON = "The host stopped answering.";
31
+ async function openHostSocket2(input) {
32
+ const socket = input.socket;
33
+ const waiting = new Map;
34
+ const eventListeners = new Set;
35
+ const textListeners = new Set;
36
+ const greeted = Promise.withResolvers();
37
+ const ended = Promise.withResolvers();
38
+ const pieces = [];
39
+ let held = 0;
40
+ let calls = 0;
41
+ let probes = 0;
42
+ let lost = null;
43
+ let welcomed = false;
44
+ let heard = Date.now();
45
+ let owedSince = heard;
46
+ let probe = null;
47
+ let watch;
48
+ greeted.promise.catch(() => {
49
+ return;
50
+ });
51
+ const finish = (closed) => {
52
+ if (lost !== null)
53
+ return;
54
+ clearTimeout(watch);
55
+ lost = new SdkError("unavailable", closed.reason === "" ? `The host closed the socket (${closed.code}).` : closed.reason);
56
+ greeted.reject(lost);
57
+ for (const entry of waiting.values())
58
+ entry.reject(lost);
59
+ waiting.clear();
60
+ ended.resolve(closed);
61
+ probe?.answered.reject(lost);
62
+ probe = null;
63
+ };
64
+ const watchAt = (at) => {
65
+ clearTimeout(watch);
66
+ watch = setTimeout(check, Math.max(0, at - Date.now()));
67
+ };
68
+ const ask = (deadline) => {
69
+ if (probe !== null) {
70
+ probe = { ...probe, deadline: Math.min(probe.deadline, deadline) };
71
+ watchAt(probe.deadline);
72
+ return probe.answered.promise;
73
+ }
74
+ const answered = Promise.withResolvers();
75
+ answered.promise.catch(() => {
76
+ return;
77
+ });
78
+ probe = { deadline, answered };
79
+ probes += 1;
80
+ socket.send(JSON.stringify({ ...PROBE_FRAME, id: `probe-${String(probes)}` }));
81
+ watchAt(deadline);
82
+ return answered.promise;
83
+ };
84
+ const check = () => {
85
+ if (lost !== null)
86
+ return;
87
+ const now = Date.now();
88
+ if (probe !== null) {
89
+ if (now < probe.deadline) {
90
+ watchAt(probe.deadline);
91
+ return;
92
+ }
93
+ finish({ code: 1006, reason: LOST_REASON });
94
+ socket.close(1000, LOST_REASON);
95
+ return;
96
+ }
97
+ const owes = waiting.size > 0 || !welcomed;
98
+ const quietSince = owes ? Math.max(heard, owedSince) : heard;
99
+ const quiet = owes ? OWED_PROBE_MS : IDLE_PROBE_MS;
100
+ if (now - quietSince < quiet) {
101
+ watchAt(quietSince + quiet);
102
+ return;
103
+ }
104
+ ask(now + PROBE_MS);
105
+ };
106
+ const read = (value) => {
107
+ if (welcomes2.Check(value)) {
108
+ welcomed = true;
109
+ greeted.resolve(value);
110
+ } else if (results2.Check(value))
111
+ settle(value.id, value.output, null);
112
+ else if (errors2.Check(value))
113
+ settle(value.id, null, decodeError2(value.error));
114
+ else if (isJsonObject(value) && events2.Check(value))
115
+ for (const listener of eventListeners)
116
+ listener(value);
117
+ else if (texts2.Check(value))
118
+ for (const listener of textListeners)
119
+ listener(value);
120
+ };
121
+ socket.addEventListener("message", (message) => {
122
+ heard = Date.now();
123
+ probe?.answered.resolve();
124
+ probe = null;
125
+ const value = typeof message.data === "string" ? readJson2(message.data) : undefined;
126
+ if (!fragments2.Check(value)) {
127
+ read(value);
128
+ return;
129
+ }
130
+ held += value.text.length;
131
+ if (held > SOCKET_LIMITS.backlogBytes) {
132
+ pieces.length = 0;
133
+ socket.close(1000, "Fragments passed the backlog limit.");
134
+ return;
135
+ }
136
+ pieces.push(value.text);
137
+ if (!value.last)
138
+ return;
139
+ const joined = readJson2(pieces.join(""));
140
+ pieces.length = 0;
141
+ held = 0;
142
+ if (joined === undefined) {
143
+ socket.close(1000, "Fragments joined to no frame.");
144
+ return;
145
+ }
146
+ read(joined);
147
+ });
148
+ socket.addEventListener("close", (event) => finish({ code: event.code, reason: event.reason }));
149
+ const settle = (id, output, failure) => {
150
+ const entry = waiting.get(id);
151
+ if (entry === undefined)
152
+ return;
153
+ waiting.delete(id);
154
+ if (failure === null)
155
+ entry.resolve(output);
156
+ else
157
+ entry.reject(failure);
158
+ };
159
+ await new Promise((opened, failed) => {
160
+ const opening = setTimeout(() => {
161
+ failed(new SdkError("unavailable", "The host's socket didn't open in time."));
162
+ socket.close();
163
+ }, OPEN_MS);
164
+ socket.addEventListener("open", () => {
165
+ clearTimeout(opening);
166
+ opened();
167
+ });
168
+ socket.addEventListener("error", () => {
169
+ clearTimeout(opening);
170
+ failed(new SdkError("unavailable", "Couldn't open the host's socket."));
171
+ });
172
+ });
173
+ socket.send(JSON.stringify({
174
+ c: "e",
175
+ type: "hello",
176
+ api_min_revision: input.apiMinRevision ?? API_MIN_REVISION,
177
+ api_revision: API_REVISION,
178
+ client: input.client
179
+ }));
180
+ heard = Date.now();
181
+ owedSince = heard;
182
+ watchAt(heard + OWED_PROBE_MS);
183
+ return {
184
+ welcome: greeted.promise,
185
+ closed: ended.promise,
186
+ call(op, value) {
187
+ if (lost !== null)
188
+ return Promise.reject(lost);
189
+ calls += 1;
190
+ const id = String(calls);
191
+ if (waiting.size === 0)
192
+ owedSince = Date.now();
193
+ return new Promise((resolve, reject) => {
194
+ waiting.set(id, { resolve, reject });
195
+ socket.send(JSON.stringify({ c: "e", type: "call", id, op, input: value }));
196
+ if (probe === null)
197
+ watchAt(Math.max(heard, owedSince) + OWED_PROBE_MS);
198
+ });
199
+ },
200
+ onEvent(listener) {
201
+ eventListeners.add(listener);
202
+ return () => {
203
+ eventListeners.delete(listener);
204
+ };
205
+ },
206
+ onText(listener) {
207
+ textListeners.add(listener);
208
+ return () => {
209
+ textListeners.delete(listener);
210
+ };
211
+ },
212
+ probe() {
213
+ if (lost !== null)
214
+ return Promise.reject(lost);
215
+ return ask(Date.now() + ASKED_PROBE_MS);
216
+ },
217
+ close() {
218
+ finish({ code: 1000, reason: "done" });
219
+ socket.close(1000, "done");
220
+ }
221
+ };
222
+ }
223
+
224
+ export { openHostSocket2 };