@base44-preview/platform 0.1.0-pr.319.cf89f7f → 0.1.0-pr.332.00d7174

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 (41) hide show
  1. package/README.md +71 -124
  2. package/dist/client/client.d.ts +30 -9
  3. package/dist/client/client.js +30 -7
  4. package/dist/client/client.types.d.ts +9 -11
  5. package/dist/client/errors.d.ts +41 -4
  6. package/dist/client/errors.js +39 -2
  7. package/dist/client/errors.types.d.ts +98 -2
  8. package/dist/client/index.d.ts +6 -5
  9. package/dist/client/index.js +1 -1
  10. package/dist/client/modules/builder-protocol.d.ts +16 -5
  11. package/dist/client/modules/builder-protocol.js +30 -8
  12. package/dist/client/modules/builder-socket.d.ts +10 -5
  13. package/dist/client/modules/builder-socket.js +114 -87
  14. package/dist/client/modules/builder-subscription.d.ts +2 -2
  15. package/dist/client/modules/builder.d.ts +1 -2
  16. package/dist/client/modules/builder.events.generated.d.ts +2194 -0
  17. package/dist/client/modules/builder.events.generated.js +3 -0
  18. package/dist/client/modules/builder.events.types.d.ts +70 -361
  19. package/dist/client/modules/builder.js +2 -2
  20. package/dist/client/modules/builder.types.d.ts +169 -23
  21. package/dist/server/index.d.ts +2 -5
  22. package/dist/server/index.js +1 -2
  23. package/dist/server/server-url.d.ts +2 -0
  24. package/dist/{shared → server}/server-url.js +1 -1
  25. package/dist/server/server.d.ts +2 -2
  26. package/dist/server/server.js +3 -6
  27. package/dist/server/server.types.d.ts +2 -7
  28. package/package.json +17 -13
  29. package/dist/server/errors.d.ts +0 -15
  30. package/dist/server/errors.js +0 -18
  31. package/dist/server/errors.types.d.ts +0 -4
  32. package/dist/server/errors.types.js +0 -1
  33. package/dist/server/modules/webhooks-signature.d.ts +0 -11
  34. package/dist/server/modules/webhooks-signature.js +0 -65
  35. package/dist/server/modules/webhooks.d.ts +0 -3
  36. package/dist/server/modules/webhooks.events.generated.d.ts +0 -174
  37. package/dist/server/modules/webhooks.events.generated.js +0 -3
  38. package/dist/server/modules/webhooks.js +0 -77
  39. package/dist/server/modules/webhooks.types.d.ts +0 -102
  40. package/dist/server/modules/webhooks.types.js +0 -1
  41. package/dist/shared/server-url.d.ts +0 -2
@@ -1,14 +1,22 @@
1
- export const eventNames = [
2
- "message.updated", "message.removed", "app.status_changed", "preview.reload_requested",
3
- "preview.navigation_requested", "queue.updated", "task.progressed", "image.resolved",
4
- "conversation.changed", "files.changed", "branch.deleted", "repository.changed", "pull_request.changed",
5
- ];
6
- /** Notices that name an app room, by the error code each one reports. */
1
+ import { serverEventNames } from "./builder.events.generated.js";
2
+ const sessionEvents = ["app.snapshot", "session.ended"];
3
+ /** App events delivered to `onEvent`: every server event except the session events the socket handles. */
4
+ export const eventNames = serverEventNames.filter((name) => !sessionEvents.includes(name) && !name.startsWith("room."));
5
+ const knownNames = serverEventNames;
6
+ /** A name newer than this SDK's protocol, delivered to `onEvent` as `unknown`. New `room.*` notices have no error code, so they are dropped. */
7
+ export const isUnknownEvent = (name) => !knownNames.includes(name) && !name.startsWith("room.");
8
+ /** Notices that name an app room, by the error code each one reports. A new notice fails to compile until it has one. */
7
9
  export const roomNotices = {
8
10
  "room.access_denied": "access_denied",
9
11
  "room.access_revoked": "access_revoked",
10
12
  "room.snapshot_unavailable": "snapshot_unavailable",
11
13
  };
14
+ // `expired` never reaches the partner: the session renews its token.
15
+ export const sessionEndings = {
16
+ expired: "session_expired",
17
+ revoked: "session_revoked",
18
+ replaced: "session_replaced",
19
+ };
12
20
  export const appPattern = /^[a-f0-9]{24}$/;
13
21
  export const roomFor = (appId) => `/apps/${appId}`;
14
22
  export function object(value) {
@@ -20,8 +28,9 @@ export function appFromRoom(value) {
20
28
  return typeof value === "string" && /^\/apps\/[a-f0-9]{24}$/.test(value) ? value.slice(6) : undefined;
21
29
  }
22
30
  /** Every event is `{room, data}`; payload schemas are the service's, so only the envelope is validated. */
23
- export function decode(type, appId, raw) {
24
- return { type, appId, data: object(object(raw).data) };
31
+ export function decode(name, appId, raw) {
32
+ const data = object(object(raw).data);
33
+ return (knownNames.includes(name) ? { type: name, appId, data } : { type: "unknown", name, appId, data });
25
34
  }
26
35
  export function decodeSnapshot(raw) {
27
36
  const frame = object(raw);
@@ -32,3 +41,16 @@ export function decodeSnapshot(raw) {
32
41
  const queue = data.queue !== null && typeof data.queue === "object" ? { queue: data.queue } : {};
33
42
  return { room: frame.room, status: data.status, messages: data.messages, ...queue };
34
43
  }
44
+ /** Keeps only the fields the socket needs; a URL with credentials, a path, query or fragment is refused. */
45
+ export function decodeSession(raw) {
46
+ const { session_token, socket_url, socket_path } = object(raw);
47
+ if (typeof session_token !== "string" || !session_token.trim())
48
+ throw new Error("Invalid session token");
49
+ if (typeof socket_url !== "string" || typeof socket_path !== "string" || !/^\/(?!\/)[^?#\s]*$/.test(socket_path))
50
+ throw new Error("Invalid socket address");
51
+ const url = new URL(socket_url);
52
+ if (!["https:", "http:"].includes(url.protocol) || url.username || url.password || url.search || url.hash || url.pathname !== "/") {
53
+ throw new Error("Invalid socket URL");
54
+ }
55
+ return { session_token, socket_url: url.origin, socket_path };
56
+ }
@@ -1,12 +1,12 @@
1
- import type { PlatformClientOptions } from "../client.types.js";
2
1
  import type { BuilderInitOptions, BuilderSession, PlatformSubscription, SubscriptionOptions } from "./builder.types.js";
3
2
  /** @internal */
4
3
  export declare class BuilderSocket implements BuilderSession {
5
- private readonly socket;
4
+ private socket?;
5
+ private address?;
6
6
  private readonly subscriptions;
7
7
  private readonly options;
8
8
  private closed;
9
- private token?;
9
+ private session?;
10
10
  private tokenFresh;
11
11
  private ending?;
12
12
  private denialRetries;
@@ -16,8 +16,9 @@ export declare class BuilderSocket implements BuilderSession {
16
16
  private connecting?;
17
17
  private resolveConnect?;
18
18
  private rejectConnect?;
19
- constructor(config: PlatformClientOptions, options: BuilderInitOptions);
20
- /** Connect with the session token. Resolves on CONNECT, before snapshots arrive.
19
+ constructor(options: BuilderInitOptions);
20
+ /** Connect with the session's token. Resolves on CONNECT, before snapshots arrive.
21
+ * The first call fetches the session, whose address the socket opens on.
21
22
  * Transport loss retries up to five times and rejoins active subscriptions.
22
23
  * Call again after a failure or `session_replaced`; concurrent calls share one attempt.
23
24
  */
@@ -29,7 +30,11 @@ export declare class BuilderSocket implements BuilderSession {
29
30
  subscribe(appId: string, options: SubscriptionOptions): PlatformSubscription;
30
31
  /** Stop delivery, cancel reconnection and release all listeners. Idempotent and terminal. */
31
32
  close(): void;
33
+ private open;
34
+ private appEvent;
35
+ private discard;
32
36
  private join;
37
+ /** Without a callback, or when a new session moves the socket, opens a socket at the session's address. */
33
38
  private authenticate;
34
39
  /** A connect the server refused. Transport errors are Socket.IO's to retry. */
35
40
  private refused;
@@ -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 } 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.serverUrl, {
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;
@@ -208,13 +236,12 @@ export class BuilderSocket {
208
236
  sessionEnded(raw) {
209
237
  try {
210
238
  const reason = object(object(raw).data).reason;
211
- const ending = reason === "expired" ? "session_expired"
212
- : reason === "revoked" ? "session_revoked"
213
- : reason === "replaced" ? "session_replaced" : undefined;
239
+ const ending = typeof reason === "string" && Object.prototype.hasOwnProperty.call(sessionEndings, reason)
240
+ ? sessionEndings[reason] : undefined;
214
241
  if (!ending)
215
242
  throw new Error("Unknown reason");
216
243
  // The server disconnects next; the disconnect handler renews or stops.
217
- this.token = undefined;
244
+ this.session = undefined;
218
245
  this.ending = ending;
219
246
  }
220
247
  catch (_a) {
@@ -1,4 +1,4 @@
1
- import type { PlatformEvent, Snapshot } from "./builder.events.types.js";
1
+ import type { PlatformEvent, PlatformSnapshot } from "./builder.events.types.js";
2
2
  import { PlatformSocketError } from "../errors.js";
3
3
  import type { PlatformSocketErrorCode } from "../errors.types.js";
4
4
  import type { PlatformSubscription, SubscriptionOptions } from "./builder.types.js";
@@ -15,7 +15,7 @@ export declare class Subscription implements PlatformSubscription {
15
15
  constructor(appId: string, options: SubscriptionOptions, remove: () => void);
16
16
  private enqueue;
17
17
  event(event: PlatformEvent): void;
18
- snapshot(snapshot: Snapshot): void;
18
+ snapshot(snapshot: PlatformSnapshot): void;
19
19
  /** A non-fatal problem; the subscription keeps receiving events. */
20
20
  warn(code: PlatformSocketErrorCode): void;
21
21
  fail(code: PlatformSocketErrorCode): void;
@@ -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;