@mitway/sdk 0.2.3 → 0.2.4
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 +514 -122
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +247 -80
- package/dist/index.d.ts +247 -80
- package/dist/index.js +513 -122
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -856,40 +856,497 @@ var Database = class {
|
|
|
856
856
|
|
|
857
857
|
// src/modules/realtime.ts
|
|
858
858
|
import { io } from "socket.io-client";
|
|
859
|
+
var PRESENCE_HEARTBEAT_MS = 2e4;
|
|
859
860
|
var DEFAULT_CONNECT_TIMEOUT_MS = 1e4;
|
|
861
|
+
var RealtimeChannel = class {
|
|
862
|
+
constructor(topic, realtime, options = {}) {
|
|
863
|
+
this.topic = topic;
|
|
864
|
+
this.realtime = realtime;
|
|
865
|
+
this.options = options;
|
|
866
|
+
}
|
|
867
|
+
topic;
|
|
868
|
+
realtime;
|
|
869
|
+
bindings = [];
|
|
870
|
+
state = "closed";
|
|
871
|
+
statusCallback = null;
|
|
872
|
+
/** Local presence state mirror — populated from `presence_state` /
|
|
873
|
+
* `presence_join` / `presence_leave` events. Read via `presenceState()`. */
|
|
874
|
+
presence = {};
|
|
875
|
+
/** Latest state this client has tracked. Non-null means the heartbeat
|
|
876
|
+
* timer is active and we'll re-emit this state every TTL/2. */
|
|
877
|
+
trackedState = null;
|
|
878
|
+
presenceHeartbeat = null;
|
|
879
|
+
/** Timestamp of the most recently received broadcast on this channel —
|
|
880
|
+
* used as the `since` anchor on replay after reconnect. ISO-8601. */
|
|
881
|
+
lastBroadcastTimestamp = null;
|
|
882
|
+
/** Configuration from `channel(topic, opts)`. Frozen at construction. */
|
|
883
|
+
options;
|
|
884
|
+
/** Whether this channel was opened as `private: true`. */
|
|
885
|
+
get isPrivate() {
|
|
886
|
+
return this.options.config?.private === true;
|
|
887
|
+
}
|
|
888
|
+
/** The user-supplied presence key, if any. */
|
|
889
|
+
get presenceKey() {
|
|
890
|
+
return this.options.config?.presence?.key;
|
|
891
|
+
}
|
|
892
|
+
/** Internal — exposed for Realtime to drive resubscription after a
|
|
893
|
+
* network hiccup. Returns the current lifecycle state. */
|
|
894
|
+
_state() {
|
|
895
|
+
return this.state;
|
|
896
|
+
}
|
|
897
|
+
/** Internal — called by `Realtime` when Socket.IO reconnects after a
|
|
898
|
+
* drop. Re-runs the registration flow; the backend assigns fresh
|
|
899
|
+
* subscription_ids and Socket.IO rejoins the per-subscription rooms,
|
|
900
|
+
* so events resume without developer intervention. The user-provided
|
|
901
|
+
* statusCallback (from the original subscribe()) fires again with
|
|
902
|
+
* 'SUBSCRIBED' or 'CHANNEL_ERROR' so the app can reflect state. */
|
|
903
|
+
async _rejoinAfterReconnect() {
|
|
904
|
+
if (this.state === "closed") {
|
|
905
|
+
return;
|
|
906
|
+
}
|
|
907
|
+
for (const b of this.bindings) {
|
|
908
|
+
if (b.type === "postgres_changes") {
|
|
909
|
+
b.subscriptionId = void 0;
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
this.state = "joining";
|
|
913
|
+
try {
|
|
914
|
+
await this.registerAllBindings();
|
|
915
|
+
if (this.trackedState) {
|
|
916
|
+
const socket = this.realtime._getSocket();
|
|
917
|
+
const key = this.presenceKey;
|
|
918
|
+
socket?.emit(
|
|
919
|
+
"realtime:presence:track",
|
|
920
|
+
key !== void 0 ? { channel: this.topic, state: this.trackedState, key } : { channel: this.topic, state: this.trackedState }
|
|
921
|
+
);
|
|
922
|
+
}
|
|
923
|
+
if (this.lastBroadcastTimestamp && this.bindings.some((b) => b.type === "broadcast")) {
|
|
924
|
+
void this.replay({ since: this.lastBroadcastTimestamp }).catch(() => void 0);
|
|
925
|
+
}
|
|
926
|
+
this.state = "joined";
|
|
927
|
+
this.statusCallback?.("SUBSCRIBED");
|
|
928
|
+
} catch (err) {
|
|
929
|
+
this.state = "errored";
|
|
930
|
+
this.statusCallback?.("CHANNEL_ERROR", {
|
|
931
|
+
code: "REJOIN_FAILED",
|
|
932
|
+
message: err instanceof Error ? err.message : String(err)
|
|
933
|
+
});
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
on(type, filter, callback) {
|
|
937
|
+
if (type === "postgres_changes") {
|
|
938
|
+
this.bindings.push({
|
|
939
|
+
type: "postgres_changes",
|
|
940
|
+
filter,
|
|
941
|
+
callback
|
|
942
|
+
});
|
|
943
|
+
} else if (type === "broadcast") {
|
|
944
|
+
this.bindings.push({
|
|
945
|
+
type: "broadcast",
|
|
946
|
+
filter,
|
|
947
|
+
callback
|
|
948
|
+
});
|
|
949
|
+
} else {
|
|
950
|
+
this.bindings.push({
|
|
951
|
+
type: "presence",
|
|
952
|
+
filter,
|
|
953
|
+
callback
|
|
954
|
+
});
|
|
955
|
+
}
|
|
956
|
+
return this;
|
|
957
|
+
}
|
|
958
|
+
// -------------------------------------------------------------------------
|
|
959
|
+
// Presence — track / untrack / state accessor
|
|
960
|
+
// -------------------------------------------------------------------------
|
|
961
|
+
/**
|
|
962
|
+
* Register or refresh this client's presence entry on the channel. Safe
|
|
963
|
+
* to call many times — state replaces (not merges). Starts a heartbeat
|
|
964
|
+
* timer at TTL/2 so the entry stays alive while the socket is open.
|
|
965
|
+
* The channel must be `subscribe()`d first (the server enforces this).
|
|
966
|
+
*/
|
|
967
|
+
async track(state) {
|
|
968
|
+
const socket = this.realtime._getSocket();
|
|
969
|
+
if (!socket) {
|
|
970
|
+
throw new MitwayBaasError("Socket not connected", 503, "NOT_CONNECTED");
|
|
971
|
+
}
|
|
972
|
+
this.trackedState = state;
|
|
973
|
+
const key = this.presenceKey;
|
|
974
|
+
socket.emit(
|
|
975
|
+
"realtime:presence:track",
|
|
976
|
+
key !== void 0 ? { channel: this.topic, state, key } : { channel: this.topic, state }
|
|
977
|
+
);
|
|
978
|
+
if (!this.presenceHeartbeat) {
|
|
979
|
+
this.presenceHeartbeat = setInterval(() => {
|
|
980
|
+
const s = this.realtime._getSocket();
|
|
981
|
+
if (s && this.trackedState) {
|
|
982
|
+
s.emit(
|
|
983
|
+
"realtime:presence:track",
|
|
984
|
+
key !== void 0 ? { channel: this.topic, state: this.trackedState, key } : { channel: this.topic, state: this.trackedState }
|
|
985
|
+
);
|
|
986
|
+
}
|
|
987
|
+
}, PRESENCE_HEARTBEAT_MS);
|
|
988
|
+
const h = this.presenceHeartbeat;
|
|
989
|
+
h.unref?.();
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
/**
|
|
993
|
+
* Remove this client's presence entry immediately, stopping the
|
|
994
|
+
* heartbeat. Safe if the client never called `track`.
|
|
995
|
+
*/
|
|
996
|
+
untrack() {
|
|
997
|
+
this.trackedState = null;
|
|
998
|
+
if (this.presenceHeartbeat) {
|
|
999
|
+
clearInterval(this.presenceHeartbeat);
|
|
1000
|
+
this.presenceHeartbeat = null;
|
|
1001
|
+
}
|
|
1002
|
+
const socket = this.realtime._getSocket();
|
|
1003
|
+
socket?.emit("realtime:presence:untrack", { channel: this.topic });
|
|
1004
|
+
}
|
|
1005
|
+
/** Snapshot of the current presence state on this channel. Keys are
|
|
1006
|
+
* opaque client identifiers (server-assigned). Re-read inside your
|
|
1007
|
+
* `.on('presence', { event: 'sync' }, ...)` handler. */
|
|
1008
|
+
presenceState() {
|
|
1009
|
+
return this.presence;
|
|
1010
|
+
}
|
|
1011
|
+
/**
|
|
1012
|
+
* Register all bindings with the server:
|
|
1013
|
+
* * For each `broadcast` binding, ensure we're subscribed to the topic
|
|
1014
|
+
* (one `realtime:subscribe` for the channel as a whole).
|
|
1015
|
+
* * For each `postgres_changes` binding, emit
|
|
1016
|
+
* `realtime:postgres_changes:subscribe` and record the assigned
|
|
1017
|
+
* subscription_id.
|
|
1018
|
+
*
|
|
1019
|
+
* `statusCallback` is invoked with `'SUBSCRIBED'` when every binding
|
|
1020
|
+
* has ack'd, or with `'CHANNEL_ERROR' | 'TIMED_OUT'` on failure.
|
|
1021
|
+
*/
|
|
1022
|
+
subscribe(statusCallback) {
|
|
1023
|
+
this.statusCallback = statusCallback ?? null;
|
|
1024
|
+
if (this.state === "joining" || this.state === "joined") {
|
|
1025
|
+
return this;
|
|
1026
|
+
}
|
|
1027
|
+
this.state = "joining";
|
|
1028
|
+
void this.realtime.connect().then(
|
|
1029
|
+
async () => {
|
|
1030
|
+
try {
|
|
1031
|
+
await this.registerAllBindings();
|
|
1032
|
+
this.state = "joined";
|
|
1033
|
+
this.statusCallback?.("SUBSCRIBED");
|
|
1034
|
+
} catch (err) {
|
|
1035
|
+
this.state = "errored";
|
|
1036
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1037
|
+
this.statusCallback?.("CHANNEL_ERROR", {
|
|
1038
|
+
code: "SUBSCRIBE_FAILED",
|
|
1039
|
+
message
|
|
1040
|
+
});
|
|
1041
|
+
}
|
|
1042
|
+
},
|
|
1043
|
+
(err) => {
|
|
1044
|
+
this.state = "errored";
|
|
1045
|
+
this.statusCallback?.("CHANNEL_ERROR", {
|
|
1046
|
+
code: "CONNECT_FAILED",
|
|
1047
|
+
message: err.message
|
|
1048
|
+
});
|
|
1049
|
+
}
|
|
1050
|
+
);
|
|
1051
|
+
return this;
|
|
1052
|
+
}
|
|
1053
|
+
/**
|
|
1054
|
+
* Tear down every binding: unsubscribe from the broadcast topic (if
|
|
1055
|
+
* any broadcast bindings exist) and remove every postgres_changes
|
|
1056
|
+
* subscription by id. Safe to call when state is already closed.
|
|
1057
|
+
*/
|
|
1058
|
+
async unsubscribe() {
|
|
1059
|
+
if (this.state === "closed") {
|
|
1060
|
+
return;
|
|
1061
|
+
}
|
|
1062
|
+
const socket = this.realtime._getSocket();
|
|
1063
|
+
if (this.presenceHeartbeat) {
|
|
1064
|
+
clearInterval(this.presenceHeartbeat);
|
|
1065
|
+
this.presenceHeartbeat = null;
|
|
1066
|
+
}
|
|
1067
|
+
if (!socket) {
|
|
1068
|
+
this.trackedState = null;
|
|
1069
|
+
this.state = "closed";
|
|
1070
|
+
return;
|
|
1071
|
+
}
|
|
1072
|
+
if (this.trackedState) {
|
|
1073
|
+
socket.emit("realtime:presence:untrack", { channel: this.topic });
|
|
1074
|
+
this.trackedState = null;
|
|
1075
|
+
}
|
|
1076
|
+
const pcBindings = this.bindings.filter(
|
|
1077
|
+
(b) => b.type === "postgres_changes"
|
|
1078
|
+
);
|
|
1079
|
+
for (const b of pcBindings) {
|
|
1080
|
+
if (b.subscriptionId) {
|
|
1081
|
+
socket.emit("realtime:postgres_changes:unsubscribe", {
|
|
1082
|
+
subscription_id: b.subscriptionId
|
|
1083
|
+
});
|
|
1084
|
+
b.subscriptionId = void 0;
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
if (this.bindings.some((b) => b.type === "broadcast" || b.type === "presence")) {
|
|
1088
|
+
socket.emit("realtime:unsubscribe", { channel: this.topic });
|
|
1089
|
+
}
|
|
1090
|
+
this.realtime._detachChannel(this);
|
|
1091
|
+
this.state = "closed";
|
|
1092
|
+
this.statusCallback?.("CLOSED");
|
|
1093
|
+
}
|
|
1094
|
+
/**
|
|
1095
|
+
* Publish a broadcast event to the topic. Broadcasts are always
|
|
1096
|
+
* ephemeral — the server fans out to every subscribed socket in memory,
|
|
1097
|
+
* with no DB persistence or webhook fan-out. For audited / durable
|
|
1098
|
+
* events, write to your own application table and enable
|
|
1099
|
+
* `postgres_changes` on it; the SDK will surface the INSERT as a
|
|
1100
|
+
* `postgres_changes` event without a separate channel.send call.
|
|
1101
|
+
*/
|
|
1102
|
+
async send(args) {
|
|
1103
|
+
if (args.type !== "broadcast") {
|
|
1104
|
+
throw new MitwayBaasError(
|
|
1105
|
+
'Only "broadcast" sends are supported \u2014 DB changes flow via your DB writes, not channel.send()',
|
|
1106
|
+
400,
|
|
1107
|
+
"UNSUPPORTED_SEND_TYPE"
|
|
1108
|
+
);
|
|
1109
|
+
}
|
|
1110
|
+
const RESERVED_BROADCAST_NAMES = /* @__PURE__ */ new Set([
|
|
1111
|
+
"postgres_changes",
|
|
1112
|
+
"presence_state",
|
|
1113
|
+
"presence_join",
|
|
1114
|
+
"presence_leave"
|
|
1115
|
+
]);
|
|
1116
|
+
if (RESERVED_BROADCAST_NAMES.has(args.event)) {
|
|
1117
|
+
throw new MitwayBaasError(
|
|
1118
|
+
`"${args.event}" is a reserved event name \u2014 pick a different name for broadcast events`,
|
|
1119
|
+
400,
|
|
1120
|
+
"RESERVED_EVENT_NAME"
|
|
1121
|
+
);
|
|
1122
|
+
}
|
|
1123
|
+
const socket = this.realtime._getSocket();
|
|
1124
|
+
if (!socket) {
|
|
1125
|
+
throw new MitwayBaasError("Socket not connected", 503, "NOT_CONNECTED");
|
|
1126
|
+
}
|
|
1127
|
+
const broadcastCfg = this.options.config?.broadcast;
|
|
1128
|
+
const wantAck = broadcastCfg?.ack === true;
|
|
1129
|
+
const self = broadcastCfg?.self;
|
|
1130
|
+
const wirePayload = {
|
|
1131
|
+
channel: this.topic,
|
|
1132
|
+
event: args.event,
|
|
1133
|
+
payload: args.payload
|
|
1134
|
+
};
|
|
1135
|
+
if (self === false) {
|
|
1136
|
+
wirePayload.self = false;
|
|
1137
|
+
}
|
|
1138
|
+
if (!wantAck) {
|
|
1139
|
+
socket.emit("realtime:publish", wirePayload);
|
|
1140
|
+
return;
|
|
1141
|
+
}
|
|
1142
|
+
return await new Promise((resolve) => {
|
|
1143
|
+
socket.emit(
|
|
1144
|
+
"realtime:publish",
|
|
1145
|
+
wirePayload,
|
|
1146
|
+
(ack) => {
|
|
1147
|
+
resolve(ack);
|
|
1148
|
+
}
|
|
1149
|
+
);
|
|
1150
|
+
});
|
|
1151
|
+
}
|
|
1152
|
+
/**
|
|
1153
|
+
* Replay SQL-originated broadcasts on this topic since the given
|
|
1154
|
+
* timestamp. Delivered only to this socket (same envelope format as
|
|
1155
|
+
* live broadcasts; the SDK routes them through `.on('broadcast', ...)`
|
|
1156
|
+
* bindings just like the real-time path). Backend caps the window at
|
|
1157
|
+
* 24 h and the limit at 1000.
|
|
1158
|
+
*/
|
|
1159
|
+
async replay(args) {
|
|
1160
|
+
const socket = this.realtime._getSocket();
|
|
1161
|
+
if (!socket) {
|
|
1162
|
+
throw new MitwayBaasError("Socket not connected", 503, "NOT_CONNECTED");
|
|
1163
|
+
}
|
|
1164
|
+
socket.emit("realtime:broadcast:replay", {
|
|
1165
|
+
channel: this.topic,
|
|
1166
|
+
since: args.since,
|
|
1167
|
+
limit: args.limit,
|
|
1168
|
+
private: this.isPrivate
|
|
1169
|
+
});
|
|
1170
|
+
}
|
|
1171
|
+
/** Internal — called by Realtime's event router on every incoming event. */
|
|
1172
|
+
_dispatch(event, envelope) {
|
|
1173
|
+
if (event === "postgres_changes") {
|
|
1174
|
+
const pcEvent = envelope;
|
|
1175
|
+
for (const b of this.bindings) {
|
|
1176
|
+
if (b.type !== "postgres_changes") {
|
|
1177
|
+
continue;
|
|
1178
|
+
}
|
|
1179
|
+
if (!b.subscriptionId || !pcEvent.ids.includes(b.subscriptionId)) {
|
|
1180
|
+
continue;
|
|
1181
|
+
}
|
|
1182
|
+
const matchesEvent = b.filter.event === "*" || b.filter.event === pcEvent.data.type;
|
|
1183
|
+
if (!matchesEvent) {
|
|
1184
|
+
continue;
|
|
1185
|
+
}
|
|
1186
|
+
try {
|
|
1187
|
+
b.callback(pcEvent.data);
|
|
1188
|
+
} catch {
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
1191
|
+
return;
|
|
1192
|
+
}
|
|
1193
|
+
if (event === "presence_state" || event === "presence_join" || event === "presence_leave") {
|
|
1194
|
+
const e = envelope;
|
|
1195
|
+
if (e.channel !== this.topic) {
|
|
1196
|
+
return;
|
|
1197
|
+
}
|
|
1198
|
+
if (event === "presence_state" && e.state) {
|
|
1199
|
+
this.presence = { ...e.state };
|
|
1200
|
+
this.firePresence({ event: "sync", state: this.presence });
|
|
1201
|
+
} else if (event === "presence_join" && e.joins) {
|
|
1202
|
+
Object.assign(this.presence, e.joins);
|
|
1203
|
+
this.firePresence({ event: "join", joins: e.joins });
|
|
1204
|
+
} else if (event === "presence_leave" && e.leaves) {
|
|
1205
|
+
for (const key of Object.keys(e.leaves)) {
|
|
1206
|
+
delete this.presence[key];
|
|
1207
|
+
}
|
|
1208
|
+
this.firePresence({ event: "leave", leaves: e.leaves });
|
|
1209
|
+
}
|
|
1210
|
+
return;
|
|
1211
|
+
}
|
|
1212
|
+
const meta = envelope.meta;
|
|
1213
|
+
if (meta?.timestamp) {
|
|
1214
|
+
if (!this.lastBroadcastTimestamp || meta.timestamp > this.lastBroadcastTimestamp) {
|
|
1215
|
+
this.lastBroadcastTimestamp = meta.timestamp;
|
|
1216
|
+
}
|
|
1217
|
+
}
|
|
1218
|
+
for (const b of this.bindings) {
|
|
1219
|
+
if (b.type !== "broadcast") {
|
|
1220
|
+
continue;
|
|
1221
|
+
}
|
|
1222
|
+
if (b.filter.event !== event) {
|
|
1223
|
+
continue;
|
|
1224
|
+
}
|
|
1225
|
+
const { meta: _meta, ...payload } = envelope;
|
|
1226
|
+
try {
|
|
1227
|
+
b.callback({ type: "broadcast", event, payload });
|
|
1228
|
+
} catch {
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
}
|
|
1232
|
+
firePresence(payload) {
|
|
1233
|
+
for (const b of this.bindings) {
|
|
1234
|
+
if (b.type !== "presence") {
|
|
1235
|
+
continue;
|
|
1236
|
+
}
|
|
1237
|
+
if (b.filter.event !== payload.event) {
|
|
1238
|
+
continue;
|
|
1239
|
+
}
|
|
1240
|
+
try {
|
|
1241
|
+
b.callback(payload);
|
|
1242
|
+
} catch {
|
|
1243
|
+
}
|
|
1244
|
+
}
|
|
1245
|
+
}
|
|
1246
|
+
async registerAllBindings() {
|
|
1247
|
+
const socket = this.realtime._getSocket();
|
|
1248
|
+
if (!socket) {
|
|
1249
|
+
throw new Error("Socket not available");
|
|
1250
|
+
}
|
|
1251
|
+
const needsRoomJoin = this.bindings.some(
|
|
1252
|
+
(b) => b.type === "broadcast" || b.type === "presence"
|
|
1253
|
+
);
|
|
1254
|
+
if (needsRoomJoin) {
|
|
1255
|
+
await new Promise((resolve, reject) => {
|
|
1256
|
+
socket.emit(
|
|
1257
|
+
"realtime:subscribe",
|
|
1258
|
+
{ channel: this.topic, private: this.isPrivate },
|
|
1259
|
+
(ack) => {
|
|
1260
|
+
if (ack.ok) {
|
|
1261
|
+
resolve();
|
|
1262
|
+
} else {
|
|
1263
|
+
reject(new Error(ack.error?.message ?? "subscribe failed"));
|
|
1264
|
+
}
|
|
1265
|
+
}
|
|
1266
|
+
);
|
|
1267
|
+
});
|
|
1268
|
+
}
|
|
1269
|
+
const pcBindings = this.bindings.filter(
|
|
1270
|
+
(b) => b.type === "postgres_changes"
|
|
1271
|
+
);
|
|
1272
|
+
await Promise.all(
|
|
1273
|
+
pcBindings.map(
|
|
1274
|
+
(b) => new Promise((resolve, reject) => {
|
|
1275
|
+
socket.emit(
|
|
1276
|
+
"realtime:postgres_changes:subscribe",
|
|
1277
|
+
{
|
|
1278
|
+
event: b.filter.event,
|
|
1279
|
+
schema: b.filter.schema ?? "public",
|
|
1280
|
+
table: b.filter.table,
|
|
1281
|
+
filter: b.filter.filter
|
|
1282
|
+
},
|
|
1283
|
+
(ack) => {
|
|
1284
|
+
if (ack.ok && ack.subscription_id) {
|
|
1285
|
+
b.subscriptionId = ack.subscription_id;
|
|
1286
|
+
resolve();
|
|
1287
|
+
} else {
|
|
1288
|
+
reject(
|
|
1289
|
+
new Error(ack.error?.message ?? "postgres_changes subscribe failed")
|
|
1290
|
+
);
|
|
1291
|
+
}
|
|
1292
|
+
}
|
|
1293
|
+
);
|
|
1294
|
+
})
|
|
1295
|
+
)
|
|
1296
|
+
);
|
|
1297
|
+
}
|
|
1298
|
+
};
|
|
860
1299
|
var Realtime = class {
|
|
861
1300
|
socket = null;
|
|
862
1301
|
baseUrl;
|
|
863
1302
|
options;
|
|
864
1303
|
anonKey;
|
|
865
1304
|
tokenManager;
|
|
866
|
-
|
|
867
|
-
reserved = {
|
|
868
|
-
connect: /* @__PURE__ */ new Set(),
|
|
869
|
-
disconnect: /* @__PURE__ */ new Set(),
|
|
870
|
-
connect_error: /* @__PURE__ */ new Set(),
|
|
871
|
-
error: /* @__PURE__ */ new Set()
|
|
872
|
-
};
|
|
1305
|
+
channels = /* @__PURE__ */ new Map();
|
|
873
1306
|
connecting = null;
|
|
874
|
-
|
|
1307
|
+
/** Flips to `true` once the initial handshake resolves. Differentiates
|
|
1308
|
+
* the first `connect` event (part of `openSocket`) from subsequent
|
|
1309
|
+
* reconnect events (which should trigger auto-resubscribe). */
|
|
1310
|
+
firstConnected = false;
|
|
875
1311
|
constructor(baseUrl, tokenManager, anonKey, options = {}) {
|
|
876
1312
|
this.baseUrl = baseUrl;
|
|
877
1313
|
this.tokenManager = tokenManager;
|
|
878
1314
|
this.anonKey = anonKey;
|
|
879
1315
|
this.options = options;
|
|
880
1316
|
}
|
|
881
|
-
// -----------------------------------------------------------------
|
|
882
|
-
// Connection lifecycle
|
|
883
|
-
// -----------------------------------------------------------------
|
|
884
1317
|
get isConnected() {
|
|
885
1318
|
return this.socket?.connected === true;
|
|
886
1319
|
}
|
|
887
1320
|
get socketId() {
|
|
888
1321
|
return this.socket?.id;
|
|
889
1322
|
}
|
|
890
|
-
/**
|
|
891
|
-
*
|
|
892
|
-
*
|
|
1323
|
+
/**
|
|
1324
|
+
* Get (or create) a channel for `topic`. Channels are cached so multiple
|
|
1325
|
+
* `.channel('same')` calls return the same instance.
|
|
1326
|
+
*
|
|
1327
|
+
* The optional `opts` argument lets the caller configure the channel:
|
|
1328
|
+
* * `config.private` — enable subscribe-side authorization against
|
|
1329
|
+
* `realtime.authorize_subscribe(...)` on the tenant DB.
|
|
1330
|
+
* * `config.broadcast.ack` — `channel.send()` resolves with the
|
|
1331
|
+
* server's ack (message_id) instead of fire-and-forget.
|
|
1332
|
+
* * `config.broadcast.self` — `false` excludes the sender from the
|
|
1333
|
+
* fan-out (defaults to `true`).
|
|
1334
|
+
* * `config.presence.key` — stable presence key to group multiple
|
|
1335
|
+
* tabs of the same user under one entry.
|
|
1336
|
+
*
|
|
1337
|
+
* Options are locked in when the channel is first created; subsequent
|
|
1338
|
+
* `.channel('same')` calls with different opts are ignored. Pass a
|
|
1339
|
+
* different topic to get a different-configured channel.
|
|
1340
|
+
*/
|
|
1341
|
+
channel(topic, opts) {
|
|
1342
|
+
const existing = this.channels.get(topic);
|
|
1343
|
+
if (existing) {
|
|
1344
|
+
return existing;
|
|
1345
|
+
}
|
|
1346
|
+
const channel = new RealtimeChannel(topic, this, opts);
|
|
1347
|
+
this.channels.set(topic, channel);
|
|
1348
|
+
return channel;
|
|
1349
|
+
}
|
|
893
1350
|
connect() {
|
|
894
1351
|
if (this.isConnected) {
|
|
895
1352
|
return Promise.resolve();
|
|
@@ -900,6 +1357,28 @@ var Realtime = class {
|
|
|
900
1357
|
this.connecting = this.openSocket();
|
|
901
1358
|
return this.connecting;
|
|
902
1359
|
}
|
|
1360
|
+
/**
|
|
1361
|
+
* Close the socket. Channels are left as-is so they can re-subscribe
|
|
1362
|
+
* on the next `connect()` — useful for auth token refresh flows.
|
|
1363
|
+
*/
|
|
1364
|
+
disconnect() {
|
|
1365
|
+
if (!this.socket) {
|
|
1366
|
+
return;
|
|
1367
|
+
}
|
|
1368
|
+
this.socket.disconnect();
|
|
1369
|
+
this.socket = null;
|
|
1370
|
+
this.firstConnected = false;
|
|
1371
|
+
}
|
|
1372
|
+
// -------------------------------------------------------------------------
|
|
1373
|
+
// internals used by RealtimeChannel
|
|
1374
|
+
// -------------------------------------------------------------------------
|
|
1375
|
+
/* istanbul ignore next — tested via channel integration */
|
|
1376
|
+
_getSocket() {
|
|
1377
|
+
return this.socket;
|
|
1378
|
+
}
|
|
1379
|
+
_detachChannel(channel) {
|
|
1380
|
+
this.channels.delete(channel.topic);
|
|
1381
|
+
}
|
|
903
1382
|
openSocket() {
|
|
904
1383
|
const token = this.tokenManager.getAccessToken() ?? this.anonKey;
|
|
905
1384
|
if (!token) {
|
|
@@ -921,13 +1400,22 @@ var Realtime = class {
|
|
|
921
1400
|
});
|
|
922
1401
|
this.socket = socket;
|
|
923
1402
|
socket.onAny((event, ...args) => this.dispatch(event, args));
|
|
924
|
-
socket.on("connect", () =>
|
|
925
|
-
|
|
926
|
-
|
|
1403
|
+
socket.on("connect", () => {
|
|
1404
|
+
if (!this.firstConnected) {
|
|
1405
|
+
return;
|
|
1406
|
+
}
|
|
1407
|
+
for (const channel of this.channels.values()) {
|
|
1408
|
+
const state = channel._state();
|
|
1409
|
+
if (state === "joined" || state === "errored") {
|
|
1410
|
+
void channel._rejoinAfterReconnect();
|
|
1411
|
+
}
|
|
1412
|
+
}
|
|
1413
|
+
});
|
|
927
1414
|
return new Promise((resolve, reject) => {
|
|
928
1415
|
const timer = setTimeout(() => {
|
|
929
1416
|
socket.off("connect", onConnect);
|
|
930
1417
|
socket.off("connect_error", onConnectError);
|
|
1418
|
+
this.connecting = null;
|
|
931
1419
|
reject(
|
|
932
1420
|
new MitwayBaasError(
|
|
933
1421
|
`Realtime connection timeout after ${timeoutMs}ms`,
|
|
@@ -935,7 +1423,6 @@ var Realtime = class {
|
|
|
935
1423
|
"CONNECTION_TIMEOUT"
|
|
936
1424
|
)
|
|
937
1425
|
);
|
|
938
|
-
this.connecting = null;
|
|
939
1426
|
}, timeoutMs);
|
|
940
1427
|
const clear = () => {
|
|
941
1428
|
clearTimeout(timer);
|
|
@@ -945,128 +1432,31 @@ var Realtime = class {
|
|
|
945
1432
|
const onConnect = () => {
|
|
946
1433
|
clear();
|
|
947
1434
|
this.connecting = null;
|
|
1435
|
+
this.firstConnected = true;
|
|
948
1436
|
resolve();
|
|
949
1437
|
};
|
|
950
1438
|
const onConnectError = (err) => {
|
|
951
1439
|
clear();
|
|
952
1440
|
this.connecting = null;
|
|
953
|
-
reject(
|
|
954
|
-
new MitwayBaasError(err.message, 0, "CONNECTION_FAILED")
|
|
955
|
-
);
|
|
1441
|
+
reject(new MitwayBaasError(err.message, 0, "CONNECTION_FAILED"));
|
|
956
1442
|
};
|
|
957
1443
|
socket.once("connect", onConnect);
|
|
958
1444
|
socket.once("connect_error", onConnectError);
|
|
959
1445
|
});
|
|
960
1446
|
}
|
|
961
|
-
/** Close the socket and clear in-memory subscription state. Reserved
|
|
962
|
-
* listeners survive so callers can reconnect later via `connect()`. */
|
|
963
|
-
disconnect() {
|
|
964
|
-
if (!this.socket) {
|
|
965
|
-
return;
|
|
966
|
-
}
|
|
967
|
-
this.socket.disconnect();
|
|
968
|
-
this.socket = null;
|
|
969
|
-
this.subscribedChannels.clear();
|
|
970
|
-
}
|
|
971
|
-
// -----------------------------------------------------------------
|
|
972
|
-
// Subscribe / Unsubscribe / Publish
|
|
973
|
-
// -----------------------------------------------------------------
|
|
974
|
-
async subscribe(channel) {
|
|
975
|
-
await this.connect();
|
|
976
|
-
const socket = this.socket;
|
|
977
|
-
if (!socket) {
|
|
978
|
-
return {
|
|
979
|
-
ok: false,
|
|
980
|
-
channel,
|
|
981
|
-
error: { code: "NOT_CONNECTED", message: "Socket is not connected" }
|
|
982
|
-
};
|
|
983
|
-
}
|
|
984
|
-
const result = await new Promise((resolve) => {
|
|
985
|
-
socket.emit("realtime:subscribe", { channel }, (ack) => {
|
|
986
|
-
resolve(ack);
|
|
987
|
-
});
|
|
988
|
-
});
|
|
989
|
-
if (result.ok) {
|
|
990
|
-
this.subscribedChannels.add(channel);
|
|
991
|
-
}
|
|
992
|
-
return result;
|
|
993
|
-
}
|
|
994
|
-
/** Fire-and-forget. No ack from the server. */
|
|
995
|
-
unsubscribe(channel) {
|
|
996
|
-
this.subscribedChannels.delete(channel);
|
|
997
|
-
this.socket?.emit("realtime:unsubscribe", { channel });
|
|
998
|
-
}
|
|
999
|
-
/** Publish via the Socket.IO transport. Subject to RLS INSERT policy
|
|
1000
|
-
* on `realtime.messages` (disabled by default — the developer must
|
|
1001
|
-
* add a policy before clients can publish). Returns immediately; any
|
|
1002
|
-
* server rejection comes through the `error` reserved event. */
|
|
1003
|
-
publish(channel, event, payload) {
|
|
1004
|
-
this.socket?.emit("realtime:publish", { channel, event, payload });
|
|
1005
|
-
}
|
|
1006
|
-
// TypeScript overload impl signature must be assignable from every
|
|
1007
|
-
// public overload. The public overloads take arg lists of different
|
|
1008
|
-
// shapes (ConnectionListener: 0 args, DisconnectListener: 1 string
|
|
1009
|
-
// arg, RealtimeListener: 2 args), so the implementation uses the
|
|
1010
|
-
// widest possible signature. This matches the pattern in socket.io
|
|
1011
|
-
// itself and is the standard TypeScript overload idiom.
|
|
1012
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
1013
|
-
on(event, cb) {
|
|
1014
|
-
if (isReserved(event)) {
|
|
1015
|
-
this.reserved[event].add(cb);
|
|
1016
|
-
return;
|
|
1017
|
-
}
|
|
1018
|
-
if (!this.listeners.has(event)) {
|
|
1019
|
-
this.listeners.set(event, /* @__PURE__ */ new Set());
|
|
1020
|
-
}
|
|
1021
|
-
this.listeners.get(event).add(cb);
|
|
1022
|
-
}
|
|
1023
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
1024
|
-
off(event, cb) {
|
|
1025
|
-
if (isReserved(event)) {
|
|
1026
|
-
this.reserved[event].delete(cb);
|
|
1027
|
-
return;
|
|
1028
|
-
}
|
|
1029
|
-
this.listeners.get(event)?.delete(cb);
|
|
1030
|
-
}
|
|
1031
|
-
// -----------------------------------------------------------------
|
|
1032
|
-
// Internals
|
|
1033
|
-
// -----------------------------------------------------------------
|
|
1034
1447
|
dispatch(event, args) {
|
|
1035
|
-
if (
|
|
1448
|
+
if (event === "postgres_changes") {
|
|
1449
|
+
const envelope2 = args[0] ?? {};
|
|
1450
|
+
this.channels.forEach((ch) => ch._dispatch("postgres_changes", envelope2));
|
|
1036
1451
|
return;
|
|
1037
1452
|
}
|
|
1038
|
-
if (event === "realtime:error") {
|
|
1039
|
-
const err = args[0] ?? {};
|
|
1040
|
-
this.reserved.error.forEach(
|
|
1041
|
-
(cb) => cb(err, {
|
|
1042
|
-
message_id: "",
|
|
1043
|
-
sender_type: "system",
|
|
1044
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
1045
|
-
})
|
|
1046
|
-
);
|
|
1047
|
-
return;
|
|
1048
|
-
}
|
|
1049
|
-
const set = this.listeners.get(event);
|
|
1050
|
-
if (!set || set.size === 0) {
|
|
1453
|
+
if (event === "connect" || event === "disconnect" || event === "connect_error" || event === "error" || event === "realtime:error" || event === "realtime:shutdown") {
|
|
1051
1454
|
return;
|
|
1052
1455
|
}
|
|
1053
1456
|
const envelope = args[0] ?? {};
|
|
1054
|
-
|
|
1055
|
-
const metaOrStub = meta ?? {
|
|
1056
|
-
message_id: "",
|
|
1057
|
-
sender_type: "system",
|
|
1058
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
1059
|
-
};
|
|
1060
|
-
set.forEach((cb) => cb(payload, metaOrStub));
|
|
1061
|
-
}
|
|
1062
|
-
emitReserved(event, ...args) {
|
|
1063
|
-
const set = this.reserved[event];
|
|
1064
|
-
set.forEach((cb) => cb(...args));
|
|
1457
|
+
this.channels.forEach((ch) => ch._dispatch(event, envelope));
|
|
1065
1458
|
}
|
|
1066
1459
|
};
|
|
1067
|
-
function isReserved(event) {
|
|
1068
|
-
return event === "connect" || event === "disconnect" || event === "connect_error" || event === "error";
|
|
1069
|
-
}
|
|
1070
1460
|
|
|
1071
1461
|
// src/client.ts
|
|
1072
1462
|
var MitwayBaasClient = class {
|
|
@@ -1110,6 +1500,7 @@ export {
|
|
|
1110
1500
|
MitwayBaasClient,
|
|
1111
1501
|
MitwayBaasError,
|
|
1112
1502
|
Realtime,
|
|
1503
|
+
RealtimeChannel,
|
|
1113
1504
|
TokenManager,
|
|
1114
1505
|
createClient,
|
|
1115
1506
|
index_default as default
|