@base44-preview/platform 0.1.0-pr.323.0c3777e → 0.1.0-pr.332.986570f

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.
@@ -1,84 +1,28 @@
1
1
  import { io } from "socket.io-client";
2
2
  import { PlatformSocketError } from "../errors.js";
3
- import { appFromRoom, appPattern, decode, decodeSnapshot, eventNames, object, roomFor, roomNotices, sessionEndings } from "./builder-protocol.js";
3
+ import { appFromRoom, appPattern, decode, decodeSession, decodeSnapshot, eventNames, isUnknownEvent, object, roomFor, roomNotices, sessionEndings } from "./builder-protocol.js";
4
4
  import { notify, Subscription } from "./builder-subscription.js";
5
5
  const MAX_DENIAL_RETRIES = 5;
6
6
  /** @internal */
7
7
  export class BuilderSocket {
8
- constructor(config, options) {
8
+ constructor(options) {
9
9
  this.subscriptions = new Map();
10
10
  this.closed = false;
11
11
  this.tokenFresh = false;
12
12
  this.denialRetries = 0;
13
13
  this.authAttempt = 0;
14
- this.options = { ...config, onError: options.onError };
15
- this.socket = io(config.socketUrl, {
16
- path: "/ws/socket.io/", transports: ["websocket"], autoConnect: false,
17
- forceNew: true, reconnectionAttempts: 5, reconnectionDelay: 1000, reconnectionDelayMax: 10000,
18
- timeout: 20000,
19
- auth: (callback) => { void this.authenticate(callback); },
20
- });
21
- this.socket.on("connect", () => {
22
- var _a;
23
- this.tokenFresh = false;
24
- this.denialRetries = 0;
25
- for (const subscription of this.subscriptions.values())
26
- this.join(subscription);
27
- (_a = this.resolveConnect) === null || _a === void 0 ? void 0 : _a.call(this);
28
- this.clearConnecting();
29
- });
30
- this.socket.on("disconnect", (reason) => {
31
- ++this.authAttempt;
32
- if (this.closed || reason !== "io server disconnect")
33
- return; // Transport loss reconnects by itself.
34
- const ending = this.ending;
35
- this.ending = undefined;
36
- if (ending === "session_expired")
37
- this.socket.connect(); // Renew through getSessionToken.
38
- else
39
- this.connectionError(new PlatformSocketError(ending !== null && ending !== void 0 ? ending : "connection_failed"));
40
- });
41
- this.socket.on("connect_error", (error) => this.refused(error));
42
- this.socket.io.on("reconnect_failed", () => this.connectionError(new PlatformSocketError("connection_failed")));
43
- this.socket.on("app.snapshot", (raw) => {
44
- var _a;
45
- try {
46
- const snapshot = decodeSnapshot(raw);
47
- (_a = this.subscriptions.get(appFromRoom(snapshot.room))) === null || _a === void 0 ? void 0 : _a.snapshot(snapshot);
48
- }
49
- catch (_b) {
50
- this.protocolError(raw);
51
- }
52
- });
53
- this.socket.on("session.ended", (raw) => this.sessionEnded(raw));
54
- for (const [name, code] of Object.entries(roomNotices))
55
- this.socket.on(name, (raw) => this.roomNotice(code, raw));
56
- for (const type of eventNames)
57
- this.socket.on(type, (raw) => {
58
- try {
59
- const appId = appFromRoom(object(raw).room);
60
- if (!appId)
61
- throw new Error("Invalid app");
62
- const event = decode(type, appId, raw);
63
- const subscription = this.subscriptions.get(appId);
64
- subscription === null || subscription === void 0 ? void 0 : subscription.event(event);
65
- // The server does not resend a snapshot after a rewrite of main: rejoining asks for one.
66
- if (subscription && event.type === "conversation.changed" && event.data.branch_id == null)
67
- this.join(subscription);
68
- }
69
- catch (_a) {
70
- this.protocolError(raw);
71
- }
72
- });
73
- }
74
- /** Connect with the session token. Resolves on CONNECT, before snapshots arrive.
14
+ this.options = { getSession: options.getSession, onError: options.onError };
15
+ }
16
+ /** Connect with the session's token. Resolves on CONNECT, before snapshots arrive.
17
+ * The first call fetches the session, whose address the socket opens on.
75
18
  * Transport loss retries up to five times and rejoins active subscriptions.
76
19
  * Call again after a failure or `session_replaced`; concurrent calls share one attempt.
77
20
  */
78
21
  connect() {
22
+ var _a;
79
23
  if (this.closed)
80
24
  return Promise.reject(new PlatformSocketError("client_closed"));
81
- if (this.socket.connected)
25
+ if ((_a = this.socket) === null || _a === void 0 ? void 0 : _a.connected)
82
26
  return Promise.resolve();
83
27
  if (this.connecting)
84
28
  return this.connecting;
@@ -87,7 +31,10 @@ export class BuilderSocket {
87
31
  this.rejectConnect = reject;
88
32
  });
89
33
  this.connecting = promise;
90
- this.socket.connect();
34
+ if (this.socket)
35
+ this.socket.connect();
36
+ else
37
+ void this.authenticate();
91
38
  return promise;
92
39
  }
93
40
  /** Subscribe before or after connecting. One subscription per app, maximum eight, each on the
@@ -95,6 +42,7 @@ export class BuilderSocket {
95
42
  * an invalid frame or a server refusal ends the subscription.
96
43
  */
97
44
  subscribe(appId, options) {
45
+ var _a;
98
46
  if (this.closed)
99
47
  throw new PlatformSocketError("client_closed");
100
48
  if (!appPattern.test(appId))
@@ -104,12 +52,13 @@ export class BuilderSocket {
104
52
  if (this.subscriptions.size >= 8)
105
53
  throw new PlatformSocketError("subscription_limit", appId);
106
54
  const subscription = new Subscription(appId, { ...options }, () => {
55
+ var _a;
107
56
  this.subscriptions.delete(appId);
108
- if (this.socket.connected)
57
+ if ((_a = this.socket) === null || _a === void 0 ? void 0 : _a.connected)
109
58
  this.socket.emit("leave", roomFor(appId));
110
59
  });
111
60
  this.subscriptions.set(appId, subscription);
112
- if (this.socket.connected)
61
+ if ((_a = this.socket) === null || _a === void 0 ? void 0 : _a.connected)
113
62
  this.join(subscription);
114
63
  return subscription;
115
64
  }
@@ -126,38 +75,117 @@ export class BuilderSocket {
126
75
  subscription.unsubscribe();
127
76
  (_b = this.rejectConnect) === null || _b === void 0 ? void 0 : _b.call(this, new PlatformSocketError("client_closed"));
128
77
  this.clearConnecting();
78
+ this.discard();
79
+ }
80
+ open(url, path) {
81
+ this.discard();
82
+ const socket = this.socket = io(url, {
83
+ path, transports: ["websocket"], autoConnect: false,
84
+ forceNew: true, reconnectionAttempts: 5, reconnectionDelay: 1000, reconnectionDelayMax: 10000,
85
+ timeout: 20000,
86
+ auth: (callback) => { void this.authenticate(callback); },
87
+ });
88
+ this.address = url + path;
89
+ socket.on("connect", () => {
90
+ var _a;
91
+ this.tokenFresh = false;
92
+ this.denialRetries = 0;
93
+ for (const subscription of this.subscriptions.values())
94
+ this.join(subscription);
95
+ (_a = this.resolveConnect) === null || _a === void 0 ? void 0 : _a.call(this);
96
+ this.clearConnecting();
97
+ });
98
+ socket.on("disconnect", (reason) => {
99
+ ++this.authAttempt;
100
+ if (this.closed || reason !== "io server disconnect")
101
+ return; // Transport loss reconnects by itself.
102
+ const ending = this.ending;
103
+ this.ending = undefined;
104
+ if (ending === "session_expired")
105
+ socket.connect(); // Renew through getSession.
106
+ else
107
+ this.connectionError(new PlatformSocketError(ending !== null && ending !== void 0 ? ending : "connection_failed"));
108
+ });
109
+ socket.on("connect_error", (error) => this.refused(error));
110
+ socket.io.on("reconnect_failed", () => this.connectionError(new PlatformSocketError("connection_failed")));
111
+ socket.on("app.snapshot", (raw) => {
112
+ var _a;
113
+ try {
114
+ const snapshot = decodeSnapshot(raw);
115
+ (_a = this.subscriptions.get(appFromRoom(snapshot.room))) === null || _a === void 0 ? void 0 : _a.snapshot(snapshot);
116
+ }
117
+ catch (_b) {
118
+ this.protocolError(raw);
119
+ }
120
+ });
121
+ socket.on("session.ended", (raw) => this.sessionEnded(raw));
122
+ for (const [name, code] of Object.entries(roomNotices))
123
+ socket.on(name, (raw) => this.roomNotice(code, raw));
124
+ for (const name of eventNames)
125
+ socket.on(name, (raw) => this.appEvent(name, raw));
126
+ // An unknown event with no app room (a future session-wide event) has nowhere to go: ignore it.
127
+ socket.onAny((name, raw) => {
128
+ if (isUnknownEvent(name) && appFromRoom(raw === null || raw === void 0 ? void 0 : raw.room))
129
+ this.appEvent(name, raw);
130
+ });
131
+ socket.connect();
132
+ }
133
+ appEvent(name, raw) {
134
+ try {
135
+ const appId = appFromRoom(object(raw).room);
136
+ if (!appId)
137
+ throw new Error("Invalid app");
138
+ const event = decode(name, appId, raw);
139
+ const subscription = this.subscriptions.get(appId);
140
+ subscription === null || subscription === void 0 ? void 0 : subscription.event(event);
141
+ // The server does not resend a snapshot after a rewrite of main: rejoining asks for one.
142
+ if (subscription && event.type === "conversation.changed" && event.data.branch_id == null)
143
+ this.join(subscription);
144
+ }
145
+ catch (_a) {
146
+ this.protocolError(raw);
147
+ }
148
+ }
149
+ discard() {
150
+ if (!this.socket)
151
+ return;
129
152
  this.socket.removeAllListeners();
153
+ this.socket.offAny();
130
154
  this.socket.io.removeAllListeners();
131
155
  this.socket.disconnect();
132
156
  }
133
157
  join(subscription) {
134
- this.socket.emit("join", roomFor(subscription.appId));
158
+ var _a;
159
+ (_a = this.socket) === null || _a === void 0 ? void 0 : _a.emit("join", roomFor(subscription.appId));
135
160
  }
161
+ /** Without a callback, or when a new session moves the socket, opens a socket at the session's address. */
136
162
  async authenticate(callback) {
137
- var _a;
163
+ var _a, _b;
138
164
  const attempt = ++this.authAttempt;
139
165
  (_a = this.cancelAuth) === null || _a === void 0 ? void 0 : _a.call(this);
140
166
  let timer;
141
167
  const timeout = new Promise((_, reject) => {
142
- timer = setTimeout(() => reject(new Error("Session token timeout")), 20000);
168
+ timer = setTimeout(() => reject(new Error("Session timeout")), 20000);
143
169
  this.cancelAuth = () => { clearTimeout(timer); reject(new Error("Cancelled")); };
144
170
  });
145
171
  try {
146
- if (!this.token) {
147
- const token = await Promise.race([Promise.resolve().then(() => this.options.getSessionToken()), timeout]);
172
+ if (!this.session) {
173
+ const session = await Promise.race([Promise.resolve().then(() => this.options.getSession()), timeout]);
148
174
  if (this.closed || attempt !== this.authAttempt)
149
175
  return;
150
- if (typeof token !== "string" || !token.trim())
151
- throw new Error("Missing session token");
152
- this.token = token;
176
+ this.session = decodeSession(session);
153
177
  this.tokenFresh = true;
154
178
  }
155
- callback({ session_token: this.token });
179
+ const { session_token, socket_url, socket_path } = this.session;
180
+ if (callback && this.address === socket_url + socket_path)
181
+ callback({ session_token });
182
+ else
183
+ this.open(socket_url, socket_path);
156
184
  }
157
- catch (_b) {
185
+ catch (_c) {
158
186
  if (this.closed || attempt !== this.authAttempt)
159
187
  return;
160
- this.socket.disconnect();
188
+ (_b = this.socket) === null || _b === void 0 ? void 0 : _b.disconnect();
161
189
  this.connectionError(new PlatformSocketError("session_unavailable"));
162
190
  }
163
191
  finally {
@@ -168,7 +196,7 @@ export class BuilderSocket {
168
196
  }
169
197
  /** A connect the server refused. Transport errors are Socket.IO's to retry. */
170
198
  refused(error) {
171
- var _a;
199
+ var _a, _b;
172
200
  if (this.closed || error.message !== "connection_denied")
173
201
  return;
174
202
  if (((_a = error.data) === null || _a === void 0 ? void 0 : _a.retryable) === true) {
@@ -177,9 +205,9 @@ export class BuilderSocket {
177
205
  }
178
206
  // A token this attempt did not just fetch may have expired: renew it once.
179
207
  const renew = !this.tokenFresh;
180
- this.token = undefined;
208
+ this.session = undefined;
181
209
  if (renew)
182
- this.socket.connect();
210
+ (_b = this.socket) === null || _b === void 0 ? void 0 : _b.connect();
183
211
  else
184
212
  this.connectionError(new PlatformSocketError("connection_denied"));
185
213
  }
@@ -190,8 +218,8 @@ export class BuilderSocket {
190
218
  return;
191
219
  }
192
220
  const delay = Math.min(1000 * 2 ** (this.denialRetries - 1), 10000) * (0.5 + Math.random() / 2);
193
- this.retryTimer = setTimeout(() => { this.retryTimer = undefined; if (!this.closed)
194
- this.socket.connect(); }, delay);
221
+ this.retryTimer = setTimeout(() => { var _a; this.retryTimer = undefined; if (!this.closed)
222
+ (_a = this.socket) === null || _a === void 0 ? void 0 : _a.connect(); }, delay);
195
223
  }
196
224
  clearConnecting() {
197
225
  this.connecting = undefined;
@@ -213,7 +241,7 @@ export class BuilderSocket {
213
241
  if (!ending)
214
242
  throw new Error("Unknown reason");
215
243
  // The server disconnects next; the disconnect handler renews or stops.
216
- this.token = undefined;
244
+ this.session = undefined;
217
245
  this.ending = ending;
218
246
  }
219
247
  catch (_a) {
@@ -1,4 +1,3 @@
1
- import type { PlatformClientOptions } from "../client.types.js";
2
1
  import type { BuilderModule } from "./builder.types.js";
3
2
  /** @internal */
4
- export declare function createBuilder(config: PlatformClientOptions): BuilderModule;
3
+ export declare function createBuilder(): BuilderModule;